forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scriptpubkeyman.cpp
2484 lines (2153 loc) · 84.7 KB
/
scriptpubkeyman.cpp
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) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key_io.h>
#include <chainparams.h>
#include <logging.h>
#include <messagesigner.h>
#include <script/descriptor.h>
#include <script/sign.h>
#include <shutdown.h>
#include <util/bip32.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <wallet/scriptpubkeyman.h>
bool LegacyScriptPubKeyMan::GetNewDestination(CTxDestination& dest, bilingual_str& error)
{
LOCK(cs_KeyStore);
error.clear();
// Generate a new key that is added to wallet
CPubKey new_key;
if (!GetKeyFromPool(new_key, false)) {
error = _("Error: Keypool ran out, please call keypoolrefill first");
return false;
}
//LearnRelatedScripts(new_key);
dest = PKHash(new_key);
return true;
}
typedef std::vector<unsigned char> valtype;
namespace {
/**
* This is an enum that tracks the execution context of a script, similar to
* SigVersion in script/interpreter. It is separate however because we want to
* distinguish between top-level scriptPubKey execution and P2SH redeemScript
* execution (a distinction that has no impact on consensus rules).
*/
enum class IsMineSigVersion
{
TOP = 0, //! scriptPubKey execution
P2SH = 1, //! P2SH redeemScript
};
/**
* This is an internal representation of isminetype + invalidity.
* Its order is significant, as we return the max of all explored
* possibilities.
*/
enum class IsMineResult
{
NO = 0, //! Not ours
WATCH_ONLY = 1, //! Included in watch-only balance
SPENDABLE = 2, //! Included in all balances
INVALID = 3, //! Not spendable by anyone (P2SH inside P2SH)
};
bool PermitsUncompressed(IsMineSigVersion sigversion)
{
return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH;
}
bool HaveKeys(const std::vector<valtype>& pubkeys, const LegacyScriptPubKeyMan& keystore)
{
for (const valtype& pubkey : pubkeys) {
CKeyID keyID = CPubKey(pubkey).GetID();
if (!keystore.HaveKey(keyID)) return false;
}
return true;
}
//! Recursively solve script and return spendable/watchonly/invalid status.
//!
//! @param keystore legacy key and script store
//! @param scriptPubKey script to solve
//! @param sigversion script type (top-level / redeemscript)
//! @param recurse_scripthash whether to recurse into nested p2sh
//! scripts or simply treat any script that has been
//! stored in the keystore as spendable
IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, bool recurse_scripthash=true)
{
IsMineResult ret = IsMineResult::NO;
std::vector<valtype> vSolutions;
TxoutType whichType = Solver(scriptPubKey, vSolutions);
CKeyID keyID;
switch (whichType) {
case TxoutType::NONSTANDARD:
case TxoutType::NULL_DATA:
break;
case TxoutType::PUBKEY:
keyID = CPubKey(vSolutions[0]).GetID();
if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) {
return IsMineResult::INVALID;
}
if (keystore.HaveKey(keyID)) {
ret = std::max(ret, IsMineResult::SPENDABLE);
}
break;
case TxoutType::PUBKEYHASH:
keyID = CKeyID(uint160(vSolutions[0]));
if (!PermitsUncompressed(sigversion)) {
CPubKey pubkey;
if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) {
return IsMineResult::INVALID;
}
}
if (keystore.HaveKey(keyID)) {
ret = std::max(ret, IsMineResult::SPENDABLE);
}
break;
case TxoutType::SCRIPTHASH:
{
if (sigversion != IsMineSigVersion::TOP) {
// P2SH inside P2SH is invalid.
return IsMineResult::INVALID;
}
CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
CScript subscript;
if (keystore.GetCScript(scriptID, subscript)) {
ret = std::max(ret, recurse_scripthash ? IsMineInner(keystore, subscript, IsMineSigVersion::P2SH) : IsMineResult::SPENDABLE);
}
break;
}
case TxoutType::MULTISIG:
{
// Never treat bare multisig outputs as ours (they can still be made watchonly-though)
if (sigversion == IsMineSigVersion::TOP) {
break;
}
// Only consider transactions "mine" if we own ALL the
// keys involved. Multi-signature transactions that are
// partially owned (somebody else has a key that can spend
// them) enable spend-out-from-under-you attacks, especially
// in shared-wallet situations.
std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
if (!PermitsUncompressed(sigversion)) {
for (size_t i = 0; i < keys.size(); i++) {
if (keys[i].size() != 33) {
return IsMineResult::INVALID;
}
}
}
if (HaveKeys(keys, keystore)) {
ret = std::max(ret, IsMineResult::SPENDABLE);
}
break;
}
} // no default case, so the compiler can warn about missing cases
if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) {
ret = std::max(ret, IsMineResult::WATCH_ONLY);
}
return ret;
}
} // namespace
isminetype LegacyScriptPubKeyMan::IsMine(const CScript& scriptPubKey) const
{
switch (IsMineInner(*this, scriptPubKey, IsMineSigVersion::TOP)) {
case IsMineResult::INVALID:
case IsMineResult::NO:
return ISMINE_NO;
case IsMineResult::WATCH_ONLY:
return ISMINE_WATCH_ONLY;
case IsMineResult::SPENDABLE:
return ISMINE_SPENDABLE;
}
assert(false);
}
isminetype LegacyScriptPubKeyMan::IsMine(const CTxDestination& dest) const
{
CScript script = GetScriptForDestination(dest);
return IsMine(script);
}
bool LegacyScriptPubKeyMan::CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys)
{
{
LOCK(cs_KeyStore);
assert(mapKeys.empty());
bool keyPass = mapCryptedKeys.empty(); // Always pass when there are no encrypted keys
bool keyFail = false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
WalletBatch batch(m_storage.GetDatabase());
for (; mi != mapCryptedKeys.end(); ++mi)
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
CKey key;
if (!DecryptKey(master_key, vchCryptedSecret, vchPubKey, key))
{
keyFail = true;
break;
}
keyPass = true;
if (fDecryptionThoroughlyChecked)
break;
else {
// Rewrite these encrypted keys with checksums
batch.WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
}
}
if (keyPass && keyFail)
{
LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
throw std::runtime_error("Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
}
if (keyFail) {
return false;
}
if (!keyPass && !accept_no_keys && (m_hd_chain.IsNull() || !m_hd_chain.IsNull() && !m_hd_chain.IsCrypted())) {
return false;
}
if(!m_hd_chain.IsNull() && !m_hd_chain.IsCrypted()) {
// try to decrypt seed and make sure it matches
CHDChain hdChainTmp;
if (!DecryptHDChain(master_key, hdChainTmp) || (m_hd_chain.GetID() != hdChainTmp.GetSeedHash())) {
return false;
}
}
fDecryptionThoroughlyChecked = true;
}
return true;
}
bool LegacyScriptPubKeyMan::Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch)
{
LOCK(cs_KeyStore);
encrypted_batch = batch;
if (!mapCryptedKeys.empty()) {
encrypted_batch = nullptr;
return false;
}
// must get current HD chain before EncryptKeys
CHDChain hdChainCurrent;
GetHDChain(hdChainCurrent);
KeyMap keys_to_encrypt;
keys_to_encrypt.swap(mapKeys); // Clear mapKeys so AddCryptedKeyInner will succeed.
for (const KeyMap::value_type& mKey : keys_to_encrypt)
{
const CKey &key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(master_key, vchSecret, vchPubKey.GetHash(), vchCryptedSecret)) {
encrypted_batch = nullptr;
return false;
}
if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) {
encrypted_batch = nullptr;
return false;
}
}
if (!hdChainCurrent.IsNull()) {
bool res = EncryptHDChain(master_key, m_hd_chain);
assert(res);
res = LoadHDChain(m_hd_chain);
assert(res);
CHDChain hdChainCrypted;
res = GetHDChain(hdChainCrypted);
assert(res);
// ids should match, seed hashes should not
assert(hdChainCurrent.GetID() == hdChainCrypted.GetID());
assert(hdChainCurrent.GetSeedHash() != hdChainCrypted.GetSeedHash());
res = AddHDChain(*encrypted_batch, hdChainCrypted);
assert(res);
}
encrypted_batch = nullptr;
return true;
}
bool LegacyScriptPubKeyMan::GetReservedDestination(bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool)
{
LOCK(cs_KeyStore);
if (!CanGetAddresses(internal)) {
return false;
}
if (!ReserveKeyFromKeyPool(index, keypool, internal)) {
return false;
}
// TODO: unify with bitcoin and use here GetDestinationForKey even if we have no type
address = PKHash(keypool.vchPubKey);
return true;
}
void LegacyScriptPubKeyMan::MarkUnusedAddresses(WalletBatch &batch, const CScript& script, const std::optional<int64_t>& block_time)
{
LOCK(cs_KeyStore);
// extract addresses and check if they match with an unused keypool key
for (const auto& keyid : GetAffectedKeys(script, *this)) {
std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
if (mi != m_pool_key_to_index.end()) {
WalletLogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
MarkReserveKeysAsUsed(mi->second);
if (!TopUpInner()) {
WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
}
}
if (block_time) {
if (mapKeyMetadata[keyid].nCreateTime > *block_time) {
WalletLogPrintf("%s: Found a key which appears to be used earlier than we expected, updating metadata\n", __func__);
CPubKey vchPubKey;
bool res = GetPubKey(keyid, vchPubKey);
assert(res); // this should never fail
mapKeyMetadata[keyid].nCreateTime = *block_time;
batch.WriteKeyMetadata(mapKeyMetadata[keyid], vchPubKey, true);
UpdateTimeFirstKey(*block_time);
}
}
}
}
void LegacyScriptPubKeyMan::UpgradeKeyMetadata()
{
LOCK(cs_KeyStore); // mapKeyMetadata
if (m_storage.IsLocked(false) || m_storage.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA) || !IsHDEnabled()) {
return;
}
CHDChain hdChainCurrent;
if (!GetHDChain(hdChainCurrent))
throw std::runtime_error(std::string(__func__) + ": GetHDChain failed");
if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
return DecryptHDChain(encryption_key, hdChainCurrent);
})) {
throw std::runtime_error(std::string(__func__) + ": DecryptHDChain failed");
}
CExtKey masterKey;
SecureVector vchSeed = hdChainCurrent.GetSeed();
masterKey.SetSeed(MakeByteSpan(vchSeed));
CKeyID master_id = masterKey.key.GetPubKey().GetID();
std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(m_storage.GetDatabase());
size_t cnt = 0;
for (auto& meta_pair : mapKeyMetadata) {
const CKeyID& keyid = meta_pair.first;
CKeyMetadata& meta = meta_pair.second;
if (!meta.has_key_origin) {
HDPubKeyMap::const_iterator mi = mapHdPubKeys.find(keyid);
if (mi == mapHdPubKeys.end()) {
continue;
}
// Add to map
std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
if (!ParseHDKeypath(mi->second.GetKeyPath(), meta.key_origin.path)) {
throw std::runtime_error("Invalid HD keypath");
}
meta.has_key_origin = true;
if (meta.nVersion < CKeyMetadata::VERSION_WITH_KEY_ORIGIN) {
meta.nVersion = CKeyMetadata::VERSION_WITH_KEY_ORIGIN;
}
// Write meta to wallet
batch->WriteKeyMetadata(meta, mi->second.extPubKey.pubkey, true);
if (++cnt % 1000 == 0) {
// avoid creating overlarge in-memory batches in case the wallet contains large amounts of keys
batch.reset(new WalletBatch(m_storage.GetDatabase()));
}
}
}
}
void LegacyScriptPubKeyMan::GenerateNewHDChain(const SecureString& secureMnemonic, const SecureString& secureMnemonicPassphrase, std::optional<CKeyingMaterial> vMasterKeyOpt)
{
assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
CHDChain newHdChain;
// NOTE: an empty mnemonic means "generate a new one for me"
// NOTE: default mnemonic passphrase is an empty string
if (!newHdChain.SetMnemonic(secureMnemonic, secureMnemonicPassphrase, /* fUpdateID = */ true)) {
throw std::runtime_error(std::string(__func__) + ": SetMnemonic failed");
}
// Add default account
newHdChain.AddAccount();
// Encryption routine if vMasterKey has been supplied
if (vMasterKeyOpt.has_value()) {
auto vMasterKey = vMasterKeyOpt.value();
if (vMasterKey.size() != WALLET_CRYPTO_KEY_SIZE) {
throw std::runtime_error(strprintf("%s : invalid vMasterKey size, got %zd (expected %lld)", __func__, vMasterKey.size(), WALLET_CRYPTO_KEY_SIZE));
}
// Maintain an unencrypted copy of the chain for sanity checking
CHDChain prevHdChain{newHdChain};
bool res = EncryptHDChain(vMasterKey, newHdChain);
assert(res);
res = LoadHDChain(newHdChain);
assert(res);
res = GetHDChain(newHdChain);
assert(res);
// IDs should match, seed hashes should not
assert(prevHdChain.GetID() == newHdChain.GetID());
assert(prevHdChain.GetSeedHash() != newHdChain.GetSeedHash());
}
if (!AddHDChainSingle(newHdChain)) {
throw std::runtime_error(std::string(__func__) + ": AddHDChainSingle failed");
}
if (!NewKeyPool()) {
throw std::runtime_error(std::string(__func__) + ": NewKeyPool failed");
}
}
bool LegacyScriptPubKeyMan::LoadHDChain(const CHDChain& chain)
{
LOCK(cs_KeyStore);
if (m_storage.HasEncryptionKeys() != chain.IsCrypted()) return false;
m_hd_chain = chain;
return true;
}
bool LegacyScriptPubKeyMan::AddHDChain(WalletBatch &batch, const CHDChain& chain)
{
LOCK(cs_KeyStore);
if (!LoadHDChain(chain))
return false;
{
if (chain.IsCrypted() && encrypted_batch) {
if (!encrypted_batch->WriteHDChain(chain))
throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed for encrypted batch");
} else {
if (!batch.WriteHDChain(chain)) {
throw std::runtime_error(std::string(__func__) + ": WriteHDChain failed");
}
}
m_storage.UnsetBlankWalletFlag(batch);
}
return true;
}
bool LegacyScriptPubKeyMan::AddHDChainSingle(const CHDChain& chain)
{
WalletBatch batch(m_storage.GetDatabase());
return AddHDChain(batch, chain);
}
bool LegacyScriptPubKeyMan::GetDecryptedHDChain(CHDChain& hdChainRet)
{
LOCK(cs_KeyStore);
CHDChain hdChainTmp;
if (!GetHDChain(hdChainTmp)) {
return false;
}
if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
return DecryptHDChain(encryption_key, hdChainTmp);
})) {
return false;
}
// make sure seed matches this chain
if (hdChainTmp.GetID() != hdChainTmp.GetSeedHash())
return false;
hdChainRet = hdChainTmp;
return true;
}
bool LegacyScriptPubKeyMan::EncryptHDChain(const CKeyingMaterial& vMasterKeyIn, CHDChain& chain)
{
LOCK(cs_KeyStore);
// should call EncryptKeys first
if (!m_storage.HasEncryptionKeys())
return false;
if (chain.IsCrypted())
return true;
// make sure seed matches this chain
if (chain.GetID() != chain.GetSeedHash())
return false;
std::vector<unsigned char> vchCryptedSeed;
if (!EncryptSecret(vMasterKeyIn, chain.GetSeed(), chain.GetID(), vchCryptedSeed))
return false;
CHDChain cryptedChain = chain;
cryptedChain.SetCrypted(true);
SecureVector vchSecureCryptedSeed(vchCryptedSeed.begin(), vchCryptedSeed.end());
if (!cryptedChain.SetSeed(vchSecureCryptedSeed, false))
return false;
SecureVector vchMnemonic;
SecureVector vchMnemonicPassphrase;
// it's ok to have no mnemonic if wallet was initialized via hdseed
if (chain.GetMnemonic(vchMnemonic, vchMnemonicPassphrase)) {
std::vector<unsigned char> vchCryptedMnemonic;
std::vector<unsigned char> vchCryptedMnemonicPassphrase;
if (!vchMnemonic.empty() && !EncryptSecret(vMasterKeyIn, vchMnemonic, chain.GetID(), vchCryptedMnemonic))
return false;
if (!vchMnemonicPassphrase.empty() && !EncryptSecret(vMasterKeyIn, vchMnemonicPassphrase, chain.GetID(), vchCryptedMnemonicPassphrase))
return false;
SecureVector vchSecureCryptedMnemonic(vchCryptedMnemonic.begin(), vchCryptedMnemonic.end());
SecureVector vchSecureCryptedMnemonicPassphrase(vchCryptedMnemonicPassphrase.begin(), vchCryptedMnemonicPassphrase.end());
if (!cryptedChain.SetMnemonic(vchSecureCryptedMnemonic, vchSecureCryptedMnemonicPassphrase, false))
return false;
}
chain = cryptedChain;
return true;
}
bool LegacyScriptPubKeyMan::DecryptHDChain(const CKeyingMaterial& vMasterKeyIn, CHDChain& hdChainRet) const
{
LOCK(cs_KeyStore);
if (!m_storage.HasEncryptionKeys())
return true;
if (m_hd_chain.IsNull())
return false;
if (!m_hd_chain.IsCrypted())
return false;
SecureVector vchSecureSeed;
SecureVector vchSecureCryptedSeed = m_hd_chain.GetSeed();
std::vector<unsigned char> vchCryptedSeed(vchSecureCryptedSeed.begin(), vchSecureCryptedSeed.end());
if (!DecryptSecret(vMasterKeyIn, vchCryptedSeed, m_hd_chain.GetID(), vchSecureSeed))
return false;
hdChainRet = m_hd_chain;
if (!hdChainRet.SetSeed(vchSecureSeed, false))
return false;
// hash of decrypted seed must match chain id
if (hdChainRet.GetSeedHash() != m_hd_chain.GetID())
return false;
SecureVector vchSecureCryptedMnemonic;
SecureVector vchSecureCryptedMnemonicPassphrase;
// it's ok to have no mnemonic if wallet was initialized via hdseed
if (m_hd_chain.GetMnemonic(vchSecureCryptedMnemonic, vchSecureCryptedMnemonicPassphrase)) {
SecureVector vchSecureMnemonic;
SecureVector vchSecureMnemonicPassphrase;
std::vector<unsigned char> vchCryptedMnemonic(vchSecureCryptedMnemonic.begin(), vchSecureCryptedMnemonic.end());
std::vector<unsigned char> vchCryptedMnemonicPassphrase(vchSecureCryptedMnemonicPassphrase.begin(), vchSecureCryptedMnemonicPassphrase.end());
if (!vchCryptedMnemonic.empty() && !DecryptSecret(vMasterKeyIn, vchCryptedMnemonic, m_hd_chain.GetID(), vchSecureMnemonic))
return false;
if (!vchCryptedMnemonicPassphrase.empty() && !DecryptSecret(vMasterKeyIn, vchCryptedMnemonicPassphrase, m_hd_chain.GetID(), vchSecureMnemonicPassphrase))
return false;
if (!hdChainRet.SetMnemonic(vchSecureMnemonic, vchSecureMnemonicPassphrase, false))
return false;
}
hdChainRet.SetCrypted(false);
return true;
}
bool LegacyScriptPubKeyMan::IsHDEnabled() const
{
CHDChain hdChainCurrent;
return GetHDChain(hdChainCurrent);
}
bool LegacyScriptPubKeyMan::CanGetAddresses(bool internal) const
{
LOCK(cs_KeyStore);
// Check if the keypool has keys
bool keypool_has_keys;
if (internal) {
keypool_has_keys = setInternalKeyPool.size() > 0;
} else {
keypool_has_keys = KeypoolCountExternalKeys() > 0;
}
// If the keypool doesn't have keys, check if we can generate them
if (!keypool_has_keys) {
return CanGenerateKeys();
}
return keypool_has_keys;
}
bool LegacyScriptPubKeyMan::HavePrivateKeys() const
{
LOCK(cs_KeyStore);
return !mapKeys.empty() || !mapCryptedKeys.empty();
}
void LegacyScriptPubKeyMan::RewriteDB()
{
LOCK(cs_KeyStore);
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
if (setKeyPool.empty()) {
// if the keypool is empty, return <NOW>
return GetTime();
}
CKeyPool keypool;
int64_t nIndex = *(setKeyPool.begin());
if (!batch.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
}
assert(keypool.vchPubKey.IsValid());
return keypool.nTime;
}
int64_t LegacyScriptPubKeyMan::GetOldestKeyPoolTime() const
{
LOCK(cs_KeyStore);
WalletBatch batch(m_storage.GetDatabase());
int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
if (IsHDEnabled()) {
oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
}
return oldestKey;
}
size_t LegacyScriptPubKeyMan::KeypoolCountExternalKeys() const
{
LOCK(cs_KeyStore);
return setExternalKeyPool.size();
}
unsigned int LegacyScriptPubKeyMan::GetKeyPoolSize() const
{
LOCK(cs_KeyStore);
return setInternalKeyPool.size() + setExternalKeyPool.size();
}
int64_t LegacyScriptPubKeyMan::GetTimeFirstKey() const
{
LOCK(cs_KeyStore);
return nTimeFirstKey;
}
std::unique_ptr<SigningProvider> LegacyScriptPubKeyMan::GetSolvingProvider(const CScript& script) const
{
return std::make_unique<LegacySigningProvider>(*this);
}
bool LegacyScriptPubKeyMan::CanProvide(const CScript& script, SignatureData& sigdata)
{
IsMineResult ismine = IsMineInner(*this, script, IsMineSigVersion::TOP, /* recurse_scripthash= */ false);
if (ismine == IsMineResult::SPENDABLE || ismine == IsMineResult::WATCH_ONLY) {
// If ismine, it means we recognize keys or script ids in the script, or
// are watching the script itself, and we can at least provide metadata
// or solving information, even if not able to sign fully.
return true;
} else {
// If, given the stuff in sigdata, we could make a valid signature, then we can provide for this script
ProduceSignature(*this, DUMMY_SIGNATURE_CREATOR, script, sigdata);
if (!sigdata.signatures.empty()) {
// If we could make signatures, make sure we have a private key to actually make a signature
bool has_privkeys = false;
for (const auto& key_sig_pair : sigdata.signatures) {
has_privkeys |= HaveKey(key_sig_pair.first);
}
return has_privkeys;
}
return false;
}
}
bool LegacyScriptPubKeyMan::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
{
return ::SignTransaction(tx, this, coins, sighash, input_errors);
}
SigningResult LegacyScriptPubKeyMan::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
{
CKey key;
if (!GetKey(ToKeyID(pkhash), key)) {
return SigningResult::PRIVATE_KEY_NOT_AVAILABLE;
}
if (MessageSign(key, message, str_sig)) {
return SigningResult::OK;
}
return SigningResult::SIGNING_FAILED;
}
bool LegacyScriptPubKeyMan::SignSpecialTxPayload(const uint256& hash, const CKeyID& keyid, std::vector<unsigned char>& vchSig) const
{
CKey key;
if (!GetKey(keyid, key)) {
return false;
}
return CHashSigner::SignHash(hash, key, vchSig);
}
TransactionError LegacyScriptPubKeyMan::FillPSBT(PartiallySignedTransaction& psbtx, int sighash_type, bool sign, bool bip32derivs, int* n_signed) const
{
if (n_signed) {
*n_signed = 0;
}
for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
const CTxIn& txin = psbtx.tx->vin[i];
PSBTInput& input = psbtx.inputs.at(i);
if (PSBTInputSigned(input)) {
continue;
}
// Get the Sighash type
if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
return TransactionError::SIGHASH_MISMATCH;
}
// Check non_witness_utxo has specified prevout
if (input.non_witness_utxo) {
if (txin.prevout.n >= input.non_witness_utxo->vout.size()) {
return TransactionError::MISSING_INPUTS;
}
} else {
// There's no UTXO so we can just skip this now
continue;
}
SignatureData sigdata;
input.FillSignatureData(sigdata);
SignPSBTInput(HidingSigningProvider(this, !sign, !bip32derivs), psbtx, i, sighash_type);
bool signed_one = PSBTInputSigned(input);
if (n_signed && (signed_one || !sign)) {
// If sign is false, we assume that we _could_ sign if we get here. This
// will never have false negatives; it is hard to tell under what i
// circumstances it could have false positives.
(*n_signed)++;
}
}
// Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
for (unsigned int i = 0; i < psbtx.tx->vout.size(); ++i) {
UpdatePSBTOutput(HidingSigningProvider(this, true, !bip32derivs), psbtx, i);
}
return TransactionError::OK;
}
std::unique_ptr<CKeyMetadata> LegacyScriptPubKeyMan::GetMetadata(const CTxDestination& dest) const
{
LOCK(cs_KeyStore);
CKeyID key_id = GetKeyForDestination(*this, dest);
if (!key_id.IsNull()) {
auto it = mapKeyMetadata.find(key_id);
if (it != mapKeyMetadata.end()) {
return std::make_unique<CKeyMetadata>(it->second);
}
}
CScript scriptPubKey = GetScriptForDestination(dest);
auto it = m_script_metadata.find(CScriptID(scriptPubKey));
if (it != m_script_metadata.end()) {
return std::make_unique<CKeyMetadata>(it->second);
}
return nullptr;
}
uint256 LegacyScriptPubKeyMan::GetID() const
{
return uint256::ONE;
}
/**
* Update wallet first key creation time. This should be called whenever keys
* are added to the wallet, with the oldest key creation time.
*/
void LegacyScriptPubKeyMan::UpdateTimeFirstKey(int64_t nCreateTime)
{
AssertLockHeld(cs_KeyStore);
if (nCreateTime <= 1) {
// Cannot determine birthday information, so set the wallet birthday to
// the beginning of time.
nTimeFirstKey = 1;
} else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
nTimeFirstKey = nCreateTime;
}
}
bool LegacyScriptPubKeyMan::LoadKey(const CKey& key, const CPubKey &pubkey)
{
return AddKeyPubKeyInner(key, pubkey);
}
bool LegacyScriptPubKeyMan::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
LOCK(cs_KeyStore);
WalletBatch batch(m_storage.GetDatabase());
return LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(batch, secret, pubkey);
}
bool LegacyScriptPubKeyMan::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
{
AssertLockHeld(cs_KeyStore);
// Make sure we aren't adding private keys to private key disabled wallets
assert(!m_storage.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
// FillableSigningProvider has no concept of wallet databases, but calls AddCryptedKey
// which is overridden below. To avoid flushes, the database handle is
// tunneled through to it.
bool needsDB = !encrypted_batch;
if (needsDB) {
encrypted_batch = &batch;
}
if (!AddKeyPubKeyInner(secret, pubkey)) {
if (needsDB) encrypted_batch = nullptr;
return false;
}
if (needsDB) encrypted_batch = nullptr;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(PKHash(pubkey));
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
if (!m_storage.HasEncryptionKeys()) {
return batch.WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
m_storage.UnsetBlankWalletFlag(batch);
return true;
}
bool LegacyScriptPubKeyMan::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return FillableSigningProvider::AddCScript(redeemScript);
}
void LegacyScriptPubKeyMan::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
{
LOCK(cs_KeyStore);
UpdateTimeFirstKey(meta.nCreateTime);
mapKeyMetadata[keyID] = meta;
}
void LegacyScriptPubKeyMan::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
{
LOCK(cs_KeyStore);
UpdateTimeFirstKey(meta.nCreateTime);
m_script_metadata[script_id] = meta;
}
bool LegacyScriptPubKeyMan::AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey)
{
LOCK(cs_KeyStore);
if (!m_storage.HasEncryptionKeys()) {
return FillableSigningProvider::AddKeyPubKey(key, pubkey);
}
if (m_storage.IsLocked(true)) {
return false;
}
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
return EncryptSecret(encryption_key, vchSecret, pubkey.GetHash(), vchCryptedSecret);
})) {
return false;
}
if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
return false;
}
return true;
}
bool LegacyScriptPubKeyMan::GetKeyInner(const CKeyID &address, CKey& keyOut) const
{
LOCK(cs_KeyStore);
if (!m_storage.HasEncryptionKeys()) {
return FillableSigningProvider::GetKey(address, keyOut);
}
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
const CPubKey &vchPubKey = (*mi).second.first;
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
return m_storage.WithEncryptionKey([&](const CKeyingMaterial& encryption_key) {
return DecryptKey(encryption_key, vchCryptedSecret, vchPubKey, keyOut);
});
}
return false;
}
bool LegacyScriptPubKeyMan::GetPubKeyInner(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
LOCK(cs_KeyStore);
if (!m_storage.HasEncryptionKeys()) {
if (!FillableSigningProvider::GetPubKey(address, vchPubKeyOut)) {
return GetWatchPubKey(address, vchPubKeyOut);
}
return true;
}
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end())
{
vchPubKeyOut = (*mi).second.first;
return true;
}
// Check for watch-only pubkeys
return GetWatchPubKey(address, vchPubKeyOut);
}
bool LegacyScriptPubKeyMan::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret, bool checksum_valid)
{
// Set fDecryptionThoroughlyChecked to false when the checksum is invalid
if (!checksum_valid) {
fDecryptionThoroughlyChecked = false;
}
return AddCryptedKeyInner(vchPubKey, vchCryptedSecret);
}
bool LegacyScriptPubKeyMan::HaveKeyInner(const CKeyID &address) const
{
LOCK(cs_KeyStore);
if (!m_storage.HasEncryptionKeys()) {
return FillableSigningProvider::HaveKey(address);
}
return mapCryptedKeys.count(address) > 0;
}
bool LegacyScriptPubKeyMan::AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
LOCK(cs_KeyStore);
assert(mapKeys.empty());
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
return true;
}
bool LegacyScriptPubKeyMan::AddCryptedKey(const CPubKey &vchPubKey,
const std::vector<unsigned char> &vchCryptedSecret)