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