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