Bitcoin ABC 0.30.12
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <wallet/wallet.h>
7
8#include <chain.h>
9#include <chainparams.h>
10#include <common/args.h>
11#include <config.h>
12#include <consensus/amount.h>
13#include <consensus/consensus.h>
15#include <interfaces/wallet.h>
16#include <key.h>
17#include <key_io.h>
18#include <policy/policy.h>
20#include <random.h>
21#include <script/descriptor.h>
22#include <script/script.h>
23#include <script/sighashtype.h>
24#include <script/sign.h>
26#include <support/cleanse.h>
27#include <txmempool.h>
28#include <univalue.h>
29#include <util/bip32.h>
30#include <util/check.h>
31#include <util/error.h>
32#include <util/fs.h>
33#include <util/fs_helpers.h>
34#include <util/moneystr.h>
35#include <util/string.h>
36#include <util/translation.h>
37#include <wallet/coincontrol.h>
38#include <wallet/fees.h>
39
40#include <variant>
41
43
44const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS{
46 "You need to rescan the blockchain in order to correctly mark used "
47 "destinations in the past. Until this is done, some destinations may "
48 "be considered unused, even if the opposite is the case."},
49};
50
52static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
53static std::list<LoadWalletFn> g_load_wallet_fns GUARDED_BY(cs_wallets);
54
56 const std::string &wallet_name) {
57 util::SettingsValue setting_value = chain.getRwSetting("wallet");
58 if (!setting_value.isArray()) {
59 setting_value.setArray();
60 }
61 for (const util::SettingsValue &value : setting_value.getValues()) {
62 if (value.isStr() && value.get_str() == wallet_name) {
63 return true;
64 }
65 }
66 setting_value.push_back(wallet_name);
67 return chain.updateRwSetting("wallet", setting_value);
68}
69
71 const std::string &wallet_name) {
72 util::SettingsValue setting_value = chain.getRwSetting("wallet");
73 if (!setting_value.isArray()) {
74 return true;
75 }
77 for (const util::SettingsValue &value : setting_value.getValues()) {
78 if (!value.isStr() || value.get_str() != wallet_name) {
79 new_value.push_back(value);
80 }
81 }
82 if (new_value.size() == setting_value.size()) {
83 return true;
84 }
85 return chain.updateRwSetting("wallet", new_value);
86}
87
89 const std::string &wallet_name,
90 std::optional<bool> load_on_startup,
91 std::vector<bilingual_str> &warnings) {
92 if (!load_on_startup) {
93 return;
94 }
95 if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
96 warnings.emplace_back(
97 Untranslated("Wallet load on startup setting could not be updated, "
98 "so wallet may not be loaded next node startup."));
99 } else if (!load_on_startup.value() &&
100 !RemoveWalletSetting(chain, wallet_name)) {
101 warnings.emplace_back(
102 Untranslated("Wallet load on startup setting could not be updated, "
103 "so wallet may still be loaded next node startup."));
104 }
105}
106
107bool AddWallet(const std::shared_ptr<CWallet> &wallet) {
109 assert(wallet);
110 std::vector<std::shared_ptr<CWallet>>::const_iterator i =
111 std::find(vpwallets.begin(), vpwallets.end(), wallet);
112 if (i != vpwallets.end()) {
113 return false;
114 }
115 vpwallets.push_back(wallet);
116 wallet->ConnectScriptPubKeyManNotifiers();
117 wallet->NotifyCanGetAddressesChanged();
118 return true;
119}
120
121bool RemoveWallet(const std::shared_ptr<CWallet> &wallet,
122 std::optional<bool> load_on_start,
123 std::vector<bilingual_str> &warnings) {
124 assert(wallet);
125
126 interfaces::Chain &chain = wallet->chain();
127 std::string name = wallet->GetName();
128
129 // Unregister with the validation interface which also drops shared ponters.
130 wallet->m_chain_notifications_handler.reset();
132 std::vector<std::shared_ptr<CWallet>>::iterator i =
133 std::find(vpwallets.begin(), vpwallets.end(), wallet);
134 if (i == vpwallets.end()) {
135 return false;
136 }
137 vpwallets.erase(i);
138
139 // Write the wallet setting
140 UpdateWalletSetting(chain, name, load_on_start, warnings);
141
142 return true;
143}
144
145bool RemoveWallet(const std::shared_ptr<CWallet> &wallet,
146 std::optional<bool> load_on_start) {
147 std::vector<bilingual_str> warnings;
148 return RemoveWallet(wallet, load_on_start, warnings);
149}
150
151std::vector<std::shared_ptr<CWallet>> GetWallets() {
153 return vpwallets;
154}
155
156std::shared_ptr<CWallet> GetWallet(const std::string &name) {
158 for (const std::shared_ptr<CWallet> &wallet : vpwallets) {
159 if (wallet->GetName() == name) {
160 return wallet;
161 }
162 }
163 return nullptr;
164}
165
166std::unique_ptr<interfaces::Handler>
169 auto it = g_load_wallet_fns.emplace(g_load_wallet_fns.end(),
170 std::move(load_wallet));
171 return interfaces::MakeHandler([it] {
173 g_load_wallet_fns.erase(it);
174 });
175}
176
179static std::condition_variable g_wallet_release_cv;
180static std::set<std::string>
181 g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
182static std::set<std::string>
183 g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
184
185// Custom deleter for shared_ptr<CWallet>.
187 const std::string name = wallet->GetName();
188 wallet->WalletLogPrintf("Releasing wallet\n");
189 wallet->Flush();
190 delete wallet;
191 // Wallet is now released, notify UnloadWallet, if any.
192 {
194 if (g_unloading_wallet_set.erase(name) == 0) {
195 // UnloadWallet was not called for this wallet, all done.
196 return;
197 }
198 }
199 g_wallet_release_cv.notify_all();
200}
201
202void UnloadWallet(std::shared_ptr<CWallet> &&wallet) {
203 // Mark wallet for unloading.
204 const std::string name = wallet->GetName();
205 {
207 auto it = g_unloading_wallet_set.insert(name);
208 assert(it.second);
209 }
210 // The wallet can be in use so it's not possible to explicitly unload here.
211 // Notify the unload intent so that all remaining shared pointers are
212 // released.
213 wallet->NotifyUnload();
214
215 // Time to ditch our shared_ptr and wait for ReleaseWallet call.
216 wallet.reset();
217 {
219 while (g_unloading_wallet_set.count(name) == 1) {
220 g_wallet_release_cv.wait(lock);
221 }
222 }
223}
224
225namespace {
226std::shared_ptr<CWallet>
227LoadWalletInternal(interfaces::Chain &chain, const std::string &name,
228 std::optional<bool> load_on_start,
229 const DatabaseOptions &options, DatabaseStatus &status,
230 bilingual_str &error, std::vector<bilingual_str> &warnings) {
231 try {
232 std::unique_ptr<WalletDatabase> database =
233 MakeWalletDatabase(name, options, status, error);
234 if (!database) {
235 error = Untranslated("Wallet file verification failed.") +
236 Untranslated(" ") + error;
237 return nullptr;
238 }
239
240 chain.initMessage(_("Loading wallet...").translated);
241 std::shared_ptr<CWallet> wallet =
242 CWallet::Create(&chain, name, std::move(database),
243 options.create_flags, error, warnings);
244 if (!wallet) {
245 error = Untranslated("Wallet loading failed.") + Untranslated(" ") +
246 error;
248 return nullptr;
249 }
251 wallet->postInitProcess();
252
253 // Write the wallet setting
254 UpdateWalletSetting(chain, name, load_on_start, warnings);
255
256 return wallet;
257 } catch (const std::runtime_error &e) {
258 error = Untranslated(e.what());
260 return nullptr;
261 }
262}
263} // namespace
264
265std::shared_ptr<CWallet>
266LoadWallet(interfaces::Chain &chain, const std::string &name,
267 std::optional<bool> load_on_start, const DatabaseOptions &options,
269 std::vector<bilingual_str> &warnings) {
270 auto result = WITH_LOCK(g_loading_wallet_mutex,
271 return g_loading_wallet_set.insert(name));
272 if (!result.second) {
273 error = Untranslated("Wallet already being loading.");
275 return nullptr;
276 }
277 auto wallet = LoadWalletInternal(chain, name, load_on_start, options,
278 status, error, warnings);
279 WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
280 return wallet;
281}
282
283std::shared_ptr<CWallet>
284CreateWallet(interfaces::Chain &chain, const std::string &name,
285 std::optional<bool> load_on_start, const DatabaseOptions &options,
287 std::vector<bilingual_str> &warnings) {
288 uint64_t wallet_creation_flags = options.create_flags;
289 const SecureString &passphrase = options.create_passphrase;
290
291 // Indicate that the wallet is actually supposed to be blank and not just
292 // blank to make it encrypted
293 bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
294
295 // Born encrypted wallets need to be created blank first.
296 if (!passphrase.empty()) {
297 wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
298 }
299
300 // Wallet::Verify will check if we're trying to create a wallet with a
301 // duplicate name.
302 std::unique_ptr<WalletDatabase> database =
303 MakeWalletDatabase(name, options, status, error);
304 if (!database) {
305 error = Untranslated("Wallet file verification failed.") +
306 Untranslated(" ") + error;
308 return nullptr;
309 }
310
311 // Do not allow a passphrase when private keys are disabled
312 if (!passphrase.empty() &&
313 (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
315 "Passphrase provided but private keys are disabled. A passphrase "
316 "is only used to encrypt private keys, so cannot be used for "
317 "wallets with private keys disabled.");
319 return nullptr;
320 }
321
322 // Make the wallet
323 chain.initMessage(_("Loading wallet...").translated);
324 std::shared_ptr<CWallet> wallet =
325 CWallet::Create(&chain, name, std::move(database),
326 wallet_creation_flags, error, warnings);
327 if (!wallet) {
328 error =
329 Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
331 return nullptr;
332 }
333
334 // Encrypt the wallet
335 if (!passphrase.empty() &&
336 !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
337 if (!wallet->EncryptWallet(passphrase)) {
338 error =
339 Untranslated("Error: Wallet created but failed to encrypt.");
341 return nullptr;
342 }
343 if (!create_blank) {
344 // Unlock the wallet
345 if (!wallet->Unlock(passphrase)) {
347 "Error: Wallet was encrypted but could not be unlocked");
349 return nullptr;
350 }
351
352 // Set a seed for the wallet
353 {
354 LOCK(wallet->cs_wallet);
355 if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
356 wallet->SetupDescriptorScriptPubKeyMans();
357 } else {
358 for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
359 if (!spk_man->SetupGeneration()) {
360 error =
361 Untranslated("Unable to generate initial keys");
363 return nullptr;
364 }
365 }
366 }
367 }
368
369 // Relock the wallet
370 wallet->Lock();
371 }
372 }
374 wallet->postInitProcess();
375
376 // Write the wallet settings
377 UpdateWalletSetting(chain, name, load_on_start, warnings);
378
380 return wallet;
381}
382
389 // Get CChainParams from interfaces::Chain, unless wallet doesn't have a
390 // chain (i.e. bitcoin-wallet), in which case return global Params()
391 return m_chain ? m_chain->params() : Params();
392}
393
394const CWalletTx *CWallet::GetWalletTx(const TxId &txid) const {
396 std::map<TxId, CWalletTx>::const_iterator it = mapWallet.find(txid);
397 if (it == mapWallet.end()) {
398 return nullptr;
399 }
400
401 return &(it->second);
402}
403
406 return;
407 }
408
409 auto spk_man = GetLegacyScriptPubKeyMan();
410 if (!spk_man) {
411 return;
412 }
413
414 spk_man->UpgradeKeyMetadata();
416}
417
418bool CWallet::Unlock(const SecureString &strWalletPassphrase,
419 bool accept_no_keys) {
420 CCrypter crypter;
421 CKeyingMaterial _vMasterKey;
422
423 {
425 for (const MasterKeyMap::value_type &pMasterKey : mapMasterKeys) {
426 if (!crypter.SetKeyFromPassphrase(
427 strWalletPassphrase, pMasterKey.second.vchSalt,
428 pMasterKey.second.nDeriveIterations,
429 pMasterKey.second.nDerivationMethod)) {
430 return false;
431 }
432 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey,
433 _vMasterKey)) {
434 // try another master key
435 continue;
436 }
437 if (Unlock(_vMasterKey, accept_no_keys)) {
438 // Now that we've unlocked, upgrade the key metadata
440 return true;
441 }
442 }
443 }
444
445 return false;
446}
447
449 const SecureString &strOldWalletPassphrase,
450 const SecureString &strNewWalletPassphrase) {
451 bool fWasLocked = IsLocked();
452
454 Lock();
455
456 CCrypter crypter;
457 CKeyingMaterial _vMasterKey;
458 for (MasterKeyMap::value_type &pMasterKey : mapMasterKeys) {
459 if (!crypter.SetKeyFromPassphrase(
460 strOldWalletPassphrase, pMasterKey.second.vchSalt,
461 pMasterKey.second.nDeriveIterations,
462 pMasterKey.second.nDerivationMethod)) {
463 return false;
464 }
465
466 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey)) {
467 return false;
468 }
469
470 if (Unlock(_vMasterKey)) {
471 int64_t nStartTime = GetTimeMillis();
472 crypter.SetKeyFromPassphrase(strNewWalletPassphrase,
473 pMasterKey.second.vchSalt,
474 pMasterKey.second.nDeriveIterations,
475 pMasterKey.second.nDerivationMethod);
476 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(
477 pMasterKey.second.nDeriveIterations *
478 (100 / ((double)(GetTimeMillis() - nStartTime))));
479
480 nStartTime = GetTimeMillis();
481 crypter.SetKeyFromPassphrase(strNewWalletPassphrase,
482 pMasterKey.second.vchSalt,
483 pMasterKey.second.nDeriveIterations,
484 pMasterKey.second.nDerivationMethod);
485 pMasterKey.second.nDeriveIterations =
486 (pMasterKey.second.nDeriveIterations +
487 static_cast<unsigned int>(
488 pMasterKey.second.nDeriveIterations * 100 /
489 double(GetTimeMillis() - nStartTime))) /
490 2;
491
492 if (pMasterKey.second.nDeriveIterations < 25000) {
493 pMasterKey.second.nDeriveIterations = 25000;
494 }
495
497 "Wallet passphrase changed to an nDeriveIterations of %i\n",
498 pMasterKey.second.nDeriveIterations);
499
500 if (!crypter.SetKeyFromPassphrase(
501 strNewWalletPassphrase, pMasterKey.second.vchSalt,
502 pMasterKey.second.nDeriveIterations,
503 pMasterKey.second.nDerivationMethod)) {
504 return false;
505 }
506
507 if (!crypter.Encrypt(_vMasterKey,
508 pMasterKey.second.vchCryptedKey)) {
509 return false;
510 }
511
512 WalletBatch(*database).WriteMasterKey(pMasterKey.first,
513 pMasterKey.second);
514 if (fWasLocked) {
515 Lock();
516 }
517
518 return true;
519 }
520 }
521
522 return false;
523}
524
526 WalletBatch batch(*database);
527 batch.WriteBestBlock(loc);
528}
529
531 bool fExplicit) {
533 if (nWalletVersion >= nVersion) {
534 return;
535 }
536
537 // When doing an explicit upgrade, if we pass the max version permitted,
538 // upgrade all the way.
539 if (fExplicit && nVersion > nWalletMaxVersion) {
540 nVersion = FEATURE_LATEST;
541 }
542
543 nWalletVersion = nVersion;
544
545 if (nVersion > nWalletMaxVersion) {
546 nWalletMaxVersion = nVersion;
547 }
548
549 WalletBatch *batch = batch_in ? batch_in : new WalletBatch(*database);
550 if (nWalletVersion > 40000) {
551 batch->WriteMinVersion(nWalletVersion);
552 }
553 if (!batch_in) {
554 delete batch;
555 }
556}
557
558bool CWallet::SetMaxVersion(int nVersion) {
560
561 // Cannot downgrade below current version
562 if (nWalletVersion > nVersion) {
563 return false;
564 }
565
566 nWalletMaxVersion = nVersion;
567
568 return true;
569}
570
571std::set<TxId> CWallet::GetConflicts(const TxId &txid) const {
572 std::set<TxId> result;
574
575 std::map<TxId, CWalletTx>::const_iterator it = mapWallet.find(txid);
576 if (it == mapWallet.end()) {
577 return result;
578 }
579
580 const CWalletTx &wtx = it->second;
581
582 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
583
584 for (const CTxIn &txin : wtx.tx->vin) {
585 if (mapTxSpends.count(txin.prevout) <= 1) {
586 // No conflict if zero or one spends.
587 continue;
588 }
589
590 range = mapTxSpends.equal_range(txin.prevout);
591 for (TxSpends::const_iterator _it = range.first; _it != range.second;
592 ++_it) {
593 result.insert(_it->second);
594 }
595 }
596
597 return result;
598}
599
600bool CWallet::HasWalletSpend(const TxId &txid) const {
602 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
603 return (iter != mapTxSpends.end() && iter->first.GetTxId() == txid);
604}
605
607 database->Flush();
608}
609
611 database->Close();
612}
613
615 std::pair<TxSpends::iterator, TxSpends::iterator> range) {
616 // We want all the wallet transactions in range to have the same metadata as
617 // the oldest (smallest nOrderPos).
618 // So: find smallest nOrderPos:
619
620 int nMinOrderPos = std::numeric_limits<int>::max();
621 const CWalletTx *copyFrom = nullptr;
622 for (TxSpends::iterator it = range.first; it != range.second; ++it) {
623 const CWalletTx *wtx = &mapWallet.at(it->second);
624 if (wtx->nOrderPos < nMinOrderPos) {
625 nMinOrderPos = wtx->nOrderPos;
626 copyFrom = wtx;
627 }
628 }
629
630 if (!copyFrom) {
631 return;
632 }
633
634 // Now copy data from copyFrom to rest:
635 for (TxSpends::iterator it = range.first; it != range.second; ++it) {
636 const TxId &txid = it->second;
637 CWalletTx *copyTo = &mapWallet.at(txid);
638 if (copyFrom == copyTo) {
639 continue;
640 }
641
642 assert(
643 copyFrom &&
644 "Oldest wallet transaction in range assumed to have been found.");
645
646 if (!copyFrom->IsEquivalentTo(*copyTo)) {
647 continue;
648 }
649
650 copyTo->mapValue = copyFrom->mapValue;
651 copyTo->vOrderForm = copyFrom->vOrderForm;
652 // fTimeReceivedIsTxTime not copied on purpose nTimeReceived not copied
653 // on purpose.
654 copyTo->nTimeSmart = copyFrom->nTimeSmart;
655 copyTo->fFromMe = copyFrom->fFromMe;
656 // nOrderPos not copied on purpose cached members not copied on purpose.
657 }
658}
659
663bool CWallet::IsSpent(const COutPoint &outpoint) const {
665
666 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range =
667 mapTxSpends.equal_range(outpoint);
668
669 for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
670 const TxId &wtxid = it->second;
671 std::map<TxId, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
672 if (mit != mapWallet.end()) {
673 int depth = GetTxDepthInMainChain(mit->second);
674 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned())) {
675 // Spent
676 return true;
677 }
678 }
679 }
680
681 return false;
682}
683
684void CWallet::AddToSpends(const COutPoint &outpoint, const TxId &wtxid) {
685 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
686
687 setLockedCoins.erase(outpoint);
688
689 std::pair<TxSpends::iterator, TxSpends::iterator> range;
690 range = mapTxSpends.equal_range(outpoint);
691 SyncMetaData(range);
692}
693
694void CWallet::AddToSpends(const TxId &wtxid) {
695 auto it = mapWallet.find(wtxid);
696 assert(it != mapWallet.end());
697 const CWalletTx &thisTx = it->second;
698 // Coinbases don't spend anything!
699 if (thisTx.IsCoinBase()) {
700 return;
701 }
702
703 for (const CTxIn &txin : thisTx.tx->vin) {
704 AddToSpends(txin.prevout, wtxid);
705 }
706}
707
708bool CWallet::EncryptWallet(const SecureString &strWalletPassphrase) {
709 if (IsCrypted()) {
710 return false;
711 }
712
713 CKeyingMaterial _vMasterKey;
714
715 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
716 GetStrongRandBytes(_vMasterKey);
717
718 CMasterKey kMasterKey;
719
720 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
721 GetStrongRandBytes(kMasterKey.vchSalt);
722
723 CCrypter crypter;
724 int64_t nStartTime = GetTimeMillis();
725 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000,
726 kMasterKey.nDerivationMethod);
727 kMasterKey.nDeriveIterations = static_cast<unsigned int>(
728 2500000 / double(GetTimeMillis() - nStartTime));
729
730 nStartTime = GetTimeMillis();
731 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt,
732 kMasterKey.nDeriveIterations,
733 kMasterKey.nDerivationMethod);
734 kMasterKey.nDeriveIterations =
735 (kMasterKey.nDeriveIterations +
736 static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 /
737 double(GetTimeMillis() - nStartTime))) /
738 2;
739
740 if (kMasterKey.nDeriveIterations < 25000) {
741 kMasterKey.nDeriveIterations = 25000;
742 }
743
744 WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n",
745 kMasterKey.nDeriveIterations);
746
747 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt,
748 kMasterKey.nDeriveIterations,
749 kMasterKey.nDerivationMethod)) {
750 return false;
751 }
752
753 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey)) {
754 return false;
755 }
756
757 {
759 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
760 WalletBatch *encrypted_batch = new WalletBatch(*database);
761 if (!encrypted_batch->TxnBegin()) {
762 delete encrypted_batch;
763 encrypted_batch = nullptr;
764 return false;
765 }
766 encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
767
768 for (const auto &spk_man_pair : m_spk_managers) {
769 auto spk_man = spk_man_pair.second.get();
770 if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
771 encrypted_batch->TxnAbort();
772 delete encrypted_batch;
773 encrypted_batch = nullptr;
774 // We now probably have half of our keys encrypted in memory,
775 // and half not... die and let the user reload the unencrypted
776 // wallet.
777 assert(false);
778 }
779 }
780
781 // Encryption was introduced in version 0.4.0
782 SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
783
784 if (!encrypted_batch->TxnCommit()) {
785 delete encrypted_batch;
786 encrypted_batch = nullptr;
787 // We now have keys encrypted in memory, but not on disk...
788 // die to avoid confusion and let the user reload the unencrypted
789 // wallet.
790 assert(false);
791 }
792
793 delete encrypted_batch;
794 encrypted_batch = nullptr;
795
796 Lock();
797 Unlock(strWalletPassphrase);
798
799 // If we are using descriptors, make new descriptors with a new seed
803 } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
804 // if we are using HD, replace the HD seed with a new one
805 if (spk_man->IsHDEnabled()) {
806 if (!spk_man->SetupGeneration(true)) {
807 return false;
808 }
809 }
810 }
811 Lock();
812
813 // Need to completely rewrite the wallet file; if we don't, bdb might
814 // keep bits of the unencrypted private key in slack space in the
815 // database file.
816 database->Rewrite();
817
818 // BDB seems to have a bad habit of writing old data into
819 // slack space in .dat files; that is bad if the old data is
820 // unencrypted private keys. So:
821 database->ReloadDbEnv();
822 }
823
825 return true;
826}
827
830 WalletBatch batch(*database);
831
832 // Old wallets didn't have any defined order for transactions. Probably a
833 // bad idea to change the output of this.
834
835 // First: get all CWalletTx into a sorted-by-time
836 // multimap.
837 TxItems txByTime;
838
839 for (auto &entry : mapWallet) {
840 CWalletTx *wtx = &entry.second;
841 txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
842 }
843
844 nOrderPosNext = 0;
845 std::vector<int64_t> nOrderPosOffsets;
846 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) {
847 CWalletTx *const pwtx = (*it).second;
848 int64_t &nOrderPos = pwtx->nOrderPos;
849
850 if (nOrderPos == -1) {
851 nOrderPos = nOrderPosNext++;
852 nOrderPosOffsets.push_back(nOrderPos);
853
854 if (!batch.WriteTx(*pwtx)) {
855 return DBErrors::LOAD_FAIL;
856 }
857 } else {
858 int64_t nOrderPosOff = 0;
859 for (const int64_t &nOffsetStart : nOrderPosOffsets) {
860 if (nOrderPos >= nOffsetStart) {
861 ++nOrderPosOff;
862 }
863 }
864
865 nOrderPos += nOrderPosOff;
866 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
867
868 if (!nOrderPosOff) {
869 continue;
870 }
871
872 // Since we're changing the order, write it back.
873 if (!batch.WriteTx(*pwtx)) {
874 return DBErrors::LOAD_FAIL;
875 }
876 }
877 }
878
879 batch.WriteOrderPosNext(nOrderPosNext);
880
881 return DBErrors::LOAD_OK;
882}
883
886 int64_t nRet = nOrderPosNext++;
887 if (batch) {
888 batch->WriteOrderPosNext(nOrderPosNext);
889 } else {
890 WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
891 }
892
893 return nRet;
894}
895
898 for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
899 item.second.MarkDirty();
900 }
901}
902
904 unsigned int n, bool used,
905 std::set<CTxDestination> &tx_destinations) {
907 const CWalletTx *srctx = GetWalletTx(txid);
908 if (!srctx) {
909 return;
910 }
911
912 CTxDestination dst;
913 if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
914 if (IsMine(dst)) {
915 if (used && !GetDestData(dst, "used", nullptr)) {
916 // p for "present", opposite of absent (null)
917 if (AddDestData(batch, dst, "used", "p")) {
918 tx_destinations.insert(dst);
919 }
920 } else if (!used && GetDestData(dst, "used", nullptr)) {
921 EraseDestData(batch, dst, "used");
922 }
923 }
924 }
925}
926
927bool CWallet::IsSpentKey(const TxId &txid, unsigned int n) const {
929 const CWalletTx *srctx = GetWalletTx(txid);
930 if (srctx) {
931 assert(srctx->tx->vout.size() > n);
932 CTxDestination dest;
933 if (!ExtractDestination(srctx->tx->vout[n].scriptPubKey, dest)) {
934 return false;
935 }
936 if (GetDestData(dest, "used", nullptr)) {
937 return true;
938 }
939 if (IsLegacy()) {
941 assert(spk_man != nullptr);
942 for (const auto &keyid :
943 GetAffectedKeys(srctx->tx->vout[n].scriptPubKey, *spk_man)) {
944 PKHash pkh_dest(keyid);
945 if (GetDestData(pkh_dest, "used", nullptr)) {
946 return true;
947 }
948 }
949 }
950 }
951 return false;
952}
953
955 const CWalletTx::Confirmation &confirm,
956 const UpdateWalletTxFn &update_wtx,
957 bool fFlushOnClose) {
959
960 WalletBatch batch(*database, fFlushOnClose);
961
962 const TxId &txid = tx->GetId();
963
965 // Mark used destinations
966 std::set<CTxDestination> tx_destinations;
967
968 for (const CTxIn &txin : tx->vin) {
969 const COutPoint &op = txin.prevout;
970 SetSpentKeyState(batch, op.GetTxId(), op.GetN(), true,
971 tx_destinations);
972 }
973
974 MarkDestinationsDirty(tx_destinations);
975 }
976
977 // Inserts only if not already there, returns tx inserted or tx found.
978 auto ret =
979 mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid),
980 std::forward_as_tuple(tx));
981 CWalletTx &wtx = (*ret.first).second;
982 bool fInsertedNew = ret.second;
983 bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
984 if (fInsertedNew) {
985 wtx.m_confirm = confirm;
986 wtx.nTimeReceived = GetTime();
987 wtx.nOrderPos = IncOrderPosNext(&batch);
988 wtx.m_it_wtxOrdered =
989 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
990 wtx.nTimeSmart = ComputeTimeSmart(wtx);
991 AddToSpends(txid);
992 }
993
994 if (!fInsertedNew) {
995 if (confirm.status != wtx.m_confirm.status) {
996 wtx.m_confirm.status = confirm.status;
997 wtx.m_confirm.nIndex = confirm.nIndex;
998 wtx.m_confirm.hashBlock = confirm.hashBlock;
999 wtx.m_confirm.block_height = confirm.block_height;
1000 fUpdated = true;
1001 } else {
1002 assert(wtx.m_confirm.nIndex == confirm.nIndex);
1003 assert(wtx.m_confirm.hashBlock == confirm.hashBlock);
1004 assert(wtx.m_confirm.block_height == confirm.block_height);
1005 }
1006 }
1007
1009 WalletLogPrintf("AddToWallet %s %s%s\n", txid.ToString(),
1010 (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1011
1012 // Write to disk
1013 if ((fInsertedNew || fUpdated) && !batch.WriteTx(wtx)) {
1014 return nullptr;
1015 }
1016
1017 // Break debit/credit balance caches:
1018 wtx.MarkDirty();
1019
1020 // Notify UI of new or updated transaction.
1021 NotifyTransactionChanged(this, txid, fInsertedNew ? CT_NEW : CT_UPDATED);
1022
1023#if defined(HAVE_SYSTEM)
1024 // Notify an external script when a wallet transaction comes in or is
1025 // updated.
1026 std::string strCmd = gArgs.GetArg("-walletnotify", "");
1027
1028 if (!strCmd.empty()) {
1029 ReplaceAll(strCmd, "%s", txid.GetHex());
1030#ifndef WIN32
1031 // Substituting the wallet name isn't currently supported on windows
1032 // because windows shell escaping has not been implemented yet:
1033 // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
1034 // A few ways it could be implemented in the future are described in:
1035 // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
1036 ReplaceAll(strCmd, "%w", ShellEscape(GetName()));
1037#endif
1038
1039 std::thread t(runCommand, strCmd);
1040 // Thread runs free.
1041 t.detach();
1042 }
1043#endif
1044
1045 return &wtx;
1046}
1047
1048bool CWallet::LoadToWallet(const TxId &txid, const UpdateWalletTxFn &fill_wtx) {
1049 const auto &ins =
1050 mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid),
1051 std::forward_as_tuple(nullptr));
1052 CWalletTx &wtx = ins.first->second;
1053 if (!fill_wtx(wtx, ins.second)) {
1054 return false;
1055 }
1056 // If wallet doesn't have a chain (e.g wallet-tool), don't bother to update
1057 // txn.
1058 if (HaveChain()) {
1059 bool active;
1060 int height;
1061 if (chain().findBlock(
1062 wtx.m_confirm.hashBlock,
1063 FoundBlock().inActiveChain(active).height(height)) &&
1064 active) {
1065 // Update cached block height variable since it not stored in the
1066 // serialized transaction.
1067 wtx.m_confirm.block_height = height;
1068 } else if (wtx.isConflicted() || wtx.isConfirmed()) {
1069 // If tx block (or conflicting block) was reorged out of chain
1070 // while the wallet was shutdown, change tx status to UNCONFIRMED
1071 // and reset block height, hash, and index. ABANDONED tx don't have
1072 // associated blocks and don't need to be updated. The case where a
1073 // transaction was reorged out while online and then reconfirmed
1074 // while offline is covered by the rescan logic.
1075 wtx.setUnconfirmed();
1077 wtx.m_confirm.block_height = 0;
1078 wtx.m_confirm.nIndex = 0;
1079 }
1080 }
1081 if (/* insertion took place */ ins.second) {
1082 wtx.m_it_wtxOrdered =
1083 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1084 }
1085 AddToSpends(txid);
1086 for (const CTxIn &txin : wtx.tx->vin) {
1087 auto it = mapWallet.find(txin.prevout.GetTxId());
1088 if (it != mapWallet.end()) {
1089 CWalletTx &prevtx = it->second;
1090 if (prevtx.isConflicted()) {
1092 prevtx.m_confirm.block_height, wtx.GetId());
1093 }
1094 }
1095 }
1096 return true;
1097}
1098
1101 bool fUpdate) {
1103
1104 const TxId &txid = ptx->GetId();
1105
1106 if (!confirm.hashBlock.IsNull()) {
1107 for (const CTxIn &txin : ptx->vin) {
1108 std::pair<TxSpends::const_iterator, TxSpends::const_iterator>
1109 range = mapTxSpends.equal_range(txin.prevout);
1110 while (range.first != range.second) {
1111 if (range.first->second != txid) {
1113 "Transaction %s (in block %s) conflicts with wallet "
1114 "transaction %s (both spend %s:%i)\n",
1115 txid.ToString(), confirm.hashBlock.ToString(),
1116 range.first->second.ToString(),
1117 range.first->first.GetTxId().ToString(),
1118 range.first->first.GetN());
1119 MarkConflicted(confirm.hashBlock, confirm.block_height,
1120 range.first->second);
1121 }
1122 range.first++;
1123 }
1124 }
1125 }
1126
1127 bool fExisted = mapWallet.count(txid) != 0;
1128 if (fExisted && !fUpdate) {
1129 return false;
1130 }
1131 if (fExisted || IsMine(*ptx) || IsFromMe(*ptx)) {
1140 // loop though all outputs
1141 for (const CTxOut &txout : ptx->vout) {
1142 for (const auto &spk_man_pair : m_spk_managers) {
1143 spk_man_pair.second->MarkUnusedAddresses(txout.scriptPubKey);
1144 }
1145 }
1146
1147 // Block disconnection override an abandoned tx as unconfirmed
1148 // which means user may have to call abandontransaction again
1149 return AddToWallet(ptx, confirm,
1150 /* update_wtx= */ nullptr,
1151 /* fFlushOnClose= */ false);
1152 }
1153 return false;
1154}
1155
1157 LOCK(cs_wallet);
1158 const CWalletTx *wtx = GetWalletTx(txid);
1159 return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 &&
1160 !wtx->InMempool();
1161}
1162
1164 for (const CTxIn &txin : tx->vin) {
1165 auto it = mapWallet.find(txin.prevout.GetTxId());
1166 if (it != mapWallet.end()) {
1167 it->second.MarkDirty();
1168 }
1169 }
1170}
1171
1173 LOCK(cs_wallet);
1174
1175 WalletBatch batch(*database);
1176
1177 std::set<TxId> todo;
1178 std::set<TxId> done;
1179
1180 // Can't mark abandoned if confirmed or in mempool
1181 auto it = mapWallet.find(txid);
1182 assert(it != mapWallet.end());
1183 const CWalletTx &origtx = it->second;
1184 if (GetTxDepthInMainChain(origtx) != 0 || origtx.InMempool()) {
1185 return false;
1186 }
1187
1188 todo.insert(txid);
1189
1190 while (!todo.empty()) {
1191 const TxId now = *todo.begin();
1192 todo.erase(now);
1193 done.insert(now);
1194 it = mapWallet.find(now);
1195 assert(it != mapWallet.end());
1196 CWalletTx &wtx = it->second;
1197 int currentconfirm = GetTxDepthInMainChain(wtx);
1198 // If the orig tx was not in block, none of its spends can be.
1199 assert(currentconfirm <= 0);
1200 // If (currentconfirm < 0) {Tx and spends are already conflicted, no
1201 // need to abandon}
1202 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1203 // If the orig tx was not in block/mempool, none of its spends can
1204 // be in mempool.
1205 assert(!wtx.InMempool());
1206 wtx.setAbandoned();
1207 wtx.MarkDirty();
1208 batch.WriteTx(wtx);
1210 // Iterate over all its outputs, and mark transactions in the wallet
1211 // that spend them abandoned too.
1212 TxSpends::const_iterator iter =
1213 mapTxSpends.lower_bound(COutPoint(now, 0));
1214 while (iter != mapTxSpends.end() && iter->first.GetTxId() == now) {
1215 if (!done.count(iter->second)) {
1216 todo.insert(iter->second);
1217 }
1218 iter++;
1219 }
1220
1221 // If a transaction changes 'conflicted' state, that changes the
1222 // balance available of the outputs it spends. So force those to be
1223 // recomputed.
1224 MarkInputsDirty(wtx.tx);
1225 }
1226 }
1227
1228 return true;
1229}
1230
1231void CWallet::MarkConflicted(const BlockHash &hashBlock, int conflicting_height,
1232 const TxId &txid) {
1233 LOCK(cs_wallet);
1234
1235 int conflictconfirms =
1236 (m_last_block_processed_height - conflicting_height + 1) * -1;
1237
1238 // If number of conflict confirms cannot be determined, this means that the
1239 // block is still unknown or not yet part of the main chain, for example
1240 // when loading the wallet during a reindex. Do nothing in that case.
1241 if (conflictconfirms >= 0) {
1242 return;
1243 }
1244
1245 // Do not flush the wallet here for performance reasons.
1246 WalletBatch batch(*database, false);
1247
1248 std::set<TxId> todo;
1249 std::set<TxId> done;
1250
1251 todo.insert(txid);
1252
1253 while (!todo.empty()) {
1254 const TxId now = *todo.begin();
1255 todo.erase(now);
1256 done.insert(now);
1257 auto it = mapWallet.find(now);
1258 assert(it != mapWallet.end());
1259 CWalletTx &wtx = it->second;
1260 int currentconfirm = GetTxDepthInMainChain(wtx);
1261 if (conflictconfirms < currentconfirm) {
1262 // Block is 'more conflicted' than current confirm; update.
1263 // Mark transaction as conflicted with this block.
1264 wtx.m_confirm.nIndex = 0;
1265 wtx.m_confirm.hashBlock = hashBlock;
1266 wtx.m_confirm.block_height = conflicting_height;
1267 wtx.setConflicted();
1268 wtx.MarkDirty();
1269 batch.WriteTx(wtx);
1270 // Iterate over all its outputs, and mark transactions in the wallet
1271 // that spend them conflicted too.
1272 TxSpends::const_iterator iter =
1273 mapTxSpends.lower_bound(COutPoint(now, 0));
1274 while (iter != mapTxSpends.end() && iter->first.GetTxId() == now) {
1275 if (!done.count(iter->second)) {
1276 todo.insert(iter->second);
1277 }
1278 iter++;
1279 }
1280 // If a transaction changes 'conflicted' state, that changes the
1281 // balance available of the outputs it spends. So force those to be
1282 // recomputed.
1283 MarkInputsDirty(wtx.tx);
1284 }
1285 }
1286}
1287
1289 CWalletTx::Confirmation confirm, bool update_tx) {
1290 if (!AddToWalletIfInvolvingMe(ptx, confirm, update_tx)) {
1291 // Not one of ours
1292 return;
1293 }
1294
1295 // If a transaction changes 'conflicted' state, that changes the balance
1296 // available of the outputs it spends. So force those to be
1297 // recomputed, also:
1298 MarkInputsDirty(ptx);
1299}
1300
1302 uint64_t mempool_sequence) {
1303 LOCK(cs_wallet);
1304
1305 SyncTransaction(tx, {CWalletTx::Status::UNCONFIRMED, /* block_height */ 0,
1306 BlockHash(), /* nIndex */ 0});
1307
1308 auto it = mapWallet.find(tx->GetId());
1309 if (it != mapWallet.end()) {
1310 it->second.fInMempool = true;
1311 }
1312}
1313
1315 MemPoolRemovalReason reason,
1316 uint64_t mempool_sequence) {
1317 LOCK(cs_wallet);
1318 auto it = mapWallet.find(tx->GetId());
1319 if (it != mapWallet.end()) {
1320 it->second.fInMempool = false;
1321 }
1322 // Handle transactions that were removed from the mempool because they
1323 // conflict with transactions in a newly connected block.
1324 if (reason == MemPoolRemovalReason::CONFLICT) {
1325 // Call SyncNotifications, so external -walletnotify notifications will
1326 // be triggered for these transactions. Set Status::UNCONFIRMED instead
1327 // of Status::CONFLICTED for a few reasons:
1328 //
1329 // 1. The transactionRemovedFromMempool callback does not currently
1330 // provide the conflicting block's hash and height, and for backwards
1331 // compatibility reasons it may not be not safe to store conflicted
1332 // wallet transactions with a null block hash. See
1333 // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1334 // 2. For most of these transactions, the wallet's internal conflict
1335 // detection in the blockConnected handler will subsequently call
1336 // MarkConflicted and update them with CONFLICTED status anyway. This
1337 // applies to any wallet transaction that has inputs spent in the
1338 // block, or that has ancestors in the wallet with inputs spent by
1339 // the block.
1340 // 3. Longstanding behavior since the sync implementation in
1341 // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1342 // implementation before that was to mark these transactions
1343 // unconfirmed rather than conflicted.
1344 //
1345 // Nothing described above should be seen as an unchangeable requirement
1346 // when improving this code in the future. The wallet's heuristics for
1347 // distinguishing between conflicted and unconfirmed transactions are
1348 // imperfect, and could be improved in general, see
1349 // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1350 SyncTransaction(tx,
1351 {CWalletTx::Status::UNCONFIRMED, /* block height */ 0,
1352 BlockHash(), /* index */ 0});
1353 }
1354}
1355
1356void CWallet::blockConnected(const CBlock &block, int height) {
1357 const BlockHash &block_hash = block.GetHash();
1358 LOCK(cs_wallet);
1359
1360 m_last_block_processed_height = height;
1361 m_last_block_processed = block_hash;
1362 for (size_t index = 0; index < block.vtx.size(); index++) {
1363 SyncTransaction(block.vtx[index], {CWalletTx::Status::CONFIRMED, height,
1364 block_hash, int(index)});
1367 0 /* mempool_sequence */);
1368 }
1369}
1370
1371void CWallet::blockDisconnected(const CBlock &block, int height) {
1372 LOCK(cs_wallet);
1373
1374 // At block disconnection, this will change an abandoned transaction to
1375 // be unconfirmed, whether or not the transaction is added back to the
1376 // mempool. User may have to call abandontransaction again. It may be
1377 // addressed in the future with a stickier abandoned state or even removing
1378 // abandontransaction call.
1379 m_last_block_processed_height = height - 1;
1380 m_last_block_processed = block.hashPrevBlock;
1381 for (const CTransactionRef &ptx : block.vtx) {
1382 SyncTransaction(ptx,
1383 {CWalletTx::Status::UNCONFIRMED, /* block_height */ 0,
1384 BlockHash(), /* nIndex */ 0});
1385 }
1386}
1387
1390}
1391
1392void CWallet::BlockUntilSyncedToCurrentChain() const {
1394 // Skip the queue-draining stuff if we know we're caught up with
1395 // chain().Tip(), otherwise put a callback in the validation interface
1396 // queue and wait for the queue to drain enough to execute it (indicating we
1397 // are caught up at least with the time we entered this function).
1398 const BlockHash last_block_hash =
1399 WITH_LOCK(cs_wallet, return m_last_block_processed);
1400 chain().waitForNotificationsIfTipChanged(last_block_hash);
1401}
1402
1403// Note that this function doesn't distinguish between a 0-valued input, and a
1404// not-"is mine" (according to the filter) input.
1405Amount CWallet::GetDebit(const CTxIn &txin, const isminefilter &filter) const {
1406 LOCK(cs_wallet);
1407 std::map<TxId, CWalletTx>::const_iterator mi =
1408 mapWallet.find(txin.prevout.GetTxId());
1409 if (mi != mapWallet.end()) {
1410 const CWalletTx &prev = (*mi).second;
1411 if (txin.prevout.GetN() < prev.tx->vout.size()) {
1412 if (IsMine(prev.tx->vout[txin.prevout.GetN()]) & filter) {
1413 return prev.tx->vout[txin.prevout.GetN()].nValue;
1414 }
1415 }
1416 }
1417
1418 return Amount::zero();
1419}
1420
1421isminetype CWallet::IsMine(const CTxOut &txout) const {
1423 return IsMine(txout.scriptPubKey);
1424}
1425
1428 return IsMine(GetScriptForDestination(dest));
1429}
1430
1431isminetype CWallet::IsMine(const CScript &script) const {
1433 isminetype result = ISMINE_NO;
1434 for (const auto &spk_man_pair : m_spk_managers) {
1435 result = std::max(result, spk_man_pair.second->IsMine(script));
1436 }
1437 return result;
1438}
1439
1440bool CWallet::IsMine(const CTransaction &tx) const {
1442 for (const CTxOut &txout : tx.vout) {
1443 if (IsMine(txout)) {
1444 return true;
1445 }
1446 }
1447
1448 return false;
1449}
1450
1451bool CWallet::IsFromMe(const CTransaction &tx) const {
1452 return GetDebit(tx, ISMINE_ALL) > Amount::zero();
1453}
1454
1455Amount CWallet::GetDebit(const CTransaction &tx,
1456 const isminefilter &filter) const {
1457 Amount nDebit = Amount::zero();
1458 for (const CTxIn &txin : tx.vin) {
1459 nDebit += GetDebit(txin, filter);
1460 if (!MoneyRange(nDebit)) {
1461 throw std::runtime_error(std::string(__func__) +
1462 ": value out of range");
1463 }
1464 }
1465
1466 return nDebit;
1467}
1468
1470 // All Active ScriptPubKeyMans must be HD for this to be true
1471 bool result = true;
1472 for (const auto &spk_man : GetActiveScriptPubKeyMans()) {
1473 result &= spk_man->IsHDEnabled();
1474 }
1475 return result;
1476}
1477
1478bool CWallet::CanGetAddresses(bool internal) const {
1479 LOCK(cs_wallet);
1480 if (m_spk_managers.empty()) {
1481 return false;
1482 }
1483 for (OutputType t : OUTPUT_TYPES) {
1484 auto spk_man = GetScriptPubKeyMan(t, internal);
1485 if (spk_man && spk_man->CanGetAddresses(internal)) {
1486 return true;
1487 }
1488 }
1489 return false;
1490}
1491
1493 LOCK(cs_wallet);
1495 if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) {
1496 throw std::runtime_error(std::string(__func__) +
1497 ": writing wallet flags failed");
1498 }
1499}
1500
1501void CWallet::UnsetWalletFlag(uint64_t flag) {
1502 WalletBatch batch(*database);
1503 UnsetWalletFlagWithDB(batch, flag);
1504}
1505
1506void CWallet::UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag) {
1507 LOCK(cs_wallet);
1508 m_wallet_flags &= ~flag;
1509 if (!batch.WriteWalletFlags(m_wallet_flags)) {
1510 throw std::runtime_error(std::string(__func__) +
1511 ": writing wallet flags failed");
1512 }
1513}
1514
1517}
1518
1519bool CWallet::IsWalletFlagSet(uint64_t flag) const {
1520 return (m_wallet_flags & flag);
1521}
1522
1524 LOCK(cs_wallet);
1525 if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1526 // contains unknown non-tolerable wallet flags
1527 return false;
1528 }
1530
1531 return true;
1532}
1533
1535 LOCK(cs_wallet);
1536 // We should never be writing unknown non-tolerable wallet flags
1537 assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1538 if (!WalletBatch(*database).WriteWalletFlags(flags)) {
1539 throw std::runtime_error(std::string(__func__) +
1540 ": writing wallet flags failed");
1541 }
1542
1543 return LoadWalletFlags(flags);
1544}
1545
1546// Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
1547// or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
1548bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout,
1549 bool use_max_sig) const {
1550 // Fill in dummy signatures for fee calculation.
1551 const CScript &scriptPubKey = txout.scriptPubKey;
1552 SignatureData sigdata;
1553
1554 std::unique_ptr<SigningProvider> provider =
1555 GetSolvingProvider(scriptPubKey);
1556 if (!provider) {
1557 // We don't know about this scriptpbuKey;
1558 return false;
1559 }
1560
1561 if (!ProduceSignature(*provider,
1564 scriptPubKey, sigdata)) {
1565 return false;
1566 }
1567
1568 UpdateInput(tx_in, sigdata);
1569 return true;
1570}
1571
1572// Helper for producing a bunch of max-sized low-S low-R signatures (eg 71
1573// bytes)
1575 const std::vector<CTxOut> &txouts,
1576 bool use_max_sig) const {
1577 // Fill in dummy signatures for fee calculation.
1578 int nIn = 0;
1579 for (const auto &txout : txouts) {
1580 if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
1581 return false;
1582 }
1583
1584 nIn++;
1585 }
1586 return true;
1587}
1588
1589bool CWallet::ImportScripts(const std::set<CScript> scripts,
1590 int64_t timestamp) {
1591 auto spk_man = GetLegacyScriptPubKeyMan();
1592 if (!spk_man) {
1593 return false;
1594 }
1595 LOCK(spk_man->cs_KeyStore);
1596 return spk_man->ImportScripts(scripts, timestamp);
1597}
1598
1599bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey> &privkey_map,
1600 const int64_t timestamp) {
1601 auto spk_man = GetLegacyScriptPubKeyMan();
1602 if (!spk_man) {
1603 return false;
1604 }
1605 LOCK(spk_man->cs_KeyStore);
1606 return spk_man->ImportPrivKeys(privkey_map, timestamp);
1607}
1608
1610 const std::vector<CKeyID> &ordered_pubkeys,
1611 const std::map<CKeyID, CPubKey> &pubkey_map,
1612 const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> &key_origins,
1613 const bool add_keypool, const bool internal, const int64_t timestamp) {
1614 auto spk_man = GetLegacyScriptPubKeyMan();
1615 if (!spk_man) {
1616 return false;
1617 }
1618 LOCK(spk_man->cs_KeyStore);
1619 return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins,
1620 add_keypool, internal, timestamp);
1621}
1622
1623bool CWallet::ImportScriptPubKeys(const std::string &label,
1624 const std::set<CScript> &script_pub_keys,
1625 const bool have_solving_data,
1626 const bool apply_label,
1627 const int64_t timestamp) {
1628 auto spk_man = GetLegacyScriptPubKeyMan();
1629 if (!spk_man) {
1630 return false;
1631 }
1632 LOCK(spk_man->cs_KeyStore);
1633 if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data,
1634 timestamp)) {
1635 return false;
1636 }
1637 if (apply_label) {
1638 WalletBatch batch(*database);
1639 for (const CScript &script : script_pub_keys) {
1640 CTxDestination dest;
1641 ExtractDestination(script, dest);
1642 if (IsValidDestination(dest)) {
1643 SetAddressBookWithDB(batch, dest, label, "receive");
1644 }
1645 }
1646 }
1647 return true;
1648}
1649
1658int64_t CWallet::RescanFromTime(int64_t startTime,
1659 const WalletRescanReserver &reserver,
1660 bool update) {
1661 // Find starting block. May be null if nCreateTime is greater than the
1662 // highest blockchain timestamp, in which case there is nothing that needs
1663 // to be scanned.
1664 int start_height = 0;
1665 BlockHash start_block;
1667 startTime - TIMESTAMP_WINDOW, 0,
1668 FoundBlock().hash(start_block).height(start_height));
1669 WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__,
1670 start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) -
1671 start_height + 1
1672 : 0);
1673
1674 if (start) {
1675 // TODO: this should take into account failure by ScanResult::USER_ABORT
1677 start_block, start_height, {} /* max_height */, reserver, update);
1678 if (result.status == ScanResult::FAILURE) {
1679 int64_t time_max;
1680 CHECK_NONFATAL(chain().findBlock(result.last_failed_block,
1681 FoundBlock().maxTime(time_max)));
1682 return time_max + TIMESTAMP_WINDOW + 1;
1683 }
1684 }
1685 return startTime;
1686}
1687
1710 const BlockHash &start_block, int start_height,
1711 std::optional<int> max_height, const WalletRescanReserver &reserver,
1712 bool fUpdate) {
1713 int64_t nNow = GetTime();
1714 int64_t start_time = GetTimeMillis();
1715
1716 assert(reserver.isReserved());
1717
1718 BlockHash block_hash = start_block;
1719 ScanResult result;
1720
1721 WalletLogPrintf("Rescan started from block %s...\n",
1722 start_block.ToString());
1723
1724 fAbortRescan = false;
1725 // Show rescan progress in GUI as dialog or on splashscreen, if -rescan on
1726 // startup.
1728 strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 0);
1729 BlockHash tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1730 BlockHash end_hash = tip_hash;
1731 if (max_height) {
1732 chain().findAncestorByHeight(tip_hash, *max_height,
1733 FoundBlock().hash(end_hash));
1734 }
1735 double progress_begin = chain().guessVerificationProgress(block_hash);
1736 double progress_end = chain().guessVerificationProgress(end_hash);
1737 double progress_current = progress_begin;
1738 int block_height = start_height;
1739 while (!fAbortRescan && !chain().shutdownRequested()) {
1740 if (progress_end - progress_begin > 0.0) {
1741 m_scanning_progress = (progress_current - progress_begin) /
1742 (progress_end - progress_begin);
1743 } else {
1744 // avoid divide-by-zero for single block scan range (i.e. start and
1745 // stop hashes are equal)
1747 }
1748 if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1750 strprintf("%s " + _("Rescanning...").translated,
1751 GetDisplayName()),
1752 std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1753 }
1754 if (GetTime() >= nNow + 60) {
1755 nNow = GetTime();
1756 WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n",
1757 block_height, progress_current);
1758 }
1759
1760 // Read block data
1761 CBlock block;
1762 chain().findBlock(block_hash, FoundBlock().data(block));
1763
1764 // Find next block separately from reading data above, because reading
1765 // is slow and there might be a reorg while it is read.
1766 bool block_still_active = false;
1767 bool next_block = false;
1768 BlockHash next_block_hash;
1769 chain().findBlock(block_hash,
1770 FoundBlock()
1771 .inActiveChain(block_still_active)
1772 .nextBlock(FoundBlock()
1773 .inActiveChain(next_block)
1774 .hash(next_block_hash)));
1775
1776 if (!block.IsNull()) {
1777 LOCK(cs_wallet);
1778 if (!block_still_active) {
1779 // Abort scan if current block is no longer active, to prevent
1780 // marking transactions as coming from the wrong block.
1781 result.last_failed_block = block_hash;
1782 result.status = ScanResult::FAILURE;
1783 break;
1784 }
1785 for (size_t posInBlock = 0; posInBlock < block.vtx.size();
1786 ++posInBlock) {
1787 CWalletTx::Confirmation confirm(CWalletTx::Status::CONFIRMED,
1788 block_height, block_hash,
1789 posInBlock);
1790 SyncTransaction(block.vtx[posInBlock],
1791 {CWalletTx::Status::CONFIRMED, block_height,
1792 block_hash, int(posInBlock)},
1793 fUpdate);
1794 }
1795 // scan succeeded, record block as most recent successfully
1796 // scanned
1797 result.last_scanned_block = block_hash;
1798 result.last_scanned_height = block_height;
1799 } else {
1800 // could not scan block, keep scanning but record this block as
1801 // the most recent failure
1802 result.last_failed_block = block_hash;
1803 result.status = ScanResult::FAILURE;
1804 }
1805 if (max_height && block_height >= *max_height) {
1806 break;
1807 }
1808 {
1809 if (!next_block) {
1810 // break successfully when rescan has reached the tip, or
1811 // previous block is no longer on the chain due to a reorg
1812 break;
1813 }
1814
1815 // increment block and verification progress
1816 block_hash = next_block_hash;
1817 ++block_height;
1818 progress_current = chain().guessVerificationProgress(block_hash);
1819
1820 // handle updated tip hash
1821 const BlockHash prev_tip_hash = tip_hash;
1822 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1823 if (!max_height && prev_tip_hash != tip_hash) {
1824 // in case the tip has changed, update progress max
1825 progress_end = chain().guessVerificationProgress(tip_hash);
1826 }
1827 }
1828 }
1829
1830 // Hide progress dialog in GUI.
1832 strprintf("%s " + _("Rescanning...").translated, GetDisplayName()),
1833 100);
1834 if (block_height && fAbortRescan) {
1835 WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n",
1836 block_height, progress_current);
1838 } else if (block_height && chain().shutdownRequested()) {
1840 "Rescan interrupted by shutdown request at block %d. Progress=%f\n",
1841 block_height, progress_current);
1843 } else {
1844 WalletLogPrintf("Rescan completed in %15dms\n",
1845 GetTimeMillis() - start_time);
1846 }
1847 return result;
1848}
1849
1852
1853 // If transactions aren't being broadcasted, don't let them into local
1854 // mempool either.
1856 return;
1857 }
1858
1859 std::map<int64_t, CWalletTx *> mapSorted;
1860
1861 // Sort pending wallet transactions based on their initial wallet insertion
1862 // order.
1863 for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
1864 const TxId &wtxid = item.first;
1865 CWalletTx &wtx = item.second;
1866 assert(wtx.GetId() == wtxid);
1867
1868 int nDepth = GetTxDepthInMainChain(wtx);
1869
1870 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1871 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1872 }
1873 }
1874
1875 // Try to add wallet transactions to memory pool.
1876 for (const std::pair<const int64_t, CWalletTx *> &item : mapSorted) {
1877 CWalletTx &wtx = *(item.second);
1878 std::string unused_err_string;
1879 SubmitTxMemoryPoolAndRelay(wtx, unused_err_string, false);
1880 }
1881}
1882
1884 std::string &err_string,
1885 bool relay) const {
1887
1888 // Can't relay if wallet is not broadcasting
1889 if (!GetBroadcastTransactions()) {
1890 return false;
1891 }
1892 // Don't relay abandoned transactions
1893 if (wtx.isAbandoned()) {
1894 return false;
1895 }
1896 // Don't try to submit coinbase transactions. These would fail anyway but
1897 // would cause log spam.
1898 if (wtx.IsCoinBase()) {
1899 return false;
1900 }
1901 // Don't try to submit conflicted or confirmed transactions.
1902 if (GetTxDepthInMainChain(wtx) != 0) {
1903 return false;
1904 }
1905
1906 // Submit transaction to mempool for relay
1907 WalletLogPrintf("Submitting wtx %s to mempool for relay\n",
1908 wtx.GetId().ToString());
1909 // We must set fInMempool here - while it will be re-set to true by the
1910 // entered-mempool callback, if we did not there would be a race where a
1911 // user could call sendmoney in a loop and hit spurious out of funds errors
1912 // because we think that this newly generated transaction's change is
1913 // unavailable as we're not yet aware that it is in the mempool.
1914 //
1915 // Irrespective of the failure reason, un-marking fInMempool
1916 // out-of-order is incorrect - it should be unmarked when
1917 // TransactionRemovedFromMempool fires.
1918 bool ret = chain().broadcastTransaction(
1919 GetConfig(), wtx.tx, m_default_max_tx_fee, relay, err_string);
1920 wtx.fInMempool |= ret;
1921 return ret;
1922}
1923
1924std::set<TxId> CWallet::GetTxConflicts(const CWalletTx &wtx) const {
1926
1927 std::set<TxId> result;
1928 const TxId &txid = wtx.GetId();
1929 result = GetConflicts(txid);
1930 result.erase(txid);
1931
1932 return result;
1933}
1934
1935// Rebroadcast transactions from the wallet. We do this on a random timer
1936// to slightly obfuscate which transactions come from our wallet.
1937//
1938// Ideally, we'd only resend transactions that we think should have been
1939// mined in the most recent block. Any transaction that wasn't in the top
1940// blockweight of transactions in the mempool shouldn't have been mined,
1941// and so is probably just sitting in the mempool waiting to be confirmed.
1942// Rebroadcasting does nothing to speed up confirmation and only damages
1943// privacy.
1945 // During reindex, importing and IBD, old wallet transactions become
1946 // unconfirmed. Don't resend them as that would spam other nodes.
1947 if (!chain().isReadyToBroadcast()) {
1948 return;
1949 }
1950
1951 // Do this infrequently and randomly to avoid giving away that these are our
1952 // transactions.
1954 return;
1955 }
1956
1957 bool fFirst = (nNextResend == 0);
1958 // resend 12-36 hours from now, ~1 day on average.
1959 nNextResend = GetTime() + (12 * 60 * 60) + GetRand(24 * 60 * 60);
1960 if (fFirst) {
1961 return;
1962 }
1963
1964 int submitted_tx_count = 0;
1965
1966 { // cs_wallet scope
1967 LOCK(cs_wallet);
1968
1969 // Relay transactions
1970 for (std::pair<const TxId, CWalletTx> &item : mapWallet) {
1971 CWalletTx &wtx = item.second;
1972 // Attempt to rebroadcast all txes more than 5 minutes older than
1973 // the last block. SubmitTxMemoryPoolAndRelay() will not rebroadcast
1974 // any confirmed or conflicting txs.
1975 if (wtx.nTimeReceived > m_best_block_time - 5 * 60) {
1976 continue;
1977 }
1978 std::string unused_err_string;
1979 if (SubmitTxMemoryPoolAndRelay(wtx, unused_err_string, true)) {
1980 ++submitted_tx_count;
1981 }
1982 }
1983 } // cs_wallet
1984
1985 if (submitted_tx_count > 0) {
1986 WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__,
1987 submitted_tx_count);
1988 }
1989}
1990 // end of mapWallet
1992
1994 for (const std::shared_ptr<CWallet> &pwallet : GetWallets()) {
1995 pwallet->ResendWalletTransactions();
1996 }
1997}
1998
2007
2008 // Build coins map
2009 std::map<COutPoint, Coin> coins;
2010 for (auto &input : tx.vin) {
2011 auto mi = mapWallet.find(input.prevout.GetTxId());
2012 if (mi == mapWallet.end() ||
2013 input.prevout.GetN() >= mi->second.tx->vout.size()) {
2014 return false;
2015 }
2016 const CWalletTx &wtx = mi->second;
2017 coins[input.prevout] =
2018 Coin(wtx.tx->vout[input.prevout.GetN()], wtx.m_confirm.block_height,
2019 wtx.IsCoinBase());
2020 }
2021 std::map<int, std::string> input_errors;
2022 return SignTransaction(tx, coins, SigHashType().withForkId(), input_errors);
2023}
2024
2026 const std::map<COutPoint, Coin> &coins,
2027 SigHashType sighash,
2028 std::map<int, std::string> &input_errors) const {
2029 // Try to sign with all ScriptPubKeyMans
2030 for (ScriptPubKeyMan *spk_man : GetAllScriptPubKeyMans()) {
2031 // spk_man->SignTransaction will return true if the transaction is
2032 // complete, so we can exit early and return true if that happens
2033 if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2034 return true;
2035 }
2036 }
2037
2038 // At this point, one input was not fully signed otherwise we would have
2039 // exited already
2040
2041 // When there are no available providers for the remaining inputs, use the
2042 // legacy provider so we can get proper error messages.
2043 auto legacy_spk_man = GetLegacyScriptPubKeyMan();
2044 if (legacy_spk_man &&
2045 legacy_spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2046 return true;
2047 }
2048
2049 return false;
2050}
2051
2053 bool &complete, SigHashType sighash_type,
2054 bool sign, bool bip32derivs) const {
2055 LOCK(cs_wallet);
2056 // Get all of the previous transactions
2057 for (size_t i = 0; i < psbtx.tx->vin.size(); ++i) {
2058 const CTxIn &txin = psbtx.tx->vin[i];
2059 PSBTInput &input = psbtx.inputs.at(i);
2060
2061 if (PSBTInputSigned(input)) {
2062 continue;
2063 }
2064
2065 // If we have no utxo, grab it from the wallet.
2066 if (input.utxo.IsNull()) {
2067 const TxId &txid = txin.prevout.GetTxId();
2068 const auto it = mapWallet.find(txid);
2069 if (it != mapWallet.end()) {
2070 const CWalletTx &wtx = it->second;
2071 CTxOut utxo = wtx.tx->vout[txin.prevout.GetN()];
2072 // Update UTXOs from the wallet.
2073 input.utxo = utxo;
2074 }
2075 }
2076 }
2077
2078 // Fill in information from ScriptPubKeyMans
2079 for (ScriptPubKeyMan *spk_man : GetAllScriptPubKeyMans()) {
2080 TransactionError res =
2081 spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs);
2082 if (res != TransactionError::OK) {
2083 return res;
2084 }
2085 }
2086
2087 // Complete if every input is now signed
2088 complete = true;
2089 for (const auto &input : psbtx.inputs) {
2090 complete &= PSBTInputSigned(input);
2091 }
2092
2093 return TransactionError::OK;
2094}
2095
2096SigningResult CWallet::SignMessage(const std::string &message,
2097 const PKHash &pkhash,
2098 std::string &str_sig) const {
2099 SignatureData sigdata;
2100 CScript script_pub_key = GetScriptForDestination(pkhash);
2101 for (const auto &spk_man_pair : m_spk_managers) {
2102 if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2103 return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2104 }
2105 }
2107}
2108
2110CWallet::TransactionChangeType(const std::optional<OutputType> &change_type,
2111 const std::vector<CRecipient> &vecSend) const {
2112 // If -changetype is specified, always use that change type.
2113 if (change_type) {
2114 return *change_type;
2115 }
2116
2117 // if m_default_address_type is legacy, use legacy address as change.
2119 return OutputType::LEGACY;
2120 }
2121
2122 // else use m_default_address_type for change
2124}
2125
2127 CTransactionRef tx, mapValue_t mapValue,
2128 std::vector<std::pair<std::string, std::string>> orderForm,
2129 bool broadcast) {
2130 LOCK(cs_wallet);
2131
2132 WalletLogPrintfToBeContinued("CommitTransaction:\n%s", tx->ToString());
2133
2134 // Add tx to wallet, because if it has change it's also ours, otherwise just
2135 // for transaction history.
2136 AddToWallet(tx, {}, [&](CWalletTx &wtx, bool new_tx) {
2137 CHECK_NONFATAL(wtx.mapValue.empty());
2138 CHECK_NONFATAL(wtx.vOrderForm.empty());
2139 wtx.mapValue = std::move(mapValue);
2140 wtx.vOrderForm = std::move(orderForm);
2141 wtx.fTimeReceivedIsTxTime = true;
2142 wtx.fFromMe = true;
2143 return true;
2144 });
2145
2146 // Notify that old coins are spent.
2147 for (const CTxIn &txin : tx->vin) {
2148 CWalletTx &coin = mapWallet.at(txin.prevout.GetTxId());
2149 coin.MarkDirty();
2151 }
2152
2153 // Get the inserted-CWalletTx from mapWallet so that the
2154 // fInMempool flag is cached properly
2155 CWalletTx &wtx = mapWallet.at(tx->GetId());
2156
2157 if (!broadcast || !fBroadcastTransactions) {
2158 // Don't submit tx to the mempool if the flag is unset for this single
2159 // transaction, or if the wallet doesn't broadcast transactions at all.
2160 return;
2161 }
2162
2163 std::string err_string;
2164 if (!SubmitTxMemoryPoolAndRelay(wtx, err_string, true)) {
2165 WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast "
2166 "immediately, %s\n",
2167 err_string);
2168 // TODO: if we expect the failure to be long term or permanent, instead
2169 // delete wtx from the wallet and return failure.
2170 }
2171}
2172
2174 LOCK(cs_wallet);
2175
2176 DBErrors nLoadWalletRet = WalletBatch(*database).LoadWallet(this);
2177 if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
2178 if (database->Rewrite("\x04pool")) {
2179 for (const auto &spk_man_pair : m_spk_managers) {
2180 spk_man_pair.second->RewriteDB();
2181 }
2182 }
2183 }
2184
2185 if (m_spk_managers.empty()) {
2188 }
2189
2190 if (nLoadWalletRet != DBErrors::LOAD_OK) {
2191 return nLoadWalletRet;
2192 }
2193
2194 return DBErrors::LOAD_OK;
2195}
2196
2197DBErrors CWallet::ZapSelectTx(std::vector<TxId> &txIdsIn,
2198 std::vector<TxId> &txIdsOut) {
2200 DBErrors nZapSelectTxRet =
2201 WalletBatch(*database).ZapSelectTx(txIdsIn, txIdsOut);
2202 for (const TxId &txid : txIdsOut) {
2203 const auto &it = mapWallet.find(txid);
2204 wtxOrdered.erase(it->second.m_it_wtxOrdered);
2205 for (const auto &txin : it->second.tx->vin) {
2206 mapTxSpends.erase(txin.prevout);
2207 }
2208 mapWallet.erase(it);
2210 }
2211
2212 if (nZapSelectTxRet == DBErrors::NEED_REWRITE) {
2213 if (database->Rewrite("\x04pool")) {
2214 for (const auto &spk_man_pair : m_spk_managers) {
2215 spk_man_pair.second->RewriteDB();
2216 }
2217 }
2218 }
2219
2220 if (nZapSelectTxRet != DBErrors::LOAD_OK) {
2221 return nZapSelectTxRet;
2222 }
2223
2224 MarkDirty();
2225
2226 return DBErrors::LOAD_OK;
2227}
2228
2230 const CTxDestination &address,
2231 const std::string &strName,
2232 const std::string &strPurpose) {
2233 bool fUpdated = false;
2234 bool is_mine;
2235 {
2236 LOCK(cs_wallet);
2237 std::map<CTxDestination, CAddressBookData>::iterator mi =
2238 m_address_book.find(address);
2239 fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
2240 m_address_book[address].SetLabel(strName);
2241 // Update purpose only if requested.
2242 if (!strPurpose.empty()) {
2243 m_address_book[address].purpose = strPurpose;
2244 }
2245 is_mine = IsMine(address) != ISMINE_NO;
2246 }
2247
2248 NotifyAddressBookChanged(this, address, strName, is_mine, strPurpose,
2249 (fUpdated ? CT_UPDATED : CT_NEW));
2250 if (!strPurpose.empty() && !batch.WritePurpose(address, strPurpose)) {
2251 return false;
2252 }
2253 return batch.WriteName(address, strName);
2254}
2255
2257 const std::string &strName,
2258 const std::string &strPurpose) {
2259 WalletBatch batch(*database);
2260 return SetAddressBookWithDB(batch, address, strName, strPurpose);
2261}
2262
2264 bool is_mine;
2265 WalletBatch batch(*database);
2266 {
2267 LOCK(cs_wallet);
2268 // If we want to delete receiving addresses, we need to take care that
2269 // DestData "used" (and possibly newer DestData) gets preserved (and the
2270 // "deleted" address transformed into a change entry instead of actually
2271 // being deleted)
2272 // NOTE: This isn't a problem for sending addresses because they never
2273 // have any DestData yet! When adding new DestData, it should be
2274 // considered here whether to retain or delete it (or move it?).
2275 if (IsMine(address)) {
2277 "%s called with IsMine address, NOT SUPPORTED. Please "
2278 "report this bug! %s\n",
2279 __func__, PACKAGE_BUGREPORT);
2280 return false;
2281 }
2282 // Delete destdata tuples associated with address
2283 for (const std::pair<const std::string, std::string> &item :
2284 m_address_book[address].destdata) {
2285 batch.EraseDestData(address, item.first);
2286 }
2287 m_address_book.erase(address);
2288 is_mine = IsMine(address) != ISMINE_NO;
2289 }
2290
2291 NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
2292
2293 batch.ErasePurpose(address);
2294 return batch.EraseName(address);
2295}
2296
2299
2300 unsigned int count = 0;
2301 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2302 count += spk_man->KeypoolCountExternalKeys();
2303 }
2304
2305 return count;
2306}
2307
2308unsigned int CWallet::GetKeyPoolSize() const {
2310
2311 unsigned int count = 0;
2312 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2313 count += spk_man->GetKeyPoolSize();
2314 }
2315 return count;
2316}
2317
2318bool CWallet::TopUpKeyPool(unsigned int kpSize) {
2319 LOCK(cs_wallet);
2320 bool res = true;
2321 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2322 res &= spk_man->TopUp(kpSize);
2323 }
2324 return res;
2325}
2326
2327bool CWallet::GetNewDestination(const OutputType type, const std::string label,
2328 CTxDestination &dest, std::string &error) {
2329 LOCK(cs_wallet);
2330 error.clear();
2331 bool result = false;
2332 auto spk_man = GetScriptPubKeyMan(type, false /* internal */);
2333 if (spk_man) {
2334 spk_man->TopUp();
2335 result = spk_man->GetNewDestination(type, dest, error);
2336 } else {
2337 error = strprintf("Error: No %s addresses available.",
2338 FormatOutputType(type));
2339 }
2340 if (result) {
2341 SetAddressBook(dest, label, "receive");
2342 }
2343
2344 return result;
2345}
2346
2348 CTxDestination &dest,
2349 std::string &error) {
2350 LOCK(cs_wallet);
2351 error.clear();
2352
2353 ReserveDestination reservedest(this, type);
2354 if (!reservedest.GetReservedDestination(dest, true)) {
2355 error = _("Error: Keypool ran out, please call keypoolrefill first")
2356 .translated;
2357 return false;
2358 }
2359
2360 reservedest.KeepDestination();
2361 return true;
2362}
2363
2365 LOCK(cs_wallet);
2366 int64_t oldestKey = std::numeric_limits<int64_t>::max();
2367 for (const auto &spk_man_pair : m_spk_managers) {
2368 oldestKey =
2369 std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
2370 }
2371 return oldestKey;
2372}
2373
2375 const std::set<CTxDestination> &destinations) {
2376 for (auto &entry : mapWallet) {
2377 CWalletTx &wtx = entry.second;
2378 if (wtx.m_is_cache_empty) {
2379 continue;
2380 }
2381
2382 for (size_t i = 0; i < wtx.tx->vout.size(); i++) {
2383 CTxDestination dst;
2384
2385 if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) &&
2386 destinations.count(dst)) {
2387 wtx.MarkDirty();
2388 break;
2389 }
2390 }
2391 }
2392}
2393
2394std::set<CTxDestination>
2395CWallet::GetLabelAddresses(const std::string &label) const {
2397 std::set<CTxDestination> result;
2398 for (const std::pair<const CTxDestination, CAddressBookData> &item :
2399 m_address_book) {
2400 if (item.second.IsChange()) {
2401 continue;
2402 }
2403 const CTxDestination &address = item.first;
2404 const std::string &strName = item.second.GetLabel();
2405 if (strName == label) {
2406 result.insert(address);
2407 }
2408 }
2409
2410 return result;
2411}
2412
2414 bool internal) {
2416 if (!m_spk_man) {
2417 return false;
2418 }
2419
2420 if (nIndex == -1) {
2421 m_spk_man->TopUp();
2422
2423 CKeyPool keypool;
2425 keypool)) {
2426 return false;
2427 }
2428 fInternal = keypool.fInternal;
2429 }
2430 dest = address;
2431 return true;
2432}
2433
2435 if (nIndex != -1) {
2437 }
2438
2439 nIndex = -1;
2441}
2442
2444 if (nIndex != -1) {
2446 }
2447 nIndex = -1;
2449}
2450
2451void CWallet::LockCoin(const COutPoint &output) {
2453 setLockedCoins.insert(output);
2454}
2455
2456void CWallet::UnlockCoin(const COutPoint &output) {
2458 setLockedCoins.erase(output);
2459}
2460
2463 setLockedCoins.clear();
2464}
2465
2466bool CWallet::IsLockedCoin(const COutPoint &outpoint) const {
2468
2469 return setLockedCoins.count(outpoint) > 0;
2470}
2471
2472void CWallet::ListLockedCoins(std::vector<COutPoint> &vOutpts) const {
2474 for (COutPoint outpoint : setLockedCoins) {
2475 vOutpts.push_back(outpoint);
2476 }
2477}
2478 // end of Actions
2480
2481void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2483 mapKeyBirth.clear();
2484
2485 // map in which we'll infer heights of other keys
2486 std::map<CKeyID, const CWalletTx::Confirmation *> mapKeyFirstBlock;
2487 CWalletTx::Confirmation max_confirm;
2488 // the tip can be reorganized; use a 144-block safety margin
2489 max_confirm.block_height =
2490 GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0;
2491 CHECK_NONFATAL(chain().findAncestorByHeight(
2492 GetLastBlockHash(), max_confirm.block_height,
2493 FoundBlock().hash(max_confirm.hashBlock)));
2494
2495 {
2497 assert(spk_man != nullptr);
2498 LOCK(spk_man->cs_KeyStore);
2499
2500 // Get birth times for keys with metadata.
2501 for (const auto &entry : spk_man->mapKeyMetadata) {
2502 if (entry.second.nCreateTime) {
2503 mapKeyBirth[entry.first] = entry.second.nCreateTime;
2504 }
2505 }
2506
2507 // Prepare to infer birth heights for keys without metadata.
2508 for (const CKeyID &keyid : spk_man->GetKeys()) {
2509 if (mapKeyBirth.count(keyid) == 0) {
2510 mapKeyFirstBlock[keyid] = &max_confirm;
2511 }
2512 }
2513
2514 // If there are no such keys, we're done.
2515 if (mapKeyFirstBlock.empty()) {
2516 return;
2517 }
2518
2519 // Find first block that affects those keys, if there are any left.
2520 for (const auto &entry : mapWallet) {
2521 // iterate over all wallet transactions...
2522 const CWalletTx &wtx = entry.second;
2524 // ... which are already in a block
2525 for (const CTxOut &txout : wtx.tx->vout) {
2526 // Iterate over all their outputs...
2527 for (const auto &keyid :
2528 GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
2529 // ... and all their affected keys.
2530 auto rit = mapKeyFirstBlock.find(keyid);
2531 if (rit != mapKeyFirstBlock.end() &&
2533 rit->second->block_height) {
2534 rit->second = &wtx.m_confirm;
2535 }
2536 }
2537 }
2538 }
2539 }
2540 }
2541
2542 // Extract block timestamps for those keys.
2543 for (const auto &entry : mapKeyFirstBlock) {
2544 int64_t block_time;
2545 CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock,
2546 FoundBlock().time(block_time)));
2547 // block times can be 2h off
2548 mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW;
2549 }
2550}
2551
2573unsigned int CWallet::ComputeTimeSmart(const CWalletTx &wtx) const {
2574 unsigned int nTimeSmart = wtx.nTimeReceived;
2575 if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
2576 int64_t blocktime;
2577 if (chain().findBlock(wtx.m_confirm.hashBlock,
2578 FoundBlock().time(blocktime))) {
2579 int64_t latestNow = wtx.nTimeReceived;
2580 int64_t latestEntry = 0;
2581
2582 // Tolerate times up to the last timestamp in the wallet not more
2583 // than 5 minutes into the future
2584 int64_t latestTolerated = latestNow + 300;
2585 const TxItems &txOrdered = wtxOrdered;
2586 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2587 CWalletTx *const pwtx = it->second;
2588 if (pwtx == &wtx) {
2589 continue;
2590 }
2591 int64_t nSmartTime;
2592 nSmartTime = pwtx->nTimeSmart;
2593 if (!nSmartTime) {
2594 nSmartTime = pwtx->nTimeReceived;
2595 }
2596 if (nSmartTime <= latestTolerated) {
2597 latestEntry = nSmartTime;
2598 if (nSmartTime > latestNow) {
2599 latestNow = nSmartTime;
2600 }
2601 break;
2602 }
2603 }
2604
2605 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2606 } else {
2607 WalletLogPrintf("%s: found %s in block %s not in index\n", __func__,
2608 wtx.GetId().ToString(),
2610 }
2611 }
2612 return nTimeSmart;
2613}
2614
2616 const std::string &key, const std::string &value) {
2617 if (std::get_if<CNoDestination>(&dest)) {
2618 return false;
2619 }
2620
2621 m_address_book[dest].destdata.insert(std::make_pair(key, value));
2622 return batch.WriteDestData(dest, key, value);
2623}
2624
2626 const std::string &key) {
2627 if (!m_address_book[dest].destdata.erase(key)) {
2628 return false;
2629 }
2630
2631 return batch.EraseDestData(dest, key);
2632}
2633
2634void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key,
2635 const std::string &value) {
2636 m_address_book[dest].destdata.insert(std::make_pair(key, value));
2637}
2638
2639bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key,
2640 std::string *value) const {
2641 std::map<CTxDestination, CAddressBookData>::const_iterator i =
2642 m_address_book.find(dest);
2643 if (i != m_address_book.end()) {
2644 CAddressBookData::StringMap::const_iterator j =
2645 i->second.destdata.find(key);
2646 if (j != i->second.destdata.end()) {
2647 if (value) {
2648 *value = j->second;
2649 }
2650
2651 return true;
2652 }
2653 }
2654 return false;
2655}
2656
2657std::vector<std::string>
2658CWallet::GetDestValues(const std::string &prefix) const {
2659 std::vector<std::string> values;
2660 for (const auto &address : m_address_book) {
2661 for (const auto &data : address.second.destdata) {
2662 if (!data.first.compare(0, prefix.size(), prefix)) {
2663 values.emplace_back(data.second);
2664 }
2665 }
2666 }
2667 return values;
2668}
2669
2670std::unique_ptr<WalletDatabase>
2671MakeWalletDatabase(const std::string &name, const DatabaseOptions &options,
2672 DatabaseStatus &status, bilingual_str &error_string) {
2673 // Do some checking on wallet path. It should be either a:
2674 //
2675 // 1. Path where a directory can be created.
2676 // 2. Path to an existing directory.
2677 // 3. Path to a symlink to a directory.
2678 // 4. For backwards compatibility, the name of a data file in -walletdir.
2679 const fs::path wallet_path =
2681 fs::file_type path_type = fs::symlink_status(wallet_path).type();
2682 if (!(path_type == fs::file_type::not_found ||
2683 path_type == fs::file_type::directory ||
2684 (path_type == fs::file_type::symlink &&
2685 fs::is_directory(wallet_path)) ||
2686 (path_type == fs::file_type::regular &&
2687 fs::PathFromString(name).filename() == fs::PathFromString(name)))) {
2688 error_string = Untranslated(
2689 strprintf("Invalid -wallet path '%s'. -wallet path should point to "
2690 "a directory where wallet.dat and "
2691 "database/log.?????????? files can be stored, a location "
2692 "where such a directory could be created, "
2693 "or (for backwards compatibility) the name of an "
2694 "existing data file in -walletdir (%s)",
2697 return nullptr;
2698 }
2699 return MakeDatabase(wallet_path, options, status, error_string);
2700}
2701
2702std::shared_ptr<CWallet>
2703CWallet::Create(interfaces::Chain *chain, const std::string &name,
2704 std::unique_ptr<WalletDatabase> database,
2705 uint64_t wallet_creation_flags, bilingual_str &error,
2706 std::vector<bilingual_str> &warnings) {
2707 const std::string &walletFile = database->Filename();
2708
2709 int64_t nStart = GetTimeMillis();
2710 // TODO: Can't use std::make_shared because we need a custom deleter but
2711 // should be possible to use std::allocate_shared.
2712 std::shared_ptr<CWallet> walletInstance(
2713 new CWallet(chain, name, std::move(database)), ReleaseWallet);
2714 DBErrors nLoadWalletRet = walletInstance->LoadWallet();
2715 if (nLoadWalletRet != DBErrors::LOAD_OK) {
2716 if (nLoadWalletRet == DBErrors::CORRUPT) {
2717 error =
2718 strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
2719 return nullptr;
2720 }
2721
2722 if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR) {
2723 warnings.push_back(
2724 strprintf(_("Error reading %s! All keys read correctly, but "
2725 "transaction data or address book entries might be "
2726 "missing or incorrect."),
2727 walletFile));
2728 } else if (nLoadWalletRet == DBErrors::TOO_NEW) {
2729 error = strprintf(
2730 _("Error loading %s: Wallet requires newer version of %s"),
2731 walletFile, PACKAGE_NAME);
2732 return nullptr;
2733 } else if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
2734 error = strprintf(
2735 _("Wallet needed to be rewritten: restart %s to complete"),
2736 PACKAGE_NAME);
2737 return nullptr;
2738 } else {
2739 error = strprintf(_("Error loading %s"), walletFile);
2740 return nullptr;
2741 }
2742 }
2743
2744 // This wallet is in its first run if there are no ScriptPubKeyMans and it
2745 // isn't blank or no privkeys
2746 const bool fFirstRun =
2747 walletInstance->m_spk_managers.empty() &&
2748 !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2749 !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
2750 if (fFirstRun) {
2751 // Ensure this wallet.dat can only be opened by clients supporting
2752 // HD with chain split and expects no default key.
2753 walletInstance->SetMinVersion(FEATURE_LATEST);
2754
2755 walletInstance->AddWalletFlags(wallet_creation_flags);
2756
2757 // Only create LegacyScriptPubKeyMan when not descriptor wallet
2758 if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2759 walletInstance->SetupLegacyScriptPubKeyMan();
2760 }
2761
2762 if (!(wallet_creation_flags &
2764 LOCK(walletInstance->cs_wallet);
2765 if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2766 walletInstance->SetupDescriptorScriptPubKeyMans();
2767 // SetupDescriptorScriptPubKeyMans already calls SetupGeneration
2768 // for us so we don't need to call SetupGeneration separately
2769 } else {
2770 // Legacy wallets need SetupGeneration here.
2771 for (auto spk_man :
2772 walletInstance->GetActiveScriptPubKeyMans()) {
2773 if (!spk_man->SetupGeneration()) {
2774 error = _("Unable to generate initial keys");
2775 return nullptr;
2776 }
2777 }
2778 }
2779 }
2780
2781 if (chain) {
2782 walletInstance->chainStateFlushed(chain->getTipLocator());
2783 }
2784 } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
2785 // Make it impossible to disable private keys after creation
2786 error = strprintf(_("Error loading %s: Private keys can only be "
2787 "disabled during creation"),
2788 walletFile);
2789 return nullptr;
2790 } else if (walletInstance->IsWalletFlagSet(
2792 for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2793 if (spk_man->HavePrivateKeys()) {
2794 warnings.push_back(
2795 strprintf(_("Warning: Private keys detected in wallet {%s} "
2796 "with disabled private keys"),
2797 walletFile));
2798 }
2799 }
2800 }
2801
2802 if (gArgs.IsArgSet("-mintxfee")) {
2803 Amount n = Amount::zero();
2804 if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) ||
2805 n == Amount::zero()) {
2806 error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
2807 return nullptr;
2808 }
2809 if (n > HIGH_TX_FEE_PER_KB) {
2810 warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
2811 _("This is the minimum transaction fee you pay "
2812 "on every transaction."));
2813 }
2814 walletInstance->m_min_fee = CFeeRate(n);
2815 }
2816
2817 if (gArgs.IsArgSet("-maxapsfee")) {
2818 const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
2819 Amount n = Amount::zero();
2820 if (max_aps_fee == "-1") {
2821 n = -1 * SATOSHI;
2822 } else if (!ParseMoney(max_aps_fee, n)) {
2823 error = AmountErrMsg("maxapsfee", max_aps_fee);
2824 return nullptr;
2825 }
2826 if (n > HIGH_APS_FEE) {
2827 warnings.push_back(
2828 AmountHighWarn("-maxapsfee") + Untranslated(" ") +
2829 _("This is the maximum transaction fee you pay (in addition to"
2830 " the normal fee) to prioritize partial spend avoidance over"
2831 " regular coin selection."));
2832 }
2833 walletInstance->m_max_aps_fee = n;
2834 }
2835
2836 if (gArgs.IsArgSet("-fallbackfee")) {
2837 Amount nFeePerK = Amount::zero();
2838 if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
2839 error =
2840 strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"),
2841 gArgs.GetArg("-fallbackfee", ""));
2842 return nullptr;
2843 }
2844 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2845 warnings.push_back(AmountHighWarn("-fallbackfee") +
2846 Untranslated(" ") +
2847 _("This is the transaction fee you may pay when "
2848 "fee estimates are not available."));
2849 }
2850 walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
2851 }
2852 // Disable fallback fee in case value was set to 0, enable if non-null value
2853 walletInstance->m_allow_fallback_fee =
2854 walletInstance->m_fallback_fee.GetFeePerK() != Amount::zero();
2855
2856 if (gArgs.IsArgSet("-paytxfee")) {
2857 Amount nFeePerK = Amount::zero();
2858 if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
2859 error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
2860 return nullptr;
2861 }
2862 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2863 warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
2864 _("This is the transaction fee you will pay if "
2865 "you send a transaction."));
2866 }
2867 walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
2868 if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
2869 error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' "
2870 "(must be at least %s)"),
2871 gArgs.GetArg("-paytxfee", ""),
2873 return nullptr;
2874 }
2875 }
2876
2877 if (gArgs.IsArgSet("-maxtxfee")) {
2878 Amount nMaxFee = Amount::zero();
2879 if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
2880 error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
2881 return nullptr;
2882 }
2883 if (nMaxFee > HIGH_MAX_TX_FEE) {
2884 warnings.push_back(_("-maxtxfee is set very high! Fees this large "
2885 "could be paid on a single transaction."));
2886 }
2887 if (chain && CFeeRate(nMaxFee, 1000) < chain->relayMinFee()) {
2888 error = strprintf(
2889 _("Invalid amount for -maxtxfee=<amount>: '%s' (must be at "
2890 "least the minrelay fee of %s to prevent stuck "
2891 "transactions)"),
2892 gArgs.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
2893 return nullptr;
2894 }
2895 walletInstance->m_default_max_tx_fee = nMaxFee;
2896 }
2897
2899 warnings.push_back(
2900 AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
2901 _("The wallet will avoid paying less than the minimum relay fee."));
2902 }
2903
2904 walletInstance->m_spend_zero_conf_change =
2905 gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
2906
2907 walletInstance->m_default_address_type = DEFAULT_ADDRESS_TYPE;
2908
2909 walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n",
2910 GetTimeMillis() - nStart);
2911
2912 // Try to top up keypool. No-op if the wallet is locked.
2913 walletInstance->TopUpKeyPool();
2914
2915 LOCK(walletInstance->cs_wallet);
2916
2917 if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
2918 return nullptr;
2919 }
2920
2921 {
2923 for (auto &load_wallet : g_load_wallet_fns) {
2924 load_wallet(interfaces::MakeWallet(walletInstance));
2925 }
2926 }
2927
2928 walletInstance->SetBroadcastTransactions(
2929 gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
2930
2931 {
2932 walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n",
2933 walletInstance->GetKeyPoolSize());
2934 walletInstance->WalletLogPrintf("mapWallet.size() = %u\n",
2935 walletInstance->mapWallet.size());
2936 walletInstance->WalletLogPrintf("m_address_book.size() = %u\n",
2937 walletInstance->m_address_book.size());
2938 }
2939
2940 return walletInstance;
2941}
2942
2943bool CWallet::AttachChain(const std::shared_ptr<CWallet> &walletInstance,
2945 std::vector<bilingual_str> &warnings) {
2946 LOCK(walletInstance->cs_wallet);
2947 // allow setting the chain if it hasn't been set already but prevent
2948 // changing it
2949 assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
2950 walletInstance->m_chain = &chain;
2951
2952 // Register wallet with validationinterface. It's done before rescan to
2953 // avoid missing block connections between end of rescan and validation
2954 // subscribing. Because of wallet lock being hold, block connection
2955 // notifications are going to be pending on the validation-side until lock
2956 // release. It's likely to have block processing duplicata (if rescan block
2957 // range overlaps with notification one) but we guarantee at least than
2958 // wallet state is correct after notifications delivery. This is temporary
2959 // until rescan and notifications delivery are unified under same interface.
2960 walletInstance->m_chain_notifications_handler =
2961 walletInstance->chain().handleNotifications(walletInstance);
2962
2963 int rescan_height = 0;
2964 if (!gArgs.GetBoolArg("-rescan", false)) {
2965 WalletBatch batch(*walletInstance->database);
2966 CBlockLocator locator;
2967 if (batch.ReadBestBlock(locator)) {
2968 if (const std::optional<int> fork_height =
2969 chain.findLocatorFork(locator)) {
2970 rescan_height = *fork_height;
2971 }
2972 }
2973 }
2974
2975 const std::optional<int> tip_height = chain.getHeight();
2976 if (tip_height) {
2977 walletInstance->m_last_block_processed =
2978 chain.getBlockHash(*tip_height);
2979 walletInstance->m_last_block_processed_height = *tip_height;
2980 } else {
2981 walletInstance->m_last_block_processed.SetNull();
2982 walletInstance->m_last_block_processed_height = -1;
2983 }
2984
2985 if (tip_height && *tip_height != rescan_height) {
2986 // Technically we could execute the code below in any case, but
2987 // performing the `while` loop below can make startup very slow, so only
2988 // check blocks on disk if necessary.
2990 int block_height = *tip_height;
2991 while (block_height > 0 &&
2992 chain.haveBlockOnDisk(block_height - 1) &&
2993 rescan_height != block_height) {
2994 --block_height;
2995 }
2996
2997 if (rescan_height != block_height) {
2998 // We can't rescan beyond blocks we don't have data for, stop
2999 // and throw an error. This might happen if a user uses an old
3000 // wallet within a pruned node or if they ran -disablewallet
3001 // for a longer time, then decided to re-enable
3002 // Exit early and print an error.
3003 // It also may happen if an assumed-valid chain is in use and
3004 // therefore not all block data is available.
3005 // If a block is pruned after this check, we will load
3006 // the wallet, but fail the rescan with a generic error.
3007
3008 error =
3010 ? _("Prune: last wallet synchronisation goes beyond "
3011 "pruned data. You need to -reindex (download the "
3012 "whole blockchain again in case of pruned node)")
3013 : strprintf(_("Error loading wallet. Wallet requires "
3014 "blocks to be downloaded, "
3015 "and software does not currently support "
3016 "loading wallets while "
3017 "blocks are being downloaded out of "
3018 "order when using assumeutxo "
3019 "snapshots. Wallet should be able to "
3020 "load successfully after "
3021 "node sync reaches height %s"),
3022 block_height);
3023 return false;
3024 }
3025 }
3026
3027 chain.initMessage(_("Rescanning...").translated);
3028 walletInstance->WalletLogPrintf(
3029 "Rescanning last %i blocks (from block %i)...\n",
3030 *tip_height - rescan_height, rescan_height);
3031
3032 // No need to read and scan block if block was created before our wallet
3033 // birthday (as adjusted for block time variability)
3034 std::optional<int64_t> time_first_key;
3035 for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
3036 int64_t time = spk_man->GetTimeFirstKey();
3037 if (!time_first_key || time < *time_first_key) {
3038 time_first_key = time;
3039 }
3040 }
3041 if (time_first_key) {
3043 *time_first_key - TIMESTAMP_WINDOW, rescan_height,
3044 FoundBlock().height(rescan_height));
3045 }
3046
3047 {
3048 WalletRescanReserver reserver(*walletInstance);
3049 if (!reserver.reserve() ||
3051 walletInstance
3052 ->ScanForWalletTransactions(
3053 chain.getBlockHash(rescan_height), rescan_height,
3054 {} /* max height */, reserver, true /* update */)
3055 .status)) {
3056 error = _("Failed to rescan the wallet during initialization");
3057 return false;
3058 }
3059 }
3060 walletInstance->chainStateFlushed(chain.getTipLocator());
3061 walletInstance->database->IncrementUpdateCounter();
3062 }
3063
3064 return true;
3065}
3066
3067const CAddressBookData *
3069 bool allow_change) const {
3070 const auto &address_book_it = m_address_book.find(dest);
3071 if (address_book_it == m_address_book.end()) {
3072 return nullptr;
3073 }
3074 if ((!allow_change) && address_book_it->second.IsChange()) {
3075 return nullptr;
3076 }
3077 return &address_book_it->second;
3078}
3079
3081 int prev_version = GetVersion();
3082 int nMaxVersion = version;
3083 // The -upgradewallet without argument case
3084 if (nMaxVersion == 0) {
3085 WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3086 nMaxVersion = FEATURE_LATEST;
3087 // permanently upgrade the wallet immediately
3089 } else {
3090 WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3091 }
3092
3093 if (nMaxVersion < GetVersion()) {
3094 error = _("Cannot downgrade wallet");
3095 return false;
3096 }
3097
3098 SetMaxVersion(nMaxVersion);
3099
3100 LOCK(cs_wallet);
3101
3102 // Do not upgrade versions to any version between HD_SPLIT and
3103 // FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
3104 int max_version = GetVersion();
3106 max_version >= FEATURE_HD_SPLIT &&
3107 max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
3108 error = _("Cannot upgrade a non HD split wallet without upgrading to "
3109 "support pre split keypool. Please use version 200300 or no "
3110 "version specified.");
3111 return false;
3112 }
3113
3114 for (auto spk_man : GetActiveScriptPubKeyMans()) {
3115 if (!spk_man->Upgrade(prev_version, error)) {
3116 return false;
3117 }
3118 }
3119
3120 return true;
3121}
3122
3124 LOCK(cs_wallet);
3125
3126 // Add wallet transactions that aren't already in a block to mempool.
3127 // Do this here as mempool requires genesis block to be loaded.
3129
3130 // Update wallet transactions with current mempool transactions.
3132}
3133
3134bool CWallet::BackupWallet(const std::string &strDest) const {
3135 return database->Backup(strDest);
3136}
3137
3139 nTime = GetTime();
3140 fInternal = false;
3141 m_pre_split = false;
3142}
3143
3144CKeyPool::CKeyPool(const CPubKey &vchPubKeyIn, bool internalIn) {
3145 nTime = GetTime();
3146 vchPubKey = vchPubKeyIn;
3147 fInternal = internalIn;
3148 m_pre_split = false;
3149}
3150
3153 if (wtx.isUnconfirmed() || wtx.isAbandoned()) {
3154 return 0;
3155 }
3156
3157 return (GetLastBlockHeight() - wtx.m_confirm.block_height + 1) *
3158 (wtx.isConflicted() ? -1 : 1);
3159}
3160
3163
3164 if (!wtx.IsCoinBase()) {
3165 return 0;
3166 }
3167 int chain_depth = GetTxDepthInMainChain(wtx);
3168 // coinbase tx should not be conflicted
3169 assert(chain_depth >= 0);
3170 return std::max(0, (COINBASE_MATURITY + 1) - chain_depth);
3171}
3172
3175
3176 // note GetBlocksToMaturity is 0 for non-coinbase tx
3177 return GetTxBlocksToMaturity(wtx) > 0;
3178}
3179
3181 return HasEncryptionKeys();
3182}
3183
3184bool CWallet::IsLocked() const {
3185 if (!IsCrypted()) {
3186 return false;
3187 }
3188 LOCK(cs_wallet);
3189 return vMasterKey.empty();
3190}
3191
3193 if (!IsCrypted()) {
3194 return false;
3195 }
3196
3197 {
3198 LOCK(cs_wallet);
3199 if (!vMasterKey.empty()) {
3200 memory_cleanse(vMasterKey.data(),
3201 vMasterKey.size() *
3202 sizeof(decltype(vMasterKey)::value_type));
3203 vMasterKey.clear();
3204 }
3205 }
3206
3207 NotifyStatusChanged(this);
3208 return true;
3209}
3210
3211bool CWallet::Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys) {
3212 {
3213 LOCK(cs_wallet);
3214 for (const auto &spk_man_pair : m_spk_managers) {
3215 if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn,
3216 accept_no_keys)) {
3217 return false;
3218 }
3219 }
3220 vMasterKey = vMasterKeyIn;
3221 }
3222 NotifyStatusChanged(this);
3223 return true;
3224}
3225
3226std::set<ScriptPubKeyMan *> CWallet::GetActiveScriptPubKeyMans() const {
3227 std::set<ScriptPubKeyMan *> spk_mans;
3228 for (bool internal : {false, true}) {
3229 for (OutputType t : OUTPUT_TYPES) {
3230 auto spk_man = GetScriptPubKeyMan(t, internal);
3231 if (spk_man) {
3232 spk_mans.insert(spk_man);
3233 }
3234 }
3235 }
3236 return spk_mans;
3237}
3238
3239std::set<ScriptPubKeyMan *> CWallet::GetAllScriptPubKeyMans() const {
3240 std::set<ScriptPubKeyMan *> spk_mans;
3241 for (const auto &spk_man_pair : m_spk_managers) {
3242 spk_mans.insert(spk_man_pair.second.get());
3243 }
3244 return spk_mans;
3245}
3246
3248 bool internal) const {
3249 const std::map<OutputType, ScriptPubKeyMan *> &spk_managers =
3251 std::map<OutputType, ScriptPubKeyMan *>::const_iterator it =
3252 spk_managers.find(type);
3253 if (it == spk_managers.end()) {
3255 "%s scriptPubKey Manager for output type %d does not exist\n",
3256 internal ? "Internal" : "External", static_cast<int>(type));
3257 return nullptr;
3258 }
3259 return it->second;
3260}
3261
3262std::set<ScriptPubKeyMan *>
3263CWallet::GetScriptPubKeyMans(const CScript &script,
3264 SignatureData &sigdata) const {
3265 std::set<ScriptPubKeyMan *> spk_mans;
3266 for (const auto &spk_man_pair : m_spk_managers) {
3267 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3268 spk_mans.insert(spk_man_pair.second.get());
3269 }
3270 }
3271 return spk_mans;
3272}
3273
3274ScriptPubKeyMan *CWallet::GetScriptPubKeyMan(const CScript &script) const {
3275 SignatureData sigdata;
3276 for (const auto &spk_man_pair : m_spk_managers) {
3277 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3278 return spk_man_pair.second.get();
3279 }
3280 }
3281 return nullptr;
3282}
3283
3285 if (m_spk_managers.count(id) > 0) {
3286 return m_spk_managers.at(id).get();
3287 }
3288 return nullptr;
3289}
3290
3291std::unique_ptr<SigningProvider>
3292CWallet::GetSolvingProvider(const CScript &script) const {
3293 SignatureData sigdata;
3294 return GetSolvingProvider(script, sigdata);
3295}
3296
3297std::unique_ptr<SigningProvider>
3298CWallet::GetSolvingProvider(const CScript &script,
3299 SignatureData &sigdata) const {
3300 for (const auto &spk_man_pair : m_spk_managers) {
3301 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3302 return spk_man_pair.second->GetSolvingProvider(script);
3303 }
3304 }
3305 return nullptr;
3306}
3307
3310 return nullptr;
3311 }
3312 // Legacy wallets only have one ScriptPubKeyMan which is a
3313 // LegacyScriptPubKeyMan. Everything in m_internal_spk_managers and
3314 // m_external_spk_managers point to the same legacyScriptPubKeyMan.
3316 if (it == m_internal_spk_managers.end()) {
3317 return nullptr;
3318 }
3319 return dynamic_cast<LegacyScriptPubKeyMan *>(it->second);
3320}
3321
3324 return GetLegacyScriptPubKeyMan();
3325}
3326
3328 if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() ||
3330 return;
3331 }
3332
3333 auto spk_manager =
3334 std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
3335 for (const auto &type : OUTPUT_TYPES) {
3336 m_internal_spk_managers[type] = spk_manager.get();
3337 m_external_spk_managers[type] = spk_manager.get();
3338 }
3339 m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
3340}
3341
3343 const std::function<bool(const CKeyingMaterial &)> &cb) const {
3344 LOCK(cs_wallet);
3345 return cb(vMasterKey);
3346}
3347
3349 return !mapMasterKeys.empty();
3350}
3351
3353 for (const auto &spk_man : GetActiveScriptPubKeyMans()) {
3354 spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
3355 spk_man->NotifyCanGetAddressesChanged.connect(
3357 }
3358}
3359
3361 WalletDescriptor &desc) {
3362 auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(
3363 new DescriptorScriptPubKeyMan(*this, desc));
3364 m_spk_managers[id] = std::move(spk_manager);
3365}
3366
3369
3370 // Make a seed
3371 CKey seed_key;
3372 seed_key.MakeNewKey(true);
3373 CPubKey seed = seed_key.GetPubKey();
3374 assert(seed_key.VerifyPubKey(seed));
3375
3376 // Get the extended key
3377 CExtKey master_key;
3378 master_key.SetSeed(seed_key);
3379
3380 for (bool internal : {false, true}) {
3381 for (OutputType t : OUTPUT_TYPES) {
3382 auto spk_manager =
3383 std::make_unique<DescriptorScriptPubKeyMan>(*this, internal);
3384 if (IsCrypted()) {
3385 if (IsLocked()) {
3386 throw std::runtime_error(
3387 std::string(__func__) +
3388 ": Wallet is locked, cannot setup new descriptors");
3389 }
3390 if (!spk_manager->CheckDecryptionKey(vMasterKey) &&
3391 !spk_manager->Encrypt(vMasterKey, nullptr)) {
3392 throw std::runtime_error(
3393 std::string(__func__) +
3394 ": Could not encrypt new descriptors");
3395 }
3396 }
3397 spk_manager->SetupDescriptorGeneration(master_key, t);
3398 uint256 id = spk_manager->GetID();
3399 m_spk_managers[id] = std::move(spk_manager);
3400 AddActiveScriptPubKeyMan(id, t, internal);
3401 }
3402 }
3403}
3404
3406 bool internal) {
3407 WalletBatch batch(*database);
3408 if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id,
3409 internal)) {
3410 throw std::runtime_error(std::string(__func__) +
3411 ": writing active ScriptPubKeyMan id failed");
3412 }
3413 LoadActiveScriptPubKeyMan(id, type, internal);
3414}
3415
3417 bool internal) {
3418 // Activating ScriptPubKeyManager for a given output and change type is
3419 // incompatible with legacy wallets.
3420 // Legacy wallets have only one ScriptPubKeyManager and it's active for all
3421 // output and change types.
3423
3425 "Setting spkMan to active: id = %s, type = %d, internal = %d\n",
3426 id.ToString(), static_cast<int>(type), static_cast<int>(internal));
3427 auto &spk_mans =
3429 auto &spk_mans_other =
3431 auto spk_man = m_spk_managers.at(id).get();
3432 spk_man->SetInternal(internal);
3433 spk_mans[type] = spk_man;
3434
3435 const auto it = spk_mans_other.find(type);
3436 if (it != spk_mans_other.end() && it->second == spk_man) {
3437 spk_mans_other.erase(type);
3438 }
3439
3441}
3442
3444 bool internal) {
3445 auto spk_man = GetScriptPubKeyMan(type, internal);
3446 if (spk_man != nullptr && spk_man->GetID() == id) {
3448 "Deactivate spkMan: id = %s, type = %d, internal = %d\n",
3449 id.ToString(), static_cast<int>(type), static_cast<int>(internal));
3450 WalletBatch batch(GetDatabase());
3451 if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type),
3452 internal)) {
3453 throw std::runtime_error(
3454 std::string(__func__) +
3455 ": erasing active ScriptPubKeyMan id failed");
3456 }
3457
3458 auto &spk_mans =
3460 spk_mans.erase(type);
3461 }
3462
3464}
3465
3466bool CWallet::IsLegacy() const {
3468 return false;
3469 }
3470 auto spk_man = dynamic_cast<LegacyScriptPubKeyMan *>(
3472 return spk_man != nullptr;
3473}
3474
3477 for (auto &spk_man_pair : m_spk_managers) {
3478 // Try to downcast to DescriptorScriptPubKeyMan then check if the
3479 // descriptors match
3480 DescriptorScriptPubKeyMan *spk_manager =
3481 dynamic_cast<DescriptorScriptPubKeyMan *>(
3482 spk_man_pair.second.get());
3483 if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3484 return spk_manager;
3485 }
3486 }
3487
3488 return nullptr;
3489}
3490
3493 const FlatSigningProvider &signing_provider,
3494 const std::string &label, bool internal) {
3496
3499 "Cannot add WalletDescriptor to a non-descriptor wallet\n");
3500 return nullptr;
3501 }
3502
3503 auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3504 if (spk_man) {
3505 WalletLogPrintf("Update existing descriptor: %s\n",
3506 desc.descriptor->ToString());
3507 spk_man->UpdateWalletDescriptor(desc);
3508 } else {
3509 auto new_spk_man =
3510 std::make_unique<DescriptorScriptPubKeyMan>(*this, desc);
3511 spk_man = new_spk_man.get();
3512
3513 // Save the descriptor to memory
3514 m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
3515 }
3516
3517 // Add the private keys to the descriptor
3518 for (const auto &entry : signing_provider.keys) {
3519 const CKey &key = entry.second;
3520 spk_man->AddDescriptorKey(key, key.GetPubKey());
3521 }
3522
3523 // Top up key pool, the manager will generate new scriptPubKeys internally
3524 if (!spk_man->TopUp()) {
3525 WalletLogPrintf("Could not top up scriptPubKeys\n");
3526 return nullptr;
3527 }
3528
3529 // Apply the label if necessary
3530 // Note: we disable labels for ranged descriptors
3531 if (!desc.descriptor->IsRange()) {
3532 auto script_pub_keys = spk_man->GetScriptPubKeys();
3533 if (script_pub_keys.empty()) {
3535 "Could not generate scriptPubKeys (cache is empty)\n");
3536 return nullptr;
3537 }
3538
3539 CTxDestination dest;
3540 if (!internal && ExtractDestination(script_pub_keys.at(0), dest)) {
3541 SetAddressBook(dest, label, "receive");
3542 }
3543 }
3544
3545 // Save the descriptor to DB
3546 spk_man->WriteDescriptor();
3547
3548 return spk_man;
3549}
bool MoneyRange(const Amount nValue)
Definition: amount.h:166
static constexpr Amount SATOSHI
Definition: amount.h:143
ArgsManager gArgs
Definition: args.cpp:38
int flags
Definition: bitcoin-tx.cpp:541
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:36
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:19
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
#define Assert(val)
Identity function.
Definition: check.h:84
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:381
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:494
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:556
Address book data.
Definition: wallet.h:199
BlockHash GetHash() const
Definition: block.cpp:11
BlockHash hashPrevBlock
Definition: block.h:27
bool IsNull() const
Definition: block.h:49
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:85
Encryption/decryption context with key information.
Definition: crypter.h:64
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< uint8_t > &vchCiphertext) const
Definition: crypter.cpp:79
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< uint8_t > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:41
bool Decrypt(const std::vector< uint8_t > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:100
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
std::string ToString() const
Definition: feerate.cpp:57
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
An encapsulated secp256k1 private key.
Definition: key.h:28
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:183
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:210
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:302
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
A key from a CWallet's keypool.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
CPubKey vchPubKey
The public key.
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
CKeyPool()
Definition: wallet.cpp:3138
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
Definition: crypter.h:31
std::vector< uint8_t > vchSalt
Definition: crypter.h:34
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:37
unsigned int nDeriveIterations
Definition: crypter.h:38
std::vector< uint8_t > vchCryptedKey
Definition: crypter.h:33
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxIn > vin
Definition: transaction.h:276
An encapsulated public key.
Definition: pubkey.h:31
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
bool IsNull() const
Definition: transaction.h:145
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:254
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3292
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:280
bool Lock()
Definition: wallet.cpp:3192
BlockHash GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1037
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script, SignatureData &sigdata) const
Get all of the ScriptPubKeyMans for a script given additional information in sigdata (populated by e....
Definition: wallet.cpp:3263
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:434
int GetTxBlocksToMaturity(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3161
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:705
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3352
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3405
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3327
bool AddDestData(WalletBatch &batch, const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, and saves it to disk When adding new fields,...
Definition: wallet.cpp:2615
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:873
const std::string GetDisplayName() const override
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
Definition: wallet.h:964
MasterKeyMap mapMasterKeys
Definition: wallet.h:413
TxItems wtxOrdered
Definition: wallet.h:439
int GetTxDepthInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:3151
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3173
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:867
RecursiveMutex cs_wallet
Definition: wallet.h:398
static std::shared_ptr< CWallet > Create(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database, uint64_t wallet_creation_flags, bilingual_str &error, std::vector< bilingual_str > &warnings)
Initializes the wallet, returns a new CWallet instance or a null pointer in case of an error.
Definition: wallet.cpp:2703
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: wallet.cpp:3211
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:882
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:975
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:457
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Create new DescriptorScriptPubKeyMans and add them to the wallet.
Definition: wallet.cpp:3367
WalletDatabase & GetDatabase() override
Definition: wallet.h:405
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:351
bool WithEncryptionKey(const std::function< bool(const CKeyingMaterial &)> &cb) const override
Pass the encryption key to cb().
Definition: wallet.cpp:3342
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3322
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:376
void DeactivateScriptPubKeyMan(const uint256 &id, OutputType type, bool internal)
Remove specified ScriptPubKeyMan from set of active SPK managers.
Definition: wallet.cpp:3443
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Look up a destination data tuple in the store, return true if found false otherwise.
Definition: wallet.cpp:2639
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3466
std::atomic< bool > fAbortRescan
Definition: wallet.h:261
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:382
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3416
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:855
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:1032
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:879
OutputType m_default_address_type
Definition: wallet.h:748
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet.
Definition: wallet.cpp:3476
static bool AttachChain(const std::shared_ptr< CWallet > &wallet, interfaces::Chain &chain, bilingual_str &error, std::vector< bilingual_str > &warnings)
Catch wallet up to current chain, scanning new blocks, updating the best block locator and m_last_blo...
Definition: wallet.cpp:2943
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3360
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3308
std::atomic< uint64_t > m_wallet_flags
Definition: wallet.h:338
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:410
int64_t nNextResend
Definition: wallet.h:276
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature
Definition: wallet.h:495
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:3134
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:2573
void WalletLogPrintfToBeContinued(std::string fmt, Params... parameters) const
Definition: wallet.h:980
std::unique_ptr< WalletDatabase > database
Internal database handle.
Definition: wallet.h:357
ScriptPubKeyMan * AddWalletDescriptor(WalletDescriptor &desc, const FlatSigningProvider &signing_provider, const std::string &label, bool internal) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a descriptor to the wallet, return a ScriptPubKeyMan & associated output type.
Definition: wallet.cpp:3492
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:3226
std::vector< std::string > GetDestValues(const std::string &prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get all destination values matching a prefix.
Definition: wallet.cpp:2658
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:870
bool IsLocked() const override
Definition: wallet.cpp:3184
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:377
std::atomic< double > m_scanning_progress
Definition: wallet.h:265
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet)
Definition: wallet.h:824
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2481
bool EraseDestData(WalletBatch &batch, const CTxDestination &dest, const std::string &key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:2625
boost::signals2::signal< void(CWallet *wallet, const TxId &txid, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:863
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3348
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > _database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:417
Amount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:760
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3080
bool fBroadcastTransactions
Definition: wallet.h:277
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3247
bool IsCrypted() const
Definition: wallet.cpp:3180
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3239
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:438
void LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, without saving it to disk.
Definition: wallet.cpp:2634
unsigned int nMasterKeyMaxID
Definition: wallet.h:414
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:604
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:3123
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3068
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
bool isAbandoned() const
Definition: transaction.h:279
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:99
CTransactionRef tx
Definition: transaction.h:160
bool isUnconfirmed() const
Definition: transaction.h:292
void setConflicted()
Definition: transaction.h:291
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet.
Definition: transaction.h:113
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: transaction.cpp:7
bool isConflicted() const
Definition: transaction.h:288
Confirmation m_confirm
Definition: transaction.h:191
TxId GetId() const
Definition: transaction.h:300
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: transaction.h:100
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node,...
Definition: transaction.h:119
void setAbandoned()
Definition: transaction.h:282
void setUnconfirmed()
Definition: transaction.h:295
bool fInMempool
Definition: transaction.h:141
unsigned int fTimeReceivedIsTxTime
Definition: transaction.h:101
bool isConfirmed() const
Definition: transaction.h:296
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:263
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: transaction.h:139
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: transaction.h:122
bool InMempool() const
Definition: transaction.cpp:21
bool IsCoinBase() const
Definition: transaction.h:301
unsigned int nTimeReceived
time received by this node
Definition: transaction.h:103
int64_t nOrderPos
position in ordered transaction list
Definition: transaction.h:121
A UTXO entry.
Definition: coins.h:28
bool HasWalletDescriptor(const WalletDescriptor &desc) const
RecursiveMutex cs_KeyStore
Different type to mark Mutex at global scope.
Definition: sync.h:144
std::set< CKeyID > GetKeys() const override
A wrapper to reserve an address from a wallet.
Definition: wallet.h:161
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:174
OutputType const type
Definition: wallet.h:168
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from.
Definition: wallet.h:167
int64_t nIndex
The index of the address's key in the keypool.
Definition: wallet.h:170
CTxDestination address
The destination.
Definition: wallet.h:172
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:164
A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
virtual bool TopUp(unsigned int size=0)
Fills internal address pool.
virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool)
virtual void KeepDestination(int64_t index, const OutputType &type)
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
Signature hash type wrapper class.
Definition: sighashtype.h:37
void push_back(UniValue val)
Definition: univalue.cpp:96
bool isArray() const
Definition: univalue.h:110
@ VARR
Definition: univalue.h:32
void setArray()
Definition: univalue.cpp:86
size_t size() const
Definition: univalue.h:92
const std::vector< UniValue > & getValues() const
Access to the wallet database.
Definition: walletdb.h:175
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1112
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:213
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:154
bool WriteName(const CTxDestination &address, const std::string &strName)
Definition: walletdb.cpp:60
bool WritePurpose(const CTxDestination &address, const std::string &purpose)
Definition: walletdb.cpp:81
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:209
bool ErasePurpose(const CTxDestination &address)
Definition: walletdb.cpp:91
bool EraseDestData(const CTxDestination &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:1090
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:1104
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:186
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:193
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:220
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:99
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1108
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1116
bool EraseName(const CTxDestination &address)
Definition: walletdb.cpp:70
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:179
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut)
Definition: walletdb.cpp:1008
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:774
bool WriteDestData(const CTxDestination &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
Definition: walletdb.cpp:1077
Descriptor with some wallet metadata.
Definition: walletutil.h:80
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:82
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1110
bool isReserved() const
Definition: wallet.h:1130
uint8_t * begin()
Definition: uint256.h:85
std::string ToString() const
Definition: uint256.h:80
void SetNull()
Definition: uint256.h:41
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:123
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual BlockHash getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height,...
virtual bool broadcastTransaction(const Config &config, const CTransactionRef &tx, const Amount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
virtual double guessVerificationProgress(const BlockHash &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
virtual const CChainParams & params() const =0
This Chain's parameters.
virtual bool havePruned()=0
Check if any block has been pruned.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
virtual bool findAncestorByHeight(const BlockHash &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
virtual void initMessage(const std::string &message)=0
Send init message.
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void waitForNotificationsIfTipChanged(const BlockHash &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee settings).
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:48
256-bit opaque blob.
Definition: uint256.h:129
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
Definition: cleanse.cpp:14
const Config & GetConfig()
Definition: config.cpp:40
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule).
Definition: consensus.h:32
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:13
std::vector< uint8_t, secure_allocator< uint8_t > > CKeyingMaterial
Definition: crypter.h:57
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:12
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:49
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:53
TransactionError
Definition: error.h:22
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2451
void MarkDestinationsDirty(const std::set< CTxDestination > &destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks all outputs in each one of the destinations dirty, so their cache is reset and does not return ...
Definition: wallet.cpp:2374
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2297
void KeepDestination()
Keep the address.
Definition: wallet.cpp:2434
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2472
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2308
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2395
bool IsLockedCoin(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2466
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2096
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2456
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2256
DBErrors LoadWallet()
Definition: wallet.cpp:2173
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2110
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2005
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2443
bool GetNewChangeDestination(const OutputType type, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:2347
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2461
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2318
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:2229
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, SigHashType sighash_type=SigHashType().withForkId(), bool sign=true, bool bip32derivs=true) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2052
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:2413
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:2364
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2263
bool GetNewDestination(const OutputType type, const std::string label, CTxDestination &dest, std::string &error)
Definition: wallet.cpp:2327
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2197
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string > > orderForm, bool broadcast=true)
Add the transaction to the wallet and maybe attempt to broadcast it.
Definition: wallet.cpp:2126
bool AddWalletFlags(uint64_t flags)
Overwrite all flags by the given uint64_t.
Definition: wallet.cpp:1534
bool ImportPubKeys(const std::vector< CKeyID > &ordered_pubkeys, const std::map< CKeyID, CPubKey > &pubkey_map, const std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > &key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1609
void blockConnected(const CBlock &block, int height) override
Definition: wallet.cpp:1356
bool LoadToWallet(const TxId &txid, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1048
void MarkConflicted(const BlockHash &hashBlock, int conflicting_height, const TxId &txid)
Mark a transaction (and its in-wallet descendants) as conflicting with a particular block.
Definition: wallet.cpp:1231
void Flush()
Flush wallet (bitdb flush)
Definition: wallet.cpp:606
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:404
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:558
std::set< TxId > GetConflicts(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get wallet transactions that conflict with given transaction (spend same outputs)
Definition: wallet.cpp:571
void MarkDirty()
Definition: wallet.cpp:896
bool SubmitTxMemoryPoolAndRelay(const CWalletTx &wtx, std::string &err_string, bool relay) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Pass this transaction to node for mempool insertion and relay to peers if flag set to true.
Definition: wallet.cpp:1883
void AddToSpends(const COutPoint &outpoint, const TxId &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:684
void SyncTransaction(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Used by TransactionAddedToMemorypool/BlockConnected/Disconnected/ScanForWalletTransactions.
Definition: wallet.cpp:1288
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1589
CWalletTx * AddToWallet(CTransactionRef tx, const CWalletTx::Confirmation &confirm, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true)
Definition: wallet.cpp:954
bool HasWalletSpend(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Check if a given transaction has any of its outputs spent by another transaction in the wallet.
Definition: wallet.cpp:600
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:448
void BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(void SetWalletFlag(uint64_t flags)
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1492
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1451
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1599
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1426
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1523
bool ImportScriptPubKeys(const std::string &label, const std::set< CScript > &script_pub_keys, const bool have_solving_data, const bool apply_label, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1623
bool CanGetAddresses(bool internal=false) const
Returns true if the wallet can give out new addresses.
Definition: wallet.cpp:1478
ScanResult ScanForWalletTransactions(const BlockHash &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1709
bool IsSpentKey(const TxId &txid, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:927
bool TransactionCanBeAbandoned(const TxId &txid) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1156
const CChainParams & GetChainParams() const override
Definition: wallet.cpp:388
Amount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
Definition: wallet.cpp:1405
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction's inputs dirty, thus forcing the outputs to be recomputed.
Definition: wallet.cpp:1163
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, CWalletTx::Confirmation confirm, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1099
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction, spends it:
Definition: wallet.cpp:663
void ReacceptWalletTransactions() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1850
bool IsHDEnabled() const
Definition: wallet.cpp:1469
void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag)
Unsets a wallet flag and saves it to disk.
Definition: wallet.cpp:1506
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:614
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:708
void updatedBlockTip() override
Definition: wallet.cpp:1388
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1501
void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override
Definition: wallet.cpp:1314
bool IsWalletFlagSet(uint64_t flag) const override
Check if a certain wallet flag is set.
Definition: wallet.cpp:1519
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1658
bool AbandonTransaction(const TxId &txid)
Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent.
Definition: wallet.cpp:1172
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1515
void SetSpentKeyState(WalletBatch &batch, const TxId &txid, unsigned int n, bool used, std::set< CTxDestination > &tx_destinations) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:903
void transactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence) override
Definition: wallet.cpp:1301
DBErrors ReorderTransactions()
Definition: wallet.cpp:828
void blockDisconnected(const CBlock &block, int height) override
Definition: wallet.cpp:1371
void Close()
Close wallet database.
Definition: wallet.cpp:610
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:884
const CWalletTx * GetWalletTx(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:394
void ResendWalletTransactions()
Definition: wallet.cpp:1944
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr, bool fExplicit=false) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:530
std::set< TxId > GetTxConflicts(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1924
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
Definition: wallet.cpp:1548
void chainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:525
uint8_t isminefilter
Definition: wallet.h:42
isminetype
IsMine() return codes.
Definition: ismine.h:18
@ ISMINE_ALL
Definition: ismine.h:23
@ ISMINE_NO
Definition: ismine.h:19
bool error(const char *fmt, const Args &...args)
Definition: logging.h:263
SigningResult
Definition: message.h:47
@ PRIVATE_KEY_NOT_AVAILABLE
bool ParseMoney(const std::string &money_string, Amount &nRet)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:37
static auto quoted(const std::string &s)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:165
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:39
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:44
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48
const std::string & FormatOutputType(OutputType type)
Definition: outputtype.cpp:27
const std::array< OutputType, 1 > OUTPUT_TYPES
Definition: outputtype.cpp:17
OutputType
Definition: outputtype.h:16
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed.
Definition: psbt.cpp:160
void GetStrongRandBytes(Span< uint8_t > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:642
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition: random.h:85
const char * prefix
Definition: rest.cpp:817
const char * name
Definition: rest.cpp:47
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:55
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:198
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:331
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:421
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:419
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:10
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
Definition: key.h:167
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:382
std::optional< int > last_scanned_height
Definition: wallet.h:627
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:626
enum CWallet::ScanResult::@20 status
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:633
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:181
uint64_t create_flags
Definition: db.h:224
SecureString create_passphrase
Definition: db.h:225
std::map< CKeyID, CKey > keys
A structure for PSBTs which contain per-input information.
Definition: psbt.h:44
CTxOut utxo
Definition: psbt.h:45
A version of CTransaction with the PSBT format.
Definition: psbt.h:334
std::vector< PSBTInput > inputs
Definition: psbt.h:336
std::optional< CMutableTransaction > tx
Definition: psbt.h:335
A TxId is the identifier of a transaction.
Definition: txid.h:14
Bilingual messages:
Definition: translation.h:17
std::string translated
Definition: translation.h:19
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:43
static int count
Definition: tests.c:31
int64_t GetTimeMillis()
Returns the system time (not mockable)
Definition: time.cpp:101
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:109
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:152
@ BLOCK
Removed for block.
@ CONFLICT
Removed for conflict with in-block transaction.
@ CT_UPDATED
Definition: ui_change_type.h:9
@ CT_DELETED
Definition: ui_change_type.h:9
@ CT_NEW
Definition: ui_change_type.h:9
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1120
DatabaseStatus
Definition: db.h:229
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:21
constexpr Amount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:110
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: wallet.h:48
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:126
constexpr Amount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:113
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:104
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:128
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:105
constexpr Amount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:100
std::unique_ptr< interfaces::Handler > HandleLoadWallet(LoadWalletFn load_wallet)
Definition: wallet.cpp:167
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:121
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:186
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2671
const std::map< uint64_t, std::string > WALLET_FLAG_CAVEATS
Definition: wallet.cpp:44
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:1993
static std::vector< std::shared_ptr< CWallet > > vpwallets GUARDED_BY(cs_wallets)
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:202
static std::condition_variable g_wallet_release_cv
Definition: wallet.cpp:179
static GlobalMutex g_loading_wallet_mutex
Definition: wallet.cpp:177
RecursiveMutex cs_wallets
Definition: wallet.cpp:51
bool AddWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Add wallet name to persistent configuration so it will be loaded on startup.
Definition: wallet.cpp:55
bool RemoveWalletSetting(interfaces::Chain &chain, const std::string &wallet_name)
Remove wallet name from persistent configuration so it will not be loaded on startup.
Definition: wallet.cpp:70
static void UpdateWalletSetting(interfaces::Chain &chain, const std::string &wallet_name, std::optional< bool > load_on_startup, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:88
static GlobalMutex g_wallet_release_mutex
Definition: wallet.cpp:178
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:156
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:151
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:107
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:266
std::shared_ptr< CWallet > CreateWallet(interfaces::Chain &chain, const std::string &name, std::optional< bool > load_on_start, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:284
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:45
@ NONCRITICAL_ERROR
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:13
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:55
@ WALLET_FLAG_AVOID_REUSE
Definition: walletutil.h:47
@ WALLET_FLAG_KEY_ORIGIN_METADATA
Definition: walletutil.h:51
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:70
@ WALLET_FLAG_BLANK_WALLET
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses,...
Definition: walletutil.h:67
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:14
@ FEATURE_HD_SPLIT
Definition: walletutil.h:28
@ FEATURE_WALLETCRYPT
Definition: walletutil.h:20
@ FEATURE_PRE_SPLIT_KEYPOOL
Definition: walletutil.h:34
@ FEATURE_LATEST
Definition: walletutil.h:36