forked from btcsuite/btcwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
2533 lines (2227 loc) · 81.3 KB
/
manager.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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014-2016 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package waddrmgr
import (
"crypto/rand"
"crypto/sha512"
"fmt"
"sync"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/btcwallet/internal/zero"
"github.com/btcsuite/btcwallet/snacl"
"github.com/btcsuite/btcwallet/walletdb"
)
const (
// MaxAccountNum is the maximum allowed account number. This value was
// chosen because accounts are hardened children and therefore must
// not exceed the hardened child range of extended keys and it provides
// a reserved account at the top of the range for supporting imported
// addresses.
MaxAccountNum = hdkeychain.HardenedKeyStart - 2 // 2^31 - 2
// MaxAddressesPerAccount is the maximum allowed number of addresses
// per account number. This value is based on the limitation of
// the underlying hierarchical deterministic key derivation.
MaxAddressesPerAccount = hdkeychain.HardenedKeyStart - 1
// ImportedAddrAccount is the account number to use for all imported
// addresses. This is useful since normal accounts are derived from the
// root hierarchical deterministic key and imported addresses do not
// fit into that model.
ImportedAddrAccount = MaxAccountNum + 1 // 2^31 - 1
// ImportedAddrAccountName is the name of the imported account.
ImportedAddrAccountName = "imported"
// DefaultAccountNum is the number of the default account.
DefaultAccountNum = 0
// defaultAccountName is the initial name of the default account. Note
// that the default account may be renamed and is not a reserved name,
// so the default account might not be named "default" and non-default
// accounts may be named "default".
//
// Account numbers never change, so the DefaultAccountNum should be used
// to refer to (and only to) the default account.
defaultAccountName = "default"
// The hierarchy described by BIP0043 is:
// m/<purpose>'/*
// This is further extended by BIP0044 to:
// m/44'/<coin type>'/<account>'/<branch>/<address index>
//
// The branch is 0 for external addresses and 1 for internal addresses.
// maxCoinType is the maximum allowed coin type used when structuring
// the BIP0044 multi-account hierarchy. This value is based on the
// limitation of the underlying hierarchical deterministic key
// derivation.
maxCoinType = hdkeychain.HardenedKeyStart - 1
// externalBranch is the child number to use when performing BIP0044
// style hierarchical deterministic key derivation for the external
// branch.
externalBranch uint32 = 0
// internalBranch is the child number to use when performing BIP0044
// style hierarchical deterministic key derivation for the internal
// branch.
internalBranch uint32 = 1
// saltSize is the number of bytes of the salt used when hashing
// private passphrases.
saltSize = 32
)
// isReservedAccountName returns true if the account name is reserved. Reserved
// accounts may never be renamed, and other accounts may not be renamed to a
// reserved name.
func isReservedAccountName(name string) bool {
return name == ImportedAddrAccountName
}
// isReservedAccountNum returns true if the account number is reserved.
// Reserved accounts may not be renamed.
func isReservedAccountNum(acct uint32) bool {
return acct == ImportedAddrAccount
}
// ScryptOptions is used to hold the scrypt parameters needed when deriving new
// passphrase keys.
type ScryptOptions struct {
N, R, P int
}
// OpenCallbacks houses caller-provided callbacks that may be called when
// opening an existing manager. The open blocks on the execution of these
// functions.
type OpenCallbacks struct {
// ObtainSeed is a callback function that is potentially invoked during
// upgrades. It is intended to be used to request the wallet seed
// from the user (or any other mechanism the caller deems fit).
ObtainSeed ObtainUserInputFunc
// ObtainPrivatePass is a callback function that is potentially invoked
// during upgrades. It is intended to be used to request the wallet
// private passphrase from the user (or any other mechanism the caller
// deems fit).
ObtainPrivatePass ObtainUserInputFunc
}
// DefaultScryptOptions is the default options used with scrypt.
var DefaultScryptOptions = ScryptOptions{
N: 262144, // 2^18
R: 8,
P: 1,
}
// addrKey is used to uniquely identify an address even when those addresses
// would end up being the same bitcoin address (as is the case for pay-to-pubkey
// and pay-to-pubkey-hash style of addresses).
type addrKey string
// accountInfo houses the current state of the internal and external branches
// of an account along with the extended keys needed to derive new keys. It
// also handles locking by keeping an encrypted version of the serialized
// private extended key so the unencrypted versions can be cleared from memory
// when the address manager is locked.
type accountInfo struct {
acctName string
// The account key is used to derive the branches which in turn derive
// the internal and external addresses.
// The accountKeyPriv will be nil when the address manager is locked.
acctKeyEncrypted []byte
acctKeyPriv *hdkeychain.ExtendedKey
acctKeyPub *hdkeychain.ExtendedKey
// The external branch is used for all addresses which are intended
// for external use.
nextExternalIndex uint32
lastExternalAddr ManagedAddress
// The internal branch is used for all adddresses which are only
// intended for internal wallet use such as change addresses.
nextInternalIndex uint32
lastInternalAddr ManagedAddress
}
// AccountProperties contains properties associated with each account, such as
// the account name, number, and the nubmer of derived and imported keys.
type AccountProperties struct {
AccountNumber uint32
AccountName string
ExternalKeyCount uint32
InternalKeyCount uint32
ImportedKeyCount uint32
}
// unlockDeriveInfo houses the information needed to derive a private key for a
// managed address when the address manager is unlocked. See the deriveOnUnlock
// field in the Manager struct for more details on how this is used.
type unlockDeriveInfo struct {
managedAddr *managedAddress
branch uint32
index uint32
}
// defaultNewSecretKey returns a new secret key. See newSecretKey.
func defaultNewSecretKey(passphrase *[]byte, config *ScryptOptions) (*snacl.SecretKey, error) {
return snacl.NewSecretKey(passphrase, config.N, config.R, config.P)
}
// newSecretKey is used as a way to replace the new secret key generation
// function used so tests can provide a version that fails for testing error
// paths.
var newSecretKey = defaultNewSecretKey
// EncryptorDecryptor provides an abstraction on top of snacl.CryptoKey so that
// our tests can use dependency injection to force the behaviour they need.
type EncryptorDecryptor interface {
Encrypt(in []byte) ([]byte, error)
Decrypt(in []byte) ([]byte, error)
Bytes() []byte
CopyBytes([]byte)
Zero()
}
// cryptoKey extends snacl.CryptoKey to implement EncryptorDecryptor.
type cryptoKey struct {
snacl.CryptoKey
}
// Bytes returns a copy of this crypto key's byte slice.
func (ck *cryptoKey) Bytes() []byte {
return ck.CryptoKey[:]
}
// CopyBytes copies the bytes from the given slice into this CryptoKey.
func (ck *cryptoKey) CopyBytes(from []byte) {
copy(ck.CryptoKey[:], from)
}
// defaultNewCryptoKey returns a new CryptoKey. See newCryptoKey.
func defaultNewCryptoKey() (EncryptorDecryptor, error) {
key, err := snacl.GenerateCryptoKey()
if err != nil {
return nil, err
}
return &cryptoKey{*key}, nil
}
// CryptoKeyType is used to differentiate between different kinds of
// crypto keys.
type CryptoKeyType byte
// Crypto key types.
const (
// CKTPrivate specifies the key that is used for encryption of private
// key material such as derived extended private keys and imported
// private keys.
CKTPrivate CryptoKeyType = iota
// CKTScript specifies the key that is used for encryption of scripts.
CKTScript
// CKTPublic specifies the key that is used for encryption of public
// key material such as dervied extended public keys and imported public
// keys.
CKTPublic
)
// newCryptoKey is used as a way to replace the new crypto key generation
// function used so tests can provide a version that fails for testing error
// paths.
var newCryptoKey = defaultNewCryptoKey
// Manager represents a concurrency safe crypto currency address manager and
// key store.
type Manager struct {
mtx sync.RWMutex
namespace walletdb.Namespace
chainParams *chaincfg.Params
addrs map[addrKey]ManagedAddress
syncState syncState
watchingOnly bool
locked bool
closed bool
// acctInfo houses information about accounts including what is needed
// to generate deterministic chained keys for each created account.
acctInfo map[uint32]*accountInfo
// masterKeyPub is the secret key used to secure the cryptoKeyPub key
// and masterKeyPriv is the secret key used to secure the cryptoKeyPriv
// key. This approach is used because it makes changing the passwords
// much simpler as it then becomes just changing these keys. It also
// provides future flexibility.
//
// NOTE: This is not the same thing as BIP0032 master node extended
// key.
//
// The underlying master private key will be zeroed when the address
// manager is locked.
masterKeyPub *snacl.SecretKey
masterKeyPriv *snacl.SecretKey
// cryptoKeyPub is the key used to encrypt public extended keys and
// addresses.
cryptoKeyPub EncryptorDecryptor
// cryptoKeyPriv is the key used to encrypt private data such as the
// master hierarchical deterministic extended key.
//
// This key will be zeroed when the address manager is locked.
cryptoKeyPrivEncrypted []byte
cryptoKeyPriv EncryptorDecryptor
// cryptoKeyScript is the key used to encrypt script data.
//
// This key will be zeroed when the address manager is locked.
cryptoKeyScriptEncrypted []byte
cryptoKeyScript EncryptorDecryptor
// deriveOnUnlock is a list of private keys which needs to be derived
// on the next unlock. This occurs when a public address is derived
// while the address manager is locked since it does not have access to
// the private extended key (hence nor the underlying private key) in
// order to encrypt it.
deriveOnUnlock []*unlockDeriveInfo
// privPassphraseSalt and hashedPrivPassphrase allow for the secure
// detection of a correct passphrase on manager unlock when the
// manager is already unlocked. The hash is zeroed each lock.
privPassphraseSalt [saltSize]byte
hashedPrivPassphrase [sha512.Size]byte
}
// lock performs a best try effort to remove and zero all secret keys associated
// with the address manager.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) lock() {
// Clear all of the account private keys.
for _, acctInfo := range m.acctInfo {
if acctInfo.acctKeyPriv != nil {
acctInfo.acctKeyPriv.Zero()
}
acctInfo.acctKeyPriv = nil
}
// Remove clear text private keys and scripts from all address entries.
for _, ma := range m.addrs {
switch addr := ma.(type) {
case *managedAddress:
addr.lock()
case *scriptAddress:
addr.lock()
}
}
// Remove clear text private master and crypto keys from memory.
m.cryptoKeyScript.Zero()
m.cryptoKeyPriv.Zero()
m.masterKeyPriv.Zero()
// Zero the hashed passphrase.
zero.Bytea64(&m.hashedPrivPassphrase)
// NOTE: m.cryptoKeyPub is intentionally not cleared here as the address
// manager needs to be able to continue to read and decrypt public data
// which uses a separate derived key from the database even when it is
// locked.
m.locked = true
}
// zeroSensitivePublicData performs a best try effort to remove and zero all
// sensitive public data associated with the address manager such as
// hierarchical deterministic extended public keys and the crypto public keys.
func (m *Manager) zeroSensitivePublicData() {
// Clear all of the account private keys.
for _, acctInfo := range m.acctInfo {
acctInfo.acctKeyPub.Zero()
acctInfo.acctKeyPub = nil
}
// Remove clear text public master and crypto keys from memory.
m.cryptoKeyPub.Zero()
m.masterKeyPub.Zero()
}
// Close cleanly shuts down the manager. It makes a best try effort to remove
// and zero all private key and sensitive public key material associated with
// the address manager from memory.
func (m *Manager) Close() error {
m.mtx.Lock()
defer m.mtx.Unlock()
// Attempt to clear private key material from memory.
if !m.watchingOnly && !m.locked {
m.lock()
}
// Attempt to clear sensitive public key material from memory too.
m.zeroSensitivePublicData()
m.closed = true
return nil
}
// keyToManaged returns a new managed address for the provided derived key and
// its derivation path which consists of the account, branch, and index.
//
// The passed derivedKey is zeroed after the new address is created.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) keyToManaged(derivedKey *hdkeychain.ExtendedKey, account, branch, index uint32) (ManagedAddress, error) {
// Create a new managed address based on the public or private key
// depending on whether the passed key is private. Also, zero the
// key after creating the managed address from it.
ma, err := newManagedAddressFromExtKey(m, account, derivedKey)
defer derivedKey.Zero()
if err != nil {
return nil, err
}
if !derivedKey.IsPrivate() {
// Add the managed address to the list of addresses that need
// their private keys derived when the address manager is next
// unlocked.
info := unlockDeriveInfo{
managedAddr: ma,
branch: branch,
index: index,
}
m.deriveOnUnlock = append(m.deriveOnUnlock, &info)
}
if branch == internalBranch {
ma.internal = true
}
return ma, nil
}
// deriveKey returns either a public or private derived extended key based on
// the private flag for the given an account info, branch, and index.
func (m *Manager) deriveKey(acctInfo *accountInfo, branch, index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Choose the public or private extended key based on whether or not
// the private flag was specified. This, in turn, allows for public or
// private child derivation.
acctKey := acctInfo.acctKeyPub
if private {
acctKey = acctInfo.acctKeyPriv
}
// Derive and return the key.
branchKey, err := acctKey.Child(branch)
if err != nil {
str := fmt.Sprintf("failed to derive extended key branch %d",
branch)
return nil, managerError(ErrKeyChain, str, err)
}
addressKey, err := branchKey.Child(index)
branchKey.Zero() // Zero branch key after it's used.
if err != nil {
str := fmt.Sprintf("failed to derive child extended key -- "+
"branch %d, child %d",
branch, index)
return nil, managerError(ErrKeyChain, str, err)
}
return addressKey, nil
}
// loadAccountInfo attempts to load and cache information about the given
// account from the database. This includes what is necessary to derive new
// keys for it and track the state of the internal and external branches.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) loadAccountInfo(account uint32) (*accountInfo, error) {
// Return the account info from cache if it's available.
if acctInfo, ok := m.acctInfo[account]; ok {
return acctInfo, nil
}
// The account is either invalid or just wasn't cached, so attempt to
// load the information from the database.
var rowInterface interface{}
err := m.namespace.View(func(tx walletdb.Tx) error {
var err error
rowInterface, err = fetchAccountInfo(tx, account)
return err
})
if err != nil {
return nil, maybeConvertDbError(err)
}
// Ensure the account type is a BIP0044 account.
row, ok := rowInterface.(*dbBIP0044AccountRow)
if !ok {
str := fmt.Sprintf("unsupported account type %T", row)
err = managerError(ErrDatabase, str, nil)
}
// Use the crypto public key to decrypt the account public extended key.
serializedKeyPub, err := m.cryptoKeyPub.Decrypt(row.pubKeyEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt public key for account %d",
account)
return nil, managerError(ErrCrypto, str, err)
}
acctKeyPub, err := hdkeychain.NewKeyFromString(string(serializedKeyPub))
if err != nil {
str := fmt.Sprintf("failed to create extended public key for "+
"account %d", account)
return nil, managerError(ErrKeyChain, str, err)
}
// Create the new account info with the known information. The rest
// of the fields are filled out below.
acctInfo := &accountInfo{
acctName: row.name,
acctKeyEncrypted: row.privKeyEncrypted,
acctKeyPub: acctKeyPub,
nextExternalIndex: row.nextExternalIndex,
nextInternalIndex: row.nextInternalIndex,
}
if !m.locked {
// Use the crypto private key to decrypt the account private
// extended keys.
decrypted, err := m.cryptoKeyPriv.Decrypt(acctInfo.acctKeyEncrypted)
if err != nil {
str := fmt.Sprintf("failed to decrypt private key for "+
"account %d", account)
return nil, managerError(ErrCrypto, str, err)
}
acctKeyPriv, err := hdkeychain.NewKeyFromString(string(decrypted))
if err != nil {
str := fmt.Sprintf("failed to create extended private "+
"key for account %d", account)
return nil, managerError(ErrKeyChain, str, err)
}
acctInfo.acctKeyPriv = acctKeyPriv
}
// Derive and cache the managed address for the last external address.
branch, index := externalBranch, row.nextExternalIndex
if index > 0 {
index--
}
lastExtKey, err := m.deriveKey(acctInfo, branch, index, !m.locked)
if err != nil {
return nil, err
}
lastExtAddr, err := m.keyToManaged(lastExtKey, account, branch, index)
if err != nil {
return nil, err
}
acctInfo.lastExternalAddr = lastExtAddr
// Derive and cache the managed address for the last internal address.
branch, index = internalBranch, row.nextInternalIndex
if index > 0 {
index--
}
lastIntKey, err := m.deriveKey(acctInfo, branch, index, !m.locked)
if err != nil {
return nil, err
}
lastIntAddr, err := m.keyToManaged(lastIntKey, account, branch, index)
if err != nil {
return nil, err
}
acctInfo.lastInternalAddr = lastIntAddr
// Add it to the cache and return it when everything is successful.
m.acctInfo[account] = acctInfo
return acctInfo, nil
}
// AccountProperties returns properties associated with the account, such as the
// account number, name, and the number of derived and imported keys.
//
// TODO: Instead of opening a second read transaction after making a change, and
// then fetching the account properties with a new read tx, this can be made
// more performant by simply returning the new account properties during the
// change.
func (m *Manager) AccountProperties(account uint32) (*AccountProperties, error) {
defer m.mtx.RUnlock()
m.mtx.RLock()
props := &AccountProperties{AccountNumber: account}
// Until keys can be imported into any account, special handling is
// required for the imported account.
//
// loadAccountInfo errors when using it on the imported account since
// the accountInfo struct is filled with a BIP0044 account's extended
// keys, and the imported accounts has none.
//
// Since only the imported account allows imports currently, the number
// of imported keys for any other account is zero, and since the
// imported account cannot contain non-imported keys, the external and
// internal key counts for it are zero.
if account != ImportedAddrAccount {
acctInfo, err := m.loadAccountInfo(account)
if err != nil {
return nil, err
}
props.AccountName = acctInfo.acctName
props.ExternalKeyCount = acctInfo.nextExternalIndex
props.InternalKeyCount = acctInfo.nextInternalIndex
} else {
props.AccountName = ImportedAddrAccountName // reserved, nonchangable
// Could be more efficient if this was tracked by the db.
var importedKeyCount uint32
err := m.namespace.View(func(tx walletdb.Tx) error {
count := func(interface{}) error {
importedKeyCount++
return nil
}
return forEachAccountAddress(tx, ImportedAddrAccount,
count)
})
if err != nil {
return nil, err
}
props.ImportedKeyCount = importedKeyCount
}
return props, nil
}
// deriveKeyFromPath returns either a public or private derived extended key
// based on the private flag for the given an account, branch, and index.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) deriveKeyFromPath(account, branch, index uint32, private bool) (*hdkeychain.ExtendedKey, error) {
// Look up the account key information.
acctInfo, err := m.loadAccountInfo(account)
if err != nil {
return nil, err
}
return m.deriveKey(acctInfo, branch, index, private)
}
// chainAddressRowToManaged returns a new managed address based on chained
// address data loaded from the database.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) chainAddressRowToManaged(row *dbChainAddressRow) (ManagedAddress, error) {
addressKey, err := m.deriveKeyFromPath(row.account, row.branch,
row.index, !m.locked)
if err != nil {
return nil, err
}
return m.keyToManaged(addressKey, row.account, row.branch, row.index)
}
// importedAddressRowToManaged returns a new managed address based on imported
// address data loaded from the database.
func (m *Manager) importedAddressRowToManaged(row *dbImportedAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported public key.
pubBytes, err := m.cryptoKeyPub.Decrypt(row.encryptedPubKey)
if err != nil {
str := "failed to decrypt public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
pubKey, err := btcec.ParsePubKey(pubBytes, btcec.S256())
if err != nil {
str := "invalid public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
compressed := len(pubBytes) == btcec.PubKeyBytesLenCompressed
ma, err := newManagedAddressWithoutPrivKey(m, row.account, pubKey,
compressed)
if err != nil {
return nil, err
}
ma.privKeyEncrypted = row.encryptedPrivKey
ma.imported = true
return ma, nil
}
// scriptAddressRowToManaged returns a new managed address based on script
// address data loaded from the database.
func (m *Manager) scriptAddressRowToManaged(row *dbScriptAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported script hash.
scriptHash, err := m.cryptoKeyPub.Decrypt(row.encryptedHash)
if err != nil {
str := "failed to decrypt imported script hash"
return nil, managerError(ErrCrypto, str, err)
}
return newScriptAddress(m, row.account, scriptHash, row.encryptedScript)
}
// rowInterfaceToManaged returns a new managed address based on the given
// address data loaded from the database. It will automatically select the
// appropriate type.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) rowInterfaceToManaged(rowInterface interface{}) (ManagedAddress, error) {
switch row := rowInterface.(type) {
case *dbChainAddressRow:
return m.chainAddressRowToManaged(row)
case *dbImportedAddressRow:
return m.importedAddressRowToManaged(row)
case *dbScriptAddressRow:
return m.scriptAddressRowToManaged(row)
}
str := fmt.Sprintf("unsupported address type %T", rowInterface)
return nil, managerError(ErrDatabase, str, nil)
}
// loadAndCacheAddress attempts to load the passed address from the database and
// caches the associated managed address.
//
// This function MUST be called with the manager lock held for writes.
func (m *Manager) loadAndCacheAddress(address btcutil.Address) (ManagedAddress, error) {
// Attempt to load the raw address information from the database.
var rowInterface interface{}
err := m.namespace.View(func(tx walletdb.Tx) error {
var err error
rowInterface, err = fetchAddress(tx, address.ScriptAddress())
return err
})
if err != nil {
if merr, ok := err.(*ManagerError); ok {
desc := fmt.Sprintf("failed to fetch address '%s': %v",
address.ScriptAddress(), merr.Description)
merr.Description = desc
return nil, merr
}
return nil, maybeConvertDbError(err)
}
// Create a new managed address for the specific type of address based
// on type.
managedAddr, err := m.rowInterfaceToManaged(rowInterface)
if err != nil {
return nil, err
}
// Cache and return the new managed address.
m.addrs[addrKey(managedAddr.Address().ScriptAddress())] = managedAddr
return managedAddr, nil
}
// Address returns a managed address given the passed address if it is known
// to the address manager. A managed address differs from the passed address
// in that it also potentially contains extra information needed to sign
// transactions such as the associated private key for pay-to-pubkey and
// pay-to-pubkey-hash addresses and the script associated with
// pay-to-script-hash addresses.
func (m *Manager) Address(address btcutil.Address) (ManagedAddress, error) {
// ScriptAddress will only return a script hash if we're
// accessing an address that is either PKH or SH. In
// the event we're passed a PK address, convert the
// PK to PKH address so that we can access it from
// the addrs map and database.
if pka, ok := address.(*btcutil.AddressPubKey); ok {
address = pka.AddressPubKeyHash()
}
// Return the address from cache if it's available.
//
// NOTE: Not using a defer on the lock here since a write lock is
// needed if the lookup fails.
m.mtx.RLock()
if ma, ok := m.addrs[addrKey(address.ScriptAddress())]; ok {
m.mtx.RUnlock()
return ma, nil
}
m.mtx.RUnlock()
m.mtx.Lock()
defer m.mtx.Unlock()
// Attempt to load the address from the database.
return m.loadAndCacheAddress(address)
}
// AddrAccount returns the account to which the given address belongs.
func (m *Manager) AddrAccount(address btcutil.Address) (uint32, error) {
var account uint32
err := m.namespace.View(func(tx walletdb.Tx) error {
var err error
account, err = fetchAddrAccount(tx, address.ScriptAddress())
return err
})
if err != nil {
return 0, maybeConvertDbError(err)
}
return account, nil
}
// ChangePassphrase changes either the public or private passphrase to the
// provided value depending on the private flag. In order to change the private
// password, the address manager must not be watching-only. The new passphrase
// keys are derived using the scrypt parameters in the options, so changing the
// passphrase may be used to bump the computational difficulty needed to brute
// force the passphrase.
func (m *Manager) ChangePassphrase(oldPassphrase, newPassphrase []byte, private bool, config *ScryptOptions) error {
// No private passphrase to change for a watching-only address manager.
if private && m.watchingOnly {
return managerError(ErrWatchingOnly, errWatchingOnly, nil)
}
m.mtx.Lock()
defer m.mtx.Unlock()
// Ensure the provided old passphrase is correct. This check is done
// using a copy of the appropriate master key depending on the private
// flag to ensure the current state is not altered. The temp key is
// cleared when done to avoid leaving a copy in memory.
var keyName string
secretKey := snacl.SecretKey{Key: &snacl.CryptoKey{}}
if private {
keyName = "private"
secretKey.Parameters = m.masterKeyPriv.Parameters
} else {
keyName = "public"
secretKey.Parameters = m.masterKeyPub.Parameters
}
if err := secretKey.DeriveKey(&oldPassphrase); err != nil {
if err == snacl.ErrInvalidPassword {
str := fmt.Sprintf("invalid passphrase for %s master "+
"key", keyName)
return managerError(ErrWrongPassphrase, str, nil)
}
str := fmt.Sprintf("failed to derive %s master key", keyName)
return managerError(ErrCrypto, str, err)
}
defer secretKey.Zero()
// Generate a new master key from the passphrase which is used to secure
// the actual secret keys.
newMasterKey, err := newSecretKey(&newPassphrase, config)
if err != nil {
str := "failed to create new master private key"
return managerError(ErrCrypto, str, err)
}
newKeyParams := newMasterKey.Marshal()
if private {
// Technically, the locked state could be checked here to only
// do the decrypts when the address manager is locked as the
// clear text keys are already available in memory when it is
// unlocked, but this is not a hot path, decryption is quite
// fast, and it's less cyclomatic complexity to simply decrypt
// in either case.
// Create a new salt that will be used for hashing the new
// passphrase each unlock.
var passphraseSalt [saltSize]byte
_, err := rand.Read(passphraseSalt[:])
if err != nil {
str := "failed to read random source for passhprase salt"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto private key using the new master
// private key.
decPriv, err := secretKey.Decrypt(m.cryptoKeyPrivEncrypted)
if err != nil {
str := "failed to decrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
encPriv, err := newMasterKey.Encrypt(decPriv)
zero.Bytes(decPriv)
if err != nil {
str := "failed to encrypt crypto private key"
return managerError(ErrCrypto, str, err)
}
// Re-encrypt the crypto script key using the new master private
// key.
decScript, err := secretKey.Decrypt(m.cryptoKeyScriptEncrypted)
if err != nil {
str := "failed to decrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
encScript, err := newMasterKey.Encrypt(decScript)
zero.Bytes(decScript)
if err != nil {
str := "failed to encrypt crypto script key"
return managerError(ErrCrypto, str, err)
}
// When the manager is locked, ensure the new clear text master
// key is cleared from memory now that it is no longer needed.
// If unlocked, create the new passphrase hash with the new
// passphrase and salt.
var hashedPassphrase [sha512.Size]byte
if m.locked {
newMasterKey.Zero()
} else {
saltedPassphrase := append(passphraseSalt[:],
newPassphrase...)
hashedPassphrase = sha512.Sum512(saltedPassphrase)
zero.Bytes(saltedPassphrase)
}
// Save the new keys and params to the the db in a single
// transaction.
err = m.namespace.Update(func(tx walletdb.Tx) error {
err := putCryptoKeys(tx, nil, encPriv, encScript)
if err != nil {
return err
}
return putMasterKeyParams(tx, nil, newKeyParams)
})
if err != nil {
return maybeConvertDbError(err)
}
// Now that the db has been successfully updated, clear the old
// key and set the new one.
copy(m.cryptoKeyPrivEncrypted[:], encPriv)
copy(m.cryptoKeyScriptEncrypted[:], encScript)
m.masterKeyPriv.Zero() // Clear the old key.
m.masterKeyPriv = newMasterKey
m.privPassphraseSalt = passphraseSalt
m.hashedPrivPassphrase = hashedPassphrase
} else {
// Re-encrypt the crypto public key using the new master public
// key.
encryptedPub, err := newMasterKey.Encrypt(m.cryptoKeyPub.Bytes())
if err != nil {
str := "failed to encrypt crypto public key"
return managerError(ErrCrypto, str, err)
}
// Save the new keys and params to the the db in a single
// transaction.
err = m.namespace.Update(func(tx walletdb.Tx) error {
err := putCryptoKeys(tx, encryptedPub, nil, nil)
if err != nil {
return err
}
return putMasterKeyParams(tx, newKeyParams, nil)
})
if err != nil {
return maybeConvertDbError(err)
}
// Now that the db has been successfully updated, clear the old
// key and set the new one.
m.masterKeyPub.Zero()
m.masterKeyPub = newMasterKey
}
return nil
}
// ConvertToWatchingOnly converts the current address manager to a locked
// watching-only address manager.
//
// WARNING: This function removes private keys from the existing address manager
// which means they will no longer be available. Typically the caller will make
// a copy of the existing wallet database and modify the copy since otherwise it
// would mean permanent loss of any imported private keys and scripts.
//
// Executing this function on a manager that is already watching-only will have
// no effect.
func (m *Manager) ConvertToWatchingOnly() error {
m.mtx.Lock()
defer m.mtx.Unlock()
// Exit now if the manager is already watching-only.
if m.watchingOnly {
return nil
}
// Remove all private key material and mark the new database as watching
// only.
err := m.namespace.Update(func(tx walletdb.Tx) error {
if err := deletePrivateKeys(tx); err != nil {
return err
}
return putWatchingOnly(tx, true)
})
if err != nil {
return maybeConvertDbError(err)
}
// Lock the manager to remove all clear text private key material from
// memory if needed.
if !m.locked {
m.lock()
}
// This section clears and removes the encrypted private key material
// that is ordinarily used to unlock the manager. Since the the manager
// is being converted to watching-only, the encrypted private key
// material is no longer needed.
// Clear and remove all of the encrypted acount private keys.
for _, acctInfo := range m.acctInfo {
zero.Bytes(acctInfo.acctKeyEncrypted)
acctInfo.acctKeyEncrypted = nil
}
// Clear and remove encrypted private keys and encrypted scripts from
// all address entries.
for _, ma := range m.addrs {
switch addr := ma.(type) {
case *managedAddress:
zero.Bytes(addr.privKeyEncrypted)
addr.privKeyEncrypted = nil
case *scriptAddress:
zero.Bytes(addr.scriptEncrypted)
addr.scriptEncrypted = nil
}
}
// Clear and remove encrypted private and script crypto keys.