-
Notifications
You must be signed in to change notification settings - Fork 587
/
scoped_manager.go
2579 lines (2213 loc) · 81.6 KB
/
scoped_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
package waddrmgr
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"sync"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/internal/zero"
"github.com/btcsuite/btcwallet/netparams"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/lightninglabs/neutrino/cache/lru"
)
// HDVersion represents the different supported schemes of hierarchical
// derivation.
type HDVersion uint32
const (
// HDVersionMainNetBIP0044 is the HDVersion for BIP-0044 on the main
// network.
HDVersionMainNetBIP0044 HDVersion = 0x0488b21e // xpub
// HDVersionMainNetBIP0049 is the HDVersion for BIP-0049 on the main
// network.
HDVersionMainNetBIP0049 HDVersion = 0x049d7cb2 // ypub
// HDVersionMainNetBIP0084 is the HDVersion for BIP-0084 on the main
// network.
HDVersionMainNetBIP0084 HDVersion = 0x04b24746 // zpub
// HDVersionTestNetBIP0044 is the HDVersion for BIP-0044 on the test
// network.
HDVersionTestNetBIP0044 HDVersion = 0x043587cf // tpub
// HDVersionTestNetBIP0049 is the HDVersion for BIP-0049 on the test
// network.
HDVersionTestNetBIP0049 HDVersion = 0x044a5262 // upub
// HDVersionTestNetBIP0084 is the HDVersion for BIP-0084 on the test
// network.
HDVersionTestNetBIP0084 HDVersion = 0x045f1cf6 // vpub
// HDVersionSimNetBIP0044 is the HDVersion for BIP-0044 on the
// simulation test network. There aren't any other versions defined for
// the simulation test network.
HDVersionSimNetBIP0044 HDVersion = 0x0420bd3a // spub
)
const (
// defaultPrivKeyCacheSize is the default size of the LRU cache that
// we'll use to cache private keys to avoid DB and EC operations within
// the wallet. With the default sisize, we'll allocate up to 320 KB to
// caching private keys (ignoring pointer overhead, etc).
defaultPrivKeyCacheSize = 10_000
)
// DerivationPath represents a derivation path from a particular key manager's
// scope. Each ScopedKeyManager starts key derivation from the end of their
// cointype hardened key: m/purpose'/cointype'. The fields in this struct allow
// further derivation to the next three child levels after the coin type key.
// This restriction is in the spriti of BIP0044 type derivation. We maintain a
// degree of coherency with the standard, but allow arbitrary derivations
// beyond the cointype key. The key derived using this path will be exactly:
// m/purpose'/cointype'/account/branch/index, where purpose' and cointype' are
// bound by the scope of a particular manager.
type DerivationPath struct {
// InternalAccount is the internal account number used within the
// wallet's database to identify accounts.
InternalAccount uint32
// Account is the account, or the first immediate child from the scoped
// manager's hardened coin type key.
Account uint32
// Branch is the branch to be derived from the account index above. For
// BIP0044-like derivation, this is either 0 (external) or 1
// (internal). However, we allow this value to vary arbitrarily within
// its size range.
Branch uint32
// Index is the final child in the derivation path. This denotes the
// key index within as a child of the account and branch.
Index uint32
// MasterKeyFingerprint represents the fingerprint of the root key (also
// known as the key with derivation path m/) corresponding to the
// account public key. This may be required by some hardware wallets for
// proper identification and signing.
MasterKeyFingerprint uint32
}
// KeyScope represents a restricted key scope from the primary root key within
// the HD chain. From the root manager (m/) we can create a nearly arbitrary
// number of ScopedKeyManagers of key derivation path: m/purpose'/cointype'.
// These scoped managers can then me managed indecently, as they house the
// encrypted cointype key and can derive any child keys from there on.
type KeyScope struct {
// Purpose is the purpose of this key scope. This is the first child of
// the master HD key.
Purpose uint32
// Coin is a value that represents the particular coin which is the
// child of the purpose key. With this key, any accounts, or other
// children can be derived at all.
Coin uint32
}
// ScopedIndex is a tuple of KeyScope and child Index. This is used to compactly
// identify a particular child key, when the account and branch can be inferred
// from context.
type ScopedIndex struct {
// Scope is the BIP44 account' used to derive the child key.
Scope KeyScope
// Index is the BIP44 address_index used to derive the child key.
Index uint32
}
// String returns a human readable version describing the keypath encapsulated
// by the target key scope.
func (k KeyScope) String() string {
return fmt.Sprintf("m/%v'/%v'", k.Purpose, k.Coin)
}
// Identity is a closure that returns the identifier of an address.
type Identity func() []byte
// ScriptHashIdentity returns the identity closure for a p2sh script.
func ScriptHashIdentity(script []byte) Identity {
return func() []byte {
return btcutil.Hash160(script)
}
}
// WitnessScriptHashIdentity returns the identity closure for a p2wsh script.
func WitnessScriptHashIdentity(script []byte) Identity {
return func() []byte {
digest := sha256.Sum256(script)
return digest[:]
}
}
// TaprootIdentity returns the identity closure for a p2tr script.
func TaprootIdentity(taprootKey *btcec.PublicKey) Identity {
return func() []byte {
return schnorr.SerializePubKey(taprootKey)
}
}
// ScopeAddrSchema is the address schema of a particular KeyScope. This will be
// persisted within the database, and will be consulted when deriving any keys
// for a particular scope to know how to encode the public keys as addresses.
type ScopeAddrSchema struct {
// ExternalAddrType is the address type for all keys within branch 0.
ExternalAddrType AddressType
// InternalAddrType is the address type for all keys within branch 1
// (change addresses).
InternalAddrType AddressType
}
var (
// KeyScopeBIP0049Plus is the key scope of our modified BIP0049
// derivation. We say this is BIP0049 "plus", as we'll actually use
// p2wkh change all change addresses.
KeyScopeBIP0049Plus = KeyScope{
Purpose: 49,
Coin: 0,
}
// KeyScopeBIP0084 is the key scope for BIP0084 derivation. BIP0084
// will be used to derive all p2wkh addresses.
KeyScopeBIP0084 = KeyScope{
Purpose: 84,
Coin: 0,
}
// KeyScopeBIP0086 is the key scope for BIP0086 derivation. BIP0086
// will be used to derive all p2tr addresses.
KeyScopeBIP0086 = KeyScope{
Purpose: 86,
Coin: 0,
}
// KeyScopeBIP0044 is the key scope for BIP0044 derivation. Legacy
// wallets will only be able to use this key scope, and no keys beyond
// it.
KeyScopeBIP0044 = KeyScope{
Purpose: 44,
Coin: 0,
}
// DefaultKeyScopes is the set of default key scopes that will be
// created by the root manager upon initial creation.
DefaultKeyScopes = []KeyScope{
KeyScopeBIP0049Plus,
KeyScopeBIP0084,
KeyScopeBIP0086,
KeyScopeBIP0044,
}
// ScopeAddrMap is a map from the default key scopes to the scope
// address schema for each scope type. This will be consulted during
// the initial creation of the root key manager.
ScopeAddrMap = map[KeyScope]ScopeAddrSchema{
KeyScopeBIP0049Plus: {
ExternalAddrType: NestedWitnessPubKey,
InternalAddrType: WitnessPubKey,
},
KeyScopeBIP0084: {
ExternalAddrType: WitnessPubKey,
InternalAddrType: WitnessPubKey,
},
KeyScopeBIP0086: {
ExternalAddrType: TaprootPubKey,
InternalAddrType: TaprootPubKey,
},
KeyScopeBIP0044: {
InternalAddrType: PubKeyHash,
ExternalAddrType: PubKeyHash,
},
}
// KeyScopeBIP0049AddrSchema is the address schema for the traditional
// BIP-0049 derivation scheme. This exists in order to support importing
// accounts from other wallets that don't use our modified BIP-0049
// derivation scheme (internal addresses are P2WKH instead of NP2WKH).
KeyScopeBIP0049AddrSchema = ScopeAddrSchema{
ExternalAddrType: NestedWitnessPubKey,
InternalAddrType: NestedWitnessPubKey,
}
// ImportedDerivationPath is the derivation path for an imported
// address. The Account, Branch, and Index members are not known, so
// they are left blank.
ImportedDerivationPath = DerivationPath{
InternalAccount: ImportedAddrAccount,
}
)
// IsDefaultScope return true if the given scope belongs to the list of default
// scopes.
func IsDefaultScope(scope KeyScope) bool {
for _, defaultScope := range DefaultKeyScopes {
if defaultScope == scope {
return true
}
}
return false
}
// ScopedKeyManager is a sub key manager under the main root key manager. The
// root key manager will handle the root HD key (m/), while each sub scoped key
// manager will handle the cointype key for a particular key scope
// (m/purpose'/cointype'). This abstraction allows higher-level applications
// built upon the root key manager to perform their own arbitrary key
// derivation, while still being protected under the encryption of the root key
// manager.
type ScopedKeyManager struct {
// scope is the scope of this key manager. We can only generate keys
// that are direct children of this scope.
scope KeyScope
// addrSchema is the address schema for this sub manager. This will be
// consulted when encoding addresses from derived keys.
addrSchema ScopeAddrSchema
// rootManager is a pointer to the root key manager. We'll maintain
// this as we need access to the crypto encryption keys before we can
// derive any new accounts of child keys of accounts.
rootManager *Manager
// addrs is a cached map of all the addresses that we currently
// manage.
addrs map[addrKey]ManagedAddress
// acctInfo houses information about accounts including what is needed
// to generate deterministic chained keys for each created account.
acctInfo map[uint32]*accountInfo
// 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
// privKeyCache stores the set of private keys that have been marked as
// items to be cached to allow us to avoid the database and EC
// operations each time a key need to be obtained.
privKeyCache *lru.Cache[DerivationPath, *cachedKey]
mtx sync.RWMutex
}
// Scope returns the exact KeyScope of this scoped key manager.
func (s *ScopedKeyManager) Scope() KeyScope {
return s.scope
}
// AddrSchema returns the set address schema for the target ScopedKeyManager.
func (s *ScopedKeyManager) AddrSchema() ScopeAddrSchema {
return s.addrSchema
}
// 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 (s *ScopedKeyManager) zeroSensitivePublicData() {
// Clear all of the account private keys.
for _, acctInfo := range s.acctInfo {
acctInfo.acctKeyPub.Zero()
acctInfo.acctKeyPub = nil
}
}
// 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 (s *ScopedKeyManager) Close() {
s.mtx.Lock()
defer s.mtx.Unlock()
// Attempt to clear sensitive public key material from memory too.
s.zeroSensitivePublicData()
}
// 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 (s *ScopedKeyManager) keyToManaged(derivedKey *hdkeychain.ExtendedKey,
derivationPath DerivationPath, acctInfo *accountInfo) (
ManagedAddress, error) {
// Choose the appropriate type of address to derive since it's possible
// for a watch-only account to have a different schema from the
// manager's.
internal := derivationPath.Branch == InternalBranch
addrType := s.accountAddrType(acctInfo, internal)
// 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(
s, derivationPath, derivedKey, addrType, acctInfo,
)
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: derivationPath.Branch,
index: derivationPath.Index,
}
s.deriveOnUnlock = append(s.deriveOnUnlock, &info)
}
if derivationPath.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 (s *ScopedKeyManager) 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.DeriveNonStandard(branch) // nolint:staticcheck
if err != nil {
str := fmt.Sprintf("failed to derive extended key branch %d",
branch)
return nil, managerError(ErrKeyChain, str, err)
}
addressKey, err := branchKey.DeriveNonStandard(index) // nolint:staticcheck
// Zero branch key after it's used.
branchKey.Zero()
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 (s *ScopedKeyManager) loadAccountInfo(ns walletdb.ReadBucket,
account uint32) (*accountInfo, error) {
// Return the account info from cache if it's available.
if acctInfo, ok := s.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.
rowInterface, err := fetchAccountInfo(ns, &s.scope, account)
if err != nil {
return nil, maybeConvertDbError(err)
}
decryptKey := func(cryptoKey EncryptorDecryptor,
encryptedKey []byte) (*hdkeychain.ExtendedKey, error) {
serializedKey, err := cryptoKey.Decrypt(encryptedKey)
if err != nil {
return nil, err
}
return hdkeychain.NewKeyFromString(string(serializedKey))
}
// The wallet will only contain private keys for default accounts if the
// wallet's not set up as watch-only and it's been unlocked.
watchOnly := s.rootManager.watchOnly()
hasPrivateKey := !s.rootManager.isLocked() && !watchOnly
// Create the new account info with the known information. The rest of
// the fields are filled out below.
var acctInfo *accountInfo
switch row := rowInterface.(type) {
case *dbDefaultAccountRow:
acctInfo = &accountInfo{
acctName: row.name,
acctType: row.acctType,
acctKeyEncrypted: row.privKeyEncrypted,
nextExternalIndex: row.nextExternalIndex,
nextInternalIndex: row.nextInternalIndex,
}
// Use the crypto public key to decrypt the account public
// extended key.
acctInfo.acctKeyPub, err = decryptKey(
s.rootManager.cryptoKeyPub, row.pubKeyEncrypted,
)
if err != nil {
str := fmt.Sprintf("failed to decrypt public key for "+
"account %d", account)
return nil, managerError(ErrCrypto, str, err)
}
if hasPrivateKey {
// Use the crypto private key to decrypt the account
// private extended keys.
acctInfo.acctKeyPriv, err = decryptKey(
s.rootManager.cryptoKeyPriv, row.privKeyEncrypted,
)
if err != nil {
str := fmt.Sprintf("failed to decrypt private "+
"key for account %d", account)
return nil, managerError(ErrCrypto, str, err)
}
}
case *dbWatchOnlyAccountRow:
acctInfo = &accountInfo{
acctName: row.name,
acctType: row.acctType,
nextExternalIndex: row.nextExternalIndex,
nextInternalIndex: row.nextInternalIndex,
addrSchema: row.addrSchema,
masterKeyFingerprint: row.masterKeyFingerprint,
}
// Use the crypto public key to decrypt the account public
// extended key.
acctInfo.acctKeyPub, err = decryptKey(
s.rootManager.cryptoKeyPub, row.pubKeyEncrypted,
)
if err != nil {
str := fmt.Sprintf("failed to decrypt public key for "+
"account %d", account)
return nil, managerError(ErrCrypto, str, err)
}
hasPrivateKey = false
default:
str := fmt.Sprintf("unsupported account type %T", row)
return nil, managerError(ErrDatabase, str, nil)
}
// Derive and cache the managed address for the last external address.
branch, index := ExternalBranch, acctInfo.nextExternalIndex
if index > 0 {
index--
}
lastExtAddrPath := DerivationPath{
InternalAccount: account,
Account: acctInfo.acctKeyPub.ChildIndex(),
Branch: branch,
Index: index,
MasterKeyFingerprint: acctInfo.masterKeyFingerprint,
}
lastExtKey, err := s.deriveKey(acctInfo, branch, index, hasPrivateKey)
if err != nil {
return nil, err
}
lastExtAddr, err := s.keyToManaged(lastExtKey, lastExtAddrPath, acctInfo)
if err != nil {
return nil, err
}
acctInfo.lastExternalAddr = lastExtAddr
// Derive and cache the managed address for the last internal address.
branch, index = InternalBranch, acctInfo.nextInternalIndex
if index > 0 {
index--
}
lastIntAddrPath := DerivationPath{
InternalAccount: account,
Account: acctInfo.acctKeyPub.ChildIndex(),
Branch: branch,
Index: index,
MasterKeyFingerprint: acctInfo.masterKeyFingerprint,
}
lastIntKey, err := s.deriveKey(acctInfo, branch, index, hasPrivateKey)
if err != nil {
return nil, err
}
lastIntAddr, err := s.keyToManaged(lastIntKey, lastIntAddrPath, acctInfo)
if err != nil {
return nil, err
}
acctInfo.lastInternalAddr = lastIntAddr
// Add it to the cache and return it when everything is successful.
s.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.
func (s *ScopedKeyManager) AccountProperties(ns walletdb.ReadBucket,
account uint32) (*AccountProperties, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
props := &AccountProperties{
AccountNumber: account,
KeyScope: s.scope,
}
// 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 := s.loadAccountInfo(ns, account)
if err != nil {
return nil, err
}
props.AccountName = acctInfo.acctName
props.ExternalKeyCount = acctInfo.nextExternalIndex
props.InternalKeyCount = acctInfo.nextInternalIndex
props.AccountPubKey = acctInfo.acctKeyPub
props.MasterKeyFingerprint = acctInfo.masterKeyFingerprint
props.IsWatchOnly = s.rootManager.WatchOnly() ||
acctInfo.acctKeyPriv == nil
props.AddrSchema = acctInfo.addrSchema
// Export the account public key with the correct version
// corresponding to the manager's key scope for non-watch-only
// accounts. This isn't done for watch-only accounts to maintain
// the account public key consistent with what the caller
// provided. Note that his is only done for the default key
// scopes, as we only know the HD versions for those.
isDefaultKeyScope := IsDefaultScope(s.scope)
if acctInfo.acctType == accountDefault && isDefaultKeyScope {
props.AccountPubKey, err = s.cloneKeyWithVersion(
acctInfo.acctKeyPub,
)
if err != nil {
return nil, fmt.Errorf("failed to retrieve "+
"account public key: %w", err)
}
}
} else {
props.AccountName = ImportedAddrAccountName // reserved, nonchangable
props.IsWatchOnly = s.rootManager.WatchOnly()
// Could be more efficient if this was tracked by the db.
var importedKeyCount uint32
count := func(interface{}) error {
importedKeyCount++
return nil
}
err := forEachAccountAddress(ns, &s.scope, ImportedAddrAccount, count)
if err != nil {
return nil, err
}
props.ImportedKeyCount = importedKeyCount
}
return props, nil
}
// cachedKey is an entry within the LRU map that stores private keys that are
// to be used frequently. We use this wrapper struct to be able too report the
// size of a given element to the cache.
type cachedKey struct {
key btcec.PrivateKey
}
// Size returns the size of this element. Rather than have the cache limit
// based on bytes, we simply report that each element is of size 1, meaning we
// can set our cached based on the amount of keys we want to store, rather than
// the total size of all the keys.
func (c *cachedKey) Size() (uint64, error) {
return 1, nil
}
// DeriveFromKeyPathCache is identical to DeriveFromKeyPath, however it'll fail
// if the account refracted in the DerivationPath isn't already in the
// in-memory cache. Callers looking for faster private key retrieval can opt to
// call this method, which may fail if things aren't in the cache, then fall
// back to the normal variant. The account can information can be drawn into
// the cache if the normal DeriveFromKeyPath method is used, or the account is
// looked up via any other means.
func (s *ScopedKeyManager) DeriveFromKeyPathCache(
kp DerivationPath) (*btcec.PrivateKey, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
// First, try to look up the key itself in the proper cache, if the key
// is here, then we don't need to do anything further.
privKeyVal, err := s.privKeyCache.Get(kp)
if err == nil {
privKey := privKeyVal.key
return &privKey, nil
}
// If the key isn't already in the cache, then we'll try to look up the
// account info in the cache, if this fails, then we exit here as we
// can't move forward without creating a DB transaction, and the point
// of this method is to avoid that.
acctInfo, ok := s.acctInfo[kp.InternalAccount]
if !ok {
return nil, managerError(
ErrAccountNotCached,
"", fmt.Errorf("acct %v not cached", kp.InternalAccount),
)
}
watchOnly := s.rootManager.WatchOnly()
private := !s.rootManager.IsLocked() && !watchOnly
// Now that we have the account information, we can derive the key
// directly.
addrKey, err := s.deriveKey(acctInfo, kp.Branch, kp.Index, private)
if err != nil {
return nil, err
}
// Now that we have the key, we'll attempt to insert it into the cache,
// and return it as is.
privKey, err := addrKey.ECPrivKey()
if err != nil {
return nil, err
}
_, err = s.privKeyCache.Put(kp, &cachedKey{key: *privKey})
if err != nil {
return nil, err
}
return privKey, nil
}
// DeriveFromKeyPath attempts to derive a maximal child key (under the BIP0044
// scheme) from a given key path. If key derivation isn't possible, then an
// error will be returned.
//
// NOTE: The key will be derived from the account stored in the database under
// the InternalAccount number.
func (s *ScopedKeyManager) DeriveFromKeyPath(ns walletdb.ReadBucket,
kp DerivationPath) (ManagedAddress, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
watchOnly := s.rootManager.WatchOnly()
private := !s.rootManager.IsLocked() && !watchOnly
addrKey, _, _, err := s.deriveKeyFromPath(
ns, kp.InternalAccount, kp.Branch, kp.Index, private,
)
if err != nil {
return nil, err
}
acctInfo, err := s.loadAccountInfo(ns, kp.InternalAccount)
if err != nil {
return nil, err
}
return s.keyToManaged(addrKey, kp, acctInfo)
}
// deriveKeyFromPath returns either a public or private derived extended key
// based on the private flag for an address given an account, branch, and index.
// The account master key is also returned.
//
// This function MUST be called with the manager lock held for writes.
func (s *ScopedKeyManager) deriveKeyFromPath(ns walletdb.ReadBucket,
internalAccount, branch, index uint32, private bool) (
*hdkeychain.ExtendedKey, *hdkeychain.ExtendedKey, uint32, error) {
// Look up the account key information.
acctInfo, err := s.loadAccountInfo(ns, internalAccount)
if err != nil {
return nil, nil, 0, err
}
private = private && acctInfo.acctKeyPriv != nil
addrKey, err := s.deriveKey(acctInfo, branch, index, private)
if err != nil {
return nil, nil, 0, err
}
acctKey := acctInfo.acctKeyPub
if private {
acctKey = acctInfo.acctKeyPriv
}
return addrKey, acctKey, acctInfo.masterKeyFingerprint, nil
}
// 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 (s *ScopedKeyManager) chainAddressRowToManaged(ns walletdb.ReadBucket,
row *dbChainAddressRow) (ManagedAddress, error) {
// Since the manger's mutex is assumed to held when invoking this
// function, we use the internal isLocked to avoid a deadlock.
private := !s.rootManager.isLocked() && !s.rootManager.watchOnly()
addressKey, acctKey, masterKeyFingerprint, err := s.deriveKeyFromPath(
ns, row.account, row.branch, row.index, private,
)
if err != nil {
return nil, err
}
acctInfo, err := s.loadAccountInfo(ns, row.account)
if err != nil {
return nil, err
}
return s.keyToManaged(
addressKey, DerivationPath{
InternalAccount: row.account,
Account: acctKey.ChildIndex(),
Branch: row.branch,
Index: row.index,
MasterKeyFingerprint: masterKeyFingerprint,
}, acctInfo,
)
}
// importedAddressRowToManaged returns a new managed address based on imported
// address data loaded from the database.
func (s *ScopedKeyManager) importedAddressRowToManaged(row *dbImportedAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported public key.
pubBytes, err := s.rootManager.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)
if err != nil {
str := "invalid public key for imported address"
return nil, managerError(ErrCrypto, str, err)
}
// TODO: Handle imported key being part of internal branch.
compressed := len(pubBytes) == btcec.PubKeyBytesLenCompressed
ma, err := newManagedAddressWithoutPrivKey(
s, ImportedDerivationPath, pubKey, compressed,
s.addrSchema.ExternalAddrType,
)
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 (s *ScopedKeyManager) scriptAddressRowToManaged(
row *dbScriptAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported script hash.
scriptHash, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedHash)
if err != nil {
str := "failed to decrypt imported script hash"
return nil, managerError(ErrCrypto, str, err)
}
return newScriptAddress(s, row.account, scriptHash, row.encryptedScript)
}
// witnessScriptAddressRowToManaged returns a new managed address based on
// witness script address data loaded from the database.
func (s *ScopedKeyManager) witnessScriptAddressRowToManaged(
row *dbWitnessScriptAddressRow) (ManagedAddress, error) {
// Use the crypto public key to decrypt the imported script hash.
scriptHash, err := s.rootManager.cryptoKeyPub.Decrypt(row.encryptedHash)
if err != nil {
str := "failed to decrypt imported witness script hash"
return nil, managerError(ErrCrypto, str, err)
}
return newWitnessScriptAddress(
s, row.account, scriptHash, row.encryptedScript,
row.witnessVersion, row.isSecretScript,
)
}
// 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 (s *ScopedKeyManager) rowInterfaceToManaged(ns walletdb.ReadBucket,
rowInterface interface{}) (ManagedAddress, error) {
switch row := rowInterface.(type) {
case *dbChainAddressRow:
return s.chainAddressRowToManaged(ns, row)
case *dbImportedAddressRow:
return s.importedAddressRowToManaged(row)
case *dbScriptAddressRow:
return s.scriptAddressRowToManaged(row)
case *dbWitnessScriptAddressRow:
return s.witnessScriptAddressRowToManaged(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 (s *ScopedKeyManager) loadAndCacheAddress(ns walletdb.ReadBucket,
address btcutil.Address) (ManagedAddress, error) {
// Attempt to load the raw address information from the database.
rowInterface, err := fetchAddress(ns, &s.scope, address.ScriptAddress())
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 := s.rowInterfaceToManaged(ns, rowInterface)
if err != nil {
return nil, err
}
// Cache and return the new managed address.
s.addrs[addrKey(managedAddr.Address().ScriptAddress())] = managedAddr
return managedAddr, nil
}
// existsAddress returns whether or not the passed address is known to the
// address manager.
//
// This function MUST be called with the manager lock held for reads.
func (s *ScopedKeyManager) existsAddress(ns walletdb.ReadBucket, addressID []byte) bool {
// Check the in-memory map first since it's faster than a db access.
if _, ok := s.addrs[addrKey(addressID)]; ok {
return true
}
// Check the database if not already found above.
return existsAddress(ns, &s.scope, addressID)
}
// 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 (s *ScopedKeyManager) Address(ns walletdb.ReadBucket,
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.
s.mtx.RLock()
if ma, ok := s.addrs[addrKey(address.ScriptAddress())]; ok {
s.mtx.RUnlock()
return ma, nil
}
s.mtx.RUnlock()
s.mtx.Lock()
defer s.mtx.Unlock()
// Attempt to load the address from the database.
return s.loadAndCacheAddress(ns, address)
}
// AddrAccount returns the account to which the given address belongs.
func (s *ScopedKeyManager) AddrAccount(ns walletdb.ReadBucket,
address btcutil.Address) (uint32, error) {
account, err := fetchAddrAccount(ns, &s.scope, address.ScriptAddress())
if err != nil {
return 0, maybeConvertDbError(err)
}
return account, nil
}
// accountAddrType determines the type of address that should be generated for
// an account based on whether it's an internal address or not.
func (s *ScopedKeyManager) accountAddrType(acctInfo *accountInfo,
internal bool) AddressType {
// If the account has a custom address schema, use it.
addrSchema := s.addrSchema
if acctInfo.addrSchema != nil {
addrSchema = *acctInfo.addrSchema
}
if internal {
return addrSchema.InternalAddrType