Bitcoin Core  26.1.0
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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 #if defined(HAVE_CONFIG_H)
10 #endif
11 #include <addresstype.h>
12 #include <blockfilter.h>
13 #include <chain.h>
14 #include <coins.h>
15 #include <common/args.h>
16 #include <common/settings.h>
17 #include <common/system.h>
18 #include <consensus/amount.h>
19 #include <consensus/consensus.h>
20 #include <consensus/validation.h>
21 #include <external_signer.h>
22 #include <interfaces/chain.h>
23 #include <interfaces/handler.h>
24 #include <interfaces/wallet.h>
25 #include <kernel/chain.h>
27 #include <key.h>
28 #include <key_io.h>
29 #include <logging.h>
30 #include <outputtype.h>
31 #include <policy/feerate.h>
32 #include <primitives/block.h>
33 #include <primitives/transaction.h>
34 #include <psbt.h>
35 #include <pubkey.h>
36 #include <random.h>
37 #include <script/descriptor.h>
38 #include <script/interpreter.h>
39 #include <script/script.h>
40 #include <script/sign.h>
41 #include <script/signingprovider.h>
42 #include <script/solver.h>
43 #include <serialize.h>
44 #include <span.h>
45 #include <streams.h>
48 #include <support/cleanse.h>
49 #include <sync.h>
50 #include <tinyformat.h>
51 #include <uint256.h>
52 #include <univalue.h>
53 #include <util/check.h>
54 #include <util/error.h>
55 #include <util/fs.h>
56 #include <util/fs_helpers.h>
57 #include <util/message.h>
58 #include <util/moneystr.h>
59 #include <util/result.h>
60 #include <util/string.h>
61 #include <util/time.h>
62 #include <util/translation.h>
63 #include <wallet/coincontrol.h>
64 #include <wallet/context.h>
65 #include <wallet/crypter.h>
66 #include <wallet/db.h>
68 #include <wallet/scriptpubkeyman.h>
69 #include <wallet/transaction.h>
70 #include <wallet/types.h>
71 #include <wallet/walletdb.h>
72 #include <wallet/walletutil.h>
73 
74 #include <algorithm>
75 #include <cassert>
76 #include <condition_variable>
77 #include <exception>
78 #include <optional>
79 #include <stdexcept>
80 #include <thread>
81 #include <tuple>
82 #include <variant>
83 
84 struct KeyOriginInfo;
85 
87 
88 namespace wallet {
89 
90 bool AddWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
91 {
92  common::SettingsValue setting_value = chain.getRwSetting("wallet");
93  if (!setting_value.isArray()) setting_value.setArray();
94  for (const common::SettingsValue& value : setting_value.getValues()) {
95  if (value.isStr() && value.get_str() == wallet_name) return true;
96  }
97  setting_value.push_back(wallet_name);
98  return chain.updateRwSetting("wallet", setting_value);
99 }
100 
101 bool RemoveWalletSetting(interfaces::Chain& chain, const std::string& wallet_name)
102 {
103  common::SettingsValue setting_value = chain.getRwSetting("wallet");
104  if (!setting_value.isArray()) return true;
106  for (const common::SettingsValue& value : setting_value.getValues()) {
107  if (!value.isStr() || value.get_str() != wallet_name) new_value.push_back(value);
108  }
109  if (new_value.size() == setting_value.size()) return true;
110  return chain.updateRwSetting("wallet", new_value);
111 }
112 
114  const std::string& wallet_name,
115  std::optional<bool> load_on_startup,
116  std::vector<bilingual_str>& warnings)
117 {
118  if (!load_on_startup) return;
119  if (load_on_startup.value() && !AddWalletSetting(chain, wallet_name)) {
120  warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may not be loaded next node startup."));
121  } else if (!load_on_startup.value() && !RemoveWalletSetting(chain, wallet_name)) {
122  warnings.emplace_back(Untranslated("Wallet load on startup setting could not be updated, so wallet may still be loaded next node startup."));
123  }
124 }
125 
132 {
133  if (chain.isInMempool(tx.GetHash())) {
134  tx.m_state = TxStateInMempool();
135  } else if (tx.state<TxStateInMempool>()) {
136  tx.m_state = TxStateInactive();
137  }
138 }
139 
140 bool AddWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
141 {
143  assert(wallet);
144  std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
145  if (i != context.wallets.end()) return false;
146  context.wallets.push_back(wallet);
147  wallet->ConnectScriptPubKeyManNotifiers();
148  wallet->NotifyCanGetAddressesChanged();
149  return true;
150 }
151 
152 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start, std::vector<bilingual_str>& warnings)
153 {
154  assert(wallet);
155 
156  interfaces::Chain& chain = wallet->chain();
157  std::string name = wallet->GetName();
158 
159  // Unregister with the validation interface which also drops shared pointers.
160  wallet->m_chain_notifications_handler.reset();
162  std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(context.wallets.begin(), context.wallets.end(), wallet);
163  if (i == context.wallets.end()) return false;
164  context.wallets.erase(i);
165 
166  // Write the wallet setting
167  UpdateWalletSetting(chain, name, load_on_start, warnings);
168 
169  return true;
170 }
171 
172 bool RemoveWallet(WalletContext& context, const std::shared_ptr<CWallet>& wallet, std::optional<bool> load_on_start)
173 {
174  std::vector<bilingual_str> warnings;
175  return RemoveWallet(context, wallet, load_on_start, warnings);
176 }
177 
178 std::vector<std::shared_ptr<CWallet>> GetWallets(WalletContext& context)
179 {
181  return context.wallets;
182 }
183 
184 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count)
185 {
187  count = context.wallets.size();
188  return count == 1 ? context.wallets[0] : nullptr;
189 }
190 
191 std::shared_ptr<CWallet> GetWallet(WalletContext& context, const std::string& name)
192 {
194  for (const std::shared_ptr<CWallet>& wallet : context.wallets) {
195  if (wallet->GetName() == name) return wallet;
196  }
197  return nullptr;
198 }
199 
200 std::unique_ptr<interfaces::Handler> HandleLoadWallet(WalletContext& context, LoadWalletFn load_wallet)
201 {
203  auto it = context.wallet_load_fns.emplace(context.wallet_load_fns.end(), std::move(load_wallet));
204  return interfaces::MakeCleanupHandler([&context, it] { LOCK(context.wallets_mutex); context.wallet_load_fns.erase(it); });
205 }
206 
207 void NotifyWalletLoaded(WalletContext& context, const std::shared_ptr<CWallet>& wallet)
208 {
210  for (auto& load_wallet : context.wallet_load_fns) {
211  load_wallet(interfaces::MakeWallet(context, wallet));
212  }
213 }
214 
217 static std::condition_variable g_wallet_release_cv;
218 static std::set<std::string> g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex);
219 static std::set<std::string> g_unloading_wallet_set GUARDED_BY(g_wallet_release_mutex);
220 
221 // Custom deleter for shared_ptr<CWallet>.
223 {
224  const std::string name = wallet->GetName();
225  wallet->WalletLogPrintf("Releasing wallet\n");
226  wallet->Flush();
227  delete wallet;
228  // Wallet is now released, notify UnloadWallet, if any.
229  {
231  if (g_unloading_wallet_set.erase(name) == 0) {
232  // UnloadWallet was not called for this wallet, all done.
233  return;
234  }
235  }
236  g_wallet_release_cv.notify_all();
237 }
238 
239 void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
240 {
241  // Mark wallet for unloading.
242  const std::string name = wallet->GetName();
243  {
245  auto it = g_unloading_wallet_set.insert(name);
246  assert(it.second);
247  }
248  // The wallet can be in use so it's not possible to explicitly unload here.
249  // Notify the unload intent so that all remaining shared pointers are
250  // released.
251  wallet->NotifyUnload();
252 
253  // Time to ditch our shared_ptr and wait for ReleaseWallet call.
254  wallet.reset();
255  {
257  while (g_unloading_wallet_set.count(name) == 1) {
258  g_wallet_release_cv.wait(lock);
259  }
260  }
261 }
262 
263 namespace {
264 std::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)
265 {
266  try {
267  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
268  if (!database) {
269  error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
270  return nullptr;
271  }
272 
273  context.chain->initMessage(_("Loading wallet…").translated);
274  std::shared_ptr<CWallet> wallet = CWallet::Create(context, name, std::move(database), options.create_flags, error, warnings);
275  if (!wallet) {
276  error = Untranslated("Wallet loading failed.") + Untranslated(" ") + error;
278  return nullptr;
279  }
280 
281  // Legacy wallets are being deprecated, warn if the loaded wallet is legacy
282  if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
283  warnings.push_back(_("Wallet loaded successfully. The legacy wallet type is being deprecated and support for creating and opening legacy wallets will be removed in the future. Legacy wallets can be migrated to a descriptor wallet with migratewallet."));
284  }
285 
288  wallet->postInitProcess();
289 
290  // Write the wallet setting
291  UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
292 
293  return wallet;
294  } catch (const std::runtime_error& e) {
295  error = Untranslated(e.what());
297  return nullptr;
298  }
299 }
300 
301 class FastWalletRescanFilter
302 {
303 public:
304  FastWalletRescanFilter(const CWallet& wallet) : m_wallet(wallet)
305  {
306  // fast rescanning via block filters is only supported by descriptor wallets right now
307  assert(!m_wallet.IsLegacy());
308 
309  // create initial filter with scripts from all ScriptPubKeyMans
310  for (auto spkm : m_wallet.GetAllScriptPubKeyMans()) {
311  auto desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};
312  assert(desc_spkm != nullptr);
313  AddScriptPubKeys(desc_spkm);
314  // save each range descriptor's end for possible future filter updates
315  if (desc_spkm->IsHDEnabled()) {
316  m_last_range_ends.emplace(desc_spkm->GetID(), desc_spkm->GetEndRange());
317  }
318  }
319  }
320 
321  void UpdateIfNeeded()
322  {
323  // repopulate filter with new scripts if top-up has happened since last iteration
324  for (const auto& [desc_spkm_id, last_range_end] : m_last_range_ends) {
325  auto desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(m_wallet.GetScriptPubKeyMan(desc_spkm_id))};
326  assert(desc_spkm != nullptr);
327  int32_t current_range_end{desc_spkm->GetEndRange()};
328  if (current_range_end > last_range_end) {
329  AddScriptPubKeys(desc_spkm, last_range_end);
330  m_last_range_ends.at(desc_spkm->GetID()) = current_range_end;
331  }
332  }
333  }
334 
335  std::optional<bool> MatchesBlock(const uint256& block_hash) const
336  {
337  return m_wallet.chain().blockFilterMatchesAny(BlockFilterType::BASIC, block_hash, m_filter_set);
338  }
339 
340 private:
341  const CWallet& m_wallet;
348  std::map<uint256, int32_t> m_last_range_ends;
350 
351  void AddScriptPubKeys(const DescriptorScriptPubKeyMan* desc_spkm, int32_t last_range_end = 0)
352  {
353  for (const auto& script_pub_key : desc_spkm->GetScriptPubKeys(last_range_end)) {
354  m_filter_set.emplace(script_pub_key.begin(), script_pub_key.end());
355  }
356  }
357 };
358 } // namespace
359 
360 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)
361 {
362  auto result = WITH_LOCK(g_loading_wallet_mutex, return g_loading_wallet_set.insert(name));
363  if (!result.second) {
364  error = Untranslated("Wallet already loading.");
366  return nullptr;
367  }
368  auto wallet = LoadWalletInternal(context, name, load_on_start, options, status, error, warnings);
369  WITH_LOCK(g_loading_wallet_mutex, g_loading_wallet_set.erase(result.first));
370  return wallet;
371 }
372 
373 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)
374 {
375  uint64_t wallet_creation_flags = options.create_flags;
376  const SecureString& passphrase = options.create_passphrase;
377 
378  if (wallet_creation_flags & WALLET_FLAG_DESCRIPTORS) options.require_format = DatabaseFormat::SQLITE;
379 
380  // Indicate that the wallet is actually supposed to be blank and not just blank to make it encrypted
381  bool create_blank = (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET);
382 
383  // Born encrypted wallets need to be created blank first.
384  if (!passphrase.empty()) {
385  wallet_creation_flags |= WALLET_FLAG_BLANK_WALLET;
386  }
387 
388  // Private keys must be disabled for an external signer wallet
389  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
390  error = Untranslated("Private keys must be disabled when using an external signer");
392  return nullptr;
393  }
394 
395  // Descriptor support must be enabled for an external signer wallet
396  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) && !(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS)) {
397  error = Untranslated("Descriptor support must be enabled when using an external signer");
399  return nullptr;
400  }
401 
402  // Do not allow a passphrase when private keys are disabled
403  if (!passphrase.empty() && (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
404  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.");
406  return nullptr;
407  }
408 
409  // Wallet::Verify will check if we're trying to create a wallet with a duplicate name.
410  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);
411  if (!database) {
412  error = Untranslated("Wallet file verification failed.") + Untranslated(" ") + error;
414  return nullptr;
415  }
416 
417  // Make the wallet
418  context.chain->initMessage(_("Loading wallet…").translated);
419  std::shared_ptr<CWallet> wallet = CWallet::Create(context, name, std::move(database), wallet_creation_flags, error, warnings);
420  if (!wallet) {
421  error = Untranslated("Wallet creation failed.") + Untranslated(" ") + error;
423  return nullptr;
424  }
425 
426  // Encrypt the wallet
427  if (!passphrase.empty() && !(wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
428  if (!wallet->EncryptWallet(passphrase)) {
429  error = Untranslated("Error: Wallet created but failed to encrypt.");
431  return nullptr;
432  }
433  if (!create_blank) {
434  // Unlock the wallet
435  if (!wallet->Unlock(passphrase)) {
436  error = Untranslated("Error: Wallet was encrypted but could not be unlocked");
438  return nullptr;
439  }
440 
441  // Set a seed for the wallet
442  {
443  LOCK(wallet->cs_wallet);
444  if (wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
445  wallet->SetupDescriptorScriptPubKeyMans();
446  } else {
447  for (auto spk_man : wallet->GetActiveScriptPubKeyMans()) {
448  if (!spk_man->SetupGeneration()) {
449  error = Untranslated("Unable to generate initial keys");
451  return nullptr;
452  }
453  }
454  }
455  }
456 
457  // Relock the wallet
458  wallet->Lock();
459  }
460  }
461 
464  wallet->postInitProcess();
465 
466  // Write the wallet settings
467  UpdateWalletSetting(*context.chain, name, load_on_start, warnings);
468 
469  // Legacy wallets are being deprecated, warn if a newly created wallet is legacy
470  if (!(wallet_creation_flags & WALLET_FLAG_DESCRIPTORS)) {
471  warnings.push_back(_("Wallet created successfully. The legacy wallet type is being deprecated and support for creating and opening legacy wallets will be removed in the future."));
472  }
473 
474  status = DatabaseStatus::SUCCESS;
475  return wallet;
476 }
477 
478 std::shared_ptr<CWallet> RestoreWallet(WalletContext& context, const fs::path& backup_file, const std::string& wallet_name, std::optional<bool> load_on_start, DatabaseStatus& status, bilingual_str& error, std::vector<bilingual_str>& warnings)
479 {
480  DatabaseOptions options;
481  ReadDatabaseArgs(*context.args, options);
482  options.require_existing = true;
483 
484  const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::u8path(wallet_name));
485  auto wallet_file = wallet_path / "wallet.dat";
486  std::shared_ptr<CWallet> wallet;
487 
488  try {
489  if (!fs::exists(backup_file)) {
490  error = Untranslated("Backup file does not exist");
492  return nullptr;
493  }
494 
495  if (fs::exists(wallet_path) || !TryCreateDirectories(wallet_path)) {
496  error = Untranslated(strprintf("Failed to create database path '%s'. Database already exists.", fs::PathToString(wallet_path)));
498  return nullptr;
499  }
500 
501  fs::copy_file(backup_file, wallet_file, fs::copy_options::none);
502 
503  wallet = LoadWallet(context, wallet_name, load_on_start, options, status, error, warnings);
504  } catch (const std::exception& e) {
505  assert(!wallet);
506  if (!error.empty()) error += Untranslated("\n");
507  error += strprintf(Untranslated("Unexpected exception: %s"), e.what());
508  }
509  if (!wallet) {
510  fs::remove_all(wallet_path);
511  }
512 
513  return wallet;
514 }
515 
521 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
522 {
524  const auto it = mapWallet.find(hash);
525  if (it == mapWallet.end())
526  return nullptr;
527  return &(it->second);
528 }
529 
531 {
533  return;
534  }
535 
536  auto spk_man = GetLegacyScriptPubKeyMan();
537  if (!spk_man) {
538  return;
539  }
540 
541  spk_man->UpgradeKeyMetadata();
542  SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
543 }
544 
546 {
548  return;
549  }
550 
551  for (ScriptPubKeyMan* spkm : GetAllScriptPubKeyMans()) {
552  DescriptorScriptPubKeyMan* desc_spkm = dynamic_cast<DescriptorScriptPubKeyMan*>(spkm);
553  desc_spkm->UpgradeDescriptorCache();
554  }
556 }
557 
558 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
559 {
560  CCrypter crypter;
561  CKeyingMaterial _vMasterKey;
562 
563  {
564  LOCK(cs_wallet);
565  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
566  {
567  if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
568  return false;
569  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
570  continue; // try another master key
571  if (Unlock(_vMasterKey, accept_no_keys)) {
572  // Now that we've unlocked, upgrade the key metadata
574  // Now that we've unlocked, upgrade the descriptor cache
576  return true;
577  }
578  }
579  }
580  return false;
581 }
582 
583 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
584 {
585  bool fWasLocked = IsLocked();
586 
587  {
589  Lock();
590 
591  CCrypter crypter;
592  CKeyingMaterial _vMasterKey;
593  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
594  {
595  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
596  return false;
597  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
598  return false;
599  if (Unlock(_vMasterKey))
600  {
601  constexpr MillisecondsDouble target{100};
602  auto start{SteadyClock::now()};
603  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
604  pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * target / (SteadyClock::now() - start));
605 
606  start = SteadyClock::now();
607  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
608  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * target / (SteadyClock::now() - start))) / 2;
609 
610  if (pMasterKey.second.nDeriveIterations < 25000)
611  pMasterKey.second.nDeriveIterations = 25000;
612 
613  WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
614 
615  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
616  return false;
617  if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
618  return false;
619  WalletBatch(GetDatabase()).WriteMasterKey(pMasterKey.first, pMasterKey.second);
620  if (fWasLocked)
621  Lock();
622  return true;
623  }
624  }
625  }
626 
627  return false;
628 }
629 
631 {
632  // Don't update the best block until the chain is attached so that in case of a shutdown,
633  // the rescan will be restarted at next startup.
635  return;
636  }
637  WalletBatch batch(GetDatabase());
638  batch.WriteBestBlock(loc);
639 }
640 
641 void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in)
642 {
643  LOCK(cs_wallet);
644  if (nWalletVersion >= nVersion)
645  return;
646  WalletLogPrintf("Setting minversion to %d\n", nVersion);
647  nWalletVersion = nVersion;
648 
649  {
650  WalletBatch* batch = batch_in ? batch_in : new WalletBatch(GetDatabase());
651  if (nWalletVersion > 40000)
652  batch->WriteMinVersion(nWalletVersion);
653  if (!batch_in)
654  delete batch;
655  }
656 }
657 
658 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
659 {
660  std::set<uint256> result;
662 
663  const auto it = mapWallet.find(txid);
664  if (it == mapWallet.end())
665  return result;
666  const CWalletTx& wtx = it->second;
667 
668  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
669 
670  for (const CTxIn& txin : wtx.tx->vin)
671  {
672  if (mapTxSpends.count(txin.prevout) <= 1)
673  continue; // No conflict if zero or one spends
674  range = mapTxSpends.equal_range(txin.prevout);
675  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
676  result.insert(_it->second);
677  }
678  return result;
679 }
680 
682 {
684  const uint256& txid = tx->GetHash();
685  for (unsigned int i = 0; i < tx->vout.size(); ++i) {
686  if (IsSpent(COutPoint(txid, i))) {
687  return true;
688  }
689  }
690  return false;
691 }
692 
694 {
695  GetDatabase().Flush();
696 }
697 
699 {
700  GetDatabase().Close();
701 }
702 
703 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
704 {
705  // We want all the wallet transactions in range to have the same metadata as
706  // the oldest (smallest nOrderPos).
707  // So: find smallest nOrderPos:
708 
709  int nMinOrderPos = std::numeric_limits<int>::max();
710  const CWalletTx* copyFrom = nullptr;
711  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
712  const CWalletTx* wtx = &mapWallet.at(it->second);
713  if (wtx->nOrderPos < nMinOrderPos) {
714  nMinOrderPos = wtx->nOrderPos;
715  copyFrom = wtx;
716  }
717  }
718 
719  if (!copyFrom) {
720  return;
721  }
722 
723  // Now copy data from copyFrom to rest:
724  for (TxSpends::iterator it = range.first; it != range.second; ++it)
725  {
726  const uint256& hash = it->second;
727  CWalletTx* copyTo = &mapWallet.at(hash);
728  if (copyFrom == copyTo) continue;
729  assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
730  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
731  copyTo->mapValue = copyFrom->mapValue;
732  copyTo->vOrderForm = copyFrom->vOrderForm;
733  // fTimeReceivedIsTxTime not copied on purpose
734  // nTimeReceived not copied on purpose
735  copyTo->nTimeSmart = copyFrom->nTimeSmart;
736  copyTo->fFromMe = copyFrom->fFromMe;
737  // nOrderPos not copied on purpose
738  // cached members not copied on purpose
739  }
740 }
741 
746 bool CWallet::IsSpent(const COutPoint& outpoint) const
747 {
748  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
749  range = mapTxSpends.equal_range(outpoint);
750 
751  for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
752  const uint256& wtxid = it->second;
753  const auto mit = mapWallet.find(wtxid);
754  if (mit != mapWallet.end()) {
755  int depth = GetTxDepthInMainChain(mit->second);
756  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
757  return true; // Spent
758  }
759  }
760  return false;
761 }
762 
763 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid, WalletBatch* batch)
764 {
765  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
766 
767  if (batch) {
768  UnlockCoin(outpoint, batch);
769  } else {
770  WalletBatch temp_batch(GetDatabase());
771  UnlockCoin(outpoint, &temp_batch);
772  }
773 
774  std::pair<TxSpends::iterator, TxSpends::iterator> range;
775  range = mapTxSpends.equal_range(outpoint);
776  SyncMetaData(range);
777 }
778 
779 
781 {
782  if (wtx.IsCoinBase()) // Coinbases don't spend anything!
783  return;
784 
785  for (const CTxIn& txin : wtx.tx->vin)
786  AddToSpends(txin.prevout, wtx.GetHash(), batch);
787 }
788 
789 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
790 {
791  if (IsCrypted())
792  return false;
793 
794  CKeyingMaterial _vMasterKey;
795 
796  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
797  GetStrongRandBytes(_vMasterKey);
798 
799  CMasterKey kMasterKey;
800 
801  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
802  GetStrongRandBytes(kMasterKey.vchSalt);
803 
804  CCrypter crypter;
805  constexpr MillisecondsDouble target{100};
806  auto start{SteadyClock::now()};
807  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
808  kMasterKey.nDeriveIterations = static_cast<unsigned int>(25000 * target / (SteadyClock::now() - start));
809 
810  start = SteadyClock::now();
811  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
812  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * target / (SteadyClock::now() - start))) / 2;
813 
814  if (kMasterKey.nDeriveIterations < 25000)
815  kMasterKey.nDeriveIterations = 25000;
816 
817  WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
818 
819  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
820  return false;
821  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
822  return false;
823 
824  {
826  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
827  WalletBatch* encrypted_batch = new WalletBatch(GetDatabase());
828  if (!encrypted_batch->TxnBegin()) {
829  delete encrypted_batch;
830  encrypted_batch = nullptr;
831  return false;
832  }
833  encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
834 
835  for (const auto& spk_man_pair : m_spk_managers) {
836  auto spk_man = spk_man_pair.second.get();
837  if (!spk_man->Encrypt(_vMasterKey, encrypted_batch)) {
838  encrypted_batch->TxnAbort();
839  delete encrypted_batch;
840  encrypted_batch = nullptr;
841  // We now probably have half of our keys encrypted in memory, and half not...
842  // die and let the user reload the unencrypted wallet.
843  assert(false);
844  }
845  }
846 
847  // Encryption was introduced in version 0.4.0
848  SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch);
849 
850  if (!encrypted_batch->TxnCommit()) {
851  delete encrypted_batch;
852  encrypted_batch = nullptr;
853  // We now have keys encrypted in memory, but not on disk...
854  // die to avoid confusion and let the user reload the unencrypted wallet.
855  assert(false);
856  }
857 
858  delete encrypted_batch;
859  encrypted_batch = nullptr;
860 
861  Lock();
862  Unlock(strWalletPassphrase);
863 
864  // If we are using descriptors, make new descriptors with a new seed
867  } else if (auto spk_man = GetLegacyScriptPubKeyMan()) {
868  // if we are using HD, replace the HD seed with a new one
869  if (spk_man->IsHDEnabled()) {
870  if (!spk_man->SetupGeneration(true)) {
871  return false;
872  }
873  }
874  }
875  Lock();
876 
877  // Need to completely rewrite the wallet file; if we don't, bdb might keep
878  // bits of the unencrypted private key in slack space in the database file.
879  GetDatabase().Rewrite();
880 
881  // BDB seems to have a bad habit of writing old data into
882  // slack space in .dat files; that is bad if the old data is
883  // unencrypted private keys. So:
885 
886  }
887  NotifyStatusChanged(this);
888 
889  return true;
890 }
891 
893 {
894  LOCK(cs_wallet);
895  WalletBatch batch(GetDatabase());
896 
897  // Old wallets didn't have any defined order for transactions
898  // Probably a bad idea to change the output of this
899 
900  // First: get all CWalletTx into a sorted-by-time multimap.
901  typedef std::multimap<int64_t, CWalletTx*> TxItems;
902  TxItems txByTime;
903 
904  for (auto& entry : mapWallet)
905  {
906  CWalletTx* wtx = &entry.second;
907  txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
908  }
909 
910  nOrderPosNext = 0;
911  std::vector<int64_t> nOrderPosOffsets;
912  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
913  {
914  CWalletTx *const pwtx = (*it).second;
915  int64_t& nOrderPos = pwtx->nOrderPos;
916 
917  if (nOrderPos == -1)
918  {
919  nOrderPos = nOrderPosNext++;
920  nOrderPosOffsets.push_back(nOrderPos);
921 
922  if (!batch.WriteTx(*pwtx))
923  return DBErrors::LOAD_FAIL;
924  }
925  else
926  {
927  int64_t nOrderPosOff = 0;
928  for (const int64_t& nOffsetStart : nOrderPosOffsets)
929  {
930  if (nOrderPos >= nOffsetStart)
931  ++nOrderPosOff;
932  }
933  nOrderPos += nOrderPosOff;
934  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
935 
936  if (!nOrderPosOff)
937  continue;
938 
939  // Since we're changing the order, write it back
940  if (!batch.WriteTx(*pwtx))
941  return DBErrors::LOAD_FAIL;
942  }
943  }
944  batch.WriteOrderPosNext(nOrderPosNext);
945 
946  return DBErrors::LOAD_OK;
947 }
948 
950 {
952  int64_t nRet = nOrderPosNext++;
953  if (batch) {
954  batch->WriteOrderPosNext(nOrderPosNext);
955  } else {
956  WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
957  }
958  return nRet;
959 }
960 
962 {
963  {
964  LOCK(cs_wallet);
965  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
966  item.second.MarkDirty();
967  }
968 }
969 
970 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
971 {
972  LOCK(cs_wallet);
973 
974  auto mi = mapWallet.find(originalHash);
975 
976  // There is a bug if MarkReplaced is not called on an existing wallet transaction.
977  assert(mi != mapWallet.end());
978 
979  CWalletTx& wtx = (*mi).second;
980 
981  // Ensure for now that we're not overwriting data
982  assert(wtx.mapValue.count("replaced_by_txid") == 0);
983 
984  wtx.mapValue["replaced_by_txid"] = newHash.ToString();
985 
986  // Refresh mempool status without waiting for transactionRemovedFromMempool or transactionAddedToMempool
987  RefreshMempoolStatus(wtx, chain());
988 
989  WalletBatch batch(GetDatabase());
990 
991  bool success = true;
992  if (!batch.WriteTx(wtx)) {
993  WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
994  success = false;
995  }
996 
997  NotifyTransactionChanged(originalHash, CT_UPDATED);
998 
999  return success;
1000 }
1001 
1002 void CWallet::SetSpentKeyState(WalletBatch& batch, const uint256& hash, unsigned int n, bool used, std::set<CTxDestination>& tx_destinations)
1003 {
1005  const CWalletTx* srctx = GetWalletTx(hash);
1006  if (!srctx) return;
1007 
1008  CTxDestination dst;
1009  if (ExtractDestination(srctx->tx->vout[n].scriptPubKey, dst)) {
1010  if (IsMine(dst)) {
1011  if (used != IsAddressPreviouslySpent(dst)) {
1012  if (used) {
1013  tx_destinations.insert(dst);
1014  }
1015  SetAddressPreviouslySpent(batch, dst, used);
1016  }
1017  }
1018  }
1019 }
1020 
1021 bool CWallet::IsSpentKey(const CScript& scriptPubKey) const
1022 {
1024  CTxDestination dest;
1025  if (!ExtractDestination(scriptPubKey, dest)) {
1026  return false;
1027  }
1028  if (IsAddressPreviouslySpent(dest)) {
1029  return true;
1030  }
1031  if (IsLegacy()) {
1033  assert(spk_man != nullptr);
1034  for (const auto& keyid : GetAffectedKeys(scriptPubKey, *spk_man)) {
1035  WitnessV0KeyHash wpkh_dest(keyid);
1036  if (IsAddressPreviouslySpent(wpkh_dest)) {
1037  return true;
1038  }
1039  ScriptHash sh_wpkh_dest(GetScriptForDestination(wpkh_dest));
1040  if (IsAddressPreviouslySpent(sh_wpkh_dest)) {
1041  return true;
1042  }
1043  PKHash pkh_dest(keyid);
1044  if (IsAddressPreviouslySpent(pkh_dest)) {
1045  return true;
1046  }
1047  }
1048  }
1049  return false;
1050 }
1051 
1052 CWalletTx* CWallet::AddToWallet(CTransactionRef tx, const TxState& state, const UpdateWalletTxFn& update_wtx, bool fFlushOnClose, bool rescanning_old_block)
1053 {
1054  LOCK(cs_wallet);
1055 
1056  WalletBatch batch(GetDatabase(), fFlushOnClose);
1057 
1058  uint256 hash = tx->GetHash();
1059 
1061  // Mark used destinations
1062  std::set<CTxDestination> tx_destinations;
1063 
1064  for (const CTxIn& txin : tx->vin) {
1065  const COutPoint& op = txin.prevout;
1066  SetSpentKeyState(batch, op.hash, op.n, true, tx_destinations);
1067  }
1068 
1069  MarkDestinationsDirty(tx_destinations);
1070  }
1071 
1072  // Inserts only if not already there, returns tx inserted or tx found
1073  auto ret = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(tx, state));
1074  CWalletTx& wtx = (*ret.first).second;
1075  bool fInsertedNew = ret.second;
1076  bool fUpdated = update_wtx && update_wtx(wtx, fInsertedNew);
1077  if (fInsertedNew) {
1078  wtx.nTimeReceived = GetTime();
1079  wtx.nOrderPos = IncOrderPosNext(&batch);
1080  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1081  wtx.nTimeSmart = ComputeTimeSmart(wtx, rescanning_old_block);
1082  AddToSpends(wtx, &batch);
1083 
1084  // Update birth time when tx time is older than it.
1086  }
1087 
1088  if (!fInsertedNew)
1089  {
1090  if (state.index() != wtx.m_state.index()) {
1091  wtx.m_state = state;
1092  fUpdated = true;
1093  } else {
1096  }
1097  // If we have a witness-stripped version of this transaction, and we
1098  // see a new version with a witness, then we must be upgrading a pre-segwit
1099  // wallet. Store the new version of the transaction with the witness,
1100  // as the stripped-version must be invalid.
1101  // TODO: Store all versions of the transaction, instead of just one.
1102  if (tx->HasWitness() && !wtx.tx->HasWitness()) {
1103  wtx.SetTx(tx);
1104  fUpdated = true;
1105  }
1106  }
1107 
1108  // Mark inactive coinbase transactions and their descendants as abandoned
1109  if (wtx.IsCoinBase() && wtx.isInactive()) {
1110  std::vector<CWalletTx*> txs{&wtx};
1111 
1112  TxStateInactive inactive_state = TxStateInactive{/*abandoned=*/true};
1113 
1114  while (!txs.empty()) {
1115  CWalletTx* desc_tx = txs.back();
1116  txs.pop_back();
1117  desc_tx->m_state = inactive_state;
1118  // Break caches since we have changed the state
1119  desc_tx->MarkDirty();
1120  batch.WriteTx(*desc_tx);
1121  MarkInputsDirty(desc_tx->tx);
1122  for (unsigned int i = 0; i < desc_tx->tx->vout.size(); ++i) {
1123  COutPoint outpoint(desc_tx->GetHash(), i);
1124  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(outpoint);
1125  for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
1126  const auto wit = mapWallet.find(it->second);
1127  if (wit != mapWallet.end()) {
1128  txs.push_back(&wit->second);
1129  }
1130  }
1131  }
1132  }
1133  }
1134 
1136  WalletLogPrintf("AddToWallet %s %s%s %s\n", hash.ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""), TxStateString(state));
1137 
1138  // Write to disk
1139  if (fInsertedNew || fUpdated)
1140  if (!batch.WriteTx(wtx))
1141  return nullptr;
1142 
1143  // Break debit/credit balance caches:
1144  wtx.MarkDirty();
1145 
1146  // Notify UI of new or updated transaction
1147  NotifyTransactionChanged(hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1148 
1149 #if HAVE_SYSTEM
1150  // notify an external script when a wallet transaction comes in or is updated
1151  std::string strCmd = m_notify_tx_changed_script;
1152 
1153  if (!strCmd.empty())
1154  {
1155  ReplaceAll(strCmd, "%s", hash.GetHex());
1156  if (auto* conf = wtx.state<TxStateConfirmed>())
1157  {
1158  ReplaceAll(strCmd, "%b", conf->confirmed_block_hash.GetHex());
1159  ReplaceAll(strCmd, "%h", ToString(conf->confirmed_block_height));
1160  } else {
1161  ReplaceAll(strCmd, "%b", "unconfirmed");
1162  ReplaceAll(strCmd, "%h", "-1");
1163  }
1164 #ifndef WIN32
1165  // Substituting the wallet name isn't currently supported on windows
1166  // because windows shell escaping has not been implemented yet:
1167  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-537384875
1168  // A few ways it could be implemented in the future are described in:
1169  // https://github.com/bitcoin/bitcoin/pull/13339#issuecomment-461288094
1170  ReplaceAll(strCmd, "%w", ShellEscape(GetName()));
1171 #endif
1172  std::thread t(runCommand, strCmd);
1173  t.detach(); // thread runs free
1174  }
1175 #endif
1176 
1177  return &wtx;
1178 }
1179 
1180 bool CWallet::LoadToWallet(const uint256& hash, const UpdateWalletTxFn& fill_wtx)
1181 {
1182  const auto& ins = mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(hash), std::forward_as_tuple(nullptr, TxStateInactive{}));
1183  CWalletTx& wtx = ins.first->second;
1184  if (!fill_wtx(wtx, ins.second)) {
1185  return false;
1186  }
1187  // If wallet doesn't have a chain (e.g when using bitcoin-wallet tool),
1188  // don't bother to update txn.
1189  if (HaveChain()) {
1190  bool active;
1191  auto lookup_block = [&](const uint256& hash, int& height, TxState& state) {
1192  // If tx block (or conflicting block) was reorged out of chain
1193  // while the wallet was shutdown, change tx status to UNCONFIRMED
1194  // and reset block height, hash, and index. ABANDONED tx don't have
1195  // associated blocks and don't need to be updated. The case where a
1196  // transaction was reorged out while online and then reconfirmed
1197  // while offline is covered by the rescan logic.
1198  if (!chain().findBlock(hash, FoundBlock().inActiveChain(active).height(height)) || !active) {
1199  state = TxStateInactive{};
1200  }
1201  };
1202  if (auto* conf = wtx.state<TxStateConfirmed>()) {
1203  lookup_block(conf->confirmed_block_hash, conf->confirmed_block_height, wtx.m_state);
1204  } else if (auto* conf = wtx.state<TxStateConflicted>()) {
1205  lookup_block(conf->conflicting_block_hash, conf->conflicting_block_height, wtx.m_state);
1206  }
1207  }
1208  if (/* insertion took place */ ins.second) {
1209  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1210  }
1211  AddToSpends(wtx);
1212  for (const CTxIn& txin : wtx.tx->vin) {
1213  auto it = mapWallet.find(txin.prevout.hash);
1214  if (it != mapWallet.end()) {
1215  CWalletTx& prevtx = it->second;
1216  if (auto* prev = prevtx.state<TxStateConflicted>()) {
1217  MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, wtx.GetHash());
1218  }
1219  }
1220  }
1221 
1222  // Update birth time when tx time is older than it.
1224 
1225  return true;
1226 }
1227 
1228 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block)
1229 {
1230  const CTransaction& tx = *ptx;
1231  {
1233 
1234  if (auto* conf = std::get_if<TxStateConfirmed>(&state)) {
1235  for (const CTxIn& txin : tx.vin) {
1236  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1237  while (range.first != range.second) {
1238  if (range.first->second != tx.GetHash()) {
1239  WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), conf->confirmed_block_hash.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1240  MarkConflicted(conf->confirmed_block_hash, conf->confirmed_block_height, range.first->second);
1241  }
1242  range.first++;
1243  }
1244  }
1245  }
1246 
1247  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1248  if (fExisted && !fUpdate) return false;
1249  if (fExisted || IsMine(tx) || IsFromMe(tx))
1250  {
1251  /* Check if any keys in the wallet keypool that were supposed to be unused
1252  * have appeared in a new transaction. If so, remove those keys from the keypool.
1253  * This can happen when restoring an old wallet backup that does not contain
1254  * the mostly recently created transactions from newer versions of the wallet.
1255  */
1256 
1257  // loop though all outputs
1258  for (const CTxOut& txout: tx.vout) {
1259  for (const auto& spk_man : GetScriptPubKeyMans(txout.scriptPubKey)) {
1260  for (auto &dest : spk_man->MarkUnusedAddresses(txout.scriptPubKey)) {
1261  // If internal flag is not defined try to infer it from the ScriptPubKeyMan
1262  if (!dest.internal.has_value()) {
1263  dest.internal = IsInternalScriptPubKeyMan(spk_man);
1264  }
1265 
1266  // skip if can't determine whether it's a receiving address or not
1267  if (!dest.internal.has_value()) continue;
1268 
1269  // If this is a receiving address and it's not in the address book yet
1270  // (e.g. it wasn't generated on this node or we're restoring from backup)
1271  // add it to the address book for proper transaction accounting
1272  if (!*dest.internal && !FindAddressBookEntry(dest.dest, /* allow_change= */ false)) {
1273  SetAddressBook(dest.dest, "", AddressPurpose::RECEIVE);
1274  }
1275  }
1276  }
1277  }
1278 
1279  // Block disconnection override an abandoned tx as unconfirmed
1280  // which means user may have to call abandontransaction again
1281  TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
1282  CWalletTx* wtx = AddToWallet(MakeTransactionRef(tx), tx_state, /*update_wtx=*/nullptr, /*fFlushOnClose=*/false, rescanning_old_block);
1283  if (!wtx) {
1284  // Can only be nullptr if there was a db write error (missing db, read-only db or a db engine internal writing error).
1285  // As we only store arriving transaction in this process, and we don't want an inconsistent state, let's throw an error.
1286  throw std::runtime_error("DB error adding transaction to wallet, write failed");
1287  }
1288  return true;
1289  }
1290  }
1291  return false;
1292 }
1293 
1295 {
1296  LOCK(cs_wallet);
1297  const CWalletTx* wtx = GetWalletTx(hashTx);
1298  return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 && !wtx->InMempool();
1299 }
1300 
1302 {
1303  for (const CTxIn& txin : tx->vin) {
1304  auto it = mapWallet.find(txin.prevout.hash);
1305  if (it != mapWallet.end()) {
1306  it->second.MarkDirty();
1307  }
1308  }
1309 }
1310 
1312 {
1313  LOCK(cs_wallet);
1314 
1315  // Can't mark abandoned if confirmed or in mempool
1316  auto it = mapWallet.find(hashTx);
1317  assert(it != mapWallet.end());
1318  const CWalletTx& origtx = it->second;
1319  if (GetTxDepthInMainChain(origtx) != 0 || origtx.InMempool()) {
1320  return false;
1321  }
1322 
1323  auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1324  // If the orig tx was not in block/mempool, none of its spends can be.
1325  assert(!wtx.isConfirmed());
1326  assert(!wtx.InMempool());
1327  // If already conflicted or abandoned, no need to set abandoned
1328  if (!wtx.isConflicted() && !wtx.isAbandoned()) {
1329  wtx.m_state = TxStateInactive{/*abandoned=*/true};
1330  return TxUpdate::NOTIFY_CHANGED;
1331  }
1332  return TxUpdate::UNCHANGED;
1333  };
1334 
1335  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1336  // States are not permanent, so these transactions can become unabandoned if they are re-added to the
1337  // mempool, or confirmed in a block, or conflicted.
1338  // Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1339  // states change will remain abandoned and will require manual broadcast if the user wants them.
1340 
1341  RecursiveUpdateTxState(hashTx, try_updating_state);
1342 
1343  return true;
1344 }
1345 
1346 void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
1347 {
1348  LOCK(cs_wallet);
1349 
1350  // If number of conflict confirms cannot be determined, this means
1351  // that the block is still unknown or not yet part of the main chain,
1352  // for example when loading the wallet during a reindex. Do nothing in that
1353  // case.
1354  if (m_last_block_processed_height < 0 || conflicting_height < 0) {
1355  return;
1356  }
1357  int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1358  if (conflictconfirms >= 0)
1359  return;
1360 
1361  auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1362  if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
1363  // Block is 'more conflicted' than current confirm; update.
1364  // Mark transaction as conflicted with this block.
1365  wtx.m_state = TxStateConflicted{hashBlock, conflicting_height};
1366  return TxUpdate::CHANGED;
1367  }
1368  return TxUpdate::UNCHANGED;
1369  };
1370 
1371  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
1372  RecursiveUpdateTxState(hashTx, try_updating_state);
1373 
1374 }
1375 
1376 void CWallet::RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1377  // Do not flush the wallet here for performance reasons
1378  WalletBatch batch(GetDatabase(), false);
1379 
1380  std::set<uint256> todo;
1381  std::set<uint256> done;
1382 
1383  todo.insert(tx_hash);
1384 
1385  while (!todo.empty()) {
1386  uint256 now = *todo.begin();
1387  todo.erase(now);
1388  done.insert(now);
1389  auto it = mapWallet.find(now);
1390  assert(it != mapWallet.end());
1391  CWalletTx& wtx = it->second;
1392 
1393  TxUpdate update_state = try_updating_state(wtx);
1394  if (update_state != TxUpdate::UNCHANGED) {
1395  wtx.MarkDirty();
1396  batch.WriteTx(wtx);
1397  // Iterate over all its outputs, and update those tx states as well (if applicable)
1398  for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
1399  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(now, i));
1400  for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
1401  if (!done.count(iter->second)) {
1402  todo.insert(iter->second);
1403  }
1404  }
1405  }
1406 
1407  if (update_state == TxUpdate::NOTIFY_CHANGED) {
1408  NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1409  }
1410 
1411  // If a transaction changes its tx state, that usually changes the balance
1412  // available of the outputs it spends. So force those to be recomputed
1413  MarkInputsDirty(wtx.tx);
1414  }
1415  }
1416 }
1417 
1418 void CWallet::SyncTransaction(const CTransactionRef& ptx, const SyncTxState& state, bool update_tx, bool rescanning_old_block)
1419 {
1420  if (!AddToWalletIfInvolvingMe(ptx, state, update_tx, rescanning_old_block))
1421  return; // Not one of ours
1422 
1423  // If a transaction changes 'conflicted' state, that changes the balance
1424  // available of the outputs it spends. So force those to be
1425  // recomputed, also:
1426  MarkInputsDirty(ptx);
1427 }
1428 
1430  LOCK(cs_wallet);
1432 
1433  auto it = mapWallet.find(tx->GetHash());
1434  if (it != mapWallet.end()) {
1435  RefreshMempoolStatus(it->second, chain());
1436  }
1437 }
1438 
1440  LOCK(cs_wallet);
1441  auto it = mapWallet.find(tx->GetHash());
1442  if (it != mapWallet.end()) {
1443  RefreshMempoolStatus(it->second, chain());
1444  }
1445  // Handle transactions that were removed from the mempool because they
1446  // conflict with transactions in a newly connected block.
1447  if (reason == MemPoolRemovalReason::CONFLICT) {
1448  // Trigger external -walletnotify notifications for these transactions.
1449  // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
1450  //
1451  // 1. The transactionRemovedFromMempool callback does not currently
1452  // provide the conflicting block's hash and height, and for backwards
1453  // compatibility reasons it may not be not safe to store conflicted
1454  // wallet transactions with a null block hash. See
1455  // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1456  // 2. For most of these transactions, the wallet's internal conflict
1457  // detection in the blockConnected handler will subsequently call
1458  // MarkConflicted and update them with CONFLICTED status anyway. This
1459  // applies to any wallet transaction that has inputs spent in the
1460  // block, or that has ancestors in the wallet with inputs spent by
1461  // the block.
1462  // 3. Longstanding behavior since the sync implementation in
1463  // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1464  // implementation before that was to mark these transactions
1465  // unconfirmed rather than conflicted.
1466  //
1467  // Nothing described above should be seen as an unchangeable requirement
1468  // when improving this code in the future. The wallet's heuristics for
1469  // distinguishing between conflicted and unconfirmed transactions are
1470  // imperfect, and could be improved in general, see
1471  // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1473  }
1474 }
1475 
1477 {
1478  if (role == ChainstateRole::BACKGROUND) {
1479  return;
1480  }
1481  assert(block.data);
1482  LOCK(cs_wallet);
1483 
1484  m_last_block_processed_height = block.height;
1485  m_last_block_processed = block.hash;
1486 
1487  // No need to scan block if it was created before the wallet birthday.
1488  // Uses chain max time and twice the grace period to adjust time for block time variability.
1489  if (block.chain_time_max < m_birth_time.load() - (TIMESTAMP_WINDOW * 2)) return;
1490 
1491  // Scan block
1492  for (size_t index = 0; index < block.data->vtx.size(); index++) {
1493  SyncTransaction(block.data->vtx[index], TxStateConfirmed{block.hash, block.height, static_cast<int>(index)});
1495  }
1496 }
1497 
1499 {
1500  assert(block.data);
1501  LOCK(cs_wallet);
1502 
1503  // At block disconnection, this will change an abandoned transaction to
1504  // be unconfirmed, whether or not the transaction is added back to the mempool.
1505  // User may have to call abandontransaction again. It may be addressed in the
1506  // future with a stickier abandoned state or even removing abandontransaction call.
1507  m_last_block_processed_height = block.height - 1;
1508  m_last_block_processed = *Assert(block.prev_hash);
1509 
1510  int disconnect_height = block.height;
1511 
1512  for (const CTransactionRef& ptx : Assert(block.data)->vtx) {
1514 
1515  for (const CTxIn& tx_in : ptx->vin) {
1516  // No other wallet transactions conflicted with this transaction
1517  if (mapTxSpends.count(tx_in.prevout) < 1) continue;
1518 
1519  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
1520 
1521  // For all of the spends that conflict with this transaction
1522  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
1523  CWalletTx& wtx = mapWallet.find(_it->second)->second;
1524 
1525  if (!wtx.isConflicted()) continue;
1526 
1527  auto try_updating_state = [&](CWalletTx& tx) {
1528  if (!tx.isConflicted()) return TxUpdate::UNCHANGED;
1529  if (tx.state<TxStateConflicted>()->conflicting_block_height >= disconnect_height) {
1530  tx.m_state = TxStateInactive{};
1531  return TxUpdate::CHANGED;
1532  }
1533  return TxUpdate::UNCHANGED;
1534  };
1535 
1536  RecursiveUpdateTxState(wtx.tx->GetHash(), try_updating_state);
1537  }
1538  }
1539  }
1540 }
1541 
1543 {
1545 }
1546 
1547 void CWallet::BlockUntilSyncedToCurrentChain() const {
1549  // Skip the queue-draining stuff if we know we're caught up with
1550  // chain().Tip(), otherwise put a callback in the validation interface queue and wait
1551  // for the queue to drain enough to execute it (indicating we are caught up
1552  // at least with the time we entered this function).
1553  uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1554  chain().waitForNotificationsIfTipChanged(last_block_hash);
1555 }
1556 
1557 // Note that this function doesn't distinguish between a 0-valued input,
1558 // and a not-"is mine" (according to the filter) input.
1559 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1560 {
1561  {
1562  LOCK(cs_wallet);
1563  const auto mi = mapWallet.find(txin.prevout.hash);
1564  if (mi != mapWallet.end())
1565  {
1566  const CWalletTx& prev = (*mi).second;
1567  if (txin.prevout.n < prev.tx->vout.size())
1568  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1569  return prev.tx->vout[txin.prevout.n].nValue;
1570  }
1571  }
1572  return 0;
1573 }
1574 
1575 isminetype CWallet::IsMine(const CTxOut& txout) const
1576 {
1578  return IsMine(txout.scriptPubKey);
1579 }
1580 
1582 {
1584  return IsMine(GetScriptForDestination(dest));
1585 }
1586 
1587 isminetype CWallet::IsMine(const CScript& script) const
1588 {
1590  isminetype result = ISMINE_NO;
1591  for (const auto& spk_man_pair : m_spk_managers) {
1592  result = std::max(result, spk_man_pair.second->IsMine(script));
1593  }
1594  return result;
1595 }
1596 
1597 bool CWallet::IsMine(const CTransaction& tx) const
1598 {
1600  for (const CTxOut& txout : tx.vout)
1601  if (IsMine(txout))
1602  return true;
1603  return false;
1604 }
1605 
1606 isminetype CWallet::IsMine(const COutPoint& outpoint) const
1607 {
1609  auto wtx = GetWalletTx(outpoint.hash);
1610  if (!wtx) {
1611  return ISMINE_NO;
1612  }
1613  if (outpoint.n >= wtx->tx->vout.size()) {
1614  return ISMINE_NO;
1615  }
1616  return IsMine(wtx->tx->vout[outpoint.n]);
1617 }
1618 
1619 bool CWallet::IsFromMe(const CTransaction& tx) const
1620 {
1621  return (GetDebit(tx, ISMINE_ALL) > 0);
1622 }
1623 
1624 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1625 {
1626  CAmount nDebit = 0;
1627  for (const CTxIn& txin : tx.vin)
1628  {
1629  nDebit += GetDebit(txin, filter);
1630  if (!MoneyRange(nDebit))
1631  throw std::runtime_error(std::string(__func__) + ": value out of range");
1632  }
1633  return nDebit;
1634 }
1635 
1637 {
1638  // All Active ScriptPubKeyMans must be HD for this to be true
1639  bool result = false;
1640  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
1641  if (!spk_man->IsHDEnabled()) return false;
1642  result = true;
1643  }
1644  return result;
1645 }
1646 
1647 bool CWallet::CanGetAddresses(bool internal) const
1648 {
1649  LOCK(cs_wallet);
1650  if (m_spk_managers.empty()) return false;
1651  for (OutputType t : OUTPUT_TYPES) {
1652  auto spk_man = GetScriptPubKeyMan(t, internal);
1653  if (spk_man && spk_man->CanGetAddresses(internal)) {
1654  return true;
1655  }
1656  }
1657  return false;
1658 }
1659 
1660 void CWallet::SetWalletFlag(uint64_t flags)
1661 {
1662  LOCK(cs_wallet);
1663  m_wallet_flags |= flags;
1664  if (!WalletBatch(GetDatabase()).WriteWalletFlags(m_wallet_flags))
1665  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1666 }
1667 
1668 void CWallet::UnsetWalletFlag(uint64_t flag)
1669 {
1670  WalletBatch batch(GetDatabase());
1671  UnsetWalletFlagWithDB(batch, flag);
1672 }
1673 
1674 void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
1675 {
1676  LOCK(cs_wallet);
1677  m_wallet_flags &= ~flag;
1678  if (!batch.WriteWalletFlags(m_wallet_flags))
1679  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1680 }
1681 
1683 {
1685 }
1686 
1687 bool CWallet::IsWalletFlagSet(uint64_t flag) const
1688 {
1689  return (m_wallet_flags & flag);
1690 }
1691 
1693 {
1694  LOCK(cs_wallet);
1695  if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1696  // contains unknown non-tolerable wallet flags
1697  return false;
1698  }
1700 
1701  return true;
1702 }
1703 
1705 {
1706  LOCK(cs_wallet);
1707 
1708  // We should never be writing unknown non-tolerable wallet flags
1709  assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1710  // This should only be used once, when creating a new wallet - so current flags are expected to be blank
1711  assert(m_wallet_flags == 0);
1712 
1713  if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
1714  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1715  }
1716 
1717  if (!LoadWalletFlags(flags)) assert(false);
1718 }
1719 
1720 bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1721 {
1722  auto spk_man = GetLegacyScriptPubKeyMan();
1723  if (!spk_man) {
1724  return false;
1725  }
1726  LOCK(spk_man->cs_KeyStore);
1727  return spk_man->ImportScripts(scripts, timestamp);
1728 }
1729 
1730 bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1731 {
1732  auto spk_man = GetLegacyScriptPubKeyMan();
1733  if (!spk_man) {
1734  return false;
1735  }
1736  LOCK(spk_man->cs_KeyStore);
1737  return spk_man->ImportPrivKeys(privkey_map, timestamp);
1738 }
1739 
1740 bool 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)
1741 {
1742  auto spk_man = GetLegacyScriptPubKeyMan();
1743  if (!spk_man) {
1744  return false;
1745  }
1746  LOCK(spk_man->cs_KeyStore);
1747  return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
1748 }
1749 
1750 bool 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)
1751 {
1752  auto spk_man = GetLegacyScriptPubKeyMan();
1753  if (!spk_man) {
1754  return false;
1755  }
1756  LOCK(spk_man->cs_KeyStore);
1757  if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
1758  return false;
1759  }
1760  if (apply_label) {
1761  WalletBatch batch(GetDatabase());
1762  for (const CScript& script : script_pub_keys) {
1763  CTxDestination dest;
1764  ExtractDestination(script, dest);
1765  if (IsValidDestination(dest)) {
1766  SetAddressBookWithDB(batch, dest, label, AddressPurpose::RECEIVE);
1767  }
1768  }
1769  }
1770  return true;
1771 }
1772 
1774 {
1775  int64_t birthtime = m_birth_time.load();
1776  if (time < birthtime) {
1777  m_birth_time = time;
1778  }
1779 }
1780 
1789 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1790 {
1791  // Find starting block. May be null if nCreateTime is greater than the
1792  // highest blockchain timestamp, in which case there is nothing that needs
1793  // to be scanned.
1794  int start_height = 0;
1795  uint256 start_block;
1796  bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
1797  WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
1798 
1799  if (start) {
1800  // TODO: this should take into account failure by ScanResult::USER_ABORT
1801  ScanResult result = ScanForWalletTransactions(start_block, start_height, /*max_height=*/{}, reserver, /*fUpdate=*/update, /*save_progress=*/false);
1802  if (result.status == ScanResult::FAILURE) {
1803  int64_t time_max;
1804  CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
1805  return time_max + TIMESTAMP_WINDOW + 1;
1806  }
1807  }
1808  return startTime;
1809 }
1810 
1833 CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, int start_height, std::optional<int> max_height, const WalletRescanReserver& reserver, bool fUpdate, const bool save_progress)
1834 {
1835  constexpr auto INTERVAL_TIME{60s};
1836  auto current_time{reserver.now()};
1837  auto start_time{reserver.now()};
1838 
1839  assert(reserver.isReserved());
1840 
1841  uint256 block_hash = start_block;
1842  ScanResult result;
1843 
1844  std::unique_ptr<FastWalletRescanFilter> fast_rescan_filter;
1845  if (!IsLegacy() && chain().hasBlockFilterIndex(BlockFilterType::BASIC)) fast_rescan_filter = std::make_unique<FastWalletRescanFilter>(*this);
1846 
1847  WalletLogPrintf("Rescan started from block %s... (%s)\n", start_block.ToString(),
1848  fast_rescan_filter ? "fast variant using block filters" : "slow variant inspecting all blocks");
1849 
1850  fAbortRescan = false;
1851  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)
1852  uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1853  uint256 end_hash = tip_hash;
1854  if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
1855  double progress_begin = chain().guessVerificationProgress(block_hash);
1856  double progress_end = chain().guessVerificationProgress(end_hash);
1857  double progress_current = progress_begin;
1858  int block_height = start_height;
1859  while (!fAbortRescan && !chain().shutdownRequested()) {
1860  if (progress_end - progress_begin > 0.0) {
1861  m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
1862  } else { // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
1863  m_scanning_progress = 0;
1864  }
1865  if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1866  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1867  }
1868 
1869  bool next_interval = reserver.now() >= current_time + INTERVAL_TIME;
1870  if (next_interval) {
1871  current_time = reserver.now();
1872  WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
1873  }
1874 
1875  bool fetch_block{true};
1876  if (fast_rescan_filter) {
1877  fast_rescan_filter->UpdateIfNeeded();
1878  auto matches_block{fast_rescan_filter->MatchesBlock(block_hash)};
1879  if (matches_block.has_value()) {
1880  if (*matches_block) {
1881  LogPrint(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block_height, block_hash.ToString());
1882  } else {
1883  result.last_scanned_block = block_hash;
1884  result.last_scanned_height = block_height;
1885  fetch_block = false;
1886  }
1887  } else {
1888  LogPrint(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (WARNING: block filter not found!)\n", block_height, block_hash.ToString());
1889  }
1890  }
1891 
1892  // Find next block separately from reading data above, because reading
1893  // is slow and there might be a reorg while it is read.
1894  bool block_still_active = false;
1895  bool next_block = false;
1896  uint256 next_block_hash;
1897  chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
1898 
1899  if (fetch_block) {
1900  // Read block data
1901  CBlock block;
1902  chain().findBlock(block_hash, FoundBlock().data(block));
1903 
1904  if (!block.IsNull()) {
1905  LOCK(cs_wallet);
1906  if (!block_still_active) {
1907  // Abort scan if current block is no longer active, to prevent
1908  // marking transactions as coming from the wrong block.
1909  result.last_failed_block = block_hash;
1910  result.status = ScanResult::FAILURE;
1911  break;
1912  }
1913  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1914  SyncTransaction(block.vtx[posInBlock], TxStateConfirmed{block_hash, block_height, static_cast<int>(posInBlock)}, fUpdate, /*rescanning_old_block=*/true);
1915  }
1916  // scan succeeded, record block as most recent successfully scanned
1917  result.last_scanned_block = block_hash;
1918  result.last_scanned_height = block_height;
1919 
1920  if (save_progress && next_interval) {
1921  CBlockLocator loc = m_chain->getActiveChainLocator(block_hash);
1922 
1923  if (!loc.IsNull()) {
1924  WalletLogPrintf("Saving scan progress %d.\n", block_height);
1925  WalletBatch batch(GetDatabase());
1926  batch.WriteBestBlock(loc);
1927  }
1928  }
1929  } else {
1930  // could not scan block, keep scanning but record this block as the most recent failure
1931  result.last_failed_block = block_hash;
1932  result.status = ScanResult::FAILURE;
1933  }
1934  }
1935  if (max_height && block_height >= *max_height) {
1936  break;
1937  }
1938  {
1939  if (!next_block) {
1940  // break successfully when rescan has reached the tip, or
1941  // previous block is no longer on the chain due to a reorg
1942  break;
1943  }
1944 
1945  // increment block and verification progress
1946  block_hash = next_block_hash;
1947  ++block_height;
1948  progress_current = chain().guessVerificationProgress(block_hash);
1949 
1950  // handle updated tip hash
1951  const uint256 prev_tip_hash = tip_hash;
1952  tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1953  if (!max_height && prev_tip_hash != tip_hash) {
1954  // in case the tip has changed, update progress max
1955  progress_end = chain().guessVerificationProgress(tip_hash);
1956  }
1957  }
1958  }
1959  if (!max_height) {
1960  WalletLogPrintf("Scanning current mempool transactions.\n");
1961  WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
1962  }
1963  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 100); // hide progress dialog in GUI
1964  if (block_height && fAbortRescan) {
1965  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
1966  result.status = ScanResult::USER_ABORT;
1967  } else if (block_height && chain().shutdownRequested()) {
1968  WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
1969  result.status = ScanResult::USER_ABORT;
1970  } else {
1971  WalletLogPrintf("Rescan completed in %15dms\n", Ticks<std::chrono::milliseconds>(reserver.now() - start_time));
1972  }
1973  return result;
1974 }
1975 
1976 bool CWallet::SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
1977 {
1979 
1980  // Can't relay if wallet is not broadcasting
1981  if (!GetBroadcastTransactions()) return false;
1982  // Don't relay abandoned transactions
1983  if (wtx.isAbandoned()) return false;
1984  // Don't try to submit coinbase transactions. These would fail anyway but would
1985  // cause log spam.
1986  if (wtx.IsCoinBase()) return false;
1987  // Don't try to submit conflicted or confirmed transactions.
1988  if (GetTxDepthInMainChain(wtx) != 0) return false;
1989 
1990  // Submit transaction to mempool for relay
1991  WalletLogPrintf("Submitting wtx %s to mempool for relay\n", wtx.GetHash().ToString());
1992  // We must set TxStateInMempool here. Even though it will also be set later by the
1993  // entered-mempool callback, if we did not there would be a race where a
1994  // user could call sendmoney in a loop and hit spurious out of funds errors
1995  // because we think that this newly generated transaction's change is
1996  // unavailable as we're not yet aware that it is in the mempool.
1997  //
1998  // If broadcast fails for any reason, trying to set wtx.m_state here would be incorrect.
1999  // If transaction was previously in the mempool, it should be updated when
2000  // TransactionRemovedFromMempool fires.
2001  bool ret = chain().broadcastTransaction(wtx.tx, m_default_max_tx_fee, relay, err_string);
2002  if (ret) wtx.m_state = TxStateInMempool{};
2003  return ret;
2004 }
2005 
2006 std::set<uint256> CWallet::GetTxConflicts(const CWalletTx& wtx) const
2007 {
2009 
2010  const uint256 myHash{wtx.GetHash()};
2011  std::set<uint256> result{GetConflicts(myHash)};
2012  result.erase(myHash);
2013  return result;
2014 }
2015 
2017 {
2018  // Don't attempt to resubmit if the wallet is configured to not broadcast
2019  if (!fBroadcastTransactions) return false;
2020 
2021  // During reindex, importing and IBD, old wallet transactions become
2022  // unconfirmed. Don't resend them as that would spam other nodes.
2023  // We only allow forcing mempool submission when not relaying to avoid this spam.
2024  if (!chain().isReadyToBroadcast()) return false;
2025 
2026  // Do this infrequently and randomly to avoid giving away
2027  // that these are our transactions.
2028  if (NodeClock::now() < m_next_resend) return false;
2029 
2030  return true;
2031 }
2032 
2034 
2035 // Resubmit transactions from the wallet to the mempool, optionally asking the
2036 // mempool to relay them. On startup, we will do this for all unconfirmed
2037 // transactions but will not ask the mempool to relay them. We do this on startup
2038 // to ensure that our own mempool is aware of our transactions. There
2039 // is a privacy side effect here as not broadcasting on startup also means that we won't
2040 // inform the world of our wallet's state, particularly if the wallet (or node) is not
2041 // yet synced.
2042 //
2043 // Otherwise this function is called periodically in order to relay our unconfirmed txs.
2044 // We do this on a random timer to slightly obfuscate which transactions
2045 // come from our wallet.
2046 //
2047 // TODO: Ideally, we'd only resend transactions that we think should have been
2048 // mined in the most recent block. Any transaction that wasn't in the top
2049 // blockweight of transactions in the mempool shouldn't have been mined,
2050 // and so is probably just sitting in the mempool waiting to be confirmed.
2051 // Rebroadcasting does nothing to speed up confirmation and only damages
2052 // privacy.
2053 //
2054 // The `force` option results in all unconfirmed transactions being submitted to
2055 // the mempool. This does not necessarily result in those transactions being relayed,
2056 // that depends on the `relay` option. Periodic rebroadcast uses the pattern
2057 // relay=true force=false, while loading into the mempool
2058 // (on start, or after import) uses relay=false force=true.
2059 void CWallet::ResubmitWalletTransactions(bool relay, bool force)
2060 {
2061  // Don't attempt to resubmit if the wallet is configured to not broadcast,
2062  // even if forcing.
2063  if (!fBroadcastTransactions) return;
2064 
2065  int submitted_tx_count = 0;
2066 
2067  { // cs_wallet scope
2068  LOCK(cs_wallet);
2069 
2070  // First filter for the transactions we want to rebroadcast.
2071  // We use a set with WalletTxOrderComparator so that rebroadcasting occurs in insertion order
2072  std::set<CWalletTx*, WalletTxOrderComparator> to_submit;
2073  for (auto& [txid, wtx] : mapWallet) {
2074  // Only rebroadcast unconfirmed txs
2075  if (!wtx.isUnconfirmed()) continue;
2076 
2077  // Attempt to rebroadcast all txes more than 5 minutes older than
2078  // the last block, or all txs if forcing.
2079  if (!force && wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
2080  to_submit.insert(&wtx);
2081  }
2082  // Now try submitting the transactions to the memory pool and (optionally) relay them.
2083  for (auto wtx : to_submit) {
2084  std::string unused_err_string;
2085  if (SubmitTxMemoryPoolAndRelay(*wtx, unused_err_string, relay)) ++submitted_tx_count;
2086  }
2087  } // cs_wallet
2088 
2089  if (submitted_tx_count > 0) {
2090  WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
2091  }
2092 }
2093  // end of mapWallet
2095 
2097 {
2098  for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
2099  if (!pwallet->ShouldResend()) continue;
2100  pwallet->ResubmitWalletTransactions(/*relay=*/true, /*force=*/false);
2101  pwallet->SetNextResend();
2102  }
2103 }
2104 
2105 
2112 {
2114 
2115  // Build coins map
2116  std::map<COutPoint, Coin> coins;
2117  for (auto& input : tx.vin) {
2118  const auto mi = mapWallet.find(input.prevout.hash);
2119  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2120  return false;
2121  }
2122  const CWalletTx& wtx = mi->second;
2123  int prev_height = wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height : 0;
2124  coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], prev_height, wtx.IsCoinBase());
2125  }
2126  std::map<int, bilingual_str> input_errors;
2127  return SignTransaction(tx, coins, SIGHASH_DEFAULT, input_errors);
2128 }
2129 
2130 bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2131 {
2132  // Try to sign with all ScriptPubKeyMans
2133  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2134  // spk_man->SignTransaction will return true if the transaction is complete,
2135  // so we can exit early and return true if that happens
2136  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2137  return true;
2138  }
2139  }
2140 
2141  // At this point, one input was not fully signed otherwise we would have exited already
2142  return false;
2143 }
2144 
2145 TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed, bool finalize) const
2146 {
2147  if (n_signed) {
2148  *n_signed = 0;
2149  }
2150  LOCK(cs_wallet);
2151  // Get all of the previous transactions
2152  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2153  const CTxIn& txin = psbtx.tx->vin[i];
2154  PSBTInput& input = psbtx.inputs.at(i);
2155 
2156  if (PSBTInputSigned(input)) {
2157  continue;
2158  }
2159 
2160  // If we have no utxo, grab it from the wallet.
2161  if (!input.non_witness_utxo) {
2162  const uint256& txhash = txin.prevout.hash;
2163  const auto it = mapWallet.find(txhash);
2164  if (it != mapWallet.end()) {
2165  const CWalletTx& wtx = it->second;
2166  // We only need the non_witness_utxo, which is a superset of the witness_utxo.
2167  // The signing code will switch to the smaller witness_utxo if this is ok.
2168  input.non_witness_utxo = wtx.tx;
2169  }
2170  }
2171  }
2172 
2173  const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
2174 
2175  // Fill in information from ScriptPubKeyMans
2176  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2177  int n_signed_this_spkm = 0;
2178  TransactionError res = spk_man->FillPSBT(psbtx, txdata, sighash_type, sign, bip32derivs, &n_signed_this_spkm, finalize);
2179  if (res != TransactionError::OK) {
2180  return res;
2181  }
2182 
2183  if (n_signed) {
2184  (*n_signed) += n_signed_this_spkm;
2185  }
2186  }
2187 
2188  RemoveUnnecessaryTransactions(psbtx, sighash_type);
2189 
2190  // Complete if every input is now signed
2191  complete = true;
2192  for (const auto& input : psbtx.inputs) {
2193  complete &= PSBTInputSigned(input);
2194  }
2195 
2196  return TransactionError::OK;
2197 }
2198 
2199 SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2200 {
2201  SignatureData sigdata;
2202  CScript script_pub_key = GetScriptForDestination(pkhash);
2203  for (const auto& spk_man_pair : m_spk_managers) {
2204  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2205  LOCK(cs_wallet); // DescriptorScriptPubKeyMan calls IsLocked which can lock cs_wallet in a deadlocking order
2206  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2207  }
2208  }
2210 }
2211 
2212 OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
2213 {
2214  // If -changetype is specified, always use that change type.
2215  if (change_type) {
2216  return *change_type;
2217  }
2218 
2219  // if m_default_address_type is legacy, use legacy address as change.
2221  return OutputType::LEGACY;
2222  }
2223 
2224  bool any_tr{false};
2225  bool any_wpkh{false};
2226  bool any_sh{false};
2227  bool any_pkh{false};
2228 
2229  for (const auto& recipient : vecSend) {
2230  if (std::get_if<WitnessV1Taproot>(&recipient.dest)) {
2231  any_tr = true;
2232  } else if (std::get_if<WitnessV0KeyHash>(&recipient.dest)) {
2233  any_wpkh = true;
2234  } else if (std::get_if<ScriptHash>(&recipient.dest)) {
2235  any_sh = true;
2236  } else if (std::get_if<PKHash>(&recipient.dest)) {
2237  any_pkh = true;
2238  }
2239  }
2240 
2241  const bool has_bech32m_spkman(GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/true));
2242  if (has_bech32m_spkman && any_tr) {
2243  // Currently tr is the only type supported by the BECH32M spkman
2244  return OutputType::BECH32M;
2245  }
2246  const bool has_bech32_spkman(GetScriptPubKeyMan(OutputType::BECH32, /*internal=*/true));
2247  if (has_bech32_spkman && any_wpkh) {
2248  // Currently wpkh is the only type supported by the BECH32 spkman
2249  return OutputType::BECH32;
2250  }
2251  const bool has_p2sh_segwit_spkman(GetScriptPubKeyMan(OutputType::P2SH_SEGWIT, /*internal=*/true));
2252  if (has_p2sh_segwit_spkman && any_sh) {
2253  // Currently sh_wpkh is the only type supported by the P2SH_SEGWIT spkman
2254  // As of 2021 about 80% of all SH are wrapping WPKH, so use that
2255  return OutputType::P2SH_SEGWIT;
2256  }
2257  const bool has_legacy_spkman(GetScriptPubKeyMan(OutputType::LEGACY, /*internal=*/true));
2258  if (has_legacy_spkman && any_pkh) {
2259  // Currently pkh is the only type supported by the LEGACY spkman
2260  return OutputType::LEGACY;
2261  }
2262 
2263  if (has_bech32m_spkman) {
2264  return OutputType::BECH32M;
2265  }
2266  if (has_bech32_spkman) {
2267  return OutputType::BECH32;
2268  }
2269  // else use m_default_address_type for change
2270  return m_default_address_type;
2271 }
2272 
2273 void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
2274 {
2275  LOCK(cs_wallet);
2276  WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); // NOLINT(bitcoin-unterminated-logprintf)
2277 
2278  // Add tx to wallet, because if it has change it's also ours,
2279  // otherwise just for transaction history.
2280  CWalletTx* wtx = AddToWallet(tx, TxStateInactive{}, [&](CWalletTx& wtx, bool new_tx) {
2281  CHECK_NONFATAL(wtx.mapValue.empty());
2282  CHECK_NONFATAL(wtx.vOrderForm.empty());
2283  wtx.mapValue = std::move(mapValue);
2284  wtx.vOrderForm = std::move(orderForm);
2285  wtx.fTimeReceivedIsTxTime = true;
2286  wtx.fFromMe = true;
2287  return true;
2288  });
2289 
2290  // wtx can only be null if the db write failed.
2291  if (!wtx) {
2292  throw std::runtime_error(std::string(__func__) + ": Wallet db error, transaction commit failed");
2293  }
2294 
2295  // Notify that old coins are spent
2296  for (const CTxIn& txin : tx->vin) {
2297  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
2298  coin.MarkDirty();
2300  }
2301 
2302  if (!fBroadcastTransactions) {
2303  // Don't submit tx to the mempool
2304  return;
2305  }
2306 
2307  std::string err_string;
2308  if (!SubmitTxMemoryPoolAndRelay(*wtx, err_string, true)) {
2309  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
2310  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2311  }
2312 }
2313 
2315 {
2316  LOCK(cs_wallet);
2317 
2318  DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
2319  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
2320  {
2321  if (GetDatabase().Rewrite("\x04pool"))
2322  {
2323  for (const auto& spk_man_pair : m_spk_managers) {
2324  spk_man_pair.second->RewriteDB();
2325  }
2326  }
2327  }
2328 
2329  if (m_spk_managers.empty()) {
2332  }
2333 
2334  return nLoadWalletRet;
2335 }
2336 
2337 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2338 {
2340  DBErrors nZapSelectTxRet = WalletBatch(GetDatabase()).ZapSelectTx(vHashIn, vHashOut);
2341  for (const uint256& hash : vHashOut) {
2342  const auto& it = mapWallet.find(hash);
2343  wtxOrdered.erase(it->second.m_it_wtxOrdered);
2344  for (const auto& txin : it->second.tx->vin)
2345  mapTxSpends.erase(txin.prevout);
2346  mapWallet.erase(it);
2348  }
2349 
2350  if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
2351  {
2352  if (GetDatabase().Rewrite("\x04pool"))
2353  {
2354  for (const auto& spk_man_pair : m_spk_managers) {
2355  spk_man_pair.second->RewriteDB();
2356  }
2357  }
2358  }
2359 
2360  if (nZapSelectTxRet != DBErrors::LOAD_OK)
2361  return nZapSelectTxRet;
2362 
2363  MarkDirty();
2364 
2365  return DBErrors::LOAD_OK;
2366 }
2367 
2368 bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
2369 {
2370  bool fUpdated = false;
2371  bool is_mine;
2372  std::optional<AddressPurpose> purpose;
2373  {
2374  LOCK(cs_wallet);
2375  std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
2376  fUpdated = (mi != m_address_book.end() && !mi->second.IsChange());
2377  m_address_book[address].SetLabel(strName);
2378  is_mine = IsMine(address) != ISMINE_NO;
2379  if (new_purpose) { /* update purpose only if requested */
2380  purpose = m_address_book[address].purpose = new_purpose;
2381  } else {
2382  purpose = m_address_book[address].purpose;
2383  }
2384  }
2385  // In very old wallets, address purpose may not be recorded so we derive it from IsMine
2386  NotifyAddressBookChanged(address, strName, is_mine,
2387  purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND),
2388  (fUpdated ? CT_UPDATED : CT_NEW));
2389  if (new_purpose && !batch.WritePurpose(EncodeDestination(address), PurposeToString(*new_purpose)))
2390  return false;
2391  return batch.WriteName(EncodeDestination(address), strName);
2392 }
2393 
2394 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose)
2395 {
2396  WalletBatch batch(GetDatabase());
2397  return SetAddressBookWithDB(batch, address, strName, purpose);
2398 }
2399 
2401 {
2402  WalletBatch batch(GetDatabase());
2403  {
2404  LOCK(cs_wallet);
2405  // If we want to delete receiving addresses, we should avoid calling EraseAddressData because it will delete the previously_spent value. Could instead just erase the label so it becomes a change address, and keep the data.
2406  // NOTE: This isn't a problem for sending addresses because they don't have any data that needs to be kept.
2407  // When adding new address data, it should be considered here whether to retain or delete it.
2408  if (IsMine(address)) {
2409  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
2410  return false;
2411  }
2412  // Delete data rows associated with this address
2413  batch.EraseAddressData(address);
2414  m_address_book.erase(address);
2415  }
2416 
2417  NotifyAddressBookChanged(address, "", /*is_mine=*/false, AddressPurpose::SEND, CT_DELETED);
2418 
2419  batch.ErasePurpose(EncodeDestination(address));
2420  return batch.EraseName(EncodeDestination(address));
2421 }
2422 
2424 {
2426 
2427  auto legacy_spk_man = GetLegacyScriptPubKeyMan();
2428  if (legacy_spk_man) {
2429  return legacy_spk_man->KeypoolCountExternalKeys();
2430  }
2431 
2432  unsigned int count = 0;
2433  for (auto spk_man : m_external_spk_managers) {
2434  count += spk_man.second->GetKeyPoolSize();
2435  }
2436 
2437  return count;
2438 }
2439 
2440 unsigned int CWallet::GetKeyPoolSize() const
2441 {
2443 
2444  unsigned int count = 0;
2445  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2446  count += spk_man->GetKeyPoolSize();
2447  }
2448  return count;
2449 }
2450 
2451 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2452 {
2453  LOCK(cs_wallet);
2454  bool res = true;
2455  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2456  res &= spk_man->TopUp(kpSize);
2457  }
2458  return res;
2459 }
2460 
2462 {
2463  LOCK(cs_wallet);
2464  auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
2465  if (!spk_man) {
2466  return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2467  }
2468 
2469  auto op_dest = spk_man->GetNewDestination(type);
2470  if (op_dest) {
2471  SetAddressBook(*op_dest, label, AddressPurpose::RECEIVE);
2472  }
2473 
2474  return op_dest;
2475 }
2476 
2478 {
2479  LOCK(cs_wallet);
2480 
2481  ReserveDestination reservedest(this, type);
2482  auto op_dest = reservedest.GetReservedDestination(true);
2483  if (op_dest) reservedest.KeepDestination();
2484 
2485  return op_dest;
2486 }
2487 
2488 std::optional<int64_t> CWallet::GetOldestKeyPoolTime() const
2489 {
2490  LOCK(cs_wallet);
2491  if (m_spk_managers.empty()) {
2492  return std::nullopt;
2493  }
2494 
2495  std::optional<int64_t> oldest_key{std::numeric_limits<int64_t>::max()};
2496  for (const auto& spk_man_pair : m_spk_managers) {
2497  oldest_key = std::min(oldest_key, spk_man_pair.second->GetOldestKeyPoolTime());
2498  }
2499  return oldest_key;
2500 }
2501 
2502 void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
2503  for (auto& entry : mapWallet) {
2504  CWalletTx& wtx = entry.second;
2505  if (wtx.m_is_cache_empty) continue;
2506  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2507  CTxDestination dst;
2508  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
2509  wtx.MarkDirty();
2510  break;
2511  }
2512  }
2513  }
2514 }
2515 
2517 {
2519  for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book) {
2520  const auto& entry = item.second;
2521  func(item.first, entry.GetLabel(), entry.IsChange(), entry.purpose);
2522  }
2523 }
2524 
2525 std::vector<CTxDestination> CWallet::ListAddrBookAddresses(const std::optional<AddrBookFilter>& _filter) const
2526 {
2528  std::vector<CTxDestination> result;
2529  AddrBookFilter filter = _filter ? *_filter : AddrBookFilter();
2530  ForEachAddrBookEntry([&result, &filter](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
2531  // Filter by change
2532  if (filter.ignore_change && is_change) return;
2533  // Filter by label
2534  if (filter.m_op_label && *filter.m_op_label != label) return;
2535  // All good
2536  result.emplace_back(dest);
2537  });
2538  return result;
2539 }
2540 
2541 std::set<std::string> CWallet::ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const
2542 {
2544  std::set<std::string> label_set;
2545  ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label,
2546  bool _is_change, const std::optional<AddressPurpose>& _purpose) {
2547  if (_is_change) return;
2548  if (!purpose || purpose == _purpose) {
2549  label_set.insert(_label);
2550  }
2551  });
2552  return label_set;
2553 }
2554 
2556 {
2557  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
2558  if (!m_spk_man) {
2559  return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2560  }
2561 
2562  if (nIndex == -1) {
2563  CKeyPool keypool;
2564  int64_t index;
2565  auto op_address = m_spk_man->GetReservedDestination(type, internal, index, keypool);
2566  if (!op_address) return op_address;
2567  nIndex = index;
2568  address = *op_address;
2569  fInternal = keypool.fInternal;
2570  }
2571  return address;
2572 }
2573 
2575 {
2576  if (nIndex != -1) {
2578  }
2579  nIndex = -1;
2580  address = CNoDestination();
2581 }
2582 
2584 {
2585  if (nIndex != -1) {
2587  }
2588  nIndex = -1;
2589  address = CNoDestination();
2590 }
2591 
2593 {
2594  CScript scriptPubKey = GetScriptForDestination(dest);
2595  for (const auto& spk_man : GetScriptPubKeyMans(scriptPubKey)) {
2596  auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan *>(spk_man);
2597  if (signer_spk_man == nullptr) {
2598  continue;
2599  }
2601  return signer_spk_man->DisplayAddress(scriptPubKey, signer);
2602  }
2603  return false;
2604 }
2605 
2606 bool CWallet::LockCoin(const COutPoint& output, WalletBatch* batch)
2607 {
2609  setLockedCoins.insert(output);
2610  if (batch) {
2611  return batch->WriteLockedUTXO(output);
2612  }
2613  return true;
2614 }
2615 
2616 bool CWallet::UnlockCoin(const COutPoint& output, WalletBatch* batch)
2617 {
2619  bool was_locked = setLockedCoins.erase(output);
2620  if (batch && was_locked) {
2621  return batch->EraseLockedUTXO(output);
2622  }
2623  return true;
2624 }
2625 
2627 {
2629  bool success = true;
2630  WalletBatch batch(GetDatabase());
2631  for (auto it = setLockedCoins.begin(); it != setLockedCoins.end(); ++it) {
2632  success &= batch.EraseLockedUTXO(*it);
2633  }
2634  setLockedCoins.clear();
2635  return success;
2636 }
2637 
2638 bool CWallet::IsLockedCoin(const COutPoint& output) const
2639 {
2641  return setLockedCoins.count(output) > 0;
2642 }
2643 
2644 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
2645 {
2647  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2648  it != setLockedCoins.end(); it++) {
2649  COutPoint outpt = (*it);
2650  vOutpts.push_back(outpt);
2651  }
2652 }
2653  // end of Actions
2655 
2656 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
2658  mapKeyBirth.clear();
2659 
2660  // map in which we'll infer heights of other keys
2661  std::map<CKeyID, const TxStateConfirmed*> mapKeyFirstBlock;
2662  TxStateConfirmed max_confirm{uint256{}, /*height=*/-1, /*index=*/-1};
2663  max_confirm.confirmed_block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
2664  CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.confirmed_block_height, FoundBlock().hash(max_confirm.confirmed_block_hash)));
2665 
2666  {
2668  assert(spk_man != nullptr);
2669  LOCK(spk_man->cs_KeyStore);
2670 
2671  // get birth times for keys with metadata
2672  for (const auto& entry : spk_man->mapKeyMetadata) {
2673  if (entry.second.nCreateTime) {
2674  mapKeyBirth[entry.first] = entry.second.nCreateTime;
2675  }
2676  }
2677 
2678  // Prepare to infer birth heights for keys without metadata
2679  for (const CKeyID &keyid : spk_man->GetKeys()) {
2680  if (mapKeyBirth.count(keyid) == 0)
2681  mapKeyFirstBlock[keyid] = &max_confirm;
2682  }
2683 
2684  // if there are no such keys, we're done
2685  if (mapKeyFirstBlock.empty())
2686  return;
2687 
2688  // find first block that affects those keys, if there are any left
2689  for (const auto& entry : mapWallet) {
2690  // iterate over all wallet transactions...
2691  const CWalletTx &wtx = entry.second;
2692  if (auto* conf = wtx.state<TxStateConfirmed>()) {
2693  // ... which are already in a block
2694  for (const CTxOut &txout : wtx.tx->vout) {
2695  // iterate over all their outputs
2696  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
2697  // ... and all their affected keys
2698  auto rit = mapKeyFirstBlock.find(keyid);
2699  if (rit != mapKeyFirstBlock.end() && conf->confirmed_block_height < rit->second->confirmed_block_height) {
2700  rit->second = conf;
2701  }
2702  }
2703  }
2704  }
2705  }
2706  }
2707 
2708  // Extract block timestamps for those keys
2709  for (const auto& entry : mapKeyFirstBlock) {
2710  int64_t block_time;
2711  CHECK_NONFATAL(chain().findBlock(entry.second->confirmed_block_hash, FoundBlock().time(block_time)));
2712  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
2713  }
2714 }
2715 
2739 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
2740 {
2741  std::optional<uint256> block_hash;
2742  if (auto* conf = wtx.state<TxStateConfirmed>()) {
2743  block_hash = conf->confirmed_block_hash;
2744  } else if (auto* conf = wtx.state<TxStateConflicted>()) {
2745  block_hash = conf->conflicting_block_hash;
2746  }
2747 
2748  unsigned int nTimeSmart = wtx.nTimeReceived;
2749  if (block_hash) {
2750  int64_t blocktime;
2751  int64_t block_max_time;
2752  if (chain().findBlock(*block_hash, FoundBlock().time(blocktime).maxTime(block_max_time))) {
2753  if (rescanning_old_block) {
2754  nTimeSmart = block_max_time;
2755  } else {
2756  int64_t latestNow = wtx.nTimeReceived;
2757  int64_t latestEntry = 0;
2758 
2759  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
2760  int64_t latestTolerated = latestNow + 300;
2761  const TxItems& txOrdered = wtxOrdered;
2762  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2763  CWalletTx* const pwtx = it->second;
2764  if (pwtx == &wtx) {
2765  continue;
2766  }
2767  int64_t nSmartTime;
2768  nSmartTime = pwtx->nTimeSmart;
2769  if (!nSmartTime) {
2770  nSmartTime = pwtx->nTimeReceived;
2771  }
2772  if (nSmartTime <= latestTolerated) {
2773  latestEntry = nSmartTime;
2774  if (nSmartTime > latestNow) {
2775  latestNow = nSmartTime;
2776  }
2777  break;
2778  }
2779  }
2780 
2781  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2782  }
2783  } else {
2784  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), block_hash->ToString());
2785  }
2786  }
2787  return nTimeSmart;
2788 }
2789 
2791 {
2792  if (std::get_if<CNoDestination>(&dest))
2793  return false;
2794 
2795  if (!used) {
2796  if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false;
2797  return batch.WriteAddressPreviouslySpent(dest, false);
2798  }
2799 
2801  return batch.WriteAddressPreviouslySpent(dest, true);
2802 }
2803 
2805 {
2806  m_address_book[dest].previously_spent = true;
2807 }
2808 
2809 void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request)
2810 {
2811  m_address_book[dest].receive_requests[id] = request;
2812 }
2813 
2815 {
2816  if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent;
2817  return false;
2818 }
2819 
2820 std::vector<std::string> CWallet::GetAddressReceiveRequests() const
2821 {
2822  std::vector<std::string> values;
2823  for (const auto& [dest, entry] : m_address_book) {
2824  for (const auto& [id, request] : entry.receive_requests) {
2825  values.emplace_back(request);
2826  }
2827  }
2828  return values;
2829 }
2830 
2831 bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
2832 {
2833  if (!batch.WriteAddressReceiveRequest(dest, id, value)) return false;
2834  m_address_book[dest].receive_requests[id] = value;
2835  return true;
2836 }
2837 
2838 bool CWallet::EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id)
2839 {
2840  if (!batch.EraseAddressReceiveRequest(dest, id)) return false;
2841  m_address_book[dest].receive_requests.erase(id);
2842  return true;
2843 }
2844 
2845 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
2846 {
2847  // Do some checking on wallet path. It should be either a:
2848  //
2849  // 1. Path where a directory can be created.
2850  // 2. Path to an existing directory.
2851  // 3. Path to a symlink to a directory.
2852  // 4. For backwards compatibility, the name of a data file in -walletdir.
2854  fs::file_type path_type = fs::symlink_status(wallet_path).type();
2855  if (!(path_type == fs::file_type::not_found || path_type == fs::file_type::directory ||
2856  (path_type == fs::file_type::symlink && fs::is_directory(wallet_path)) ||
2857  (path_type == fs::file_type::regular && fs::PathFromString(name).filename() == fs::PathFromString(name)))) {
2858  error_string = Untranslated(strprintf(
2859  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
2860  "database/log.?????????? files can be stored, a location where such a directory could be created, "
2861  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
2864  return nullptr;
2865  }
2866  return MakeDatabase(wallet_path, options, status, error_string);
2867 }
2868 
2869 std::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)
2870 {
2871  interfaces::Chain* chain = context.chain;
2872  ArgsManager& args = *Assert(context.args);
2873  const std::string& walletFile = database->Filename();
2874 
2875  const auto start{SteadyClock::now()};
2876  // TODO: Can't use std::make_shared because we need a custom deleter but
2877  // should be possible to use std::allocate_shared.
2878  std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
2879  walletInstance->m_keypool_size = std::max(args.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{1});
2880  walletInstance->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
2881 
2882  // Load wallet
2883  bool rescan_required = false;
2884  DBErrors nLoadWalletRet = walletInstance->LoadWallet();
2885  if (nLoadWalletRet != DBErrors::LOAD_OK) {
2886  if (nLoadWalletRet == DBErrors::CORRUPT) {
2887  error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
2888  return nullptr;
2889  }
2890  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
2891  {
2892  warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
2893  " or address metadata may be missing or incorrect."),
2894  walletFile));
2895  }
2896  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
2897  error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
2898  return nullptr;
2899  }
2900  else if (nLoadWalletRet == DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED) {
2901  error = strprintf(_("Error loading %s: External signer wallet being loaded without external signer support compiled"), walletFile);
2902  return nullptr;
2903  }
2904  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
2905  {
2906  error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
2907  return nullptr;
2908  } else if (nLoadWalletRet == DBErrors::NEED_RESCAN) {
2909  warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
2910  " Rescanning wallet."), walletFile));
2911  rescan_required = true;
2912  } else if (nLoadWalletRet == DBErrors::UNKNOWN_DESCRIPTOR) {
2913  error = strprintf(_("Unrecognized descriptor found. Loading wallet %s\n\n"
2914  "The wallet might had been created on a newer version.\n"
2915  "Please try running the latest software version.\n"), walletFile);
2916  return nullptr;
2917  } else if (nLoadWalletRet == DBErrors::UNEXPECTED_LEGACY_ENTRY) {
2918  error = strprintf(_("Unexpected legacy entry in descriptor wallet found. Loading wallet %s\n\n"
2919  "The wallet might have been tampered with or created with malicious intent.\n"), walletFile);
2920  return nullptr;
2921  } else {
2922  error = strprintf(_("Error loading %s"), walletFile);
2923  return nullptr;
2924  }
2925  }
2926 
2927  // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
2928  const bool fFirstRun = walletInstance->m_spk_managers.empty() &&
2929  !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2930  !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
2931  if (fFirstRun)
2932  {
2933  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
2934  walletInstance->SetMinVersion(FEATURE_LATEST);
2935 
2936  walletInstance->InitWalletFlags(wallet_creation_flags);
2937 
2938  // Only create LegacyScriptPubKeyMan when not descriptor wallet
2939  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2940  walletInstance->SetupLegacyScriptPubKeyMan();
2941  }
2942 
2943  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) || !(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
2944  LOCK(walletInstance->cs_wallet);
2945  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2946  walletInstance->SetupDescriptorScriptPubKeyMans();
2947  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
2948  } else {
2949  // Legacy wallets need SetupGeneration here.
2950  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2951  if (!spk_man->SetupGeneration()) {
2952  error = _("Unable to generate initial keys");
2953  return nullptr;
2954  }
2955  }
2956  }
2957  }
2958 
2959  if (chain) {
2960  walletInstance->chainStateFlushed(ChainstateRole::NORMAL, chain->getTipLocator());
2961  }
2962  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
2963  // Make it impossible to disable private keys after creation
2964  error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
2965  return nullptr;
2966  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
2967  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2968  if (spk_man->HavePrivateKeys()) {
2969  warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
2970  break;
2971  }
2972  }
2973  }
2974 
2975  if (!args.GetArg("-addresstype", "").empty()) {
2976  std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-addresstype", ""));
2977  if (!parsed) {
2978  error = strprintf(_("Unknown address type '%s'"), args.GetArg("-addresstype", ""));
2979  return nullptr;
2980  }
2981  walletInstance->m_default_address_type = parsed.value();
2982  }
2983 
2984  if (!args.GetArg("-changetype", "").empty()) {
2985  std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-changetype", ""));
2986  if (!parsed) {
2987  error = strprintf(_("Unknown change type '%s'"), args.GetArg("-changetype", ""));
2988  return nullptr;
2989  }
2990  walletInstance->m_default_change_type = parsed.value();
2991  }
2992 
2993  if (args.IsArgSet("-mintxfee")) {
2994  std::optional<CAmount> min_tx_fee = ParseMoney(args.GetArg("-mintxfee", ""));
2995  if (!min_tx_fee) {
2996  error = AmountErrMsg("mintxfee", args.GetArg("-mintxfee", ""));
2997  return nullptr;
2998  } else if (min_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
2999  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
3000  _("This is the minimum transaction fee you pay on every transaction."));
3001  }
3002 
3003  walletInstance->m_min_fee = CFeeRate{min_tx_fee.value()};
3004  }
3005 
3006  if (args.IsArgSet("-maxapsfee")) {
3007  const std::string max_aps_fee{args.GetArg("-maxapsfee", "")};
3008  if (max_aps_fee == "-1") {
3009  walletInstance->m_max_aps_fee = -1;
3010  } else if (std::optional<CAmount> max_fee = ParseMoney(max_aps_fee)) {
3011  if (max_fee.value() > HIGH_APS_FEE) {
3012  warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
3013  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
3014  }
3015  walletInstance->m_max_aps_fee = max_fee.value();
3016  } else {
3017  error = AmountErrMsg("maxapsfee", max_aps_fee);
3018  return nullptr;
3019  }
3020  }
3021 
3022  if (args.IsArgSet("-fallbackfee")) {
3023  std::optional<CAmount> fallback_fee = ParseMoney(args.GetArg("-fallbackfee", ""));
3024  if (!fallback_fee) {
3025  error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-fallbackfee", args.GetArg("-fallbackfee", ""));
3026  return nullptr;
3027  } else if (fallback_fee.value() > HIGH_TX_FEE_PER_KB) {
3028  warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
3029  _("This is the transaction fee you may pay when fee estimates are not available."));
3030  }
3031  walletInstance->m_fallback_fee = CFeeRate{fallback_fee.value()};
3032  }
3033 
3034  // Disable fallback fee in case value was set to 0, enable if non-null value
3035  walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
3036 
3037  if (args.IsArgSet("-discardfee")) {
3038  std::optional<CAmount> discard_fee = ParseMoney(args.GetArg("-discardfee", ""));
3039  if (!discard_fee) {
3040  error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-discardfee", args.GetArg("-discardfee", ""));
3041  return nullptr;
3042  } else if (discard_fee.value() > HIGH_TX_FEE_PER_KB) {
3043  warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
3044  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
3045  }
3046  walletInstance->m_discard_rate = CFeeRate{discard_fee.value()};
3047  }
3048 
3049  if (args.IsArgSet("-paytxfee")) {
3050  std::optional<CAmount> pay_tx_fee = ParseMoney(args.GetArg("-paytxfee", ""));
3051  if (!pay_tx_fee) {
3052  error = AmountErrMsg("paytxfee", args.GetArg("-paytxfee", ""));
3053  return nullptr;
3054  } else if (pay_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
3055  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
3056  _("This is the transaction fee you will pay if you send a transaction."));
3057  }
3058 
3059  walletInstance->m_pay_tx_fee = CFeeRate{pay_tx_fee.value(), 1000};
3060 
3061  if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
3062  error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least %s)"),
3063  "-paytxfee", args.GetArg("-paytxfee", ""), chain->relayMinFee().ToString());
3064  return nullptr;
3065  }
3066  }
3067 
3068  if (args.IsArgSet("-maxtxfee")) {
3069  std::optional<CAmount> max_fee = ParseMoney(args.GetArg("-maxtxfee", ""));
3070  if (!max_fee) {
3071  error = AmountErrMsg("maxtxfee", args.GetArg("-maxtxfee", ""));
3072  return nullptr;
3073  } else if (max_fee.value() > HIGH_MAX_TX_FEE) {
3074  warnings.push_back(strprintf(_("%s is set very high! Fees this large could be paid on a single transaction."), "-maxtxfee"));
3075  }
3076 
3077  if (chain && CFeeRate{max_fee.value(), 1000} < chain->relayMinFee()) {
3078  error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3079  "-maxtxfee", args.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
3080  return nullptr;
3081  }
3082 
3083  walletInstance->m_default_max_tx_fee = max_fee.value();
3084  }
3085 
3086  if (args.IsArgSet("-consolidatefeerate")) {
3087  if (std::optional<CAmount> consolidate_feerate = ParseMoney(args.GetArg("-consolidatefeerate", ""))) {
3088  walletInstance->m_consolidate_feerate = CFeeRate(*consolidate_feerate);
3089  } else {
3090  error = AmountErrMsg("consolidatefeerate", args.GetArg("-consolidatefeerate", ""));
3091  return nullptr;
3092  }
3093  }
3094 
3096  warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
3097  _("The wallet will avoid paying less than the minimum relay fee."));
3098  }
3099 
3100  walletInstance->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3101  walletInstance->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3102  walletInstance->m_signal_rbf = args.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3103 
3104  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
3105 
3106  // Try to top up keypool. No-op if the wallet is locked.
3107  walletInstance->TopUpKeyPool();
3108 
3109  // Cache the first key time
3110  std::optional<int64_t> time_first_key;
3111  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
3112  int64_t time = spk_man->GetTimeFirstKey();
3113  if (!time_first_key || time < *time_first_key) time_first_key = time;
3114  }
3115  if (time_first_key) walletInstance->MaybeUpdateBirthTime(*time_first_key);
3116 
3117  if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
3118  return nullptr;
3119  }
3120 
3121  {
3122  LOCK(walletInstance->cs_wallet);
3123  walletInstance->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3124  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3125  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3126  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
3127  }
3128 
3129  return walletInstance;
3130 }
3131 
3132 bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings)
3133 {
3134  LOCK(walletInstance->cs_wallet);
3135  // allow setting the chain if it hasn't been set already but prevent changing it
3136  assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
3137  walletInstance->m_chain = &chain;
3138 
3139  // Unless allowed, ensure wallet files are not reused across chains:
3140  if (!gArgs.GetBoolArg("-walletcrosschain", DEFAULT_WALLETCROSSCHAIN)) {
3141  WalletBatch batch(walletInstance->GetDatabase());
3142  CBlockLocator locator;
3143  if (batch.ReadBestBlock(locator) && locator.vHave.size() > 0 && chain.getHeight()) {
3144  // Wallet is assumed to be from another chain, if genesis block in the active
3145  // chain differs from the genesis block known to the wallet.
3146  if (chain.getBlockHash(0) != locator.vHave.back()) {
3147  error = Untranslated("Wallet files should not be reused across chains. Restart bitcoind with -walletcrosschain to override.");
3148  return false;
3149  }
3150  }
3151  }
3152 
3153  // Register wallet with validationinterface. It's done before rescan to avoid
3154  // missing block connections between end of rescan and validation subscribing.
3155  // Because of wallet lock being hold, block connection notifications are going to
3156  // be pending on the validation-side until lock release. It's likely to have
3157  // block processing duplicata (if rescan block range overlaps with notification one)
3158  // but we guarantee at least than wallet state is correct after notifications delivery.
3159  // However, chainStateFlushed notifications are ignored until the rescan is finished
3160  // so that in case of a shutdown event, the rescan will be repeated at the next start.
3161  // This is temporary until rescan and notifications delivery are unified under same
3162  // interface.
3163  walletInstance->m_attaching_chain = true; //ignores chainStateFlushed notifications
3164  walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
3165 
3166  // If rescan_required = true, rescan_height remains equal to 0
3167  int rescan_height = 0;
3168  if (!rescan_required)
3169  {
3170  WalletBatch batch(walletInstance->GetDatabase());
3171  CBlockLocator locator;
3172  if (batch.ReadBestBlock(locator)) {
3173  if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
3174  rescan_height = *fork_height;
3175  }
3176  }
3177  }
3178 
3179  const std::optional<int> tip_height = chain.getHeight();
3180  if (tip_height) {
3181  walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
3182  walletInstance->m_last_block_processed_height = *tip_height;
3183  } else {
3184  walletInstance->m_last_block_processed.SetNull();
3185  walletInstance->m_last_block_processed_height = -1;
3186  }
3187 
3188  if (tip_height && *tip_height != rescan_height)
3189  {
3190  // No need to read and scan block if block was created before
3191  // our wallet birthday (as adjusted for block time variability)
3192  std::optional<int64_t> time_first_key = walletInstance->m_birth_time.load();
3193  if (time_first_key) {
3194  FoundBlock found = FoundBlock().height(rescan_height);
3195  chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
3196  if (!found.found) {
3197  // We were unable to find a block that had a time more recent than our earliest timestamp
3198  // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
3199  // current chain tip. Skip rescanning in this case.
3200  rescan_height = *tip_height;
3201  }
3202  }
3203 
3204  // Technically we could execute the code below in any case, but performing the
3205  // `while` loop below can make startup very slow, so only check blocks on disk
3206  // if necessary.
3208  int block_height = *tip_height;
3209  while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
3210  --block_height;
3211  }
3212 
3213  if (rescan_height != block_height) {
3214  // We can't rescan beyond blocks we don't have data for, stop and throw an error.
3215  // This might happen if a user uses an old wallet within a pruned node
3216  // or if they ran -disablewallet for a longer time, then decided to re-enable
3217  // Exit early and print an error.
3218  // It also may happen if an assumed-valid chain is in use and therefore not
3219  // all block data is available.
3220  // If a block is pruned after this check, we will load the wallet,
3221  // but fail the rescan with a generic error.
3222 
3223  error = chain.havePruned() ?
3224  _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)") :
3225  strprintf(_(
3226  "Error loading wallet. Wallet requires blocks to be downloaded, "
3227  "and software does not currently support loading wallets while "
3228  "blocks are being downloaded out of order when using assumeutxo "
3229  "snapshots. Wallet should be able to load successfully after "
3230  "node sync reaches height %s"), block_height);
3231  return false;
3232  }
3233  }
3234 
3235  chain.initMessage(_("Rescanning…").translated);
3236  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
3237 
3238  {
3239  WalletRescanReserver reserver(*walletInstance);
3240  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, /*max_height=*/{}, reserver, /*fUpdate=*/true, /*save_progress=*/true).status)) {
3241  error = _("Failed to rescan the wallet during initialization");
3242  return false;
3243  }
3244  }
3245  walletInstance->m_attaching_chain = false;
3246  walletInstance->chainStateFlushed(ChainstateRole::NORMAL, chain.getTipLocator());
3247  walletInstance->GetDatabase().IncrementUpdateCounter();
3248  }
3249  walletInstance->m_attaching_chain = false;
3250 
3251  return true;
3252 }
3253 
3254 const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
3255 {
3256  const auto& address_book_it = m_address_book.find(dest);
3257  if (address_book_it == m_address_book.end()) return nullptr;
3258  if ((!allow_change) && address_book_it->second.IsChange()) {
3259  return nullptr;
3260  }
3261  return &address_book_it->second;
3262 }
3263 
3265 {
3266  int prev_version = GetVersion();
3267  if (version == 0) {
3268  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3269  version = FEATURE_LATEST;
3270  } else {
3271  WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
3272  }
3273  if (version < prev_version) {
3274  error = strprintf(_("Cannot downgrade wallet from version %i to version %i. Wallet version unchanged."), prev_version, version);
3275  return false;
3276  }
3277 
3278  LOCK(cs_wallet);
3279 
3280  // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
3282  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);
3283  return false;
3284  }
3285 
3286  // Permanently upgrade to the version
3288 
3289  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3290  if (!spk_man->Upgrade(prev_version, version, error)) {
3291  return false;
3292  }
3293  }
3294  return true;
3295 }
3296 
3298 {
3299  // Add wallet transactions that aren't already in a block to mempool
3300  // Do this here as mempool requires genesis block to be loaded
3301  ResubmitWalletTransactions(/*relay=*/false, /*force=*/true);
3302 
3303  // Update wallet transactions with current mempool transactions.
3304  WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
3305 }
3306 
3307 bool CWallet::BackupWallet(const std::string& strDest) const
3308 {
3309  return GetDatabase().Backup(strDest);
3310 }
3311 
3313 {
3314  nTime = GetTime();
3315  fInternal = false;
3316  m_pre_split = false;
3317 }
3318 
3319 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
3320 {
3321  nTime = GetTime();
3322  vchPubKey = vchPubKeyIn;
3323  fInternal = internalIn;
3324  m_pre_split = false;
3325 }
3326 
3328 {
3330  if (auto* conf = wtx.state<TxStateConfirmed>()) {
3331  return GetLastBlockHeight() - conf->confirmed_block_height + 1;
3332  } else if (auto* conf = wtx.state<TxStateConflicted>()) {
3333  return -1 * (GetLastBlockHeight() - conf->conflicting_block_height + 1);
3334  } else {
3335  return 0;
3336  }
3337 }
3338 
3340 {
3342 
3343  if (!wtx.IsCoinBase()) {
3344  return 0;
3345  }
3346  int chain_depth = GetTxDepthInMainChain(wtx);
3347  assert(chain_depth >= 0); // coinbase tx should not be conflicted
3348  return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
3349 }
3350 
3352 {
3354 
3355  // note GetBlocksToMaturity is 0 for non-coinbase tx
3356  return GetTxBlocksToMaturity(wtx) > 0;
3357 }
3358 
3360 {
3361  return HasEncryptionKeys();
3362 }
3363 
3364 bool CWallet::IsLocked() const
3365 {
3366  if (!IsCrypted()) {
3367  return false;
3368  }
3369  LOCK(cs_wallet);
3370  return vMasterKey.empty();
3371 }
3372 
3374 {
3375  if (!IsCrypted())
3376  return false;
3377 
3378  {
3380  if (!vMasterKey.empty()) {
3381  memory_cleanse(vMasterKey.data(), vMasterKey.size() * sizeof(decltype(vMasterKey)::value_type));
3382  vMasterKey.clear();
3383  }
3384  }
3385 
3386  NotifyStatusChanged(this);
3387  return true;
3388 }
3389 
3390 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn, bool accept_no_keys)
3391 {
3392  {
3393  LOCK(cs_wallet);
3394  for (const auto& spk_man_pair : m_spk_managers) {
3395  if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn, accept_no_keys)) {
3396  return false;
3397  }
3398  }
3399  vMasterKey = vMasterKeyIn;
3400  }
3401  NotifyStatusChanged(this);
3402  return true;
3403 }
3404 
3405 std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
3406 {
3407  std::set<ScriptPubKeyMan*> spk_mans;
3408  for (bool internal : {false, true}) {
3409  for (OutputType t : OUTPUT_TYPES) {
3410  auto spk_man = GetScriptPubKeyMan(t, internal);
3411  if (spk_man) {
3412  spk_mans.insert(spk_man);
3413  }
3414  }
3415  }
3416  return spk_mans;
3417 }
3418 
3419 std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
3420 {
3421  std::set<ScriptPubKeyMan*> spk_mans;
3422  for (const auto& spk_man_pair : m_spk_managers) {
3423  spk_mans.insert(spk_man_pair.second.get());
3424  }
3425  return spk_mans;
3426 }
3427 
3428 ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
3429 {
3430  const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
3431  std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
3432  if (it == spk_managers.end()) {
3433  return nullptr;
3434  }
3435  return it->second;
3436 }
3437 
3438 std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script) const
3439 {
3440  std::set<ScriptPubKeyMan*> spk_mans;
3441  SignatureData sigdata;
3442  for (const auto& spk_man_pair : m_spk_managers) {
3443  if (spk_man_pair.second->CanProvide(script, sigdata)) {
3444  spk_mans.insert(spk_man_pair.second.get());
3445  }
3446  }
3447  return spk_mans;
3448 }
3449 
3451 {
3452  if (m_spk_managers.count(id) > 0) {
3453  return m_spk_managers.at(id).get();
3454  }
3455  return nullptr;
3456 }
3457 
3458 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
3459 {
3460  SignatureData sigdata;
3461  return GetSolvingProvider(script, sigdata);
3462 }
3463 
3464 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
3465 {
3466  for (const auto& spk_man_pair : m_spk_managers) {
3467  if (spk_man_pair.second->CanProvide(script, sigdata)) {
3468  return spk_man_pair.second->GetSolvingProvider(script);
3469  }
3470  }
3471  return nullptr;
3472 }
3473 
3474 std::vector<WalletDescriptor> CWallet::GetWalletDescriptors(const CScript& script) const
3475 {
3476  std::vector<WalletDescriptor> descs;
3477  for (const auto spk_man: GetScriptPubKeyMans(script)) {
3478  if (const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man)) {
3479  LOCK(desc_spk_man->cs_desc_man);
3480  descs.push_back(desc_spk_man->GetWalletDescriptor());
3481  }
3482  }
3483  return descs;
3484 }
3485 
3487 {
3489  return nullptr;
3490  }
3491  // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
3492  // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
3494  if (it == m_internal_spk_managers.end()) return nullptr;
3495  return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
3496 }
3497 
3499 {
3501  return GetLegacyScriptPubKeyMan();
3502 }
3503 
3504 void CWallet::AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man)
3505 {
3506  // Add spkm_man to m_spk_managers before calling any method
3507  // that might access it.
3508  const auto& spkm = m_spk_managers[id] = std::move(spkm_man);
3509 
3510  // Update birth time if needed
3511  MaybeUpdateBirthTime(spkm->GetTimeFirstKey());
3512 }
3513 
3515 {
3517  return;
3518  }
3519 
3520  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this, m_keypool_size));
3521  for (const auto& type : LEGACY_OUTPUT_TYPES) {
3522  m_internal_spk_managers[type] = spk_manager.get();
3523  m_external_spk_managers[type] = spk_manager.get();
3524  }
3525  uint256 id = spk_manager->GetID();
3526  AddScriptPubKeyMan(id, std::move(spk_manager));
3527 }
3528 
3530 {
3531  return vMasterKey;
3532 }
3533 
3535 {
3536  return !mapMasterKeys.empty();
3537 }
3538 
3540 {
3541  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
3542  spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
3543  spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
3544  spk_man->NotifyFirstKeyTimeChanged.connect(std::bind(&CWallet::MaybeUpdateBirthTime, this, std::placeholders::_2));
3545  }
3546 }
3547 
3549 {
3551  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, desc, m_keypool_size));
3552  AddScriptPubKeyMan(id, std::move(spk_manager));
3553  } else {
3554  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size));
3555  AddScriptPubKeyMan(id, std::move(spk_manager));
3556  }
3557 }
3558 
3560 {
3562 
3563  for (bool internal : {false, true}) {
3564  for (OutputType t : OUTPUT_TYPES) {
3565  auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, m_keypool_size));
3566  if (IsCrypted()) {
3567  if (IsLocked()) {
3568  throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
3569  }
3570  if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, nullptr)) {
3571  throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
3572  }
3573  }
3574  spk_manager->SetupDescriptorGeneration(master_key, t, internal);
3575  uint256 id = spk_manager->GetID();
3576  AddScriptPubKeyMan(id, std::move(spk_manager));
3577  AddActiveScriptPubKeyMan(id, t, internal);
3578  }
3579  }
3580 }
3581 
3583 {
3585 
3587  // Make a seed
3588  CKey seed_key;
3589  seed_key.MakeNewKey(true);
3590  CPubKey seed = seed_key.GetPubKey();
3591  assert(seed_key.VerifyPubKey(seed));
3592 
3593  // Get the extended key
3594  CExtKey master_key;
3595  master_key.SetSeed(seed_key);
3596 
3597  SetupDescriptorScriptPubKeyMans(master_key);
3598  } else {
3600 
3601  // TODO: add account parameter
3602  int account = 0;
3603  UniValue signer_res = signer.GetDescriptors(account);
3604 
3605  if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3606  for (bool internal : {false, true}) {
3607  const UniValue& descriptor_vals = signer_res.find_value(internal ? "internal" : "receive");
3608  if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3609  for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
3610  const std::string& desc_str = desc_val.getValStr();
3611  FlatSigningProvider keys;
3612  std::string desc_error;
3613  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, desc_error, false);
3614  if (desc == nullptr) {
3615  throw std::runtime_error(std::string(__func__) + ": Invalid descriptor \"" + desc_str + "\" (" + desc_error + ")");
3616  }
3617  if (!desc->GetOutputType()) {
3618  continue;
3619  }
3620  OutputType t = *desc->GetOutputType();
3621  auto spk_manager = std::unique_ptr<ExternalSignerScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, m_keypool_size));
3622  spk_manager->SetupDescriptor(std::move(desc));
3623  uint256 id = spk_manager->GetID();
3624  AddScriptPubKeyMan(id, std::move(spk_manager));
3625  AddActiveScriptPubKeyMan(id, t, internal);
3626  }
3627  }
3628  }
3629 }
3630 
3632 {
3633  WalletBatch batch(GetDatabase());
3634  if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
3635  throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
3636  }
3637  LoadActiveScriptPubKeyMan(id, type, internal);
3638 }
3639 
3641 {
3642  // Activating ScriptPubKeyManager for a given output and change type is incompatible with legacy wallets.
3643  // Legacy wallets have only one ScriptPubKeyManager and it's active for all output and change types.
3645 
3646  WalletLogPrintf("Setting spkMan to active: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3647  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3648  auto& spk_mans_other = internal ? m_external_spk_managers : m_internal_spk_managers;
3649  auto spk_man = m_spk_managers.at(id).get();
3650  spk_mans[type] = spk_man;
3651 
3652  const auto it = spk_mans_other.find(type);
3653  if (it != spk_mans_other.end() && it->second == spk_man) {
3654  spk_mans_other.erase(type);
3655  }
3656 
3658 }
3659 
3661 {
3662  auto spk_man = GetScriptPubKeyMan(type, internal);
3663  if (spk_man != nullptr && spk_man->GetID() == id) {
3664  WalletLogPrintf("Deactivate spkMan: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3665  WalletBatch batch(GetDatabase());
3666  if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type), internal)) {
3667  throw std::runtime_error(std::string(__func__) + ": erasing active ScriptPubKeyMan id failed");
3668  }
3669 
3670  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3671  spk_mans.erase(type);
3672  }
3673 
3675 }
3676 
3677 bool CWallet::IsLegacy() const
3678 {
3679  if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
3680  return false;
3681  }
3682  auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
3683  return spk_man != nullptr;
3684 }
3685 
3687 {
3688  for (auto& spk_man_pair : m_spk_managers) {
3689  // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
3690  DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
3691  if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3692  return spk_manager;
3693  }
3694  }
3695 
3696  return nullptr;
3697 }
3698 
3699 std::optional<bool> CWallet::IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const
3700 {
3701  // Legacy script pubkey man can't be either external or internal
3702  if (IsLegacy()) {
3703  return std::nullopt;
3704  }
3705 
3706  // only active ScriptPubKeyMan can be internal
3707  if (!GetActiveScriptPubKeyMans().count(spk_man)) {
3708  return std::nullopt;
3709  }
3710 
3711  const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
3712  if (!desc_spk_man) {
3713  throw std::runtime_error(std::string(__func__) + ": unexpected ScriptPubKeyMan type.");
3714  }
3715 
3716  LOCK(desc_spk_man->cs_desc_man);
3717  const auto& type = desc_spk_man->GetWalletDescriptor().descriptor->GetOutputType();
3718  assert(type.has_value());
3719 
3720  return GetScriptPubKeyMan(*type, /* internal= */ true) == desc_spk_man;
3721 }
3722 
3723 ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
3724 {
3726 
3728  WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
3729  return nullptr;
3730  }
3731 
3732  auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3733  if (spk_man) {
3734  WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
3735  spk_man->UpdateWalletDescriptor(desc);
3736  } else {
3737  auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size));
3738  spk_man = new_spk_man.get();
3739 
3740  // Save the descriptor to memory
3741  uint256 id = new_spk_man->GetID();
3742  AddScriptPubKeyMan(id, std::move(new_spk_man));
3743  }
3744 
3745  // Add the private keys to the descriptor
3746  for (const auto& entry : signing_provider.keys) {
3747  const CKey& key = entry.second;
3748  spk_man->AddDescriptorKey(key, key.GetPubKey());
3749  }
3750 
3751  // Top up key pool, the manager will generate new scriptPubKeys internally
3752  if (!spk_man->TopUp()) {
3753  WalletLogPrintf("Could not top up scriptPubKeys\n");
3754  return nullptr;
3755  }
3756 
3757  // Apply the label if necessary
3758  // Note: we disable labels for ranged descriptors
3759  if (!desc.descriptor->IsRange()) {
3760  auto script_pub_keys = spk_man->GetScriptPubKeys();
3761  if (script_pub_keys.empty()) {
3762  WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
3763  return nullptr;
3764  }
3765 
3766  if (!internal) {
3767  for (const auto& script : script_pub_keys) {
3768  CTxDestination dest;
3769  if (ExtractDestination(script, dest)) {
3771  }
3772  }
3773  }
3774  }
3775 
3776  // Save the descriptor to DB
3777  spk_man->WriteDescriptor();
3778 
3779  return spk_man;
3780 }
3781 
3783 {
3785 
3786  WalletLogPrintf("Migrating wallet storage database from BerkeleyDB to SQLite.\n");
3787 
3788  if (m_database->Format() == "sqlite") {
3789  error = _("Error: This wallet already uses SQLite");
3790  return false;
3791  }
3792 
3793  // Get all of the records for DB type migration
3794  std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();
3795  std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
3796  std::vector<std::pair<SerializeData, SerializeData>> records;
3797  if (!cursor) {
3798  error = _("Error: Unable to begin reading all records in the database");
3799  return false;
3800  }
3802  while (true) {
3803  DataStream ss_key{};
3804  DataStream ss_value{};
3805  status = cursor->Next(ss_key, ss_value);
3806  if (status != DatabaseCursor::Status::MORE) {
3807  break;
3808  }
3809  SerializeData key(ss_key.begin(), ss_key.end());
3810  SerializeData value(ss_value.begin(), ss_value.end());
3811  records.emplace_back(key, value);
3812  }
3813  cursor.reset();
3814  batch.reset();
3815  if (status != DatabaseCursor::Status::DONE) {
3816  error = _("Error: Unable to read all records in the database");
3817  return false;
3818  }
3819 
3820  // Close this database and delete the file
3821  fs::path db_path = fs::PathFromString(m_database->Filename());
3822  m_database->Close();
3823  fs::remove(db_path);
3824 
3825  // Generate the path for the location of the migrated wallet
3826  // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
3828 
3829  // Make new DB
3830  DatabaseOptions opts;
3831  opts.require_create = true;
3833  DatabaseStatus db_status;
3834  std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
3835  assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
3836  m_database.reset();
3837  m_database = std::move(new_db);
3838 
3839  // Write existing records into the new DB
3840  batch = m_database->MakeBatch();
3841  bool began = batch->TxnBegin();
3842  assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3843  for (const auto& [key, value] : records) {
3844  if (!batch->Write(Span{key}, Span{value})) {
3845  batch->TxnAbort();
3846  m_database->Close();
3847  fs::remove(m_database->Filename());
3848  assert(false); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3849  }
3850  }
3851  bool committed = batch->TxnCommit();
3852  assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.
3853  return true;
3854 }
3855 
3856 std::optional<MigrationData> CWallet::GetDescriptorsForLegacy(bilingual_str& error) const
3857 {
3859 
3861  assert(legacy_spkm);
3862 
3863  std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();
3864  if (res == std::nullopt) {
3865  error = _("Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.");
3866  return std::nullopt;
3867  }
3868  return res;
3869 }
3870 
3872 {
3874 
3876  if (!legacy_spkm) {
3877  error = _("Error: This wallet is already a descriptor wallet");
3878  return false;
3879  }
3880 
3881  // Get all invalid or non-watched scripts that will not be migrated
3882  std::set<CTxDestination> not_migrated_dests;
3883  for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {
3884  CTxDestination dest;
3885  if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);
3886  }
3887 
3888  for (auto& desc_spkm : data.desc_spkms) {
3889  if (m_spk_managers.count(desc_spkm->GetID()) > 0) {
3890  error = _("Error: Duplicate descriptors created during migration. Your wallet may be corrupted.");
3891  return false;
3892  }
3893  uint256 id = desc_spkm->GetID();
3894  AddScriptPubKeyMan(id, std::move(desc_spkm));
3895  }
3896 
3897  // Remove the LegacyScriptPubKeyMan from disk
3898  if (!legacy_spkm->DeleteRecords()) {
3899  return false;
3900  }
3901 
3902  // Remove the LegacyScriptPubKeyMan from memory
3903  m_spk_managers.erase(legacy_spkm->GetID());
3904  m_external_spk_managers.clear();
3905  m_internal_spk_managers.clear();
3906 
3907  // Setup new descriptors
3908  SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
3910  // Use the existing master key if we have it
3911  if (data.master_key.key.IsValid()) {
3913  } else {
3914  // Setup with a new seed if we don't.
3916  }
3917  }
3918 
3919  // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.
3920  // We need to go through these in the tx insertion order so that lookups to spends works.
3921  std::vector<uint256> txids_to_delete;
3922  std::unique_ptr<WalletBatch> watchonly_batch;
3923  if (data.watchonly_wallet) {
3924  watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());
3925  // Copy the next tx order pos to the watchonly wallet
3926  LOCK(data.watchonly_wallet->cs_wallet);
3927  data.watchonly_wallet->nOrderPosNext = nOrderPosNext;
3928  watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);
3929  }
3930  for (const auto& [_pos, wtx] : wtxOrdered) {
3931  if (!IsMine(*wtx->tx) && !IsFromMe(*wtx->tx)) {
3932  // Check it is the watchonly wallet's
3933  // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for
3934  if (data.watchonly_wallet) {
3935  LOCK(data.watchonly_wallet->cs_wallet);
3936  if (data.watchonly_wallet->IsMine(*wtx->tx) || data.watchonly_wallet->IsFromMe(*wtx->tx)) {
3937  // Add to watchonly wallet
3938  const uint256& hash = wtx->GetHash();
3939  const CWalletTx& to_copy_wtx = *wtx;
3940  if (!data.watchonly_wallet->LoadToWallet(hash, [&](CWalletTx& ins_wtx, bool new_tx) EXCLUSIVE_LOCKS_REQUIRED(data.watchonly_wallet->cs_wallet) {
3941  if (!new_tx) return false;
3942  ins_wtx.SetTx(to_copy_wtx.tx);
3943  ins_wtx.CopyFrom(to_copy_wtx);
3944  return true;
3945  })) {
3946  error = strprintf(_("Error: Could not add watchonly tx %s to watchonly wallet"), wtx->GetHash().GetHex());
3947  return false;
3948  }
3949  watchonly_batch->WriteTx(data.watchonly_wallet->mapWallet.at(hash));
3950  // Mark as to remove from this wallet
3951  txids_to_delete.push_back(hash);
3952  continue;
3953  }
3954  }
3955  // Both not ours and not in the watchonly wallet
3956  error = strprintf(_("Error: Transaction %s in wallet cannot be identified to belong to migrated wallets"), wtx->GetHash().GetHex());
3957  return false;
3958  }
3959  }
3960  watchonly_batch.reset(); // Flush
3961  // Do the removes
3962  if (txids_to_delete.size() > 0) {
3963  std::vector<uint256> deleted_txids;
3964  if (ZapSelectTx(txids_to_delete, deleted_txids) != DBErrors::LOAD_OK) {
3965  error = _("Error: Could not delete watchonly transactions");
3966  return false;
3967  }
3968  if (deleted_txids != txids_to_delete) {
3969  error = _("Error: Not all watchonly txs could be deleted");
3970  return false;
3971  }
3972  // Tell the GUI of each tx
3973  for (const uint256& txid : deleted_txids) {
3975  }
3976  }
3977 
3978  // Check the address book data in the same way we did for transactions
3979  std::vector<CTxDestination> dests_to_delete;
3980  for (const auto& addr_pair : m_address_book) {
3981  // Labels applied to receiving addresses should go based on IsMine
3982  if (addr_pair.second.purpose == AddressPurpose::RECEIVE) {
3983  if (!IsMine(addr_pair.first)) {
3984  // Check the address book data is the watchonly wallet's
3985  if (data.watchonly_wallet) {
3986  LOCK(data.watchonly_wallet->cs_wallet);
3987  if (data.watchonly_wallet->IsMine(addr_pair.first)) {
3988  // Add to the watchonly. Preserve the labels, purpose, and change-ness
3989  std::string label = addr_pair.second.GetLabel();
3990  data.watchonly_wallet->m_address_book[addr_pair.first].purpose = addr_pair.second.purpose;
3991  if (!addr_pair.second.IsChange()) {
3992  data.watchonly_wallet->m_address_book[addr_pair.first].SetLabel(label);
3993  }
3994  dests_to_delete.push_back(addr_pair.first);
3995  continue;
3996  }
3997  }
3998  if (data.solvable_wallet) {
3999  LOCK(data.solvable_wallet->cs_wallet);
4000  if (data.solvable_wallet->IsMine(addr_pair.first)) {
4001  // Add to the solvable. Preserve the labels, purpose, and change-ness
4002  std::string label = addr_pair.second.GetLabel();
4003  data.solvable_wallet->m_address_book[addr_pair.first].purpose = addr_pair.second.purpose;
4004  if (!addr_pair.second.IsChange()) {
4005  data.solvable_wallet->m_address_book[addr_pair.first].SetLabel(label);
4006  }
4007  dests_to_delete.push_back(addr_pair.first);
4008  continue;
4009  }
4010  }
4011 
4012  // Skip invalid/non-watched scripts that will not be migrated
4013  if (not_migrated_dests.count(addr_pair.first) > 0) {
4014  dests_to_delete.push_back(addr_pair.first);
4015  continue;
4016  }
4017 
4018  // Not ours, not in watchonly wallet, and not in solvable
4019  error = _("Error: Address book data in wallet cannot be identified to belong to migrated wallets");
4020  return false;
4021  }
4022  } else {
4023  // Labels for everything else ("send") should be cloned to all
4024  if (data.watchonly_wallet) {
4025  LOCK(data.watchonly_wallet->cs_wallet);
4026  // Add to the watchonly. Preserve the labels, purpose, and change-ness
4027  std::string label = addr_pair.second.GetLabel();
4028  data.watchonly_wallet->m_address_book[addr_pair.first].purpose = addr_pair.second.purpose;
4029  if (!addr_pair.second.IsChange()) {
4030  data.watchonly_wallet->m_address_book[addr_pair.first].SetLabel(label);
4031  }
4032  }
4033  if (data.solvable_wallet) {
4034  LOCK(data.solvable_wallet->cs_wallet);
4035  // Add to the solvable. Preserve the labels, purpose, and change-ness
4036  std::string label = addr_pair.second.GetLabel();
4037  data.solvable_wallet->m_address_book[addr_pair.first].purpose = addr_pair.second.purpose;
4038  if (!addr_pair.second.IsChange()) {
4039  data.solvable_wallet->m_address_book[addr_pair.first].SetLabel(label);
4040  }
4041  }
4042  }
4043  }
4044 
4045  // Persist added address book entries (labels, purpose) for watchonly and solvable wallets
4046  auto persist_address_book = [](const CWallet& wallet) {
4047  LOCK(wallet.cs_wallet);
4048  WalletBatch batch{wallet.GetDatabase()};
4049  for (const auto& [destination, addr_book_data] : wallet.m_address_book) {
4050  auto address{EncodeDestination(destination)};
4051  std::optional<std::string> label = addr_book_data.IsChange() ? std::nullopt : std::make_optional(addr_book_data.GetLabel());
4052  // don't bother writing default values (unknown purpose)
4053  if (addr_book_data.purpose) batch.WritePurpose(address, PurposeToString(*addr_book_data.purpose));
4054  if (label) batch.WriteName(address, *label);
4055  }
4056  };
4057  if (data.watchonly_wallet) persist_address_book(*data.watchonly_wallet);
4058  if (data.solvable_wallet) persist_address_book(*data.solvable_wallet);
4059 
4060  // Remove the things to delete
4061  if (dests_to_delete.size() > 0) {
4062  for (const auto& dest : dests_to_delete) {
4063  if (!DelAddressBook(dest)) {
4064  error = _("Error: Unable to remove watchonly address book data");
4065  return false;
4066  }
4067  }
4068  }
4069 
4070  // Connect the SPKM signals
4073 
4074  WalletLogPrintf("Wallet migration complete.\n");
4075 
4076  return true;
4077 }
4078 
4080 {
4082 }
4083 
4085 {
4086  AssertLockHeld(wallet.cs_wallet);
4087 
4088  // Get all of the descriptors from the legacy wallet
4089  std::optional<MigrationData> data = wallet.GetDescriptorsForLegacy(error);
4090  if (data == std::nullopt) return false;
4091 
4092  // Create the watchonly and solvable wallets if necessary
4093  if (data->watch_descs.size() > 0 || data->solvable_descs.size() > 0) {
4094  DatabaseOptions options;
4095  options.require_existing = false;
4096  options.require_create = true;
4098 
4099  WalletContext empty_context;
4100  empty_context.args = context.args;
4101 
4102  // Make the wallets
4104  if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
4106  }
4107  if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
4109  }
4110  if (data->watch_descs.size() > 0) {
4111  wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts\n");
4112 
4113  DatabaseStatus status;
4114  std::vector<bilingual_str> warnings;
4115  std::string wallet_name = wallet.GetName() + "_watchonly";
4116  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4117  if (!database) {
4118  error = strprintf(_("Wallet file creation failed: %s"), error);
4119  return false;
4120  }
4121 
4122  data->watchonly_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4123  if (!data->watchonly_wallet) {
4124  error = _("Error: Failed to create new watchonly wallet");
4125  return false;
4126  }
4127  res.watchonly_wallet = data->watchonly_wallet;
4128  LOCK(data->watchonly_wallet->cs_wallet);
4129 
4130  // Parse the descriptors and add them to the new wallet
4131  for (const auto& [desc_str, creation_time] : data->watch_descs) {
4132  // Parse the descriptor
4133  FlatSigningProvider keys;
4134  std::string parse_err;
4135  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, parse_err, /* require_checksum */ true);
4136  assert(desc); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor
4137  assert(!desc->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4138 
4139  // Add to the wallet
4140  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
4141  data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, "", false);
4142  }
4143 
4144  // Add the wallet to settings
4145  UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4146  }
4147  if (data->solvable_descs.size() > 0) {
4148  wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts\n");
4149 
4150  DatabaseStatus status;
4151  std::vector<bilingual_str> warnings;
4152  std::string wallet_name = wallet.GetName() + "_solvables";
4153  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4154  if (!database) {
4155  error = strprintf(_("Wallet file creation failed: %s"), error);
4156  return false;
4157  }
4158 
4159  data->solvable_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4160  if (!data->solvable_wallet) {
4161  error = _("Error: Failed to create new watchonly wallet");
4162  return false;
4163  }
4164  res.solvables_wallet = data->solvable_wallet;
4165  LOCK(data->solvable_wallet->cs_wallet);
4166 
4167  // Parse the descriptors and add them to the new wallet
4168  for (const auto& [desc_str, creation_time] : data->solvable_descs) {
4169  // Parse the descriptor
4170  FlatSigningProvider keys;
4171  std::string parse_err;
4172  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, parse_err, /* require_checksum */ true);
4173  assert(desc); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor
4174  assert(!desc->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4175 
4176  // Add to the wallet
4177  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
4178  data->solvable_wallet->AddWalletDescriptor(w_desc, keys, "", false);
4179  }
4180 
4181  // Add the wallet to settings
4182  UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4183  }
4184  }
4185 
4186  // Add the descriptors to wallet, remove LegacyScriptPubKeyMan, and cleanup txs and address book data
4187  if (!wallet.ApplyMigrationData(*data, error)) {
4188  return false;
4189  }
4190  return true;
4191 }
4192 
4194 {
4195  MigrationResult res;
4197  std::vector<bilingual_str> warnings;
4198 
4199  // If the wallet is still loaded, unload it so that nothing else tries to use it while we're changing it
4200  if (auto wallet = GetWallet(context, wallet_name)) {
4201  if (!RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt, warnings)) {
4202  return util::Error{_("Unable to unload the wallet before migrating")};
4203  }
4204  UnloadWallet(std::move(wallet));
4205  }
4206 
4207  // Load the wallet but only in the context of this function.
4208  // No signals should be connected nor should anything else be aware of this wallet
4209  WalletContext empty_context;
4210  empty_context.args = context.args;
4211  DatabaseOptions options;
4212  options.require_existing = true;
4213  DatabaseStatus status;
4214  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4215  if (!database) {
4216  return util::Error{Untranslated("Wallet file verification failed.") + Untranslated(" ") + error};
4217  }
4218 
4219  // Make the local wallet
4220  std::shared_ptr<CWallet> local_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4221  if (!local_wallet) {
4222  return util::Error{Untranslated("Wallet loading failed.") + Untranslated(" ") + error};
4223  }
4224 
4225  // Before anything else, check if there is something to migrate.
4226  if (!local_wallet->GetLegacyScriptPubKeyMan()) {
4227  return util::Error{_("Error: This wallet is already a descriptor wallet")};
4228  }
4229 
4230  // Make a backup of the DB
4231  fs::path this_wallet_dir = fs::absolute(fs::PathFromString(local_wallet->GetDatabase().Filename())).parent_path();
4232  fs::path backup_filename = fs::PathFromString(strprintf("%s-%d.legacy.bak", wallet_name, GetTime()));
4233  fs::path backup_path = this_wallet_dir / backup_filename;
4234  if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
4235  return util::Error{_("Error: Unable to make a backup of your wallet")};
4236  }
4237  res.backup_path = backup_path;
4238 
4239  bool success = false;
4240  {
4241  LOCK(local_wallet->cs_wallet);
4242 
4243  // Unlock the wallet if needed
4244  if (local_wallet->IsLocked() && !local_wallet->Unlock(passphrase)) {
4245  if (passphrase.find('\0') == std::string::npos) {
4246  return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase was not provided or was incorrect.")};
4247  } else {
4248  return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase entered was incorrect. "
4249  "The passphrase contains a null character (ie - a zero byte). "
4250  "If this passphrase was set with a version of this software prior to 25.0, "
4251  "please try again with only the characters up to — but not including — "
4252  "the first null character.")};
4253  }
4254  }
4255 
4256  // First change to using SQLite
4257  if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
4258 
4259  // Do the migration, and cleanup if it fails
4260  success = DoMigration(*local_wallet, context, error, res);
4261  }
4262 
4263  // In case of reloading failure, we need to remember the wallet dirs to remove
4264  // Set is used as it may be populated with the same wallet directory paths multiple times,
4265  // both before and after reloading. This ensures the set is complete even if one of the wallets
4266  // fails to reload.
4267  std::set<fs::path> wallet_dirs;
4268  if (success) {
4269  // Migration successful, unload all wallets locally, then reload them.
4270  const auto& reload_wallet = [&](std::shared_ptr<CWallet>& to_reload) {
4271  assert(to_reload.use_count() == 1);
4272  std::string name = to_reload->GetName();
4273  wallet_dirs.insert(fs::PathFromString(to_reload->GetDatabase().Filename()).parent_path());
4274  to_reload.reset();
4275  to_reload = LoadWallet(context, name, /*load_on_start=*/std::nullopt, options, status, error, warnings);
4276  return to_reload != nullptr;
4277  };
4278  // Reload the main wallet
4279  success = reload_wallet(local_wallet);
4280  res.wallet = local_wallet;
4281  res.wallet_name = wallet_name;
4282  if (success && res.watchonly_wallet) {
4283  // Reload watchonly
4284  success = reload_wallet(res.watchonly_wallet);
4285  }
4286  if (success && res.solvables_wallet) {
4287  // Reload solvables
4288  success = reload_wallet(res.solvables_wallet);
4289  }
4290  }
4291  if (!success) {
4292  // Migration failed, cleanup
4293  // Copy the backup to the actual wallet dir
4294  fs::path temp_backup_location = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
4295  fs::copy_file(backup_path, temp_backup_location, fs::copy_options::none);
4296 
4297  // Make list of wallets to cleanup
4298  std::vector<std::shared_ptr<CWallet>> created_wallets;
4299  if (local_wallet) created_wallets.push_back(std::move(local_wallet));
4300  if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));
4301  if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));
4302 
4303  // Get the directories to remove after unloading
4304  for (std::shared_ptr<CWallet>& w : created_wallets) {
4305  wallet_dirs.emplace(fs::PathFromString(w->GetDatabase().Filename()).parent_path());
4306  }
4307 
4308  // Unload the wallets
4309  for (std::shared_ptr<CWallet>& w : created_wallets) {
4310  if (w->HaveChain()) {
4311  // Unloading for wallets that were loaded for normal use
4312  if (!RemoveWallet(context, w, /*load_on_start=*/false)) {
4313  error += _("\nUnable to cleanup failed migration");
4314  return util::Error{error};
4315  }
4316  UnloadWallet(std::move(w));
4317  } else {
4318  // Unloading for wallets in local context
4319  assert(w.use_count() == 1);
4320  w.reset();
4321  }
4322  }
4323 
4324  // Delete the wallet directories
4325  for (const fs::path& dir : wallet_dirs) {
4326  fs::remove_all(dir);
4327  }
4328 
4329  // Restore the backup
4330  DatabaseStatus status;
4331  std::vector<bilingual_str> warnings;
4332  if (!RestoreWallet(context, temp_backup_location, wallet_name, /*load_on_start=*/std::nullopt, status, error, warnings)) {
4333  error += _("\nUnable to restore backup of wallet.");
4334  return util::Error{error};
4335  }
4336 
4337  // Move the backup to the wallet dir
4338  fs::copy_file(temp_backup_location, backup_path, fs::copy_options::none);
4339  fs::remove(temp_backup_location);
4340 
4341  return util::Error{error};
4342  }
4343  return res;
4344 }
4345 } // namespace wallet
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1437
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:620
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2583
void SyncTransaction(const CTransactionRef &tx, const SyncTxState &state, bool update_tx=true, bool rescanning_old_block=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1418
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
NodeClock::time_point m_next_resend
The next scheduled rebroadcast of wallet transactions.
Definition: wallet.h:319
static const std::string sighash
Definition: sighash.json.h:3
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:285
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3264
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:52
enum wallet::CWallet::ScanResult::@17 status
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:34
std::optional< DatabaseFormat > require_format
Definition: db.h:186
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:173
bool isObject() const
Definition: univalue.h:85
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:309
void MaybeUpdateBirthTime(int64_t time)
Updates wallet birth time if &#39;time&#39; is below it.
Definition: wallet.cpp:1773
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:763
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:911
void push_back(UniValue val)
Definition: univalue.cpp:104
int ret
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:370
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:523
std::atomic< bool > fAbortRescan
Definition: wallet.h:307
State of transaction added to mempool.
Definition: transaction.h:36
std::vector< CTxDestination > ListAddrBookAddresses(const std::optional< AddrBookFilter > &filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Filter and retrieve destinations stored in the addressbook.
Definition: wallet.cpp:2525
void ReadDatabaseArgs(const ArgsManager &args, DatabaseOptions &options)
Definition: db.cpp:142
void chainStateFlushed(ChainstateRole role, const CBlockLocator &loc) override
Definition: wallet.cpp:630
virtual bool updateRwSetting(const std::string &name, const common::SettingsValue &value, bool write=true)=0
Write a setting to <datadir>/settings.json.
interfaces::Chain & chain() const
Interface for accessing chain state.
Definition: wallet.h:495
std::chrono::time_point< NodeClock > time_point
Definition: time.h:17
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:35
Enables interaction with an external signing device or service, such as a hardware wallet...
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: transaction.h:199
AssertLockHeld(pool.cs)
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:308
bool EraseAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2838
bool EraseAddressData(const CTxDestination &dest)
Definition: walletdb.cpp:1360
const std::vector< UniValue > & getValues() const
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1647
int64_t nIndex
The index of the address&#39;s key in the keypool.
Definition: wallet.h:197
std::map< OutputType, ScriptPubKeyMan * > m_external_spk_managers
Definition: wallet.h:411
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:140
virtual std::optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
bool ImportScripts(const std::set< CScript > scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1720
bilingual_str AmountErrMsg(const std::string &optname, const std::string &strValue)
Definition: error.cpp:64
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...
bool HasEncryptionKeys() const override
Definition: wallet.cpp:3534
const T * state() const
Definition: transaction.h:325
#define LogPrint(category,...)
Definition: logging.h:246
assert(!tx.IsCoinBase())
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:123
CScript scriptPubKey
Definition: transaction.h:161
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3254
virtual bool Backup(const std::string &strDest) const =0
Back up the entire database to a file.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
bool SubmitTxMemoryPoolAndRelay(CWalletTx &wtx, std::string &err_string, bool relay) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Pass this transaction to node for mempool insertion and relay to peers if flag set to true...
Definition: wallet.cpp:1976
int GetTxBlocksToMaturity(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3339
std::optional< int > last_scanned_height
Definition: wallet.h:614
CKey key
Definition: key.h:213
bool DoMigration(CWallet &wallet, WalletContext &context, bilingual_str &error, MigrationResult &res) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: wallet.cpp:4084
void UpgradeDescriptorCache() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade DescriptorCaches.
Definition: wallet.cpp:545
bool LoadToWallet(const uint256 &hash, const UpdateWalletTxFn &fill_wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1180
A UTXO entry.
Definition: coins.h:31
isminetype IsMine(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1581
Bilingual messages:
Definition: translation.h:18
bool IsAddressPreviouslySpent(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2814
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:658
Definition: block.h:68
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:949
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:47
bool ApplyMigrationData(MigrationData &data, bilingual_str &error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds the ScriptPubKeyMans given in MigrationData to this wallet, removes LegacyScriptPubKeyMan, and where needed, moves tx and address book entries to watchonly_wallet or solvable_wallet.
Definition: wallet.cpp:3871
virtual CBlockLocator getActiveChainLocator(const uint256 &block_hash)=0
Return a locator that refers to a block in the active chain.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:613
RecursiveMutex cs_KeyStore
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:144
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:242
void LoadAddressReceiveRequest(const CTxDestination &dest, const std::string &id, const std::string &request) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Appends payment request to destination.
Definition: wallet.cpp:2809
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:188
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:40
bool SetAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2831
virtual bool hasBlockFilterIndex(BlockFilterType filter_type)=0
Returns whether a block filter index is available.
GCSFilter::ElementSet m_filter_set
Definition: wallet.cpp:349
std::vector< CTxIn > vin
Definition: transaction.h:381
std::string m_notify_tx_changed_script
Notify external script when a wallet transaction comes in or is updated (handled by -walletnotify) ...
Definition: wallet.h:726
bool MigrateToSQLite(bilingual_str &error) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Move all records from the BDB database to a new SQLite database for storage.
Definition: wallet.cpp:3782
std::map< CKeyID, CKey > keys
SigningResult
Definition: message.h:43
CWalletTx * AddToWallet(CTransactionRef tx, const TxState &state, const UpdateWalletTxFn &update_wtx=nullptr, bool fFlushOnClose=true, bool rescanning_old_block=false)
Add the transaction to the wallet, wrapping it up inside a CWalletTx.
Definition: wallet.cpp:1052
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:1750
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
std::optional< MigrationData > MigrateToDescriptor()
Get the DescriptorScriptPubKeyMans (with private keys) that have the same scriptPubKeys as this Legac...
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
virtual void Flush()=0
Make sure all changes are flushed to database file.
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: transaction.h:200
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:446
void transactionAddedToMempool(const CTransactionRef &tx) override
Definition: wallet.cpp:1429
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:360
Definition: key.h:208
struct containing information needed for migrating legacy wallets to descriptor wallets ...
std::atomic< int64_t > m_birth_time
Definition: wallet.h:328
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:46
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:72
bool WriteAddressReceiveRequest(const CTxDestination &dest, const std::string &id, const std::string &receive_request)
Definition: walletdb.cpp:1350
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3677
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:58
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:149
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: transaction.h:231
Removed for conflict with in-block transaction.
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2337
MasterKeyMap mapMasterKeys
Definition: wallet.h:449
WalletDatabase & GetDatabase() const override
Definition: wallet.h:438
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
Definition: consensus.h:19
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
std::string PurposeToString(AddressPurpose p)
Definition: wallet.h:271
bool TxnAbort()
Abort current transaction.
Definition: walletdb.cpp:1432
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:201
std::optional< int64_t > GetOldestKeyPoolTime() const
Definition: wallet.cpp:2488
const CWallet *const pwallet
The wallet to reserve from.
Definition: wallet.h:192
SigningResult SignMessage(const std::string &message, const PKHash &pkhash, std::string &str_sig) const
Definition: wallet.cpp:2199
void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Remove specified ScriptPubKeyMan from set of active SPK managers.
Definition: wallet.cpp:3660
std::string TxStateString(const T &state)
Return TxState or SyncTxState as a string for logging or debugging.
Definition: transaction.h:119
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2400
CTxDestination address
The destination.
Definition: wallet.h:199
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:436
#define PACKAGE_NAME
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Fetch the inputs and sign with SIGHASH_ALL.
Definition: wallet.cpp:2111
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
State of transaction not confirmed or conflicting with a known block and not in the mempool...
Definition: transaction.h:53
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:101
virtual void Close()=0
Flush to the database file and close the database.
const UniValue & get_array() const
std::variant< TxStateConfirmed, TxStateInMempool, TxStateInactive > SyncTxState
Subset of states transaction sync logic is implemented to handle.
Definition: transaction.h:76
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1043
std::unique_ptr< Wallet > MakeWallet(wallet::WalletContext &context, const std::shared_ptr< wallet::CWallet > &wallet)
Return implementation of Wallet interface.
Definition: interfaces.cpp:682
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:477
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:292
bool DeleteRecords()
Delete all the records ofthis LegacyScriptPubKeyMan from disk.
static GlobalMutex g_loading_wallet_mutex
Definition: wallet.cpp:215
A version of CTransaction with the PSBT format.
Definition: psbt.h:946
bool IsNull() const
Definition: block.h:152
bool isConflicted() const
Definition: transaction.h:329
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:207
std::vector< std::string > GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2820
const CWalletTx * GetWalletTx(const uint256 &hash) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:521
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1054
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:506
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
std::shared_ptr< CWallet > solvable_wallet
Access to the wallet database.
Definition: walletdb.h:190
ScriptPubKeyMan * GetScriptPubKeyMan(const OutputType &type, bool internal) const
Get the ScriptPubKeyMan for the given OutputType and internal/external chain.
Definition: wallet.cpp:3428
std::atomic< uint64_t > m_wallet_flags
WalletFlags set on this wallet.
Definition: wallet.h:376
A key from a CWallet&#39;s keypool.
RecursiveMutex m_relock_mutex
Definition: wallet.h:569
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:832
State of transaction confirmed in a block.
Definition: transaction.h:26
bool IsEquivalentTo(const CWalletTx &tx) const
True if only scriptSigs are different.
Definition: transaction.cpp:8
bool fBroadcastTransactions
Whether this wallet will submit newly created transactions to the node&#39;s mempool and prompt rebroadca...
Definition: wallet.h:322
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const SyncTxState &state, bool fUpdate, bool rescanning_old_block) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1228
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:187
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: walletutil.cpp:11
std::function< void(const CTxDestination &dest, const std::string &label, bool is_change, const std::optional< AddressPurpose > purpose)> ListAddrBookFunc
Walk-through the address book entries.
Definition: wallet.h:755
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:33
virtual bool Rewrite(const char *pszSkip=nullptr)=0
Rewrite the entire database on disk, with the exception of key pszSkip if non-zero.
LegacyScriptPubKeyMan * GetLegacyScriptPubKeyMan() const
Get the LegacyScriptPubKeyMan which is used for all types, internal, and external.
Definition: wallet.cpp:3486
const std::string & getValStr() const
Definition: univalue.h:67
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:113
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2656
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:32
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3419
virtual double guessVerificationProgress(const uint256 &block_hash)=0
Estimate fraction of total transactions verified if blocks up to the specified block hash are verifie...
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:789
OutputType
Definition: outputtype.h:17
static NodeClock::time_point GetDefaultNextResend()
Definition: wallet.cpp:2033
bool isAbandoned() const
Definition: transaction.h:328
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: walletutil.h:71
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:142
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
static constexpr auto OUTPUT_TYPES
Definition: outputtype.h:25
void updatedBlockTip() override
Definition: wallet.cpp:1542
const std::vector< CTxIn > vin
Definition: transaction.h:305
std::optional< bool > IsInternalScriptPubKeyMan(ScriptPubKeyMan *spk_man) const
Returns whether the provided ScriptPubKeyMan is internal.
Definition: wallet.cpp:3699
int64_t GetTxTime() const
Definition: transaction.cpp:22
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:703
bool LockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2606
constexpr unsigned char * begin()
Definition: uint256.h:68
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:175
static const bool DEFAULT_WALLET_RBF
-walletrbf default
Definition: wallet.h:133
void MaybeResendWalletTxs(WalletContext &context)
Called periodically by the schedule thread.
Definition: wallet.cpp:2096
std::set< std::string > ListAddrBookLabels(const std::optional< AddressPurpose > purpose) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Retrieve all the known labels in the address book.
Definition: wallet.cpp:2541
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:127
std::map< uint256, std::unique_ptr< ScriptPubKeyMan > > m_spk_managers
Definition: wallet.h:416
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
Definition: wallet.h:838
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
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...
bool DisplayAddress(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Display address on an external signer.
Definition: wallet.cpp:2592
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
bool HasWalletSpend(const CTransactionRef &tx) 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:681
void LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3548
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:90
const uint256 & hash
Definition: chain.h:84
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:171
interfaces::Chain * m_chain
Interface for accessing chain state.
Definition: wallet.h:387
std::function< TxUpdate(CWalletTx &wtx)> TryUpdatingStateFn
Definition: wallet.h:363
CWallet(interfaces::Chain *chain, const std::string &name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
Definition: wallet.h:453
void LoadAddressPreviouslySpent(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks destination as previously spent.
Definition: wallet.cpp:2804
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:76
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
DescriptorScriptPubKeyMan * GetDescriptorScriptPubKeyMan(const WalletDescriptor &desc) const
Return the DescriptorScriptPubKeyMan for a WalletDescriptor if it is already in the wallet...
Definition: wallet.cpp:3686
bool SetAddressPreviouslySpent(WalletBatch &batch, const CTxDestination &dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2790
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:83
bool IsLocked() const override
Definition: wallet.cpp:3364
Indicates that the wallet needs an external signer.
Definition: walletutil.h:77
void SetupLegacyScriptPubKeyMan()
Make a LegacyScriptPubKeyMan and set it for all types, internal, and external.
Definition: wallet.cpp:3514
#define LOCK2(cs1, cs2)
Definition: sync.h:259
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:1146
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction.
Definition: wallet.cpp:970
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
Definition: cleanse.cpp:14
virtual bool hasAssumedValidChain()=0
Return true if an assumed-valid chain is in use.
const CBlock * data
Definition: chain.h:89
std::underlying_type< isminetype >::type isminefilter
used for bitflags of isminetype
Definition: wallet.h:43
void AddActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Adds the active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3631
bool ShouldResend() const
Return true if all conditions for periodically resending transactions are met.
Definition: wallet.cpp:2016
std::set< CKeyID > GetKeys() const override
std::set< ScriptPubKeyMan * > GetActiveScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans in m_internal_spk_managers and m_external_spk_managers.
Definition: wallet.cpp:3405
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
std::shared_ptr< CWallet > wallet
Definition: wallet.h:1093
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1427
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
SecureString create_passphrase
Definition: db.h:188
ArgsManager & args
Definition: bitcoind.cpp:269
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:212
std::string wallet_name
Definition: wallet.h:1092
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
CPubKey vchPubKey
The public key.
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: transaction.h:220
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
int64_t m_keypool_size
Number of pre-generated keys/scripts by each spkm (part of the look-ahead process, used to detect payments)
Definition: wallet.h:723
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.
const uint256 * prev_hash
Definition: chain.h:85
uint64_t create_flags
Definition: db.h:187
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:850
bool WriteAddressPreviouslySpent(const CTxDestination &dest, bool previously_spent)
Definition: walletdb.cpp:1344
An input of a transaction.
Definition: transaction.h:74
static constexpr uint64_t KNOWN_WALLET_FLAGS
Definition: wallet.h:151
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
Definition: wallet.h:959
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr) override
signify that a particular wallet feature is now used.
Definition: wallet.cpp:641
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:32
#define LOCK(cs)
Definition: sync.h:258
const char * name
Definition: rest.cpp:45
static const unsigned int DEFAULT_TX_CONFIRM_TARGET
-txconfirmtarget default
Definition: wallet.h:131
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:192
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction&#39;s inputs dirty, thus forcing the outputs to be recomputed.
Definition: wallet.cpp:1301
std::vector< std::byte, zero_after_free_allocator< std::byte > > SerializeData
Byte-vector that clears its contents before deletion.
Definition: zeroafterfree.h:49
void Flush()
Flush wallet (bitdb flush)
Definition: wallet.cpp:693
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:93
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:412
const uint256 & GetHash() const
Definition: transaction.h:337
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:74
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:583
util::Result< CTxDestination > GetReservedDestination(bool internal)
Reserve an address.
Definition: wallet.cpp:2555
virtual void ReloadDbEnv()=0
std::optional< OutputType > ParseOutputType(const std::string &type)
Definition: outputtype.cpp:24
void blockDisconnected(const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1498
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:59
Fast randomness source.
Definition: random.h:143
void blockConnected(ChainstateRole role, const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1476
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:87
An encapsulated public key.
Definition: pubkey.h:33
CAmount m_default_max_tx_fee
Absolute maximum transaction fee (in satoshis) used by default for the wallet.
Definition: wallet.h:720
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: types.h:40
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
std::chrono::duration< double, std::chrono::milliseconds::period > MillisecondsDouble
Definition: time.h:60
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1619
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:207
uint32_t n
Definition: transaction.h:39
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1789
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:161
const std::vector< CTxOut > vout
Definition: transaction.h:306
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
Definition: moneystr.cpp:42
WalletFeature
(client) version numbers for particular wallet features
Definition: walletutil.h:15
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1311
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:2739
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
bool IsHDEnabled() const
Definition: wallet.cpp:1636
void RecursiveUpdateTxState(const uint256 &tx_hash, const TryUpdatingStateFn &try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Mark a transaction (and its in-wallet descendants) as a particular tx state.
Definition: wallet.cpp:1376
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:3307
WalletContext context
static int TxStateSerializedIndex(const TxState &state)
Get TxState serialized block index. Inverse of TxStateInterpretSerialized.
Definition: transaction.h:106
virtual void waitForNotificationsIfTipChanged(const uint256 &old_tip)=0
Wait for pending notifications to be processed unless block hash points to the current chain tip...
std::unique_ptr< Handler > MakeCleanupHandler(std::function< void()> cleanup)
Return handler wrapping a cleanup function.
Definition: interfaces.cpp:42
std::set< uint256 > GetTxConflicts(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2006
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:300
void transactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason) override
Definition: wallet.cpp:1439
A structure for PSBTs which contain per-input information.
Definition: psbt.h:191
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2440
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:1372
#define WAIT_LOCK(cs, name)
Definition: sync.h:263
An output of a transaction.
Definition: transaction.h:157
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:10
unsigned int nDeriveIterations
Definition: crypter.h:42
DBErrors LoadWallet()
Definition: wallet.cpp:2314
std::string ToString() const
Definition: uint256.cpp:55
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3351
bool UnlockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2616
void MarkDirty()
Definition: wallet.cpp:961
std::string m_name
Wallet name: relative directory name or "" for default wallet.
Definition: wallet.h:390
bool IsWalletFlagSet(uint64_t flag) const override
check if a certain wallet flag is set
Definition: wallet.cpp:1687
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:35
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1682
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: wallet.cpp:3390
TxItems wtxOrdered
Definition: wallet.h:478
static const std::unordered_set< OutputType > LEGACY_OUTPUT_TYPES
OutputTypes supported by the LegacyScriptPubKeyMan.
ScanResult ScanForWalletTransactions(const uint256 &start_block, int start_height, std::optional< int > max_height, const WalletRescanReserver &reserver, bool fUpdate, const bool save_progress)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1833
std::unordered_set< CScript, SaltedSipHasher > GetNotMineScriptPubKeys() const
Retrieves scripts that were imported by bugs into the legacy spkm and are simply invalid, such as a sh(sh(pkh())) script, or not watched.
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:239
util::Result< MigrationResult > MigrateLegacyToDescriptor(const std::string &wallet_name, const SecureString &passphrase, WalletContext &context)
Do all steps to migrate a legacy wallet to a descriptor wallet.
Definition: wallet.cpp:4193
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:835
std::vector< PSBTInput > inputs
Definition: psbt.h:952
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:90
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
void ForEachAddrBookEntry(const ListAddrBookFunc &func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2516
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1095
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:88
static uint256 TxStateSerializedBlockHash(const TxState &state)
Get TxState serialized block hash. Inverse of TxStateInterpretSerialized.
Definition: transaction.h:94
uint256 GetID() const override
UniValue GetDescriptors(const int account)
Get receive and change Descriptor(s) from device for a given account.
std::unordered_set< Element, ByteVectorHash > ElementSet
Definition: blockfilter.h:32
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:41
ScriptPubKeyMan * m_spk_man
The ScriptPubKeyMan to reserve from. Based on type when GetReservedDestination is called...
Definition: wallet.h:194
Descriptor with some wallet metadata.
Definition: walletutil.h:84
void Close()
Close wallet database.
Definition: wallet.cpp:698
virtual void KeepDestination(int64_t index, const OutputType &type)
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
static const bool DEFAULT_WALLETBROADCAST
Definition: wallet.h:134
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:3297
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:222
ArgsManager gArgs
Definition: args.cpp:42
bool RemoveWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet, std::optional< bool > load_on_start, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:152
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:129
if(!SetupNetworking())
int flags
Definition: bitcoin-tx.cpp:528
const std::string & FormatOutputType(OutputType type)
Definition: outputtype.cpp:38
std::shared_ptr< CWallet > GetWallet(WalletContext &context, const std::string &name)
Definition: wallet.cpp:191
std::map< uint256, int32_t > m_last_range_ends
Map for keeping track of each range descriptor&#39;s last seen end range.
Definition: wallet.cpp:348
std::atomic< int64_t > m_best_block_time
Definition: wallet.h:324
DatabaseStatus
Definition: db.h:197
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1730
256-bit opaque blob.
Definition: uint256.h:106
bool Unlock(const SecureString &strWalletPassphrase, bool accept_no_keys=false)
Definition: wallet.cpp:558
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:70
unsigned int fTimeReceivedIsTxTime
Definition: transaction.h:201
void WalletLogPrintf(const char *fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
Definition: wallet.h:919
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
std::vector< CTransactionRef > vtx
Definition: block.h:72
void ResubmitWalletTransactions(bool relay, bool force)
Definition: wallet.cpp:2059
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:178
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:381
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1294
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2451
bool CanGrindR() const
Whether the (external) signer performs R-value signature grinding.
Definition: wallet.cpp:4079
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::optional< AddressPurpose > &strPurpose)
Definition: wallet.cpp:2368
constexpr void SetNull()
Definition: uint256.h:49
bool IsLockedCoin(const COutPoint &output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2638
State of rejected transaction that conflicts with a confirmed block.
Definition: transaction.h:41
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:122
void KeepDestination()
Keep the address. Do not return its key to the keypool when this object goes out of scope...
Definition: wallet.cpp:2574
bool error(const char *fmt, const Args &... args)
Definition: logging.h:262
bool IsSpent(const COutPoint &outpoint) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:746
Removed for block.
std::function< bool(CWalletTx &wtx, bool new_tx)> UpdateWalletTxFn
Callback for updating transaction metadata in mapWallet.
Definition: wallet.h:593
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
bool IsNull() const
Definition: block.h:49
void LoadActiveScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Loads an active ScriptPubKeyMan for the specified type and internal.
Definition: wallet.cpp:3640
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:481
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: transaction.h:218
void InitWalletFlags(uint64_t flags)
overwrite all flags by the given uint64_t flags must be uninitialised (or 0) only known flags may be ...
Definition: wallet.cpp:1704
void AddScriptPubKeyMan(const uint256 &id, std::unique_ptr< ScriptPubKeyMan > spkm_man)
Definition: wallet.cpp:3504
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1094
virtual util::Result< CTxDestination > GetReservedDestination(const OutputType type, bool internal, int64_t &index, CKeyPool &keypool)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:456
bool EraseAddressReceiveRequest(const CTxDestination &dest, const std::string &id)
Definition: walletdb.cpp:1355
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script) const
Get all the ScriptPubKeyMans for a script.
Definition: wallet.cpp:3438
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2423
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:847
CTransactionRef non_witness_utxo
Definition: psbt.h:193
bool InMempool() const
Definition: transaction.cpp:17
std::optional< std::string > m_op_label
Definition: wallet.h:736
static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status)
const uint256 & GetHash() const
Definition: transaction.h:333
bool IsCrypted() const
Definition: wallet.cpp:3359
virtual void initMessage(const std::string &message)=0
Send init message.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
Address book data.
Definition: wallet.h:229
std::string GetHex() const
Definition: uint256.cpp:11
OutputType const type
Definition: wallet.h:195
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: transaction.h:212
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:200
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1422
WalletContext struct containing references to state shared between CWallet instances, like the reference to the chain interface, and the list of opened wallets.
Definition: context.h:35
A wrapper to reserve an address from a wallet.
Definition: wallet.h:188
DBErrors ReorderTransactions()
Definition: wallet.cpp:892
std::vector< unsigned char > vchSalt
Definition: crypter.h:38
TransactionError
Definition: error.h:22
bool HaveChain() const
Interface to assert chain access.
Definition: wallet.h:471
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
bool LoadWalletFlags(uint64_t flags)
Loads the flags into the wallet.
Definition: wallet.cpp:1692
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:1002
#define AssertLockNotHeld(cs)
Definition: sync.h:148
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:14
std::optional< MigrationData > GetDescriptorsForLegacy(bilingual_str &error) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get all of the descriptors from a legacy wallet.
Definition: wallet.cpp:3856
bool require_existing
Definition: db.h:184
static int count
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:131
Encryption/decryption context with key information.
Definition: crypter.h:70
interfaces::Chain * chain
Definition: context.h:36
std::vector< WalletDescriptor > GetWalletDescriptors(const CScript &script) const
Get the wallet descriptors for a script.
Definition: wallet.cpp:3474
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:71
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:287
A mutable version of CTransaction.
Definition: transaction.h:379
std::shared_ptr< CWallet > watchonly_wallet
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:965
bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2626
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:293
std::unique_ptr< WalletDatabase > m_database
Internal database handle.
Definition: wallet.h:393
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range)
Return the time point advanced by a uniform random duration.
Definition: random.h:231
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1668
bool IsCoinBase() const
Definition: transaction.h:335
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:530
static GlobalMutex g_wallet_release_mutex
Definition: wallet.cpp:216
int GetVersion() const
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:802
static auto quoted(const std::string &s)
Definition: fs.h:94
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:2502
FoundBlock & height(int &height)
Definition: chain.h:56
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
unsigned int nTimeReceived
time received by this node
Definition: transaction.h:202
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...
size_t size() const
Definition: univalue.h:70
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:37
An encapsulated private key.
Definition: key.h:32
A Span is an object that can refer to a contiguous sequence of objects.
Definition: solver.h:20
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
Different type to mark Mutex at global scope.
Definition: sync.h:141
static const bool DEFAULT_WALLETCROSSCHAIN
Definition: wallet.h:136
std::shared_ptr< CWallet > wallet
constexpr CAmount HIGH_APS_FEE
discourage APS fee higher than this amount
Definition: wallet.h:123
int64_t nOrderPos
position in ordered transaction list
Definition: transaction.h:219
OutputType m_default_address_type
Definition: wallet.h:711
void RemoveUnnecessaryTransactions(PartiallySignedTransaction &psbtx, const int &sighash_type)
Reduces the size of the PSBT by dropping unnecessary non_witness_utxos (i.e.
Definition: psbt.cpp:448
bool EraseLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:297
void setArray()
Definition: univalue.cpp:92
std::optional< CMutableTransaction > tx
Definition: psbt.h:948
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
const CWallet & m_wallet
Definition: wallet.cpp:341
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::optional< AddressPurpose > &purpose)
Definition: wallet.cpp:2394
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:1740
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:373
static bool exists(const path &p)
Definition: fs.h:88
boost::signals2::signal< void(const CTxDestination &address, const std::string &label, bool isMine, AddressPurpose purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
Definition: wallet.h:826
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:218
static path u8path(const std::string &utf8_str)
Definition: fs.h:70
std::shared_ptr< CWallet > RestoreWallet(WalletContext &context, const fs::path &backup_file, const std::string &wallet_name, std::optional< bool > load_on_start, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings)
Definition: wallet.cpp:478
util::Result< CTxDestination > GetNewDestination(const OutputType type, const std::string label)
Definition: wallet.cpp:2461
unsigned int nMasterKeyMaxID
Definition: wallet.h:450
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
unsigned int chain_time_max
Definition: chain.h:93
COutPoint prevout
Definition: transaction.h:77
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:1280
virtual common::SettingsValue getRwSetting(const std::string &name)=0
Return <datadir>/settings.json setting value.
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:15
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
static path absolute(const path &p)
Definition: fs.h:81
const CKeyingMaterial & GetEncryptionKey() const override
Definition: wallet.cpp:3529
ArgsManager * args
Definition: context.h:37
bool isInactive() const
Definition: transaction.h:330
std::shared_ptr< CWallet > GetDefaultWallet(WalletContext &context, size_t &count)
Definition: wallet.cpp:184
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:83
bool AddWallet(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:140
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:1346
std::atomic< double > m_scanning_progress
Definition: wallet.h:312
static std::set< std::string > g_loading_wallet_set GUARDED_BY(g_loading_wallet_mutex)
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
void SetTx(CTransactionRef arg)
Definition: transaction.h:302
bool isArray() const
Definition: univalue.h:84
CTransactionRef tx
Definition: transaction.h:253
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3539
CAmount GetFeePerK() const
Return the fee in satoshis for a vsize of 1000 vbytes.
Definition: feerate.h:65
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2644
bool HasWalletDescriptor(const WalletDescriptor &desc) const
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:73
WalletFeature GetClosestWalletFeature(int version)
Definition: walletutil.cpp:38
TransactionError FillPSBT(PartiallySignedTransaction &psbtx, bool &complete, int sighash_type=SIGHASH_DEFAULT, bool sign=true, bool bip32derivs=true, size_t *n_signed=nullptr, bool finalize=true) const
Fills out a PSBT with information from the wallet.
Definition: wallet.cpp:2145
#define PACKAGE_BUGREPORT
static std::condition_variable g_wallet_release_cv
Definition: wallet.cpp:217
boost::signals2::signal< void()> NotifyCanGetAddressesChanged
Keypool has new keys.
Definition: wallet.h:841
void CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm)
Submit the transaction to the node&#39;s mempool and then relay to peers.
Definition: wallet.cpp:2273
virtual bool havePruned()=0
Check if any block has been pruned.
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2477
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:62
void UnsetWalletFlagWithDB(WalletBatch &batch, uint64_t flag)
Unsets a wallet flag and saves it to disk.
Definition: wallet.cpp:1674
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:3723
Clock::time_point now() const
Definition: wallet.h:1072
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2845
#define Assert(val)
Identity function.
Definition: check.h:73
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: context.h:23
bool IsSpentKey(const CScript &scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1021
std::vector< std::unique_ptr< DescriptorScriptPubKeyMan > > desc_spkms
static bool copy_file(const path &from, const path &to, copy_options options)
Definition: fs.h:127
void GetStrongRandBytes(Span< unsigned char > bytes) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
Definition: random.cpp:562
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2212
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:2869
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:119
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:3132
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3498
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3582
std::atomic< bool > m_attaching_chain
Definition: wallet.h:309
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:1559
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:358
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:107
uint256 hash
Definition: transaction.h:38
int GetTxDepthInMainChain(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:3327
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3458