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