Bitcoin ABC 0.33.12
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 The Bitcoin Core developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <wallet/wallet.h>
7
8#include <chain.h>
9#include <chainparams.h>
10#include <common/args.h>
11#include <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 if (txin.prevout.GetN() >= wtx.tx->vout.size()) {
2150 return PSBTError::MISSING_INPUTS;
2151 }
2152 // Update UTXOs from the wallet.
2153 input.utxo = wtx.tx->vout[txin.prevout.GetN()];
2154 }
2155 }
2156 }
2157
2158 // Fill in information from ScriptPubKeyMans
2159 for (ScriptPubKeyMan *spk_man : GetAllScriptPubKeyMans()) {
2160 const auto error{
2161 spk_man->FillPSBT(psbtx, sighash_type, sign, bip32derivs)};
2162 if (error) {
2163 return error;
2164 }
2165 }
2166
2167 // Complete if every input is now signed
2168 complete = true;
2169 for (const auto &input : psbtx.inputs) {
2170 complete &= PSBTInputSigned(input);
2171 }
2172
2173 return {};
2174}
2175
2176SigningResult CWallet::SignMessage(const std::string &message,
2177 const PKHash &pkhash,
2178 std::string &str_sig) const {
2179 SignatureData sigdata;
2180 CScript script_pub_key = GetScriptForDestination(pkhash);
2181 for (const auto &spk_man_pair : m_spk_managers) {
2182 if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2183 LOCK(cs_wallet); // DescriptorScriptPubKeyMan calls IsLocked which
2184 // can lock cs_wallet in a deadlocking order
2185 return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2186 }
2187 }
2189}
2190
2192CWallet::TransactionChangeType(const std::optional<OutputType> &change_type,
2193 const std::vector<CRecipient> &vecSend) const {
2194 // If -changetype is specified, always use that change type.
2195 if (change_type) {
2196 return *change_type;
2197 }
2198
2199 // if m_default_address_type is legacy, use legacy address as change.
2201 return OutputType::LEGACY;
2202 }
2203
2204 // else use m_default_address_type for change
2206}
2207
2209 CTransactionRef tx, mapValue_t mapValue,
2210 std::vector<std::pair<std::string, std::string>> orderForm,
2211 bool broadcast) {
2212 LOCK(cs_wallet);
2213
2214 WalletLogPrintfToBeContinued("CommitTransaction:\n%s", tx->ToString());
2215
2216 // Add tx to wallet, because if it has change it's also ours, otherwise just
2217 // for transaction history.
2218 AddToWallet(tx, {}, [&](CWalletTx &wtx, bool new_tx) {
2219 CHECK_NONFATAL(wtx.mapValue.empty());
2220 CHECK_NONFATAL(wtx.vOrderForm.empty());
2221 wtx.mapValue = std::move(mapValue);
2222 wtx.vOrderForm = std::move(orderForm);
2223 wtx.fTimeReceivedIsTxTime = true;
2224 wtx.fFromMe = true;
2225 return true;
2226 });
2227
2228 // Notify that old coins are spent.
2229 for (const CTxIn &txin : tx->vin) {
2230 CWalletTx &coin = mapWallet.at(txin.prevout.GetTxId());
2231 coin.MarkDirty();
2233 }
2234
2235 // Get the inserted-CWalletTx from mapWallet so that the
2236 // fInMempool flag is cached properly
2237 CWalletTx &wtx = mapWallet.at(tx->GetId());
2238
2239 if (!broadcast || !fBroadcastTransactions) {
2240 // Don't submit tx to the mempool if the flag is unset for this single
2241 // transaction, or if the wallet doesn't broadcast transactions at all.
2242 return;
2243 }
2244
2245 std::string err_string;
2246 if (!SubmitTxMemoryPoolAndRelay(wtx, err_string, true)) {
2247 WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast "
2248 "immediately, %s\n",
2249 err_string);
2250 // TODO: if we expect the failure to be long term or permanent, instead
2251 // delete wtx from the wallet and return failure.
2252 }
2253}
2254
2256 LOCK(cs_wallet);
2257
2258 DBErrors nLoadWalletRet = WalletBatch(*database).LoadWallet(this);
2259 if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
2260 if (database->Rewrite("\x04pool")) {
2261 for (const auto &spk_man_pair : m_spk_managers) {
2262 spk_man_pair.second->RewriteDB();
2263 }
2264 }
2265 }
2266
2267 if (m_spk_managers.empty()) {
2270 }
2271
2272 if (nLoadWalletRet != DBErrors::LOAD_OK) {
2273 return nLoadWalletRet;
2274 }
2275
2276 return DBErrors::LOAD_OK;
2277}
2278
2279DBErrors CWallet::ZapSelectTx(std::vector<TxId> &txIdsIn,
2280 std::vector<TxId> &txIdsOut) {
2282 DBErrors nZapSelectTxRet =
2283 WalletBatch(*database).ZapSelectTx(txIdsIn, txIdsOut);
2284 for (const TxId &txid : txIdsOut) {
2285 const auto &it = mapWallet.find(txid);
2286 wtxOrdered.erase(it->second.m_it_wtxOrdered);
2287 for (const auto &txin : it->second.tx->vin) {
2288 mapTxSpends.erase(txin.prevout);
2289 }
2290 mapWallet.erase(it);
2292 }
2293
2294 if (nZapSelectTxRet == DBErrors::NEED_REWRITE) {
2295 if (database->Rewrite("\x04pool")) {
2296 for (const auto &spk_man_pair : m_spk_managers) {
2297 spk_man_pair.second->RewriteDB();
2298 }
2299 }
2300 }
2301
2302 if (nZapSelectTxRet != DBErrors::LOAD_OK) {
2303 return nZapSelectTxRet;
2304 }
2305
2306 MarkDirty();
2307
2308 return DBErrors::LOAD_OK;
2309}
2310
2312 const CTxDestination &address,
2313 const std::string &strName,
2314 const std::string &strPurpose) {
2315 bool fUpdated = false;
2316 bool is_mine;
2317 {
2318 LOCK(cs_wallet);
2319 std::map<CTxDestination, CAddressBookData>::iterator mi =
2320 m_address_book.find(address);
2321 fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
2322 m_address_book[address].SetLabel(strName);
2323 // Update purpose only if requested.
2324 if (!strPurpose.empty()) {
2325 m_address_book[address].purpose = strPurpose;
2326 }
2327 is_mine = IsMine(address) != ISMINE_NO;
2328 }
2329
2330 NotifyAddressBookChanged(this, address, strName, is_mine, strPurpose,
2331 (fUpdated ? CT_UPDATED : CT_NEW));
2332 if (!strPurpose.empty() && !batch.WritePurpose(address, strPurpose)) {
2333 return false;
2334 }
2335 return batch.WriteName(address, strName);
2336}
2337
2339 const std::string &strName,
2340 const std::string &strPurpose) {
2341 WalletBatch batch(*database);
2342 return SetAddressBookWithDB(batch, address, strName, strPurpose);
2343}
2344
2346 bool is_mine;
2347 WalletBatch batch(*database);
2348 {
2349 LOCK(cs_wallet);
2350 // If we want to delete receiving addresses, we need to take care that
2351 // DestData "used" (and possibly newer DestData) gets preserved (and the
2352 // "deleted" address transformed into a change entry instead of actually
2353 // being deleted)
2354 // NOTE: This isn't a problem for sending addresses because they never
2355 // have any DestData yet! When adding new DestData, it should be
2356 // considered here whether to retain or delete it (or move it?).
2357 if (IsMine(address)) {
2359 "%s called with IsMine address, NOT SUPPORTED. Please "
2360 "report this bug! %s\n",
2361 __func__, PACKAGE_BUGREPORT);
2362 return false;
2363 }
2364 // Delete destdata tuples associated with address
2365 for (const std::pair<const std::string, std::string> &item :
2366 m_address_book[address].destdata) {
2367 batch.EraseDestData(address, item.first);
2368 }
2369 m_address_book.erase(address);
2370 is_mine = IsMine(address) != ISMINE_NO;
2371 }
2372
2373 NotifyAddressBookChanged(this, address, "", is_mine, "", CT_DELETED);
2374
2375 batch.ErasePurpose(address);
2376 return batch.EraseName(address);
2377}
2378
2381
2382 unsigned int count = 0;
2383 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2384 count += spk_man->KeypoolCountExternalKeys();
2385 }
2386
2387 return count;
2388}
2389
2390unsigned int CWallet::GetKeyPoolSize() const {
2392
2393 unsigned int count = 0;
2394 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2395 count += spk_man->GetKeyPoolSize();
2396 }
2397 return count;
2398}
2399
2400bool CWallet::TopUpKeyPool(unsigned int kpSize) {
2401 LOCK(cs_wallet);
2402 bool res = true;
2403 for (auto spk_man : GetActiveScriptPubKeyMans()) {
2404 res &= spk_man->TopUp(kpSize);
2405 }
2406 return res;
2407}
2408
2410CWallet::GetNewDestination(const OutputType type, const std::string &label) {
2411 LOCK(cs_wallet);
2412 auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
2413 if (!spk_man) {
2414 return util::Error{strprintf(_("Error: No %s addresses available."),
2415 FormatOutputType(type))};
2416 }
2417 spk_man->TopUp();
2418 auto op_dest = spk_man->GetNewDestination(type);
2419 if (op_dest) {
2420 SetAddressBook(*op_dest, label, "receive");
2421 }
2422
2423 return op_dest;
2424}
2425
2428 LOCK(cs_wallet);
2429
2430 CTxDestination dest;
2431 ReserveDestination reservedest(this, type);
2432 if (!reservedest.GetReservedDestination(dest, true)) {
2433 return util::Error{
2434 _("Error: Keypool ran out, please call keypoolrefill first")};
2435 }
2436
2437 reservedest.KeepDestination();
2438 return dest;
2439}
2440
2442 LOCK(cs_wallet);
2443 int64_t oldestKey = std::numeric_limits<int64_t>::max();
2444 for (const auto &spk_man_pair : m_spk_managers) {
2445 oldestKey =
2446 std::min(oldestKey, spk_man_pair.second->GetOldestKeyPoolTime());
2447 }
2448 return oldestKey;
2449}
2450
2452 const std::set<CTxDestination> &destinations) {
2453 for (auto &entry : mapWallet) {
2454 CWalletTx &wtx = entry.second;
2455 if (wtx.m_is_cache_empty) {
2456 continue;
2457 }
2458
2459 for (size_t i = 0; i < wtx.tx->vout.size(); i++) {
2460 CTxDestination dst;
2461
2462 if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) &&
2463 destinations.count(dst)) {
2464 wtx.MarkDirty();
2465 break;
2466 }
2467 }
2468 }
2469}
2470
2471std::set<CTxDestination>
2472CWallet::GetLabelAddresses(const std::string &label) const {
2474 std::set<CTxDestination> result;
2475 for (const std::pair<const CTxDestination, CAddressBookData> &item :
2476 m_address_book) {
2477 if (item.second.IsChange()) {
2478 continue;
2479 }
2480 const CTxDestination &address = item.first;
2481 const std::string &strName = item.second.GetLabel();
2482 if (strName == label) {
2483 result.insert(address);
2484 }
2485 }
2486
2487 return result;
2488}
2489
2491 bool internal) {
2493 if (!m_spk_man) {
2494 return false;
2495 }
2496
2497 if (nIndex == -1) {
2498 m_spk_man->TopUp();
2499
2500 CKeyPool keypool;
2502 keypool)) {
2503 return false;
2504 }
2505 fInternal = keypool.fInternal;
2506 }
2507 dest = address;
2508 return true;
2509}
2510
2512 if (nIndex != -1) {
2514 }
2515
2516 nIndex = -1;
2518}
2519
2521 if (nIndex != -1) {
2523 }
2524 nIndex = -1;
2526}
2527
2528void CWallet::LockCoin(const COutPoint &output) {
2530 setLockedCoins.insert(output);
2531}
2532
2533void CWallet::UnlockCoin(const COutPoint &output) {
2535 setLockedCoins.erase(output);
2536}
2537
2540 setLockedCoins.clear();
2541}
2542
2543bool CWallet::IsLockedCoin(const COutPoint &outpoint) const {
2545
2546 return setLockedCoins.count(outpoint) > 0;
2547}
2548
2549void CWallet::ListLockedCoins(std::vector<COutPoint> &vOutpts) const {
2551 for (COutPoint outpoint : setLockedCoins) {
2552 vOutpts.push_back(outpoint);
2553 }
2554}
2555 // end of Actions
2557
2558void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2560 mapKeyBirth.clear();
2561
2562 // map in which we'll infer heights of other keys
2563 std::map<CKeyID, const CWalletTx::Confirmation *> mapKeyFirstBlock;
2564 CWalletTx::Confirmation max_confirm;
2565 // the tip can be reorganized; use a 144-block safety margin
2566 max_confirm.block_height =
2567 GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0;
2568 CHECK_NONFATAL(chain().findAncestorByHeight(
2569 GetLastBlockHash(), max_confirm.block_height,
2570 FoundBlock().hash(max_confirm.hashBlock)));
2571
2572 {
2574 assert(spk_man != nullptr);
2575 LOCK(spk_man->cs_KeyStore);
2576
2577 // Get birth times for keys with metadata.
2578 for (const auto &entry : spk_man->mapKeyMetadata) {
2579 if (entry.second.nCreateTime) {
2580 mapKeyBirth[entry.first] = entry.second.nCreateTime;
2581 }
2582 }
2583
2584 // Prepare to infer birth heights for keys without metadata.
2585 for (const CKeyID &keyid : spk_man->GetKeys()) {
2586 if (mapKeyBirth.count(keyid) == 0) {
2587 mapKeyFirstBlock[keyid] = &max_confirm;
2588 }
2589 }
2590
2591 // If there are no such keys, we're done.
2592 if (mapKeyFirstBlock.empty()) {
2593 return;
2594 }
2595
2596 // Find first block that affects those keys, if there are any left.
2597 for (const auto &entry : mapWallet) {
2598 // iterate over all wallet transactions...
2599 const CWalletTx &wtx = entry.second;
2601 // ... which are already in a block
2602 for (const CTxOut &txout : wtx.tx->vout) {
2603 // Iterate over all their outputs...
2604 for (const auto &keyid :
2605 GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
2606 // ... and all their affected keys.
2607 auto rit = mapKeyFirstBlock.find(keyid);
2608 if (rit != mapKeyFirstBlock.end() &&
2610 rit->second->block_height) {
2611 rit->second = &wtx.m_confirm;
2612 }
2613 }
2614 }
2615 }
2616 }
2617 }
2618
2619 // Extract block timestamps for those keys.
2620 for (const auto &entry : mapKeyFirstBlock) {
2621 int64_t block_time;
2622 CHECK_NONFATAL(chain().findBlock(entry.second->hashBlock,
2623 FoundBlock().time(block_time)));
2624 // block times can be 2h off
2625 mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW;
2626 }
2627}
2628
2650unsigned int CWallet::ComputeTimeSmart(const CWalletTx &wtx) const {
2651 unsigned int nTimeSmart = wtx.nTimeReceived;
2652 if (!wtx.isUnconfirmed() && !wtx.isAbandoned()) {
2653 int64_t blocktime;
2654 if (chain().findBlock(wtx.m_confirm.hashBlock,
2655 FoundBlock().time(blocktime))) {
2656 int64_t latestNow = wtx.nTimeReceived;
2657 int64_t latestEntry = 0;
2658
2659 // Tolerate times up to the last timestamp in the wallet not more
2660 // than 5 minutes into the future
2661 int64_t latestTolerated = latestNow + 300;
2662 const TxItems &txOrdered = wtxOrdered;
2663 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2664 CWalletTx *const pwtx = it->second;
2665 if (pwtx == &wtx) {
2666 continue;
2667 }
2668 int64_t nSmartTime;
2669 nSmartTime = pwtx->nTimeSmart;
2670 if (!nSmartTime) {
2671 nSmartTime = pwtx->nTimeReceived;
2672 }
2673 if (nSmartTime <= latestTolerated) {
2674 latestEntry = nSmartTime;
2675 if (nSmartTime > latestNow) {
2676 latestNow = nSmartTime;
2677 }
2678 break;
2679 }
2680 }
2681
2682 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2683 } else {
2684 WalletLogPrintf("%s: found %s in block %s not in index\n", __func__,
2685 wtx.GetId().ToString(),
2687 }
2688 }
2689 return nTimeSmart;
2690}
2691
2693 const std::string &key, const std::string &value) {
2694 if (std::get_if<CNoDestination>(&dest)) {
2695 return false;
2696 }
2697
2698 m_address_book[dest].destdata.insert(std::make_pair(key, value));
2699 return batch.WriteDestData(dest, key, value);
2700}
2701
2703 const std::string &key) {
2704 if (!m_address_book[dest].destdata.erase(key)) {
2705 return false;
2706 }
2707
2708 return batch.EraseDestData(dest, key);
2709}
2710
2711void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key,
2712 const std::string &value) {
2713 m_address_book[dest].destdata.insert(std::make_pair(key, value));
2714}
2715
2716bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key,
2717 std::string *value) const {
2718 std::map<CTxDestination, CAddressBookData>::const_iterator i =
2719 m_address_book.find(dest);
2720 if (i != m_address_book.end()) {
2721 CAddressBookData::StringMap::const_iterator j =
2722 i->second.destdata.find(key);
2723 if (j != i->second.destdata.end()) {
2724 if (value) {
2725 *value = j->second;
2726 }
2727
2728 return true;
2729 }
2730 }
2731 return false;
2732}
2733
2734std::vector<std::string>
2735CWallet::GetDestValues(const std::string &prefix) const {
2736 std::vector<std::string> values;
2737 for (const auto &address : m_address_book) {
2738 for (const auto &data : address.second.destdata) {
2739 if (!data.first.compare(0, prefix.size(), prefix)) {
2740 values.emplace_back(data.second);
2741 }
2742 }
2743 }
2744 return values;
2745}
2746
2747std::unique_ptr<WalletDatabase>
2748MakeWalletDatabase(const std::string &name, const DatabaseOptions &options,
2749 DatabaseStatus &status, bilingual_str &error_string) {
2750 // Do some checking on wallet path. It should be either a:
2751 //
2752 // 1. Path where a directory can be created.
2753 // 2. Path to an existing directory.
2754 // 3. Path to a symlink to a directory.
2755 // 4. For backwards compatibility, the name of a data file in -walletdir.
2756 const fs::path wallet_path =
2758 fs::file_type path_type = fs::symlink_status(wallet_path).type();
2759 if (!(path_type == fs::file_type::not_found ||
2760 path_type == fs::file_type::directory ||
2761 (path_type == fs::file_type::symlink &&
2762 fs::is_directory(wallet_path)) ||
2763 (path_type == fs::file_type::regular &&
2764 fs::PathFromString(name).filename() == fs::PathFromString(name)))) {
2765 error_string = Untranslated(
2766 strprintf("Invalid -wallet path '%s'. -wallet path should point to "
2767 "a directory where wallet.dat and "
2768 "database/log.?????????? files can be stored, a location "
2769 "where such a directory could be created, "
2770 "or (for backwards compatibility) the name of an "
2771 "existing data file in -walletdir (%s)",
2774 return nullptr;
2775 }
2776 return MakeDatabase(wallet_path, options, status, error_string);
2777}
2778
2779std::shared_ptr<CWallet>
2780CWallet::Create(WalletContext &context, const std::string &name,
2781 std::unique_ptr<WalletDatabase> database,
2782 uint64_t wallet_creation_flags, bilingual_str &error,
2783 std::vector<bilingual_str> &warnings) {
2784 interfaces::Chain *chain = context.chain;
2785 const std::string &walletFile = database->Filename();
2786
2787 int64_t nStart = GetTimeMillis();
2788 // TODO: Can't use std::make_shared because we need a custom deleter but
2789 // should be possible to use std::allocate_shared.
2790 std::shared_ptr<CWallet> walletInstance(
2791 new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);
2792 DBErrors nLoadWalletRet = walletInstance->LoadWallet();
2793 if (nLoadWalletRet != DBErrors::LOAD_OK) {
2794 if (nLoadWalletRet == DBErrors::CORRUPT) {
2795 error =
2796 strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
2797 return nullptr;
2798 }
2799
2800 if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR) {
2801 warnings.push_back(
2802 strprintf(_("Error reading %s! All keys read correctly, but "
2803 "transaction data or address book entries might be "
2804 "missing or incorrect."),
2805 walletFile));
2806 } else if (nLoadWalletRet == DBErrors::TOO_NEW) {
2807 error = strprintf(
2808 _("Error loading %s: Wallet requires newer version of %s"),
2809 walletFile, PACKAGE_NAME);
2810 return nullptr;
2811 } else if (nLoadWalletRet == DBErrors::NEED_REWRITE) {
2812 error = strprintf(
2813 _("Wallet needed to be rewritten: restart %s to complete"),
2814 PACKAGE_NAME);
2815 return nullptr;
2816 } else {
2817 error = strprintf(_("Error loading %s"), walletFile);
2818 return nullptr;
2819 }
2820 }
2821
2822 // This wallet is in its first run if there are no ScriptPubKeyMans and it
2823 // isn't blank or no privkeys
2824 const bool fFirstRun =
2825 walletInstance->m_spk_managers.empty() &&
2826 !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2827 !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
2828 if (fFirstRun) {
2829 // Ensure this wallet.dat can only be opened by clients supporting
2830 // HD with chain split and expects no default key.
2831 walletInstance->SetMinVersion(FEATURE_LATEST);
2832
2833 walletInstance->AddWalletFlags(wallet_creation_flags);
2834
2835 // Only create LegacyScriptPubKeyMan when not descriptor wallet
2836 if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2837 walletInstance->SetupLegacyScriptPubKeyMan();
2838 }
2839
2840 if (!(wallet_creation_flags &
2842 LOCK(walletInstance->cs_wallet);
2843 if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2844 walletInstance->SetupDescriptorScriptPubKeyMans();
2845 // SetupDescriptorScriptPubKeyMans already calls SetupGeneration
2846 // for us so we don't need to call SetupGeneration separately
2847 } else {
2848 // Legacy wallets need SetupGeneration here.
2849 for (auto spk_man :
2850 walletInstance->GetActiveScriptPubKeyMans()) {
2851 if (!spk_man->SetupGeneration()) {
2852 error = _("Unable to generate initial keys");
2853 return nullptr;
2854 }
2855 }
2856 }
2857 }
2858
2859 if (chain) {
2860 walletInstance->chainStateFlushed(ChainstateRole::NORMAL,
2861 chain->getTipLocator());
2862 }
2863 } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
2864 // Make it impossible to disable private keys after creation
2865 error = strprintf(_("Error loading %s: Private keys can only be "
2866 "disabled during creation"),
2867 walletFile);
2868 return nullptr;
2869 } else if (walletInstance->IsWalletFlagSet(
2871 for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2872 if (spk_man->HavePrivateKeys()) {
2873 warnings.push_back(
2874 strprintf(_("Warning: Private keys detected in wallet {%s} "
2875 "with disabled private keys"),
2876 walletFile));
2877 }
2878 }
2879 }
2880
2881 if (gArgs.IsArgSet("-mintxfee")) {
2882 Amount n = Amount::zero();
2883 if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) ||
2884 n == Amount::zero()) {
2885 error = AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""));
2886 return nullptr;
2887 }
2888 if (n > HIGH_TX_FEE_PER_KB) {
2889 warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
2890 _("This is the minimum transaction fee you pay "
2891 "on every transaction."));
2892 }
2893 walletInstance->m_min_fee = CFeeRate(n);
2894 }
2895
2896 if (gArgs.IsArgSet("-maxapsfee")) {
2897 const std::string max_aps_fee{gArgs.GetArg("-maxapsfee", "")};
2898 Amount n = Amount::zero();
2899 if (max_aps_fee == "-1") {
2900 n = -1 * SATOSHI;
2901 } else if (!ParseMoney(max_aps_fee, n)) {
2902 error = AmountErrMsg("maxapsfee", max_aps_fee);
2903 return nullptr;
2904 }
2905 if (n > HIGH_APS_FEE) {
2906 warnings.push_back(
2907 AmountHighWarn("-maxapsfee") + Untranslated(" ") +
2908 _("This is the maximum transaction fee you pay (in addition to"
2909 " the normal fee) to prioritize partial spend avoidance over"
2910 " regular coin selection."));
2911 }
2912 walletInstance->m_max_aps_fee = n;
2913 }
2914
2915 if (gArgs.IsArgSet("-fallbackfee")) {
2916 Amount nFeePerK = Amount::zero();
2917 if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
2918 error =
2919 strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"),
2920 gArgs.GetArg("-fallbackfee", ""));
2921 return nullptr;
2922 }
2923 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2924 warnings.push_back(AmountHighWarn("-fallbackfee") +
2925 Untranslated(" ") +
2926 _("This is the transaction fee you may pay when "
2927 "fee estimates are not available."));
2928 }
2929 walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
2930 }
2931 // Disable fallback fee in case value was set to 0, enable if non-null value
2932 walletInstance->m_allow_fallback_fee =
2933 walletInstance->m_fallback_fee.GetFeePerK() != Amount::zero();
2934
2935 if (gArgs.IsArgSet("-paytxfee")) {
2936 Amount nFeePerK = Amount::zero();
2937 if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
2938 error = AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""));
2939 return nullptr;
2940 }
2941 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
2942 warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
2943 _("This is the transaction fee you will pay if "
2944 "you send a transaction."));
2945 }
2946 walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
2947 if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
2948 error = strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' "
2949 "(must be at least %s)"),
2950 gArgs.GetArg("-paytxfee", ""),
2952 return nullptr;
2953 }
2954 }
2955
2956 if (gArgs.IsArgSet("-maxtxfee")) {
2957 Amount nMaxFee = Amount::zero();
2958 if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
2959 error = AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""));
2960 return nullptr;
2961 }
2962 if (nMaxFee > HIGH_MAX_TX_FEE) {
2963 warnings.push_back(_("-maxtxfee is set very high! Fees this large "
2964 "could be paid on a single transaction."));
2965 }
2966 if (chain && CFeeRate(nMaxFee, 1000) < chain->relayMinFee()) {
2967 error = strprintf(
2968 _("Invalid amount for -maxtxfee=<amount>: '%s' (must be at "
2969 "least the minrelay fee of %s to prevent stuck "
2970 "transactions)"),
2971 gArgs.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
2972 return nullptr;
2973 }
2974 walletInstance->m_default_max_tx_fee = nMaxFee;
2975 }
2976
2978 warnings.push_back(
2979 AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
2980 _("The wallet will avoid paying less than the minimum relay fee."));
2981 }
2982
2983 walletInstance->m_spend_zero_conf_change =
2984 gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
2985
2986 walletInstance->m_default_address_type = DEFAULT_ADDRESS_TYPE;
2987
2988 walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n",
2989 GetTimeMillis() - nStart);
2990
2991 // Try to top up keypool. No-op if the wallet is locked.
2992 walletInstance->TopUpKeyPool();
2993
2994 if (chain && !AttachChain(walletInstance, *chain, error, warnings)) {
2995 // Reset this pointer so that the wallet will actually be unloaded
2996 walletInstance->m_chain_notifications_handler.reset();
2997 return nullptr;
2998 }
2999
3000 {
3001 LOCK(walletInstance->cs_wallet);
3002 walletInstance->SetBroadcastTransactions(
3003 gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3004 walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n",
3005 walletInstance->GetKeyPoolSize());
3006 walletInstance->WalletLogPrintf("mapWallet.size() = %u\n",
3007 walletInstance->mapWallet.size());
3008 walletInstance->WalletLogPrintf("m_address_book.size() = %u\n",
3009 walletInstance->m_address_book.size());
3010 }
3011
3012 return walletInstance;
3013}
3014
3015bool CWallet::AttachChain(const std::shared_ptr<CWallet> &walletInstance,
3016 interfaces::Chain &chain, bilingual_str &error,
3017 std::vector<bilingual_str> &warnings) {
3018 LOCK(walletInstance->cs_wallet);
3019 // allow setting the chain if it hasn't been set already but prevent
3020 // changing it
3021 assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
3022 walletInstance->m_chain = &chain;
3023
3024 // Register wallet with validationinterface. It's done before rescan to
3025 // avoid missing block connections between end of rescan and validation
3026 // subscribing. Because of wallet lock being hold, block connection
3027 // notifications are going to be pending on the validation-side until lock
3028 // release. It's likely to have block processing duplicata (if rescan block
3029 // range overlaps with notification one) but we guarantee at least than
3030 // wallet state is correct after notifications delivery.
3031 // However, chainStateFlushed notifications are ignored until the rescan
3032 // is finished so that in case of a shutdown event, the rescan will be
3033 // repeated at the next start.
3034 // This is temporary until rescan and notifications delivery are unified
3035 // under same interface.
3036 walletInstance->m_attaching_chain = true;
3037 walletInstance->m_chain_notifications_handler =
3038 walletInstance->chain().handleNotifications(walletInstance);
3039
3040 int rescan_height = 0;
3041 if (!gArgs.GetBoolArg("-rescan", false)) {
3042 WalletBatch batch(*walletInstance->database);
3043 CBlockLocator locator;
3044 if (batch.ReadBestBlock(locator)) {
3045 if (const std::optional<int> fork_height =
3046 chain.findLocatorFork(locator)) {
3047 rescan_height = *fork_height;
3048 }
3049 }
3050 }
3051
3052 const std::optional<int> tip_height = chain.getHeight();
3053 if (tip_height) {
3054 walletInstance->m_last_block_processed =
3055 chain.getBlockHash(*tip_height);
3056 walletInstance->m_last_block_processed_height = *tip_height;
3057 } else {
3058 walletInstance->m_last_block_processed.SetNull();
3059 walletInstance->m_last_block_processed_height = -1;
3060 }
3061
3062 if (tip_height && *tip_height != rescan_height) {
3063 // Technically we could execute the code below in any case, but
3064 // performing the `while` loop below can make startup very slow, so only
3065 // check blocks on disk if necessary.
3067 int block_height = *tip_height;
3068 while (block_height > 0 &&
3069 chain.haveBlockOnDisk(block_height - 1) &&
3070 rescan_height != block_height) {
3071 --block_height;
3072 }
3073
3074 if (rescan_height != block_height) {
3075 // We can't rescan beyond blocks we don't have data for, stop
3076 // and throw an error. This might happen if a user uses an old
3077 // wallet within a pruned node or if they ran -disablewallet
3078 // for a longer time, then decided to re-enable
3079 // Exit early and print an error.
3080 // It also may happen if an assumed-valid chain is in use and
3081 // therefore not all block data is available.
3082 // If a block is pruned after this check, we will load
3083 // the wallet, but fail the rescan with a generic error.
3084
3085 error =
3087 ? _("Prune: last wallet synchronisation goes beyond "
3088 "pruned data. You need to -reindex (download the "
3089 "whole blockchain again in case of pruned node)")
3090 : strprintf(_("Error loading wallet. Wallet requires "
3091 "blocks to be downloaded, "
3092 "and software does not currently support "
3093 "loading wallets while "
3094 "blocks are being downloaded out of "
3095 "order when using assumeutxo "
3096 "snapshots. Wallet should be able to "
3097 "load successfully after "
3098 "node sync reaches height %s"),
3099 block_height);
3100 return false;
3101 }
3102 }
3103
3104 chain.initMessage(_("Rescanning...").translated);
3105 walletInstance->WalletLogPrintf(
3106 "Rescanning last %i blocks (from block %i)...\n",
3107 *tip_height - rescan_height, rescan_height);
3108
3109 // No need to read and scan block if block was created before our wallet
3110 // birthday (as adjusted for block time variability)
3111 std::optional<int64_t> time_first_key;
3112 for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
3113 int64_t time = spk_man->GetTimeFirstKey();
3114 if (!time_first_key || time < *time_first_key) {
3115 time_first_key = time;
3116 }
3117 }
3118 if (time_first_key) {
3120 *time_first_key - TIMESTAMP_WINDOW, rescan_height,
3121 FoundBlock().height(rescan_height));
3122 }
3123
3124 {
3125 WalletRescanReserver reserver(*walletInstance);
3126 if (!reserver.reserve() ||
3128 walletInstance
3129 ->ScanForWalletTransactions(
3130 chain.getBlockHash(rescan_height), rescan_height,
3131 {} /* max height */, reserver, true /* update */)
3132 .status)) {
3133 error = _("Failed to rescan the wallet during initialization");
3134 return false;
3135 }
3136 }
3137 // The flag must be reset before calling chainStateFlushed
3138 walletInstance->m_attaching_chain = false;
3139 walletInstance->chainStateFlushed(ChainstateRole::NORMAL,
3141 walletInstance->database->IncrementUpdateCounter();
3142 }
3143 walletInstance->m_attaching_chain = false;
3144
3145 return true;
3146}
3147
3148const CAddressBookData *
3150 bool allow_change) const {
3151 const auto &address_book_it = m_address_book.find(dest);
3152 if (address_book_it == m_address_book.end()) {
3153 return nullptr;
3154 }
3155 if ((!allow_change) && address_book_it->second.IsChange()) {
3156 return nullptr;
3157 }
3158 return &address_book_it->second;
3159}
3160
3161bool CWallet::UpgradeWallet(int version, bilingual_str &error) {
3162 int prev_version = GetVersion();
3163 int nMaxVersion = version;
3164 // The -upgradewallet without argument case
3165 if (nMaxVersion == 0) {
3166 WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3167 nMaxVersion = FEATURE_LATEST;
3168 // permanently upgrade the wallet immediately
3170 } else {
3171 WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3172 }
3173
3174 if (nMaxVersion < GetVersion()) {
3175 error = _("Cannot downgrade wallet");
3176 return false;
3177 }
3178
3179 SetMaxVersion(nMaxVersion);
3180
3181 LOCK(cs_wallet);
3182
3183 // Do not upgrade versions to any version between HD_SPLIT and
3184 // FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
3185 int max_version = GetVersion();
3187 max_version >= FEATURE_HD_SPLIT &&
3188 max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
3189 error = _("Cannot upgrade a non HD split wallet without upgrading to "
3190 "support pre split keypool. Please use version 200300 or no "
3191 "version specified.");
3192 return false;
3193 }
3194
3195 for (auto spk_man : GetActiveScriptPubKeyMans()) {
3196 if (!spk_man->Upgrade(prev_version, error)) {
3197 return false;
3198 }
3199 }
3200
3201 return true;
3202}
3203
3205 LOCK(cs_wallet);
3206
3207 // Add wallet transactions that aren't already in a block to mempool.
3208 // Do this here as mempool requires genesis block to be loaded.
3210
3211 // Update wallet transactions with current mempool transactions.
3213}
3214
3215bool CWallet::BackupWallet(const std::string &strDest) const {
3216 if (m_chain) {
3217 CBlockLocator loc;
3218 WITH_LOCK(cs_wallet, chain().findBlock(m_last_block_processed,
3219 FoundBlock().locator(loc)));
3220 if (!loc.IsNull()) {
3221 WalletBatch batch(*database);
3222 batch.WriteBestBlock(loc);
3223 }
3224 }
3225 return database->Backup(strDest);
3226}
3227
3229 nTime = GetTime();
3230 fInternal = false;
3231 m_pre_split = false;
3232}
3233
3234CKeyPool::CKeyPool(const CPubKey &vchPubKeyIn, bool internalIn) {
3235 nTime = GetTime();
3236 vchPubKey = vchPubKeyIn;
3237 fInternal = internalIn;
3238 m_pre_split = false;
3239}
3240
3243 if (wtx.isUnconfirmed() || wtx.isAbandoned()) {
3244 return 0;
3245 }
3246
3247 return (GetLastBlockHeight() - wtx.m_confirm.block_height + 1) *
3248 (wtx.isConflicted() ? -1 : 1);
3249}
3250
3253
3254 if (!wtx.IsCoinBase()) {
3255 return 0;
3256 }
3257 int chain_depth = GetTxDepthInMainChain(wtx);
3258 // coinbase tx should not be conflicted
3259 assert(chain_depth >= 0);
3260 return std::max(0, (COINBASE_MATURITY + 1) - chain_depth);
3261}
3262
3265
3266 // note GetBlocksToMaturity is 0 for non-coinbase tx
3267 return GetTxBlocksToMaturity(wtx) > 0;
3268}
3269
3271 return HasEncryptionKeys();
3272}
3273
3274bool CWallet::IsLocked() const {
3275 if (!IsCrypted()) {
3276 return false;
3277 }
3278 LOCK(cs_wallet);
3279 return vMasterKey.empty();
3280}
3281
3283 if (!IsCrypted()) {
3284 return false;
3285 }
3286
3287 {
3288 LOCK(cs_wallet);
3289 if (!vMasterKey.empty()) {
3290 memory_cleanse(vMasterKey.data(),
3291 vMasterKey.size() *
3292 sizeof(decltype(vMasterKey)::value_type));
3293 vMasterKey.clear();
3294 }
3295 }
3296
3297 NotifyStatusChanged(this);
3298 return true;
3299}
3300
3301bool CWallet::Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys) {
3302 {
3303 LOCK(cs_wallet);
3304 for (const auto &spk_man_pair : m_spk_managers) {
3305 if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn,
3306 accept_no_keys)) {
3307 return false;
3308 }
3309 }
3310 vMasterKey = vMasterKeyIn;
3311 }
3312 NotifyStatusChanged(this);
3313 return true;
3314}
3315
3316std::set<ScriptPubKeyMan *> CWallet::GetActiveScriptPubKeyMans() const {
3317 std::set<ScriptPubKeyMan *> spk_mans;
3318 for (bool internal : {false, true}) {
3319 for (OutputType t : OUTPUT_TYPES) {
3320 auto spk_man = GetScriptPubKeyMan(t, internal);
3321 if (spk_man) {
3322 spk_mans.insert(spk_man);
3323 }
3324 }
3325 }
3326 return spk_mans;
3327}
3328
3329std::set<ScriptPubKeyMan *> CWallet::GetAllScriptPubKeyMans() const {
3330 std::set<ScriptPubKeyMan *> spk_mans;
3331 for (const auto &spk_man_pair : m_spk_managers) {
3332 spk_mans.insert(spk_man_pair.second.get());
3333 }
3334 return spk_mans;
3335}
3336
3338 bool internal) const {
3339 const std::map<OutputType, ScriptPubKeyMan *> &spk_managers =
3341 std::map<OutputType, ScriptPubKeyMan *>::const_iterator it =
3342 spk_managers.find(type);
3343 if (it == spk_managers.end()) {
3345 "%s scriptPubKey Manager for output type %d does not exist\n",
3346 internal ? "Internal" : "External", static_cast<int>(type));
3347 return nullptr;
3348 }
3349 return it->second;
3350}
3351
3352std::set<ScriptPubKeyMan *>
3354 SignatureData &sigdata) const {
3355 std::set<ScriptPubKeyMan *> spk_mans;
3356 for (const auto &spk_man_pair : m_spk_managers) {
3357 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3358 spk_mans.insert(spk_man_pair.second.get());
3359 }
3360 }
3361 return spk_mans;
3362}
3363
3365 SignatureData sigdata;
3366 for (const auto &spk_man_pair : m_spk_managers) {
3367 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3368 return spk_man_pair.second.get();
3369 }
3370 }
3371 return nullptr;
3372}
3373
3375 if (m_spk_managers.count(id) > 0) {
3376 return m_spk_managers.at(id).get();
3377 }
3378 return nullptr;
3379}
3380
3381std::unique_ptr<SigningProvider>
3383 SignatureData sigdata;
3384 return GetSolvingProvider(script, sigdata);
3385}
3386
3387std::unique_ptr<SigningProvider>
3389 SignatureData &sigdata) const {
3390 for (const auto &spk_man_pair : m_spk_managers) {
3391 if (spk_man_pair.second->CanProvide(script, sigdata)) {
3392 return spk_man_pair.second->GetSolvingProvider(script);
3393 }
3394 }
3395 return nullptr;
3396}
3397
3400 return nullptr;
3401 }
3402 // Legacy wallets only have one ScriptPubKeyMan which is a
3403 // LegacyScriptPubKeyMan. Everything in m_internal_spk_managers and
3404 // m_external_spk_managers point to the same legacyScriptPubKeyMan.
3406 if (it == m_internal_spk_managers.end()) {
3407 return nullptr;
3408 }
3409 return dynamic_cast<LegacyScriptPubKeyMan *>(it->second);
3410}
3411
3414 return GetLegacyScriptPubKeyMan();
3415}
3416
3418 if (!m_internal_spk_managers.empty() || !m_external_spk_managers.empty() ||
3420 return;
3421 }
3422
3423 auto spk_manager =
3424 std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this));
3425 for (const auto &type : OUTPUT_TYPES) {
3426 m_internal_spk_managers[type] = spk_manager.get();
3427 m_external_spk_managers[type] = spk_manager.get();
3428 }
3429 m_spk_managers[spk_manager->GetID()] = std::move(spk_manager);
3430}
3431
3433 const std::function<bool(const CKeyingMaterial &)> &cb) const {
3434 LOCK(cs_wallet);
3435 return cb(vMasterKey);
3436}
3437
3439 return !mapMasterKeys.empty();
3440}
3441
3443 for (const auto &spk_man : GetActiveScriptPubKeyMans()) {
3444 spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
3445 spk_man->NotifyCanGetAddressesChanged.connect(
3447 }
3448}
3449
3451 WalletDescriptor &desc) {
3452 auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(
3453 new DescriptorScriptPubKeyMan(*this, desc));
3454 m_spk_managers[id] = std::move(spk_manager);
3455}
3456
3459
3460 // Make a seed
3461 CKey seed_key;
3462 seed_key.MakeNewKey(true);
3463 CPubKey seed = seed_key.GetPubKey();
3464 assert(seed_key.VerifyPubKey(seed));
3465
3466 // Get the extended key
3467 CExtKey master_key;
3468 master_key.SetSeed(seed_key);
3469
3470 for (bool internal : {false, true}) {
3471 for (OutputType t : OUTPUT_TYPES) {
3472 auto spk_manager =
3473 std::make_unique<DescriptorScriptPubKeyMan>(*this, internal);
3474 if (IsCrypted()) {
3475 if (IsLocked()) {
3476 throw std::runtime_error(
3477 std::string(__func__) +
3478 ": Wallet is locked, cannot setup new descriptors");
3479 }
3480 if (!spk_manager->CheckDecryptionKey(vMasterKey) &&
3481 !spk_manager->Encrypt(vMasterKey, nullptr)) {
3482 throw std::runtime_error(
3483 std::string(__func__) +
3484 ": Could not encrypt new descriptors");
3485 }
3486 }
3487 spk_manager->SetupDescriptorGeneration(master_key, t);
3488 uint256 id = spk_manager->GetID();
3489 m_spk_managers[id] = std::move(spk_manager);
3490 AddActiveScriptPubKeyMan(id, t, internal);
3491 }
3492 }
3493}
3494
3496 bool internal) {
3497 WalletBatch batch(*database);
3498 if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id,
3499 internal)) {
3500 throw std::runtime_error(std::string(__func__) +
3501 ": writing active ScriptPubKeyMan id failed");
3502 }
3503 LoadActiveScriptPubKeyMan(id, type, internal);
3504}
3505
3507 bool internal) {
3508 // Activating ScriptPubKeyManager for a given output and change type is
3509 // incompatible with legacy wallets.
3510 // Legacy wallets have only one ScriptPubKeyManager and it's active for all
3511 // output and change types.
3513
3515 "Setting spkMan to active: id = %s, type = %d, internal = %d\n",
3516 id.ToString(), static_cast<int>(type), static_cast<int>(internal));
3517 auto &spk_mans =
3519 auto &spk_mans_other =
3521 auto spk_man = m_spk_managers.at(id).get();
3522 spk_man->SetInternal(internal);
3523 spk_mans[type] = spk_man;
3524
3525 const auto it = spk_mans_other.find(type);
3526 if (it != spk_mans_other.end() && it->second == spk_man) {
3527 spk_mans_other.erase(type);
3528 }
3529
3531}
3532
3534 bool internal) {
3535 auto spk_man = GetScriptPubKeyMan(type, internal);
3536 if (spk_man != nullptr && spk_man->GetID() == id) {
3538 "Deactivate spkMan: id = %s, type = %d, internal = %d\n",
3539 id.ToString(), static_cast<int>(type), static_cast<int>(internal));
3540 WalletBatch batch(GetDatabase());
3541 if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type),
3542 internal)) {
3543 throw std::runtime_error(
3544 std::string(__func__) +
3545 ": erasing active ScriptPubKeyMan id failed");
3546 }
3547
3548 auto &spk_mans =
3550 spk_mans.erase(type);
3551 }
3552
3554}
3555
3556bool CWallet::IsLegacy() const {
3558 return false;
3559 }
3560 auto spk_man = dynamic_cast<LegacyScriptPubKeyMan *>(
3562 return spk_man != nullptr;
3563}
3564
3567 for (auto &spk_man_pair : m_spk_managers) {
3568 // Try to downcast to DescriptorScriptPubKeyMan then check if the
3569 // descriptors match
3570 DescriptorScriptPubKeyMan *spk_manager =
3571 dynamic_cast<DescriptorScriptPubKeyMan *>(
3572 spk_man_pair.second.get());
3573 if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3574 return spk_manager;
3575 }
3576 }
3577
3578 return nullptr;
3579}
3580
3583 const FlatSigningProvider &signing_provider,
3584 const std::string &label, bool internal) {
3586
3589 "Cannot add WalletDescriptor to a non-descriptor wallet\n");
3590 return nullptr;
3591 }
3592
3593 auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3594 if (spk_man) {
3595 WalletLogPrintf("Update existing descriptor: %s\n",
3596 desc.descriptor->ToString());
3597 spk_man->UpdateWalletDescriptor(desc);
3598 } else {
3599 auto new_spk_man =
3600 std::make_unique<DescriptorScriptPubKeyMan>(*this, desc);
3601 spk_man = new_spk_man.get();
3602
3603 // Save the descriptor to memory
3604 m_spk_managers[new_spk_man->GetID()] = std::move(new_spk_man);
3605 }
3606
3607 // Add the private keys to the descriptor
3608 for (const auto &entry : signing_provider.keys) {
3609 const CKey &key = entry.second;
3610 spk_man->AddDescriptorKey(key, key.GetPubKey());
3611 }
3612
3613 // Top up key pool, the manager will generate new scriptPubKeys internally
3614 if (!spk_man->TopUp()) {
3615 WalletLogPrintf("Could not top up scriptPubKeys\n");
3616 return nullptr;
3617 }
3618
3619 // Apply the label if necessary
3620 // Note: we disable labels for ranged descriptors
3621 if (!desc.descriptor->IsRange()) {
3622 auto script_pub_keys = spk_man->GetScriptPubKeys();
3623 if (script_pub_keys.empty()) {
3625 "Could not generate scriptPubKeys (cache is empty)\n");
3626 return nullptr;
3627 }
3628
3629 CTxDestination dest;
3630 if (!internal && ExtractDestination(script_pub_keys.at(0), dest)) {
3631 SetAddressBook(dest, label, "receive");
3632 }
3633 }
3634
3635 // Save the descriptor to DB
3636 spk_man->WriteDescriptor();
3637
3638 return spk_man;
3639}
bool MoneyRange(const Amount nValue)
Definition: amount.h:177
static constexpr Amount SATOSHI
Definition: amount.h:153
ArgsManager gArgs
Definition: args.cpp:39
int flags
Definition: bitcoin-tx.cpp: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:83
#define Assert(val)
Identity function.
Definition: check.h:87
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:371
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:462
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:524
Address book data.
Definition: wallet.h:214
BlockHash GetHash() const
Definition: block.cpp:11
BlockHash hashPrevBlock
Definition: block.h:27
bool IsNull() const
Definition: block.h:49
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
Encryption/decryption context with key information.
Definition: crypter.h:64
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< uint8_t > &vchCiphertext) const
Definition: crypter.cpp:79
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< uint8_t > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:41
bool Decrypt(const std::vector< uint8_t > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:100
Fee rate in satoshis per kilobyte: Amount / kB.
Definition: feerate.h:21
std::string ToString() const
Definition: feerate.cpp:57
Amount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:54
An encapsulated secp256k1 private key.
Definition: key.h:28
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:182
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:209
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:301
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:22
A key from a CWallet's keypool.
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
CPubKey vchPubKey
The public key.
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
CKeyPool()
Definition: wallet.cpp:3228
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:3382
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:297
bool Lock()
Definition: wallet.cpp:3282
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:3353
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:3251
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:3442
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3495
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3417
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:2692
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:3241
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3263
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:3301
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:3457
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:3432
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3412
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:3533
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:2716
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3556
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:3506
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:3566
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:3015
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3450
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3398
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:3215
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:2650
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:3582
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:3316
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:2735
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:889
bool IsLocked() const override
Definition: wallet.cpp:3274
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:2558
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:2702
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:2780
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3438
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:3161
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:3337
bool IsCrypted() const
Definition: wallet.cpp:3270
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3329
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:2711
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:3204
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3149
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:65
bool isAbandoned() const
Definition: transaction.h:280
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:99
CTransactionRef tx
Definition: transaction.h:160
bool isUnconfirmed() const
Definition: transaction.h:293
void setConflicted()
Definition: transaction.h:292
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet.
Definition: transaction.h:113
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: transaction.cpp:7
bool isConflicted() const
Definition: transaction.h:289
Confirmation m_confirm
Definition: transaction.h:191
TxId GetId() const
Definition: transaction.h:301
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: transaction.h:100
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node,...
Definition: transaction.h:119
void setAbandoned()
Definition: transaction.h:283
void setUnconfirmed()
Definition: transaction.h:296
bool fInMempool
Definition: transaction.h:141
unsigned int fTimeReceivedIsTxTime
Definition: transaction.h:101
bool isConfirmed() const
Definition: transaction.h:297
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:264
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: transaction.h:139
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: transaction.h:122
bool InMempool() const
Definition: transaction.cpp:21
bool IsCoinBase() const
Definition: transaction.h:302
unsigned int nTimeReceived
time received by this node
Definition: transaction.h:103
int64_t nOrderPos
position in ordered transaction list
Definition: transaction.h:121
A UTXO entry.
Definition: coins.h:31
bool HasWalletDescriptor(const WalletDescriptor &desc) const
Fast randomness source.
Definition: random.h:411
RecursiveMutex cs_KeyStore
Different type to mark Mutex at global scope.
Definition: sync.h:144
std::set< CKeyID > GetKeys() const override
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:266
A wrapper to reserve an address from a wallet.
Definition: wallet.h:176
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:189
OutputType const type
Definition: wallet.h:183
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from.
Definition: wallet.h:182
int64_t nIndex
The index of the address's key in the keypool.
Definition: wallet.h:185
CTxDestination address
The destination.
Definition: wallet.h:187
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:179
A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
virtual bool TopUp(unsigned int size=0)
Fills internal address pool.
virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination &address, int64_t &index, CKeyPool &keypool)
virtual void KeepDestination(int64_t index, const OutputType &type)
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
Signature hash type wrapper class.
Definition: sighashtype.h:37
void push_back(UniValue val)
Definition: univalue.cpp:96
bool isArray() const
Definition: univalue.h:110
@ VARR
Definition: univalue.h:32
void setArray()
Definition: univalue.cpp:86
size_t size() const
Definition: univalue.h:92
const std::vector< UniValue > & getValues() const
Access to the wallet database.
Definition: walletdb.h:176
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1110
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:213
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:154
bool WriteName(const CTxDestination &address, const std::string &strName)
Definition: walletdb.cpp:60
bool WritePurpose(const CTxDestination &address, const std::string &purpose)
Definition: walletdb.cpp:81
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:209
bool ErasePurpose(const CTxDestination &address)
Definition: walletdb.cpp:91
bool EraseDestData(const CTxDestination &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:1088
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:1102
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:186
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:193
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:220
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:99
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1106
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1114
bool EraseName(const CTxDestination &address)
Definition: walletdb.cpp:70
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:179
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut)
Definition: walletdb.cpp:1006
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:774
bool WriteDestData(const CTxDestination &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
Definition: walletdb.cpp:1075
Descriptor with some wallet metadata.
Definition: walletutil.h:80
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:82
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1129
bool isReserved() const
Definition: wallet.h:1148
constexpr bool IsNull() const
Definition: uint256.h:40
constexpr uint8_t * begin()
Definition: uint256.h:89
std::string ToString() const
Definition: uint256.h:84
constexpr void SetNull()
Definition: uint256.h:45
std::string GetHex() const
Definition: uint256.cpp:10
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:136
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
virtual BlockHash getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
virtual bool findBlock(const BlockHash &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
virtual std::unique_ptr< Handler > handleNotifications(std::shared_ptr< Notifications > notifications)=0
Register handler for notifications.
virtual bool updateRwSetting(const std::string &name, const util::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
virtual bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock &block={})=0
Find first block in the chain with timestamp >= the given time and height >= than the given height,...
virtual bool broadcastTransaction(const Config &config, const CTransactionRef &tx, const Amount &max_tx_fee, bool relay, std::string &err_string)=0
Transaction is added to memory pool, if the transaction fee is below the amount specified by max_tx_f...
virtual util::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
virtual double guessVerificationProgress(const BlockHash &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
virtual const CChainParams & params() const =0
This Chain's parameters.
virtual bool havePruned()=0
Check if any block has been pruned.
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
virtual bool findAncestorByHeight(const BlockHash &block_hash, int ancestor_height, const FoundBlock &ancestor_out={})=0
Find ancestor of block at specified height and optionally return ancestor information.
virtual void initMessage(const std::string &message)=0
Send init message.
virtual std::optional< int > findLocatorFork(const CBlockLocator &locator)=0
Return height of the highest block on chain in common with the locator, which will either be the orig...
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send transactionAddedToMempool notifications about all current mempool transactions to ...
virtual void waitForNotificationsIfTipChanged(const BlockHash &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip.
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee settings).
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:55
256-bit opaque blob.
Definition: uint256.h:127
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:2528
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:2451
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2379
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:2410
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2427
void KeepDestination()
Keep the address.
Definition: wallet.cpp:2511
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2549
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2390
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2472
bool IsLockedCoin(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2543
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2176
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2533
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:2338
DBErrors LoadWallet()
Definition: wallet.cpp:2255
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2192
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2082
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2520
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2538
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2400
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::string &strPurpose)
Definition: wallet.cpp:2311
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
Definition: wallet.cpp:2490
int64_t GetOldestKeyPoolTime() const
Definition: wallet.cpp:2441
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2345
DBErrors ZapSelectTx(std::vector< TxId > &txIdsIn, std::vector< TxId > &txIdsOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2279
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:2208
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:41
PSBTError
Definition: types.h:17
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: messages.cpp:73
bilingual_str AmountHighWarn(const std::string &optname)
Definition: messages.cpp:69
static path u8path(const std::string &utf8_str)
Definition: fs.h:90
static auto quoted(const std::string &s)
Definition: fs.h:112
static bool exists(const path &p)
Definition: fs.h:107
static bool copy_file(const path &from, const path &to, copy_options options)
Definition: fs.h:124
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:170
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:39
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Definition: dummywallet.cpp:44
std::unique_ptr< Handler > MakeHandler(boost::signals2::connection connection)
Return handler wrapping a boost signal connection.
Definition: handler.cpp:48
void ReplaceAll(std::string &in_out, 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:200
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:333
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:423
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:421
SigningResult
Definition: signmessage.h:47
@ PRIVATE_KEY_NOT_AVAILABLE
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:23
static constexpr Amount zero() noexcept
Definition: amount.h:36
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:108
bool IsNull() const
Definition: block.h:135
Definition: key.h:167
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:381
std::optional< int > last_scanned_height
Definition: wallet.h:646
BlockHash last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:645
BlockHash last_failed_block
Hash of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:652
enum CWallet::ScanResult::@19 status
Confirmation includes tx status and a triplet of {block height/block hash/tx index in block} at which...
Definition: transaction.h:181
uint64_t create_flags
Definition: db.h:220
bool require_existing
Definition: db.h:218
SecureString create_passphrase
Definition: db.h:221
std::map< CKeyID, CKey > keys
A structure for PSBTs which contain per-input information.
Definition: psbt.h:44
CTxOut utxo
Definition: psbt.h:45
A version of CTransaction with the PSBT format.
Definition: psbt.h:334
std::vector< PSBTInput > inputs
Definition: psbt.h:336
std::optional< CMutableTransaction > tx
Definition: psbt.h:335
A TxId is the identifier of a transaction.
Definition: txid.h:14
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:35
Mutex wallets_mutex
Definition: context.h:42
interfaces::Chain * chain
Definition: context.h:36
Bilingual messages:
Definition: translation.h:17
bool empty() const
Definition: translation.h:27
#define WAIT_LOCK(cs, name)
Definition: sync.h: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:1203
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:159
@ BLOCK
Removed for block.
@ CONFLICT
Removed for conflict with in-block transaction.
@ CT_UPDATED
Definition: ui_change_type.h:9
@ CT_DELETED
Definition: ui_change_type.h:9
@ CT_NEW
Definition: ui_change_type.h:9
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: context.h:23
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1118
DatabaseStatus
Definition: db.h:225
@ FAILED_INVALID_BACKUP_FILE
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:21
constexpr Amount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:125
constexpr OutputType DEFAULT_ADDRESS_TYPE
Default for -addresstype.
Definition: wallet.h:141
constexpr Amount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:128
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:119
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:143
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:120
constexpr Amount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:115
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:177
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2748
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