Bitcoin Core  27.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 {
142  LOCK(context.wallets_mutex);
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();
161  LOCK(context.wallets_mutex);
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 {
180  LOCK(context.wallets_mutex);
181  return context.wallets;
182 }
183 
184 std::shared_ptr<CWallet> GetDefaultWallet(WalletContext& context, size_t& count)
185 {
186  LOCK(context.wallets_mutex);
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 {
193  LOCK(context.wallets_mutex);
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 {
202  LOCK(context.wallets_mutex);
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 {
209  LOCK(context.wallets_mutex);
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 
286  NotifyWalletLoaded(context, wallet);
287  AddWallet(context, wallet);
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 
462  NotifyWalletLoaded(context, wallet);
463  AddWallet(context, wallet);
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)
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)) {
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 Txid& 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  wtx.updateState(chain());
1191  }
1192  if (/* insertion took place */ ins.second) {
1193  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1194  }
1195  AddToSpends(wtx);
1196  for (const CTxIn& txin : wtx.tx->vin) {
1197  auto it = mapWallet.find(txin.prevout.hash);
1198  if (it != mapWallet.end()) {
1199  CWalletTx& prevtx = it->second;
1200  if (auto* prev = prevtx.state<TxStateConflicted>()) {
1201  MarkConflicted(prev->conflicting_block_hash, prev->conflicting_block_height, wtx.GetHash());
1202  }
1203  }
1204  }
1205 
1206  // Update birth time when tx time is older than it.
1208 
1209  return true;
1210 }
1211 
1212 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const SyncTxState& state, bool fUpdate, bool rescanning_old_block)
1213 {
1214  const CTransaction& tx = *ptx;
1215  {
1217 
1218  if (auto* conf = std::get_if<TxStateConfirmed>(&state)) {
1219  for (const CTxIn& txin : tx.vin) {
1220  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1221  while (range.first != range.second) {
1222  if (range.first->second != tx.GetHash()) {
1223  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);
1224  MarkConflicted(conf->confirmed_block_hash, conf->confirmed_block_height, range.first->second);
1225  }
1226  range.first++;
1227  }
1228  }
1229  }
1230 
1231  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1232  if (fExisted && !fUpdate) return false;
1233  if (fExisted || IsMine(tx) || IsFromMe(tx))
1234  {
1235  /* Check if any keys in the wallet keypool that were supposed to be unused
1236  * have appeared in a new transaction. If so, remove those keys from the keypool.
1237  * This can happen when restoring an old wallet backup that does not contain
1238  * the mostly recently created transactions from newer versions of the wallet.
1239  */
1240 
1241  // loop though all outputs
1242  for (const CTxOut& txout: tx.vout) {
1243  for (const auto& spk_man : GetScriptPubKeyMans(txout.scriptPubKey)) {
1244  for (auto &dest : spk_man->MarkUnusedAddresses(txout.scriptPubKey)) {
1245  // If internal flag is not defined try to infer it from the ScriptPubKeyMan
1246  if (!dest.internal.has_value()) {
1247  dest.internal = IsInternalScriptPubKeyMan(spk_man);
1248  }
1249 
1250  // skip if can't determine whether it's a receiving address or not
1251  if (!dest.internal.has_value()) continue;
1252 
1253  // If this is a receiving address and it's not in the address book yet
1254  // (e.g. it wasn't generated on this node or we're restoring from backup)
1255  // add it to the address book for proper transaction accounting
1256  if (!*dest.internal && !FindAddressBookEntry(dest.dest, /* allow_change= */ false)) {
1257  SetAddressBook(dest.dest, "", AddressPurpose::RECEIVE);
1258  }
1259  }
1260  }
1261  }
1262 
1263  // Block disconnection override an abandoned tx as unconfirmed
1264  // which means user may have to call abandontransaction again
1265  TxState tx_state = std::visit([](auto&& s) -> TxState { return s; }, state);
1266  CWalletTx* wtx = AddToWallet(MakeTransactionRef(tx), tx_state, /*update_wtx=*/nullptr, /*fFlushOnClose=*/false, rescanning_old_block);
1267  if (!wtx) {
1268  // Can only be nullptr if there was a db write error (missing db, read-only db or a db engine internal writing error).
1269  // As we only store arriving transaction in this process, and we don't want an inconsistent state, let's throw an error.
1270  throw std::runtime_error("DB error adding transaction to wallet, write failed");
1271  }
1272  return true;
1273  }
1274  }
1275  return false;
1276 }
1277 
1279 {
1280  LOCK(cs_wallet);
1281  const CWalletTx* wtx = GetWalletTx(hashTx);
1282  return wtx && !wtx->isAbandoned() && GetTxDepthInMainChain(*wtx) == 0 && !wtx->InMempool();
1283 }
1284 
1286 {
1287  for (const CTxIn& txin : tx->vin) {
1288  auto it = mapWallet.find(txin.prevout.hash);
1289  if (it != mapWallet.end()) {
1290  it->second.MarkDirty();
1291  }
1292  }
1293 }
1294 
1296 {
1297  LOCK(cs_wallet);
1298 
1299  // Can't mark abandoned if confirmed or in mempool
1300  auto it = mapWallet.find(hashTx);
1301  assert(it != mapWallet.end());
1302  const CWalletTx& origtx = it->second;
1303  if (GetTxDepthInMainChain(origtx) != 0 || origtx.InMempool()) {
1304  return false;
1305  }
1306 
1307  auto try_updating_state = [](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1308  // If the orig tx was not in block/mempool, none of its spends can be.
1309  assert(!wtx.isConfirmed());
1310  assert(!wtx.InMempool());
1311  // If already conflicted or abandoned, no need to set abandoned
1312  if (!wtx.isConflicted() && !wtx.isAbandoned()) {
1313  wtx.m_state = TxStateInactive{/*abandoned=*/true};
1314  return TxUpdate::NOTIFY_CHANGED;
1315  }
1316  return TxUpdate::UNCHANGED;
1317  };
1318 
1319  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too.
1320  // States are not permanent, so these transactions can become unabandoned if they are re-added to the
1321  // mempool, or confirmed in a block, or conflicted.
1322  // Note: If the reorged coinbase is re-added to the main chain, the descendants that have not had their
1323  // states change will remain abandoned and will require manual broadcast if the user wants them.
1324 
1325  RecursiveUpdateTxState(hashTx, try_updating_state);
1326 
1327  return true;
1328 }
1329 
1330 void CWallet::MarkConflicted(const uint256& hashBlock, int conflicting_height, const uint256& hashTx)
1331 {
1332  LOCK(cs_wallet);
1333 
1334  // If number of conflict confirms cannot be determined, this means
1335  // that the block is still unknown or not yet part of the main chain,
1336  // for example when loading the wallet during a reindex. Do nothing in that
1337  // case.
1338  if (m_last_block_processed_height < 0 || conflicting_height < 0) {
1339  return;
1340  }
1341  int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1342  if (conflictconfirms >= 0)
1343  return;
1344 
1345  auto try_updating_state = [&](CWalletTx& wtx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1346  if (conflictconfirms < GetTxDepthInMainChain(wtx)) {
1347  // Block is 'more conflicted' than current confirm; update.
1348  // Mark transaction as conflicted with this block.
1349  wtx.m_state = TxStateConflicted{hashBlock, conflicting_height};
1350  return TxUpdate::CHANGED;
1351  }
1352  return TxUpdate::UNCHANGED;
1353  };
1354 
1355  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too.
1356  RecursiveUpdateTxState(hashTx, try_updating_state);
1357 
1358 }
1359 
1360 void CWallet::RecursiveUpdateTxState(const uint256& tx_hash, const TryUpdatingStateFn& try_updating_state) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet) {
1361  // Do not flush the wallet here for performance reasons
1362  WalletBatch batch(GetDatabase(), false);
1363 
1364  std::set<uint256> todo;
1365  std::set<uint256> done;
1366 
1367  todo.insert(tx_hash);
1368 
1369  while (!todo.empty()) {
1370  uint256 now = *todo.begin();
1371  todo.erase(now);
1372  done.insert(now);
1373  auto it = mapWallet.find(now);
1374  assert(it != mapWallet.end());
1375  CWalletTx& wtx = it->second;
1376 
1377  TxUpdate update_state = try_updating_state(wtx);
1378  if (update_state != TxUpdate::UNCHANGED) {
1379  wtx.MarkDirty();
1380  batch.WriteTx(wtx);
1381  // Iterate over all its outputs, and update those tx states as well (if applicable)
1382  for (unsigned int i = 0; i < wtx.tx->vout.size(); ++i) {
1383  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(COutPoint(Txid::FromUint256(now), i));
1384  for (TxSpends::const_iterator iter = range.first; iter != range.second; ++iter) {
1385  if (!done.count(iter->second)) {
1386  todo.insert(iter->second);
1387  }
1388  }
1389  }
1390 
1391  if (update_state == TxUpdate::NOTIFY_CHANGED) {
1392  NotifyTransactionChanged(wtx.GetHash(), CT_UPDATED);
1393  }
1394 
1395  // If a transaction changes its tx state, that usually changes the balance
1396  // available of the outputs it spends. So force those to be recomputed
1397  MarkInputsDirty(wtx.tx);
1398  }
1399  }
1400 }
1401 
1402 void CWallet::SyncTransaction(const CTransactionRef& ptx, const SyncTxState& state, bool update_tx, bool rescanning_old_block)
1403 {
1404  if (!AddToWalletIfInvolvingMe(ptx, state, update_tx, rescanning_old_block))
1405  return; // Not one of ours
1406 
1407  // If a transaction changes 'conflicted' state, that changes the balance
1408  // available of the outputs it spends. So force those to be
1409  // recomputed, also:
1410  MarkInputsDirty(ptx);
1411 }
1412 
1414  LOCK(cs_wallet);
1416 
1417  auto it = mapWallet.find(tx->GetHash());
1418  if (it != mapWallet.end()) {
1419  RefreshMempoolStatus(it->second, chain());
1420  }
1421 }
1422 
1424  LOCK(cs_wallet);
1425  auto it = mapWallet.find(tx->GetHash());
1426  if (it != mapWallet.end()) {
1427  RefreshMempoolStatus(it->second, chain());
1428  }
1429  // Handle transactions that were removed from the mempool because they
1430  // conflict with transactions in a newly connected block.
1431  if (reason == MemPoolRemovalReason::CONFLICT) {
1432  // Trigger external -walletnotify notifications for these transactions.
1433  // Set Status::UNCONFIRMED instead of Status::CONFLICTED for a few reasons:
1434  //
1435  // 1. The transactionRemovedFromMempool callback does not currently
1436  // provide the conflicting block's hash and height, and for backwards
1437  // compatibility reasons it may not be not safe to store conflicted
1438  // wallet transactions with a null block hash. See
1439  // https://github.com/bitcoin/bitcoin/pull/18600#discussion_r420195993.
1440  // 2. For most of these transactions, the wallet's internal conflict
1441  // detection in the blockConnected handler will subsequently call
1442  // MarkConflicted and update them with CONFLICTED status anyway. This
1443  // applies to any wallet transaction that has inputs spent in the
1444  // block, or that has ancestors in the wallet with inputs spent by
1445  // the block.
1446  // 3. Longstanding behavior since the sync implementation in
1447  // https://github.com/bitcoin/bitcoin/pull/9371 and the prior sync
1448  // implementation before that was to mark these transactions
1449  // unconfirmed rather than conflicted.
1450  //
1451  // Nothing described above should be seen as an unchangeable requirement
1452  // when improving this code in the future. The wallet's heuristics for
1453  // distinguishing between conflicted and unconfirmed transactions are
1454  // imperfect, and could be improved in general, see
1455  // https://github.com/bitcoin-core/bitcoin-devwiki/wiki/Wallet-Transaction-Conflict-Tracking
1457  }
1458 }
1459 
1461 {
1462  if (role == ChainstateRole::BACKGROUND) {
1463  return;
1464  }
1465  assert(block.data);
1466  LOCK(cs_wallet);
1467 
1468  m_last_block_processed_height = block.height;
1469  m_last_block_processed = block.hash;
1470 
1471  // No need to scan block if it was created before the wallet birthday.
1472  // Uses chain max time and twice the grace period to adjust time for block time variability.
1473  if (block.chain_time_max < m_birth_time.load() - (TIMESTAMP_WINDOW * 2)) return;
1474 
1475  // Scan block
1476  for (size_t index = 0; index < block.data->vtx.size(); index++) {
1477  SyncTransaction(block.data->vtx[index], TxStateConfirmed{block.hash, block.height, static_cast<int>(index)});
1479  }
1480 }
1481 
1483 {
1484  assert(block.data);
1485  LOCK(cs_wallet);
1486 
1487  // At block disconnection, this will change an abandoned transaction to
1488  // be unconfirmed, whether or not the transaction is added back to the mempool.
1489  // User may have to call abandontransaction again. It may be addressed in the
1490  // future with a stickier abandoned state or even removing abandontransaction call.
1491  m_last_block_processed_height = block.height - 1;
1492  m_last_block_processed = *Assert(block.prev_hash);
1493 
1494  int disconnect_height = block.height;
1495 
1496  for (const CTransactionRef& ptx : Assert(block.data)->vtx) {
1498 
1499  for (const CTxIn& tx_in : ptx->vin) {
1500  // No other wallet transactions conflicted with this transaction
1501  if (mapTxSpends.count(tx_in.prevout) < 1) continue;
1502 
1503  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(tx_in.prevout);
1504 
1505  // For all of the spends that conflict with this transaction
1506  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it) {
1507  CWalletTx& wtx = mapWallet.find(_it->second)->second;
1508 
1509  if (!wtx.isConflicted()) continue;
1510 
1511  auto try_updating_state = [&](CWalletTx& tx) {
1512  if (!tx.isConflicted()) return TxUpdate::UNCHANGED;
1513  if (tx.state<TxStateConflicted>()->conflicting_block_height >= disconnect_height) {
1514  tx.m_state = TxStateInactive{};
1515  return TxUpdate::CHANGED;
1516  }
1517  return TxUpdate::UNCHANGED;
1518  };
1519 
1520  RecursiveUpdateTxState(wtx.tx->GetHash(), try_updating_state);
1521  }
1522  }
1523  }
1524 }
1525 
1527 {
1529 }
1530 
1531 void CWallet::BlockUntilSyncedToCurrentChain() const {
1533  // Skip the queue-draining stuff if we know we're caught up with
1534  // chain().Tip(), otherwise put a callback in the validation interface queue and wait
1535  // for the queue to drain enough to execute it (indicating we are caught up
1536  // at least with the time we entered this function).
1537  uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1538  chain().waitForNotificationsIfTipChanged(last_block_hash);
1539 }
1540 
1541 // Note that this function doesn't distinguish between a 0-valued input,
1542 // and a not-"is mine" (according to the filter) input.
1543 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1544 {
1545  {
1546  LOCK(cs_wallet);
1547  const auto mi = mapWallet.find(txin.prevout.hash);
1548  if (mi != mapWallet.end())
1549  {
1550  const CWalletTx& prev = (*mi).second;
1551  if (txin.prevout.n < prev.tx->vout.size())
1552  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1553  return prev.tx->vout[txin.prevout.n].nValue;
1554  }
1555  }
1556  return 0;
1557 }
1558 
1559 isminetype CWallet::IsMine(const CTxOut& txout) const
1560 {
1562  return IsMine(txout.scriptPubKey);
1563 }
1564 
1566 {
1568  return IsMine(GetScriptForDestination(dest));
1569 }
1570 
1571 isminetype CWallet::IsMine(const CScript& script) const
1572 {
1574 
1575  // Search the cache so that IsMine is called only on the relevant SPKMs instead of on everything in m_spk_managers
1576  const auto& it = m_cached_spks.find(script);
1577  if (it != m_cached_spks.end()) {
1578  isminetype res = ISMINE_NO;
1579  for (const auto& spkm : it->second) {
1580  res = std::max(res, spkm->IsMine(script));
1581  }
1582  Assume(res == ISMINE_SPENDABLE);
1583  return res;
1584  }
1585 
1586  // Legacy wallet
1587  if (IsLegacy()) return GetLegacyScriptPubKeyMan()->IsMine(script);
1588 
1589  return ISMINE_NO;
1590 }
1591 
1592 bool CWallet::IsMine(const CTransaction& tx) const
1593 {
1595  for (const CTxOut& txout : tx.vout)
1596  if (IsMine(txout))
1597  return true;
1598  return false;
1599 }
1600 
1601 isminetype CWallet::IsMine(const COutPoint& outpoint) const
1602 {
1604  auto wtx = GetWalletTx(outpoint.hash);
1605  if (!wtx) {
1606  return ISMINE_NO;
1607  }
1608  if (outpoint.n >= wtx->tx->vout.size()) {
1609  return ISMINE_NO;
1610  }
1611  return IsMine(wtx->tx->vout[outpoint.n]);
1612 }
1613 
1614 bool CWallet::IsFromMe(const CTransaction& tx) const
1615 {
1616  return (GetDebit(tx, ISMINE_ALL) > 0);
1617 }
1618 
1619 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1620 {
1621  CAmount nDebit = 0;
1622  for (const CTxIn& txin : tx.vin)
1623  {
1624  nDebit += GetDebit(txin, filter);
1625  if (!MoneyRange(nDebit))
1626  throw std::runtime_error(std::string(__func__) + ": value out of range");
1627  }
1628  return nDebit;
1629 }
1630 
1632 {
1633  // All Active ScriptPubKeyMans must be HD for this to be true
1634  bool result = false;
1635  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
1636  if (!spk_man->IsHDEnabled()) return false;
1637  result = true;
1638  }
1639  return result;
1640 }
1641 
1642 bool CWallet::CanGetAddresses(bool internal) const
1643 {
1644  LOCK(cs_wallet);
1645  if (m_spk_managers.empty()) return false;
1646  for (OutputType t : OUTPUT_TYPES) {
1647  auto spk_man = GetScriptPubKeyMan(t, internal);
1648  if (spk_man && spk_man->CanGetAddresses(internal)) {
1649  return true;
1650  }
1651  }
1652  return false;
1653 }
1654 
1655 void CWallet::SetWalletFlag(uint64_t flags)
1656 {
1657  LOCK(cs_wallet);
1658  m_wallet_flags |= flags;
1659  if (!WalletBatch(GetDatabase()).WriteWalletFlags(m_wallet_flags))
1660  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1661 }
1662 
1663 void CWallet::UnsetWalletFlag(uint64_t flag)
1664 {
1665  WalletBatch batch(GetDatabase());
1666  UnsetWalletFlagWithDB(batch, flag);
1667 }
1668 
1669 void CWallet::UnsetWalletFlagWithDB(WalletBatch& batch, uint64_t flag)
1670 {
1671  LOCK(cs_wallet);
1672  m_wallet_flags &= ~flag;
1673  if (!batch.WriteWalletFlags(m_wallet_flags))
1674  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1675 }
1676 
1678 {
1680 }
1681 
1682 bool CWallet::IsWalletFlagSet(uint64_t flag) const
1683 {
1684  return (m_wallet_flags & flag);
1685 }
1686 
1688 {
1689  LOCK(cs_wallet);
1690  if (((flags & KNOWN_WALLET_FLAGS) >> 32) ^ (flags >> 32)) {
1691  // contains unknown non-tolerable wallet flags
1692  return false;
1693  }
1695 
1696  return true;
1697 }
1698 
1700 {
1701  LOCK(cs_wallet);
1702 
1703  // We should never be writing unknown non-tolerable wallet flags
1704  assert(((flags & KNOWN_WALLET_FLAGS) >> 32) == (flags >> 32));
1705  // This should only be used once, when creating a new wallet - so current flags are expected to be blank
1706  assert(m_wallet_flags == 0);
1707 
1708  if (!WalletBatch(GetDatabase()).WriteWalletFlags(flags)) {
1709  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1710  }
1711 
1712  if (!LoadWalletFlags(flags)) assert(false);
1713 }
1714 
1715 bool CWallet::ImportScripts(const std::set<CScript> scripts, int64_t timestamp)
1716 {
1717  auto spk_man = GetLegacyScriptPubKeyMan();
1718  if (!spk_man) {
1719  return false;
1720  }
1721  LOCK(spk_man->cs_KeyStore);
1722  return spk_man->ImportScripts(scripts, timestamp);
1723 }
1724 
1725 bool CWallet::ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp)
1726 {
1727  auto spk_man = GetLegacyScriptPubKeyMan();
1728  if (!spk_man) {
1729  return false;
1730  }
1731  LOCK(spk_man->cs_KeyStore);
1732  return spk_man->ImportPrivKeys(privkey_map, timestamp);
1733 }
1734 
1735 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)
1736 {
1737  auto spk_man = GetLegacyScriptPubKeyMan();
1738  if (!spk_man) {
1739  return false;
1740  }
1741  LOCK(spk_man->cs_KeyStore);
1742  return spk_man->ImportPubKeys(ordered_pubkeys, pubkey_map, key_origins, add_keypool, internal, timestamp);
1743 }
1744 
1745 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)
1746 {
1747  auto spk_man = GetLegacyScriptPubKeyMan();
1748  if (!spk_man) {
1749  return false;
1750  }
1751  LOCK(spk_man->cs_KeyStore);
1752  if (!spk_man->ImportScriptPubKeys(script_pub_keys, have_solving_data, timestamp)) {
1753  return false;
1754  }
1755  if (apply_label) {
1756  WalletBatch batch(GetDatabase());
1757  for (const CScript& script : script_pub_keys) {
1758  CTxDestination dest;
1759  ExtractDestination(script, dest);
1760  if (IsValidDestination(dest)) {
1761  SetAddressBookWithDB(batch, dest, label, AddressPurpose::RECEIVE);
1762  }
1763  }
1764  }
1765  return true;
1766 }
1767 
1769 {
1770  int64_t birthtime = m_birth_time.load();
1771  if (time < birthtime) {
1772  m_birth_time = time;
1773  }
1774 }
1775 
1784 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1785 {
1786  // Find starting block. May be null if nCreateTime is greater than the
1787  // highest blockchain timestamp, in which case there is nothing that needs
1788  // to be scanned.
1789  int start_height = 0;
1790  uint256 start_block;
1791  bool start = chain().findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, FoundBlock().hash(start_block).height(start_height));
1792  WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, start ? WITH_LOCK(cs_wallet, return GetLastBlockHeight()) - start_height + 1 : 0);
1793 
1794  if (start) {
1795  // TODO: this should take into account failure by ScanResult::USER_ABORT
1796  ScanResult result = ScanForWalletTransactions(start_block, start_height, /*max_height=*/{}, reserver, /*fUpdate=*/update, /*save_progress=*/false);
1797  if (result.status == ScanResult::FAILURE) {
1798  int64_t time_max;
1799  CHECK_NONFATAL(chain().findBlock(result.last_failed_block, FoundBlock().maxTime(time_max)));
1800  return time_max + TIMESTAMP_WINDOW + 1;
1801  }
1802  }
1803  return startTime;
1804 }
1805 
1828 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)
1829 {
1830  constexpr auto INTERVAL_TIME{60s};
1831  auto current_time{reserver.now()};
1832  auto start_time{reserver.now()};
1833 
1834  assert(reserver.isReserved());
1835 
1836  uint256 block_hash = start_block;
1837  ScanResult result;
1838 
1839  std::unique_ptr<FastWalletRescanFilter> fast_rescan_filter;
1840  if (!IsLegacy() && chain().hasBlockFilterIndex(BlockFilterType::BASIC)) fast_rescan_filter = std::make_unique<FastWalletRescanFilter>(*this);
1841 
1842  WalletLogPrintf("Rescan started from block %s... (%s)\n", start_block.ToString(),
1843  fast_rescan_filter ? "fast variant using block filters" : "slow variant inspecting all blocks");
1844 
1845  fAbortRescan = false;
1846  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)
1847  uint256 tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1848  uint256 end_hash = tip_hash;
1849  if (max_height) chain().findAncestorByHeight(tip_hash, *max_height, FoundBlock().hash(end_hash));
1850  double progress_begin = chain().guessVerificationProgress(block_hash);
1851  double progress_end = chain().guessVerificationProgress(end_hash);
1852  double progress_current = progress_begin;
1853  int block_height = start_height;
1854  while (!fAbortRescan && !chain().shutdownRequested()) {
1855  if (progress_end - progress_begin > 0.0) {
1856  m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
1857  } else { // avoid divide-by-zero for single block scan range (i.e. start and stop hashes are equal)
1858  m_scanning_progress = 0;
1859  }
1860  if (block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1861  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1862  }
1863 
1864  bool next_interval = reserver.now() >= current_time + INTERVAL_TIME;
1865  if (next_interval) {
1866  current_time = reserver.now();
1867  WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", block_height, progress_current);
1868  }
1869 
1870  bool fetch_block{true};
1871  if (fast_rescan_filter) {
1872  fast_rescan_filter->UpdateIfNeeded();
1873  auto matches_block{fast_rescan_filter->MatchesBlock(block_hash)};
1874  if (matches_block.has_value()) {
1875  if (*matches_block) {
1876  LogPrint(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (filter matched)\n", block_height, block_hash.ToString());
1877  } else {
1878  result.last_scanned_block = block_hash;
1879  result.last_scanned_height = block_height;
1880  fetch_block = false;
1881  }
1882  } else {
1883  LogPrint(BCLog::SCAN, "Fast rescan: inspect block %d [%s] (WARNING: block filter not found!)\n", block_height, block_hash.ToString());
1884  }
1885  }
1886 
1887  // Find next block separately from reading data above, because reading
1888  // is slow and there might be a reorg while it is read.
1889  bool block_still_active = false;
1890  bool next_block = false;
1891  uint256 next_block_hash;
1892  chain().findBlock(block_hash, FoundBlock().inActiveChain(block_still_active).nextBlock(FoundBlock().inActiveChain(next_block).hash(next_block_hash)));
1893 
1894  if (fetch_block) {
1895  // Read block data
1896  CBlock block;
1897  chain().findBlock(block_hash, FoundBlock().data(block));
1898 
1899  if (!block.IsNull()) {
1900  LOCK(cs_wallet);
1901  if (!block_still_active) {
1902  // Abort scan if current block is no longer active, to prevent
1903  // marking transactions as coming from the wrong block.
1904  result.last_failed_block = block_hash;
1905  result.status = ScanResult::FAILURE;
1906  break;
1907  }
1908  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1909  SyncTransaction(block.vtx[posInBlock], TxStateConfirmed{block_hash, block_height, static_cast<int>(posInBlock)}, fUpdate, /*rescanning_old_block=*/true);
1910  }
1911  // scan succeeded, record block as most recent successfully scanned
1912  result.last_scanned_block = block_hash;
1913  result.last_scanned_height = block_height;
1914 
1915  if (save_progress && next_interval) {
1916  CBlockLocator loc = m_chain->getActiveChainLocator(block_hash);
1917 
1918  if (!loc.IsNull()) {
1919  WalletLogPrintf("Saving scan progress %d.\n", block_height);
1920  WalletBatch batch(GetDatabase());
1921  batch.WriteBestBlock(loc);
1922  }
1923  }
1924  } else {
1925  // could not scan block, keep scanning but record this block as the most recent failure
1926  result.last_failed_block = block_hash;
1927  result.status = ScanResult::FAILURE;
1928  }
1929  }
1930  if (max_height && block_height >= *max_height) {
1931  break;
1932  }
1933  {
1934  if (!next_block) {
1935  // break successfully when rescan has reached the tip, or
1936  // previous block is no longer on the chain due to a reorg
1937  break;
1938  }
1939 
1940  // increment block and verification progress
1941  block_hash = next_block_hash;
1942  ++block_height;
1943  progress_current = chain().guessVerificationProgress(block_hash);
1944 
1945  // handle updated tip hash
1946  const uint256 prev_tip_hash = tip_hash;
1947  tip_hash = WITH_LOCK(cs_wallet, return GetLastBlockHash());
1948  if (!max_height && prev_tip_hash != tip_hash) {
1949  // in case the tip has changed, update progress max
1950  progress_end = chain().guessVerificationProgress(tip_hash);
1951  }
1952  }
1953  }
1954  if (!max_height) {
1955  WalletLogPrintf("Scanning current mempool transactions.\n");
1956  WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
1957  }
1958  ShowProgress(strprintf("%s " + _("Rescanning…").translated, GetDisplayName()), 100); // hide progress dialog in GUI
1959  if (block_height && fAbortRescan) {
1960  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", block_height, progress_current);
1961  result.status = ScanResult::USER_ABORT;
1962  } else if (block_height && chain().shutdownRequested()) {
1963  WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", block_height, progress_current);
1964  result.status = ScanResult::USER_ABORT;
1965  } else {
1966  WalletLogPrintf("Rescan completed in %15dms\n", Ticks<std::chrono::milliseconds>(reserver.now() - start_time));
1967  }
1968  return result;
1969 }
1970 
1971 bool CWallet::SubmitTxMemoryPoolAndRelay(CWalletTx& wtx, std::string& err_string, bool relay) const
1972 {
1974 
1975  // Can't relay if wallet is not broadcasting
1976  if (!GetBroadcastTransactions()) return false;
1977  // Don't relay abandoned transactions
1978  if (wtx.isAbandoned()) return false;
1979  // Don't try to submit coinbase transactions. These would fail anyway but would
1980  // cause log spam.
1981  if (wtx.IsCoinBase()) return false;
1982  // Don't try to submit conflicted or confirmed transactions.
1983  if (GetTxDepthInMainChain(wtx) != 0) return false;
1984 
1985  // Submit transaction to mempool for relay
1986  WalletLogPrintf("Submitting wtx %s to mempool for relay\n", wtx.GetHash().ToString());
1987  // We must set TxStateInMempool here. Even though it will also be set later by the
1988  // entered-mempool callback, if we did not there would be a race where a
1989  // user could call sendmoney in a loop and hit spurious out of funds errors
1990  // because we think that this newly generated transaction's change is
1991  // unavailable as we're not yet aware that it is in the mempool.
1992  //
1993  // If broadcast fails for any reason, trying to set wtx.m_state here would be incorrect.
1994  // If transaction was previously in the mempool, it should be updated when
1995  // TransactionRemovedFromMempool fires.
1996  bool ret = chain().broadcastTransaction(wtx.tx, m_default_max_tx_fee, relay, err_string);
1997  if (ret) wtx.m_state = TxStateInMempool{};
1998  return ret;
1999 }
2000 
2001 std::set<uint256> CWallet::GetTxConflicts(const CWalletTx& wtx) const
2002 {
2004 
2005  const uint256 myHash{wtx.GetHash()};
2006  std::set<uint256> result{GetConflicts(myHash)};
2007  result.erase(myHash);
2008  return result;
2009 }
2010 
2012 {
2013  // Don't attempt to resubmit if the wallet is configured to not broadcast
2014  if (!fBroadcastTransactions) return false;
2015 
2016  // During reindex, importing and IBD, old wallet transactions become
2017  // unconfirmed. Don't resend them as that would spam other nodes.
2018  // We only allow forcing mempool submission when not relaying to avoid this spam.
2019  if (!chain().isReadyToBroadcast()) return false;
2020 
2021  // Do this infrequently and randomly to avoid giving away
2022  // that these are our transactions.
2023  if (NodeClock::now() < m_next_resend) return false;
2024 
2025  return true;
2026 }
2027 
2029 
2030 // Resubmit transactions from the wallet to the mempool, optionally asking the
2031 // mempool to relay them. On startup, we will do this for all unconfirmed
2032 // transactions but will not ask the mempool to relay them. We do this on startup
2033 // to ensure that our own mempool is aware of our transactions. There
2034 // is a privacy side effect here as not broadcasting on startup also means that we won't
2035 // inform the world of our wallet's state, particularly if the wallet (or node) is not
2036 // yet synced.
2037 //
2038 // Otherwise this function is called periodically in order to relay our unconfirmed txs.
2039 // We do this on a random timer to slightly obfuscate which transactions
2040 // come from our wallet.
2041 //
2042 // TODO: Ideally, we'd only resend transactions that we think should have been
2043 // mined in the most recent block. Any transaction that wasn't in the top
2044 // blockweight of transactions in the mempool shouldn't have been mined,
2045 // and so is probably just sitting in the mempool waiting to be confirmed.
2046 // Rebroadcasting does nothing to speed up confirmation and only damages
2047 // privacy.
2048 //
2049 // The `force` option results in all unconfirmed transactions being submitted to
2050 // the mempool. This does not necessarily result in those transactions being relayed,
2051 // that depends on the `relay` option. Periodic rebroadcast uses the pattern
2052 // relay=true force=false, while loading into the mempool
2053 // (on start, or after import) uses relay=false force=true.
2054 void CWallet::ResubmitWalletTransactions(bool relay, bool force)
2055 {
2056  // Don't attempt to resubmit if the wallet is configured to not broadcast,
2057  // even if forcing.
2058  if (!fBroadcastTransactions) return;
2059 
2060  int submitted_tx_count = 0;
2061 
2062  { // cs_wallet scope
2063  LOCK(cs_wallet);
2064 
2065  // First filter for the transactions we want to rebroadcast.
2066  // We use a set with WalletTxOrderComparator so that rebroadcasting occurs in insertion order
2067  std::set<CWalletTx*, WalletTxOrderComparator> to_submit;
2068  for (auto& [txid, wtx] : mapWallet) {
2069  // Only rebroadcast unconfirmed txs
2070  if (!wtx.isUnconfirmed()) continue;
2071 
2072  // Attempt to rebroadcast all txes more than 5 minutes older than
2073  // the last block, or all txs if forcing.
2074  if (!force && wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
2075  to_submit.insert(&wtx);
2076  }
2077  // Now try submitting the transactions to the memory pool and (optionally) relay them.
2078  for (auto wtx : to_submit) {
2079  std::string unused_err_string;
2080  if (SubmitTxMemoryPoolAndRelay(*wtx, unused_err_string, relay)) ++submitted_tx_count;
2081  }
2082  } // cs_wallet
2083 
2084  if (submitted_tx_count > 0) {
2085  WalletLogPrintf("%s: resubmit %u unconfirmed transactions\n", __func__, submitted_tx_count);
2086  }
2087 }
2088  // end of mapWallet
2090 
2092 {
2093  for (const std::shared_ptr<CWallet>& pwallet : GetWallets(context)) {
2094  if (!pwallet->ShouldResend()) continue;
2095  pwallet->ResubmitWalletTransactions(/*relay=*/true, /*force=*/false);
2096  pwallet->SetNextResend();
2097  }
2098 }
2099 
2100 
2107 {
2109 
2110  // Build coins map
2111  std::map<COutPoint, Coin> coins;
2112  for (auto& input : tx.vin) {
2113  const auto mi = mapWallet.find(input.prevout.hash);
2114  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2115  return false;
2116  }
2117  const CWalletTx& wtx = mi->second;
2118  int prev_height = wtx.state<TxStateConfirmed>() ? wtx.state<TxStateConfirmed>()->confirmed_block_height : 0;
2119  coins[input.prevout] = Coin(wtx.tx->vout[input.prevout.n], prev_height, wtx.IsCoinBase());
2120  }
2121  std::map<int, bilingual_str> input_errors;
2122  return SignTransaction(tx, coins, SIGHASH_DEFAULT, input_errors);
2123 }
2124 
2125 bool CWallet::SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, bilingual_str>& input_errors) const
2126 {
2127  // Try to sign with all ScriptPubKeyMans
2128  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2129  // spk_man->SignTransaction will return true if the transaction is complete,
2130  // so we can exit early and return true if that happens
2131  if (spk_man->SignTransaction(tx, coins, sighash, input_errors)) {
2132  return true;
2133  }
2134  }
2135 
2136  // At this point, one input was not fully signed otherwise we would have exited already
2137  return false;
2138 }
2139 
2140 TransactionError CWallet::FillPSBT(PartiallySignedTransaction& psbtx, bool& complete, int sighash_type, bool sign, bool bip32derivs, size_t * n_signed, bool finalize) const
2141 {
2142  if (n_signed) {
2143  *n_signed = 0;
2144  }
2145  LOCK(cs_wallet);
2146  // Get all of the previous transactions
2147  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
2148  const CTxIn& txin = psbtx.tx->vin[i];
2149  PSBTInput& input = psbtx.inputs.at(i);
2150 
2151  if (PSBTInputSigned(input)) {
2152  continue;
2153  }
2154 
2155  // If we have no utxo, grab it from the wallet.
2156  if (!input.non_witness_utxo) {
2157  const uint256& txhash = txin.prevout.hash;
2158  const auto it = mapWallet.find(txhash);
2159  if (it != mapWallet.end()) {
2160  const CWalletTx& wtx = it->second;
2161  // We only need the non_witness_utxo, which is a superset of the witness_utxo.
2162  // The signing code will switch to the smaller witness_utxo if this is ok.
2163  input.non_witness_utxo = wtx.tx;
2164  }
2165  }
2166  }
2167 
2168  const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
2169 
2170  // Fill in information from ScriptPubKeyMans
2171  for (ScriptPubKeyMan* spk_man : GetAllScriptPubKeyMans()) {
2172  int n_signed_this_spkm = 0;
2173  TransactionError res = spk_man->FillPSBT(psbtx, txdata, sighash_type, sign, bip32derivs, &n_signed_this_spkm, finalize);
2174  if (res != TransactionError::OK) {
2175  return res;
2176  }
2177 
2178  if (n_signed) {
2179  (*n_signed) += n_signed_this_spkm;
2180  }
2181  }
2182 
2183  RemoveUnnecessaryTransactions(psbtx, sighash_type);
2184 
2185  // Complete if every input is now signed
2186  complete = true;
2187  for (const auto& input : psbtx.inputs) {
2188  complete &= PSBTInputSigned(input);
2189  }
2190 
2191  return TransactionError::OK;
2192 }
2193 
2194 SigningResult CWallet::SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const
2195 {
2196  SignatureData sigdata;
2197  CScript script_pub_key = GetScriptForDestination(pkhash);
2198  for (const auto& spk_man_pair : m_spk_managers) {
2199  if (spk_man_pair.second->CanProvide(script_pub_key, sigdata)) {
2200  LOCK(cs_wallet); // DescriptorScriptPubKeyMan calls IsLocked which can lock cs_wallet in a deadlocking order
2201  return spk_man_pair.second->SignMessage(message, pkhash, str_sig);
2202  }
2203  }
2205 }
2206 
2207 OutputType CWallet::TransactionChangeType(const std::optional<OutputType>& change_type, const std::vector<CRecipient>& vecSend) const
2208 {
2209  // If -changetype is specified, always use that change type.
2210  if (change_type) {
2211  return *change_type;
2212  }
2213 
2214  // if m_default_address_type is legacy, use legacy address as change.
2216  return OutputType::LEGACY;
2217  }
2218 
2219  bool any_tr{false};
2220  bool any_wpkh{false};
2221  bool any_sh{false};
2222  bool any_pkh{false};
2223 
2224  for (const auto& recipient : vecSend) {
2225  if (std::get_if<WitnessV1Taproot>(&recipient.dest)) {
2226  any_tr = true;
2227  } else if (std::get_if<WitnessV0KeyHash>(&recipient.dest)) {
2228  any_wpkh = true;
2229  } else if (std::get_if<ScriptHash>(&recipient.dest)) {
2230  any_sh = true;
2231  } else if (std::get_if<PKHash>(&recipient.dest)) {
2232  any_pkh = true;
2233  }
2234  }
2235 
2236  const bool has_bech32m_spkman(GetScriptPubKeyMan(OutputType::BECH32M, /*internal=*/true));
2237  if (has_bech32m_spkman && any_tr) {
2238  // Currently tr is the only type supported by the BECH32M spkman
2239  return OutputType::BECH32M;
2240  }
2241  const bool has_bech32_spkman(GetScriptPubKeyMan(OutputType::BECH32, /*internal=*/true));
2242  if (has_bech32_spkman && any_wpkh) {
2243  // Currently wpkh is the only type supported by the BECH32 spkman
2244  return OutputType::BECH32;
2245  }
2246  const bool has_p2sh_segwit_spkman(GetScriptPubKeyMan(OutputType::P2SH_SEGWIT, /*internal=*/true));
2247  if (has_p2sh_segwit_spkman && any_sh) {
2248  // Currently sh_wpkh is the only type supported by the P2SH_SEGWIT spkman
2249  // As of 2021 about 80% of all SH are wrapping WPKH, so use that
2250  return OutputType::P2SH_SEGWIT;
2251  }
2252  const bool has_legacy_spkman(GetScriptPubKeyMan(OutputType::LEGACY, /*internal=*/true));
2253  if (has_legacy_spkman && any_pkh) {
2254  // Currently pkh is the only type supported by the LEGACY spkman
2255  return OutputType::LEGACY;
2256  }
2257 
2258  if (has_bech32m_spkman) {
2259  return OutputType::BECH32M;
2260  }
2261  if (has_bech32_spkman) {
2262  return OutputType::BECH32;
2263  }
2264  // else use m_default_address_type for change
2265  return m_default_address_type;
2266 }
2267 
2268 void CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm)
2269 {
2270  LOCK(cs_wallet);
2271  WalletLogPrintf("CommitTransaction:\n%s", tx->ToString()); // NOLINT(bitcoin-unterminated-logprintf)
2272 
2273  // Add tx to wallet, because if it has change it's also ours,
2274  // otherwise just for transaction history.
2275  CWalletTx* wtx = AddToWallet(tx, TxStateInactive{}, [&](CWalletTx& wtx, bool new_tx) {
2276  CHECK_NONFATAL(wtx.mapValue.empty());
2277  CHECK_NONFATAL(wtx.vOrderForm.empty());
2278  wtx.mapValue = std::move(mapValue);
2279  wtx.vOrderForm = std::move(orderForm);
2280  wtx.fTimeReceivedIsTxTime = true;
2281  wtx.fFromMe = true;
2282  return true;
2283  });
2284 
2285  // wtx can only be null if the db write failed.
2286  if (!wtx) {
2287  throw std::runtime_error(std::string(__func__) + ": Wallet db error, transaction commit failed");
2288  }
2289 
2290  // Notify that old coins are spent
2291  for (const CTxIn& txin : tx->vin) {
2292  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
2293  coin.MarkDirty();
2295  }
2296 
2297  if (!fBroadcastTransactions) {
2298  // Don't submit tx to the mempool
2299  return;
2300  }
2301 
2302  std::string err_string;
2303  if (!SubmitTxMemoryPoolAndRelay(*wtx, err_string, true)) {
2304  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", err_string);
2305  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2306  }
2307 }
2308 
2310 {
2311  LOCK(cs_wallet);
2312 
2313  Assert(m_spk_managers.empty());
2314  Assert(m_wallet_flags == 0);
2315  DBErrors nLoadWalletRet = WalletBatch(GetDatabase()).LoadWallet(this);
2316  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
2317  {
2318  if (GetDatabase().Rewrite("\x04pool"))
2319  {
2320  for (const auto& spk_man_pair : m_spk_managers) {
2321  spk_man_pair.second->RewriteDB();
2322  }
2323  }
2324  }
2325 
2326  if (m_spk_managers.empty()) {
2329  }
2330 
2331  return nLoadWalletRet;
2332 }
2333 
2334 util::Result<void> CWallet::RemoveTxs(std::vector<uint256>& txs_to_remove)
2335 {
2337  WalletBatch batch(GetDatabase());
2338  if (!batch.TxnBegin()) return util::Error{_("Error starting db txn for wallet transactions removal")};
2339 
2340  // Check for transaction existence and remove entries from disk
2341  using TxIterator = std::unordered_map<uint256, CWalletTx, SaltedTxidHasher>::const_iterator;
2342  std::vector<TxIterator> erased_txs;
2343  bilingual_str str_err;
2344  for (const uint256& hash : txs_to_remove) {
2345  auto it_wtx = mapWallet.find(hash);
2346  if (it_wtx == mapWallet.end()) {
2347  str_err = strprintf(_("Transaction %s does not belong to this wallet"), hash.GetHex());
2348  break;
2349  }
2350  if (!batch.EraseTx(hash)) {
2351  str_err = strprintf(_("Failure removing transaction: %s"), hash.GetHex());
2352  break;
2353  }
2354  erased_txs.emplace_back(it_wtx);
2355  }
2356 
2357  // Roll back removals in case of an error
2358  if (!str_err.empty()) {
2359  batch.TxnAbort();
2360  return util::Error{str_err};
2361  }
2362 
2363  // Dump changes to disk
2364  if (!batch.TxnCommit()) return util::Error{_("Error committing db txn for wallet transactions removal")};
2365 
2366  // Update the in-memory state and notify upper layers about the removals
2367  for (const auto& it : erased_txs) {
2368  const uint256 hash{it->first};
2369  wtxOrdered.erase(it->second.m_it_wtxOrdered);
2370  for (const auto& txin : it->second.tx->vin)
2371  mapTxSpends.erase(txin.prevout);
2372  mapWallet.erase(it);
2374  }
2375 
2376  MarkDirty();
2377 
2378  return {}; // all good
2379 }
2380 
2381 bool CWallet::SetAddressBookWithDB(WalletBatch& batch, const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& new_purpose)
2382 {
2383  bool fUpdated = false;
2384  bool is_mine;
2385  std::optional<AddressPurpose> purpose;
2386  {
2387  LOCK(cs_wallet);
2388  std::map<CTxDestination, CAddressBookData>::iterator mi = m_address_book.find(address);
2389  fUpdated = mi != m_address_book.end() && !mi->second.IsChange();
2390 
2391  CAddressBookData& record = mi != m_address_book.end() ? mi->second : m_address_book[address];
2392  record.SetLabel(strName);
2393  is_mine = IsMine(address) != ISMINE_NO;
2394  if (new_purpose) { /* update purpose only if requested */
2395  record.purpose = new_purpose;
2396  }
2397  purpose = record.purpose;
2398  }
2399 
2400  const std::string& encoded_dest = EncodeDestination(address);
2401  if (new_purpose && !batch.WritePurpose(encoded_dest, PurposeToString(*new_purpose))) {
2402  WalletLogPrintf("Error: fail to write address book 'purpose' entry\n");
2403  return false;
2404  }
2405  if (!batch.WriteName(encoded_dest, strName)) {
2406  WalletLogPrintf("Error: fail to write address book 'name' entry\n");
2407  return false;
2408  }
2409 
2410  // In very old wallets, address purpose may not be recorded so we derive it from IsMine
2411  NotifyAddressBookChanged(address, strName, is_mine,
2412  purpose.value_or(is_mine ? AddressPurpose::RECEIVE : AddressPurpose::SEND),
2413  (fUpdated ? CT_UPDATED : CT_NEW));
2414  return true;
2415 }
2416 
2417 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::optional<AddressPurpose>& purpose)
2418 {
2419  WalletBatch batch(GetDatabase());
2420  return SetAddressBookWithDB(batch, address, strName, purpose);
2421 }
2422 
2424 {
2425  return RunWithinTxn(GetDatabase(), /*process_desc=*/"address book entry removal", [&](WalletBatch& batch){
2426  return DelAddressBookWithDB(batch, address);
2427  });
2428 }
2429 
2431 {
2432  const std::string& dest = EncodeDestination(address);
2433  {
2434  LOCK(cs_wallet);
2435  // 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.
2436  // NOTE: This isn't a problem for sending addresses because they don't have any data that needs to be kept.
2437  // When adding new address data, it should be considered here whether to retain or delete it.
2438  if (IsMine(address)) {
2439  WalletLogPrintf("%s called with IsMine address, NOT SUPPORTED. Please report this bug! %s\n", __func__, PACKAGE_BUGREPORT);
2440  return false;
2441  }
2442  // Delete data rows associated with this address
2443  if (!batch.EraseAddressData(address)) {
2444  WalletLogPrintf("Error: cannot erase address book entry data\n");
2445  return false;
2446  }
2447 
2448  // Delete purpose entry
2449  if (!batch.ErasePurpose(dest)) {
2450  WalletLogPrintf("Error: cannot erase address book entry purpose\n");
2451  return false;
2452  }
2453 
2454  // Delete name entry
2455  if (!batch.EraseName(dest)) {
2456  WalletLogPrintf("Error: cannot erase address book entry name\n");
2457  return false;
2458  }
2459 
2460  // finally, remove it from the map
2461  m_address_book.erase(address);
2462  }
2463 
2464  // All good, signal changes
2465  NotifyAddressBookChanged(address, "", /*is_mine=*/false, AddressPurpose::SEND, CT_DELETED);
2466  return true;
2467 }
2468 
2470 {
2472 
2473  auto legacy_spk_man = GetLegacyScriptPubKeyMan();
2474  if (legacy_spk_man) {
2475  return legacy_spk_man->KeypoolCountExternalKeys();
2476  }
2477 
2478  unsigned int count = 0;
2479  for (auto spk_man : m_external_spk_managers) {
2480  count += spk_man.second->GetKeyPoolSize();
2481  }
2482 
2483  return count;
2484 }
2485 
2486 unsigned int CWallet::GetKeyPoolSize() const
2487 {
2489 
2490  unsigned int count = 0;
2491  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2492  count += spk_man->GetKeyPoolSize();
2493  }
2494  return count;
2495 }
2496 
2497 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2498 {
2499  LOCK(cs_wallet);
2500  bool res = true;
2501  for (auto spk_man : GetActiveScriptPubKeyMans()) {
2502  res &= spk_man->TopUp(kpSize);
2503  }
2504  return res;
2505 }
2506 
2508 {
2509  LOCK(cs_wallet);
2510  auto spk_man = GetScriptPubKeyMan(type, /*internal=*/false);
2511  if (!spk_man) {
2512  return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2513  }
2514 
2515  auto op_dest = spk_man->GetNewDestination(type);
2516  if (op_dest) {
2517  SetAddressBook(*op_dest, label, AddressPurpose::RECEIVE);
2518  }
2519 
2520  return op_dest;
2521 }
2522 
2524 {
2525  LOCK(cs_wallet);
2526 
2527  ReserveDestination reservedest(this, type);
2528  auto op_dest = reservedest.GetReservedDestination(true);
2529  if (op_dest) reservedest.KeepDestination();
2530 
2531  return op_dest;
2532 }
2533 
2534 std::optional<int64_t> CWallet::GetOldestKeyPoolTime() const
2535 {
2536  LOCK(cs_wallet);
2537  if (m_spk_managers.empty()) {
2538  return std::nullopt;
2539  }
2540 
2541  std::optional<int64_t> oldest_key{std::numeric_limits<int64_t>::max()};
2542  for (const auto& spk_man_pair : m_spk_managers) {
2543  oldest_key = std::min(oldest_key, spk_man_pair.second->GetOldestKeyPoolTime());
2544  }
2545  return oldest_key;
2546 }
2547 
2548 void CWallet::MarkDestinationsDirty(const std::set<CTxDestination>& destinations) {
2549  for (auto& entry : mapWallet) {
2550  CWalletTx& wtx = entry.second;
2551  if (wtx.m_is_cache_empty) continue;
2552  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2553  CTxDestination dst;
2554  if (ExtractDestination(wtx.tx->vout[i].scriptPubKey, dst) && destinations.count(dst)) {
2555  wtx.MarkDirty();
2556  break;
2557  }
2558  }
2559  }
2560 }
2561 
2563 {
2565  for (const std::pair<const CTxDestination, CAddressBookData>& item : m_address_book) {
2566  const auto& entry = item.second;
2567  func(item.first, entry.GetLabel(), entry.IsChange(), entry.purpose);
2568  }
2569 }
2570 
2571 std::vector<CTxDestination> CWallet::ListAddrBookAddresses(const std::optional<AddrBookFilter>& _filter) const
2572 {
2574  std::vector<CTxDestination> result;
2575  AddrBookFilter filter = _filter ? *_filter : AddrBookFilter();
2576  ForEachAddrBookEntry([&result, &filter](const CTxDestination& dest, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
2577  // Filter by change
2578  if (filter.ignore_change && is_change) return;
2579  // Filter by label
2580  if (filter.m_op_label && *filter.m_op_label != label) return;
2581  // All good
2582  result.emplace_back(dest);
2583  });
2584  return result;
2585 }
2586 
2587 std::set<std::string> CWallet::ListAddrBookLabels(const std::optional<AddressPurpose> purpose) const
2588 {
2590  std::set<std::string> label_set;
2591  ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label,
2592  bool _is_change, const std::optional<AddressPurpose>& _purpose) {
2593  if (_is_change) return;
2594  if (!purpose || purpose == _purpose) {
2595  label_set.insert(_label);
2596  }
2597  });
2598  return label_set;
2599 }
2600 
2602 {
2603  m_spk_man = pwallet->GetScriptPubKeyMan(type, internal);
2604  if (!m_spk_man) {
2605  return util::Error{strprintf(_("Error: No %s addresses available."), FormatOutputType(type))};
2606  }
2607 
2608  if (nIndex == -1) {
2609  CKeyPool keypool;
2610  int64_t index;
2611  auto op_address = m_spk_man->GetReservedDestination(type, internal, index, keypool);
2612  if (!op_address) return op_address;
2613  nIndex = index;
2614  address = *op_address;
2615  fInternal = keypool.fInternal;
2616  }
2617  return address;
2618 }
2619 
2621 {
2622  if (nIndex != -1) {
2624  }
2625  nIndex = -1;
2626  address = CNoDestination();
2627 }
2628 
2630 {
2631  if (nIndex != -1) {
2633  }
2634  nIndex = -1;
2635  address = CNoDestination();
2636 }
2637 
2639 {
2640  CScript scriptPubKey = GetScriptForDestination(dest);
2641  for (const auto& spk_man : GetScriptPubKeyMans(scriptPubKey)) {
2642  auto signer_spk_man = dynamic_cast<ExternalSignerScriptPubKeyMan *>(spk_man);
2643  if (signer_spk_man == nullptr) {
2644  continue;
2645  }
2647  return signer_spk_man->DisplayAddress(scriptPubKey, signer);
2648  }
2649  return false;
2650 }
2651 
2652 bool CWallet::LockCoin(const COutPoint& output, WalletBatch* batch)
2653 {
2655  setLockedCoins.insert(output);
2656  if (batch) {
2657  return batch->WriteLockedUTXO(output);
2658  }
2659  return true;
2660 }
2661 
2662 bool CWallet::UnlockCoin(const COutPoint& output, WalletBatch* batch)
2663 {
2665  bool was_locked = setLockedCoins.erase(output);
2666  if (batch && was_locked) {
2667  return batch->EraseLockedUTXO(output);
2668  }
2669  return true;
2670 }
2671 
2673 {
2675  bool success = true;
2676  WalletBatch batch(GetDatabase());
2677  for (auto it = setLockedCoins.begin(); it != setLockedCoins.end(); ++it) {
2678  success &= batch.EraseLockedUTXO(*it);
2679  }
2680  setLockedCoins.clear();
2681  return success;
2682 }
2683 
2684 bool CWallet::IsLockedCoin(const COutPoint& output) const
2685 {
2687  return setLockedCoins.count(output) > 0;
2688 }
2689 
2690 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
2691 {
2693  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2694  it != setLockedCoins.end(); it++) {
2695  COutPoint outpt = (*it);
2696  vOutpts.push_back(outpt);
2697  }
2698 }
2699  // end of Actions
2701 
2702 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const {
2704  mapKeyBirth.clear();
2705 
2706  // map in which we'll infer heights of other keys
2707  std::map<CKeyID, const TxStateConfirmed*> mapKeyFirstBlock;
2708  TxStateConfirmed max_confirm{uint256{}, /*height=*/-1, /*index=*/-1};
2709  max_confirm.confirmed_block_height = GetLastBlockHeight() > 144 ? GetLastBlockHeight() - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
2710  CHECK_NONFATAL(chain().findAncestorByHeight(GetLastBlockHash(), max_confirm.confirmed_block_height, FoundBlock().hash(max_confirm.confirmed_block_hash)));
2711 
2712  {
2714  assert(spk_man != nullptr);
2715  LOCK(spk_man->cs_KeyStore);
2716 
2717  // get birth times for keys with metadata
2718  for (const auto& entry : spk_man->mapKeyMetadata) {
2719  if (entry.second.nCreateTime) {
2720  mapKeyBirth[entry.first] = entry.second.nCreateTime;
2721  }
2722  }
2723 
2724  // Prepare to infer birth heights for keys without metadata
2725  for (const CKeyID &keyid : spk_man->GetKeys()) {
2726  if (mapKeyBirth.count(keyid) == 0)
2727  mapKeyFirstBlock[keyid] = &max_confirm;
2728  }
2729 
2730  // if there are no such keys, we're done
2731  if (mapKeyFirstBlock.empty())
2732  return;
2733 
2734  // find first block that affects those keys, if there are any left
2735  for (const auto& entry : mapWallet) {
2736  // iterate over all wallet transactions...
2737  const CWalletTx &wtx = entry.second;
2738  if (auto* conf = wtx.state<TxStateConfirmed>()) {
2739  // ... which are already in a block
2740  for (const CTxOut &txout : wtx.tx->vout) {
2741  // iterate over all their outputs
2742  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *spk_man)) {
2743  // ... and all their affected keys
2744  auto rit = mapKeyFirstBlock.find(keyid);
2745  if (rit != mapKeyFirstBlock.end() && conf->confirmed_block_height < rit->second->confirmed_block_height) {
2746  rit->second = conf;
2747  }
2748  }
2749  }
2750  }
2751  }
2752  }
2753 
2754  // Extract block timestamps for those keys
2755  for (const auto& entry : mapKeyFirstBlock) {
2756  int64_t block_time;
2757  CHECK_NONFATAL(chain().findBlock(entry.second->confirmed_block_hash, FoundBlock().time(block_time)));
2758  mapKeyBirth[entry.first] = block_time - TIMESTAMP_WINDOW; // block times can be 2h off
2759  }
2760 }
2761 
2785 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx, bool rescanning_old_block) const
2786 {
2787  std::optional<uint256> block_hash;
2788  if (auto* conf = wtx.state<TxStateConfirmed>()) {
2789  block_hash = conf->confirmed_block_hash;
2790  } else if (auto* conf = wtx.state<TxStateConflicted>()) {
2791  block_hash = conf->conflicting_block_hash;
2792  }
2793 
2794  unsigned int nTimeSmart = wtx.nTimeReceived;
2795  if (block_hash) {
2796  int64_t blocktime;
2797  int64_t block_max_time;
2798  if (chain().findBlock(*block_hash, FoundBlock().time(blocktime).maxTime(block_max_time))) {
2799  if (rescanning_old_block) {
2800  nTimeSmart = block_max_time;
2801  } else {
2802  int64_t latestNow = wtx.nTimeReceived;
2803  int64_t latestEntry = 0;
2804 
2805  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
2806  int64_t latestTolerated = latestNow + 300;
2807  const TxItems& txOrdered = wtxOrdered;
2808  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
2809  CWalletTx* const pwtx = it->second;
2810  if (pwtx == &wtx) {
2811  continue;
2812  }
2813  int64_t nSmartTime;
2814  nSmartTime = pwtx->nTimeSmart;
2815  if (!nSmartTime) {
2816  nSmartTime = pwtx->nTimeReceived;
2817  }
2818  if (nSmartTime <= latestTolerated) {
2819  latestEntry = nSmartTime;
2820  if (nSmartTime > latestNow) {
2821  latestNow = nSmartTime;
2822  }
2823  break;
2824  }
2825  }
2826 
2827  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
2828  }
2829  } else {
2830  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), block_hash->ToString());
2831  }
2832  }
2833  return nTimeSmart;
2834 }
2835 
2837 {
2838  if (std::get_if<CNoDestination>(&dest))
2839  return false;
2840 
2841  if (!used) {
2842  if (auto* data{common::FindKey(m_address_book, dest)}) data->previously_spent = false;
2843  return batch.WriteAddressPreviouslySpent(dest, false);
2844  }
2845 
2847  return batch.WriteAddressPreviouslySpent(dest, true);
2848 }
2849 
2851 {
2852  m_address_book[dest].previously_spent = true;
2853 }
2854 
2855 void CWallet::LoadAddressReceiveRequest(const CTxDestination& dest, const std::string& id, const std::string& request)
2856 {
2857  m_address_book[dest].receive_requests[id] = request;
2858 }
2859 
2861 {
2862  if (auto* data{common::FindKey(m_address_book, dest)}) return data->previously_spent;
2863  return false;
2864 }
2865 
2866 std::vector<std::string> CWallet::GetAddressReceiveRequests() const
2867 {
2868  std::vector<std::string> values;
2869  for (const auto& [dest, entry] : m_address_book) {
2870  for (const auto& [id, request] : entry.receive_requests) {
2871  values.emplace_back(request);
2872  }
2873  }
2874  return values;
2875 }
2876 
2877 bool CWallet::SetAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id, const std::string& value)
2878 {
2879  if (!batch.WriteAddressReceiveRequest(dest, id, value)) return false;
2880  m_address_book[dest].receive_requests[id] = value;
2881  return true;
2882 }
2883 
2884 bool CWallet::EraseAddressReceiveRequest(WalletBatch& batch, const CTxDestination& dest, const std::string& id)
2885 {
2886  if (!batch.EraseAddressReceiveRequest(dest, id)) return false;
2887  m_address_book[dest].receive_requests.erase(id);
2888  return true;
2889 }
2890 
2891 std::unique_ptr<WalletDatabase> MakeWalletDatabase(const std::string& name, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error_string)
2892 {
2893  // Do some checking on wallet path. It should be either a:
2894  //
2895  // 1. Path where a directory can be created.
2896  // 2. Path to an existing directory.
2897  // 3. Path to a symlink to a directory.
2898  // 4. For backwards compatibility, the name of a data file in -walletdir.
2900  fs::file_type path_type = fs::symlink_status(wallet_path).type();
2901  if (!(path_type == fs::file_type::not_found || path_type == fs::file_type::directory ||
2902  (path_type == fs::file_type::symlink && fs::is_directory(wallet_path)) ||
2903  (path_type == fs::file_type::regular && fs::PathFromString(name).filename() == fs::PathFromString(name)))) {
2904  error_string = Untranslated(strprintf(
2905  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
2906  "database/log.?????????? files can be stored, a location where such a directory could be created, "
2907  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
2910  return nullptr;
2911  }
2912  return MakeDatabase(wallet_path, options, status, error_string);
2913 }
2914 
2915 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)
2916 {
2917  interfaces::Chain* chain = context.chain;
2918  ArgsManager& args = *Assert(context.args);
2919  const std::string& walletFile = database->Filename();
2920 
2921  const auto start{SteadyClock::now()};
2922  // TODO: Can't use std::make_shared because we need a custom deleter but
2923  // should be possible to use std::allocate_shared.
2924  std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), ReleaseWallet);
2925  walletInstance->m_keypool_size = std::max(args.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE), int64_t{1});
2926  walletInstance->m_notify_tx_changed_script = args.GetArg("-walletnotify", "");
2927 
2928  // Load wallet
2929  bool rescan_required = false;
2930  DBErrors nLoadWalletRet = walletInstance->LoadWallet();
2931  if (nLoadWalletRet != DBErrors::LOAD_OK) {
2932  if (nLoadWalletRet == DBErrors::CORRUPT) {
2933  error = strprintf(_("Error loading %s: Wallet corrupted"), walletFile);
2934  return nullptr;
2935  }
2936  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
2937  {
2938  warnings.push_back(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
2939  " or address metadata may be missing or incorrect."),
2940  walletFile));
2941  }
2942  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
2943  error = strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, PACKAGE_NAME);
2944  return nullptr;
2945  }
2946  else if (nLoadWalletRet == DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED) {
2947  error = strprintf(_("Error loading %s: External signer wallet being loaded without external signer support compiled"), walletFile);
2948  return nullptr;
2949  }
2950  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
2951  {
2952  error = strprintf(_("Wallet needed to be rewritten: restart %s to complete"), PACKAGE_NAME);
2953  return nullptr;
2954  } else if (nLoadWalletRet == DBErrors::NEED_RESCAN) {
2955  warnings.push_back(strprintf(_("Error reading %s! Transaction data may be missing or incorrect."
2956  " Rescanning wallet."), walletFile));
2957  rescan_required = true;
2958  } else if (nLoadWalletRet == DBErrors::UNKNOWN_DESCRIPTOR) {
2959  error = strprintf(_("Unrecognized descriptor found. Loading wallet %s\n\n"
2960  "The wallet might had been created on a newer version.\n"
2961  "Please try running the latest software version.\n"), walletFile);
2962  return nullptr;
2963  } else if (nLoadWalletRet == DBErrors::UNEXPECTED_LEGACY_ENTRY) {
2964  error = strprintf(_("Unexpected legacy entry in descriptor wallet found. Loading wallet %s\n\n"
2965  "The wallet might have been tampered with or created with malicious intent.\n"), walletFile);
2966  return nullptr;
2967  } else {
2968  error = strprintf(_("Error loading %s"), walletFile);
2969  return nullptr;
2970  }
2971  }
2972 
2973  // This wallet is in its first run if there are no ScriptPubKeyMans and it isn't blank or no privkeys
2974  const bool fFirstRun = walletInstance->m_spk_managers.empty() &&
2975  !walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) &&
2976  !walletInstance->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
2977  if (fFirstRun)
2978  {
2979  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
2980  walletInstance->SetMinVersion(FEATURE_LATEST);
2981 
2982  walletInstance->InitWalletFlags(wallet_creation_flags);
2983 
2984  // Only create LegacyScriptPubKeyMan when not descriptor wallet
2985  if (!walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2986  walletInstance->SetupLegacyScriptPubKeyMan();
2987  }
2988 
2989  if ((wallet_creation_flags & WALLET_FLAG_EXTERNAL_SIGNER) || !(wallet_creation_flags & (WALLET_FLAG_DISABLE_PRIVATE_KEYS | WALLET_FLAG_BLANK_WALLET))) {
2990  LOCK(walletInstance->cs_wallet);
2991  if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
2992  walletInstance->SetupDescriptorScriptPubKeyMans();
2993  // SetupDescriptorScriptPubKeyMans already calls SetupGeneration for us so we don't need to call SetupGeneration separately
2994  } else {
2995  // Legacy wallets need SetupGeneration here.
2996  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
2997  if (!spk_man->SetupGeneration()) {
2998  error = _("Unable to generate initial keys");
2999  return nullptr;
3000  }
3001  }
3002  }
3003  }
3004 
3005  if (chain) {
3006  walletInstance->chainStateFlushed(ChainstateRole::NORMAL, chain->getTipLocator());
3007  }
3008  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
3009  // Make it impossible to disable private keys after creation
3010  error = strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile);
3011  return nullptr;
3012  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3013  for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {
3014  if (spk_man->HavePrivateKeys()) {
3015  warnings.push_back(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
3016  break;
3017  }
3018  }
3019  }
3020 
3021  if (!args.GetArg("-addresstype", "").empty()) {
3022  std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-addresstype", ""));
3023  if (!parsed) {
3024  error = strprintf(_("Unknown address type '%s'"), args.GetArg("-addresstype", ""));
3025  return nullptr;
3026  }
3027  walletInstance->m_default_address_type = parsed.value();
3028  }
3029 
3030  if (!args.GetArg("-changetype", "").empty()) {
3031  std::optional<OutputType> parsed = ParseOutputType(args.GetArg("-changetype", ""));
3032  if (!parsed) {
3033  error = strprintf(_("Unknown change type '%s'"), args.GetArg("-changetype", ""));
3034  return nullptr;
3035  }
3036  walletInstance->m_default_change_type = parsed.value();
3037  }
3038 
3039  if (args.IsArgSet("-mintxfee")) {
3040  std::optional<CAmount> min_tx_fee = ParseMoney(args.GetArg("-mintxfee", ""));
3041  if (!min_tx_fee) {
3042  error = AmountErrMsg("mintxfee", args.GetArg("-mintxfee", ""));
3043  return nullptr;
3044  } else if (min_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
3045  warnings.push_back(AmountHighWarn("-mintxfee") + Untranslated(" ") +
3046  _("This is the minimum transaction fee you pay on every transaction."));
3047  }
3048 
3049  walletInstance->m_min_fee = CFeeRate{min_tx_fee.value()};
3050  }
3051 
3052  if (args.IsArgSet("-maxapsfee")) {
3053  const std::string max_aps_fee{args.GetArg("-maxapsfee", "")};
3054  if (max_aps_fee == "-1") {
3055  walletInstance->m_max_aps_fee = -1;
3056  } else if (std::optional<CAmount> max_fee = ParseMoney(max_aps_fee)) {
3057  if (max_fee.value() > HIGH_APS_FEE) {
3058  warnings.push_back(AmountHighWarn("-maxapsfee") + Untranslated(" ") +
3059  _("This is the maximum transaction fee you pay (in addition to the normal fee) to prioritize partial spend avoidance over regular coin selection."));
3060  }
3061  walletInstance->m_max_aps_fee = max_fee.value();
3062  } else {
3063  error = AmountErrMsg("maxapsfee", max_aps_fee);
3064  return nullptr;
3065  }
3066  }
3067 
3068  if (args.IsArgSet("-fallbackfee")) {
3069  std::optional<CAmount> fallback_fee = ParseMoney(args.GetArg("-fallbackfee", ""));
3070  if (!fallback_fee) {
3071  error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-fallbackfee", args.GetArg("-fallbackfee", ""));
3072  return nullptr;
3073  } else if (fallback_fee.value() > HIGH_TX_FEE_PER_KB) {
3074  warnings.push_back(AmountHighWarn("-fallbackfee") + Untranslated(" ") +
3075  _("This is the transaction fee you may pay when fee estimates are not available."));
3076  }
3077  walletInstance->m_fallback_fee = CFeeRate{fallback_fee.value()};
3078  }
3079 
3080  // Disable fallback fee in case value was set to 0, enable if non-null value
3081  walletInstance->m_allow_fallback_fee = walletInstance->m_fallback_fee.GetFeePerK() != 0;
3082 
3083  if (args.IsArgSet("-discardfee")) {
3084  std::optional<CAmount> discard_fee = ParseMoney(args.GetArg("-discardfee", ""));
3085  if (!discard_fee) {
3086  error = strprintf(_("Invalid amount for %s=<amount>: '%s'"), "-discardfee", args.GetArg("-discardfee", ""));
3087  return nullptr;
3088  } else if (discard_fee.value() > HIGH_TX_FEE_PER_KB) {
3089  warnings.push_back(AmountHighWarn("-discardfee") + Untranslated(" ") +
3090  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
3091  }
3092  walletInstance->m_discard_rate = CFeeRate{discard_fee.value()};
3093  }
3094 
3095  if (args.IsArgSet("-paytxfee")) {
3096  std::optional<CAmount> pay_tx_fee = ParseMoney(args.GetArg("-paytxfee", ""));
3097  if (!pay_tx_fee) {
3098  error = AmountErrMsg("paytxfee", args.GetArg("-paytxfee", ""));
3099  return nullptr;
3100  } else if (pay_tx_fee.value() > HIGH_TX_FEE_PER_KB) {
3101  warnings.push_back(AmountHighWarn("-paytxfee") + Untranslated(" ") +
3102  _("This is the transaction fee you will pay if you send a transaction."));
3103  }
3104 
3105  walletInstance->m_pay_tx_fee = CFeeRate{pay_tx_fee.value(), 1000};
3106 
3107  if (chain && walletInstance->m_pay_tx_fee < chain->relayMinFee()) {
3108  error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least %s)"),
3109  "-paytxfee", args.GetArg("-paytxfee", ""), chain->relayMinFee().ToString());
3110  return nullptr;
3111  }
3112  }
3113 
3114  if (args.IsArgSet("-maxtxfee")) {
3115  std::optional<CAmount> max_fee = ParseMoney(args.GetArg("-maxtxfee", ""));
3116  if (!max_fee) {
3117  error = AmountErrMsg("maxtxfee", args.GetArg("-maxtxfee", ""));
3118  return nullptr;
3119  } else if (max_fee.value() > HIGH_MAX_TX_FEE) {
3120  warnings.push_back(strprintf(_("%s is set very high! Fees this large could be paid on a single transaction."), "-maxtxfee"));
3121  }
3122 
3123  if (chain && CFeeRate{max_fee.value(), 1000} < chain->relayMinFee()) {
3124  error = strprintf(_("Invalid amount for %s=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3125  "-maxtxfee", args.GetArg("-maxtxfee", ""), chain->relayMinFee().ToString());
3126  return nullptr;
3127  }
3128 
3129  walletInstance->m_default_max_tx_fee = max_fee.value();
3130  }
3131 
3132  if (args.IsArgSet("-consolidatefeerate")) {
3133  if (std::optional<CAmount> consolidate_feerate = ParseMoney(args.GetArg("-consolidatefeerate", ""))) {
3134  walletInstance->m_consolidate_feerate = CFeeRate(*consolidate_feerate);
3135  } else {
3136  error = AmountErrMsg("consolidatefeerate", args.GetArg("-consolidatefeerate", ""));
3137  return nullptr;
3138  }
3139  }
3140 
3142  warnings.push_back(AmountHighWarn("-minrelaytxfee") + Untranslated(" ") +
3143  _("The wallet will avoid paying less than the minimum relay fee."));
3144  }
3145 
3146  walletInstance->m_confirm_target = args.GetIntArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3147  walletInstance->m_spend_zero_conf_change = args.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3148  walletInstance->m_signal_rbf = args.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3149 
3150  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));
3151 
3152  // Try to top up keypool. No-op if the wallet is locked.
3153  walletInstance->TopUpKeyPool();
3154 
3155  // Cache the first key time
3156  std::optional<int64_t> time_first_key;
3157  for (auto spk_man : walletInstance->GetAllScriptPubKeyMans()) {
3158  int64_t time = spk_man->GetTimeFirstKey();
3159  if (!time_first_key || time < *time_first_key) time_first_key = time;
3160  }
3161  if (time_first_key) walletInstance->MaybeUpdateBirthTime(*time_first_key);
3162 
3163  if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {
3164  walletInstance->m_chain_notifications_handler.reset(); // Reset this pointer so that the wallet will actually be unloaded
3165  return nullptr;
3166  }
3167 
3168  {
3169  LOCK(walletInstance->cs_wallet);
3170  walletInstance->SetBroadcastTransactions(args.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3171  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3172  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3173  walletInstance->WalletLogPrintf("m_address_book.size() = %u\n", walletInstance->m_address_book.size());
3174  }
3175 
3176  return walletInstance;
3177 }
3178 
3179 bool CWallet::AttachChain(const std::shared_ptr<CWallet>& walletInstance, interfaces::Chain& chain, const bool rescan_required, bilingual_str& error, std::vector<bilingual_str>& warnings)
3180 {
3181  LOCK(walletInstance->cs_wallet);
3182  // allow setting the chain if it hasn't been set already but prevent changing it
3183  assert(!walletInstance->m_chain || walletInstance->m_chain == &chain);
3184  walletInstance->m_chain = &chain;
3185 
3186  // Unless allowed, ensure wallet files are not reused across chains:
3187  if (!gArgs.GetBoolArg("-walletcrosschain", DEFAULT_WALLETCROSSCHAIN)) {
3188  WalletBatch batch(walletInstance->GetDatabase());
3189  CBlockLocator locator;
3190  if (batch.ReadBestBlock(locator) && locator.vHave.size() > 0 && chain.getHeight()) {
3191  // Wallet is assumed to be from another chain, if genesis block in the active
3192  // chain differs from the genesis block known to the wallet.
3193  if (chain.getBlockHash(0) != locator.vHave.back()) {
3194  error = Untranslated("Wallet files should not be reused across chains. Restart bitcoind with -walletcrosschain to override.");
3195  return false;
3196  }
3197  }
3198  }
3199 
3200  // Register wallet with validationinterface. It's done before rescan to avoid
3201  // missing block connections between end of rescan and validation subscribing.
3202  // Because of wallet lock being hold, block connection notifications are going to
3203  // be pending on the validation-side until lock release. It's likely to have
3204  // block processing duplicata (if rescan block range overlaps with notification one)
3205  // but we guarantee at least than wallet state is correct after notifications delivery.
3206  // However, chainStateFlushed notifications are ignored until the rescan is finished
3207  // so that in case of a shutdown event, the rescan will be repeated at the next start.
3208  // This is temporary until rescan and notifications delivery are unified under same
3209  // interface.
3210  walletInstance->m_attaching_chain = true; //ignores chainStateFlushed notifications
3211  walletInstance->m_chain_notifications_handler = walletInstance->chain().handleNotifications(walletInstance);
3212 
3213  // If rescan_required = true, rescan_height remains equal to 0
3214  int rescan_height = 0;
3215  if (!rescan_required)
3216  {
3217  WalletBatch batch(walletInstance->GetDatabase());
3218  CBlockLocator locator;
3219  if (batch.ReadBestBlock(locator)) {
3220  if (const std::optional<int> fork_height = chain.findLocatorFork(locator)) {
3221  rescan_height = *fork_height;
3222  }
3223  }
3224  }
3225 
3226  const std::optional<int> tip_height = chain.getHeight();
3227  if (tip_height) {
3228  walletInstance->m_last_block_processed = chain.getBlockHash(*tip_height);
3229  walletInstance->m_last_block_processed_height = *tip_height;
3230  } else {
3231  walletInstance->m_last_block_processed.SetNull();
3232  walletInstance->m_last_block_processed_height = -1;
3233  }
3234 
3235  if (tip_height && *tip_height != rescan_height)
3236  {
3237  // No need to read and scan block if block was created before
3238  // our wallet birthday (as adjusted for block time variability)
3239  std::optional<int64_t> time_first_key = walletInstance->m_birth_time.load();
3240  if (time_first_key) {
3241  FoundBlock found = FoundBlock().height(rescan_height);
3242  chain.findFirstBlockWithTimeAndHeight(*time_first_key - TIMESTAMP_WINDOW, rescan_height, found);
3243  if (!found.found) {
3244  // We were unable to find a block that had a time more recent than our earliest timestamp
3245  // or a height higher than the wallet was synced to, indicating that the wallet is newer than the
3246  // current chain tip. Skip rescanning in this case.
3247  rescan_height = *tip_height;
3248  }
3249  }
3250 
3251  // Technically we could execute the code below in any case, but performing the
3252  // `while` loop below can make startup very slow, so only check blocks on disk
3253  // if necessary.
3255  int block_height = *tip_height;
3256  while (block_height > 0 && chain.haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
3257  --block_height;
3258  }
3259 
3260  if (rescan_height != block_height) {
3261  // We can't rescan beyond blocks we don't have data for, stop and throw an error.
3262  // This might happen if a user uses an old wallet within a pruned node
3263  // or if they ran -disablewallet for a longer time, then decided to re-enable
3264  // Exit early and print an error.
3265  // It also may happen if an assumed-valid chain is in use and therefore not
3266  // all block data is available.
3267  // If a block is pruned after this check, we will load the wallet,
3268  // but fail the rescan with a generic error.
3269 
3270  error = chain.havePruned() ?
3271  _("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)") :
3272  strprintf(_(
3273  "Error loading wallet. Wallet requires blocks to be downloaded, "
3274  "and software does not currently support loading wallets while "
3275  "blocks are being downloaded out of order when using assumeutxo "
3276  "snapshots. Wallet should be able to load successfully after "
3277  "node sync reaches height %s"), block_height);
3278  return false;
3279  }
3280  }
3281 
3282  chain.initMessage(_("Rescanning…").translated);
3283  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
3284 
3285  {
3286  WalletRescanReserver reserver(*walletInstance);
3287  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(chain.getBlockHash(rescan_height), rescan_height, /*max_height=*/{}, reserver, /*fUpdate=*/true, /*save_progress=*/true).status)) {
3288  error = _("Failed to rescan the wallet during initialization");
3289  return false;
3290  }
3291  }
3292  walletInstance->m_attaching_chain = false;
3293  walletInstance->chainStateFlushed(ChainstateRole::NORMAL, chain.getTipLocator());
3294  walletInstance->GetDatabase().IncrementUpdateCounter();
3295  }
3296  walletInstance->m_attaching_chain = false;
3297 
3298  return true;
3299 }
3300 
3301 const CAddressBookData* CWallet::FindAddressBookEntry(const CTxDestination& dest, bool allow_change) const
3302 {
3303  const auto& address_book_it = m_address_book.find(dest);
3304  if (address_book_it == m_address_book.end()) return nullptr;
3305  if ((!allow_change) && address_book_it->second.IsChange()) {
3306  return nullptr;
3307  }
3308  return &address_book_it->second;
3309 }
3310 
3312 {
3313  int prev_version = GetVersion();
3314  if (version == 0) {
3315  WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3316  version = FEATURE_LATEST;
3317  } else {
3318  WalletLogPrintf("Allowing wallet upgrade up to %i\n", version);
3319  }
3320  if (version < prev_version) {
3321  error = strprintf(_("Cannot downgrade wallet from version %i to version %i. Wallet version unchanged."), prev_version, version);
3322  return false;
3323  }
3324 
3325  LOCK(cs_wallet);
3326 
3327  // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
3329  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);
3330  return false;
3331  }
3332 
3333  // Permanently upgrade to the version
3335 
3336  for (auto spk_man : GetActiveScriptPubKeyMans()) {
3337  if (!spk_man->Upgrade(prev_version, version, error)) {
3338  return false;
3339  }
3340  }
3341  return true;
3342 }
3343 
3345 {
3346  // Add wallet transactions that aren't already in a block to mempool
3347  // Do this here as mempool requires genesis block to be loaded
3348  ResubmitWalletTransactions(/*relay=*/false, /*force=*/true);
3349 
3350  // Update wallet transactions with current mempool transactions.
3351  WITH_LOCK(cs_wallet, chain().requestMempoolTransactions(*this));
3352 }
3353 
3354 bool CWallet::BackupWallet(const std::string& strDest) const
3355 {
3356  return GetDatabase().Backup(strDest);
3357 }
3358 
3360 {
3361  nTime = GetTime();
3362  fInternal = false;
3363  m_pre_split = false;
3364 }
3365 
3366 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
3367 {
3368  nTime = GetTime();
3369  vchPubKey = vchPubKeyIn;
3370  fInternal = internalIn;
3371  m_pre_split = false;
3372 }
3373 
3375 {
3377  if (auto* conf = wtx.state<TxStateConfirmed>()) {
3378  assert(conf->confirmed_block_height >= 0);
3379  return GetLastBlockHeight() - conf->confirmed_block_height + 1;
3380  } else if (auto* conf = wtx.state<TxStateConflicted>()) {
3381  assert(conf->conflicting_block_height >= 0);
3382  return -1 * (GetLastBlockHeight() - conf->conflicting_block_height + 1);
3383  } else {
3384  return 0;
3385  }
3386 }
3387 
3389 {
3391 
3392  if (!wtx.IsCoinBase()) {
3393  return 0;
3394  }
3395  int chain_depth = GetTxDepthInMainChain(wtx);
3396  assert(chain_depth >= 0); // coinbase tx should not be conflicted
3397  return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
3398 }
3399 
3401 {
3403 
3404  // note GetBlocksToMaturity is 0 for non-coinbase tx
3405  return GetTxBlocksToMaturity(wtx) > 0;
3406 }
3407 
3409 {
3410  return HasEncryptionKeys();
3411 }
3412 
3413 bool CWallet::IsLocked() const
3414 {
3415  if (!IsCrypted()) {
3416  return false;
3417  }
3418  LOCK(cs_wallet);
3419  return vMasterKey.empty();
3420 }
3421 
3423 {
3424  if (!IsCrypted())
3425  return false;
3426 
3427  {
3429  if (!vMasterKey.empty()) {
3430  memory_cleanse(vMasterKey.data(), vMasterKey.size() * sizeof(decltype(vMasterKey)::value_type));
3431  vMasterKey.clear();
3432  }
3433  }
3434 
3435  NotifyStatusChanged(this);
3436  return true;
3437 }
3438 
3439 bool CWallet::Unlock(const CKeyingMaterial& vMasterKeyIn)
3440 {
3441  {
3442  LOCK(cs_wallet);
3443  for (const auto& spk_man_pair : m_spk_managers) {
3444  if (!spk_man_pair.second->CheckDecryptionKey(vMasterKeyIn)) {
3445  return false;
3446  }
3447  }
3448  vMasterKey = vMasterKeyIn;
3449  }
3450  NotifyStatusChanged(this);
3451  return true;
3452 }
3453 
3454 std::set<ScriptPubKeyMan*> CWallet::GetActiveScriptPubKeyMans() const
3455 {
3456  std::set<ScriptPubKeyMan*> spk_mans;
3457  for (bool internal : {false, true}) {
3458  for (OutputType t : OUTPUT_TYPES) {
3459  auto spk_man = GetScriptPubKeyMan(t, internal);
3460  if (spk_man) {
3461  spk_mans.insert(spk_man);
3462  }
3463  }
3464  }
3465  return spk_mans;
3466 }
3467 
3468 std::set<ScriptPubKeyMan*> CWallet::GetAllScriptPubKeyMans() const
3469 {
3470  std::set<ScriptPubKeyMan*> spk_mans;
3471  for (const auto& spk_man_pair : m_spk_managers) {
3472  spk_mans.insert(spk_man_pair.second.get());
3473  }
3474  return spk_mans;
3475 }
3476 
3477 ScriptPubKeyMan* CWallet::GetScriptPubKeyMan(const OutputType& type, bool internal) const
3478 {
3479  const std::map<OutputType, ScriptPubKeyMan*>& spk_managers = internal ? m_internal_spk_managers : m_external_spk_managers;
3480  std::map<OutputType, ScriptPubKeyMan*>::const_iterator it = spk_managers.find(type);
3481  if (it == spk_managers.end()) {
3482  return nullptr;
3483  }
3484  return it->second;
3485 }
3486 
3487 std::set<ScriptPubKeyMan*> CWallet::GetScriptPubKeyMans(const CScript& script) const
3488 {
3489  std::set<ScriptPubKeyMan*> spk_mans;
3490 
3491  // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3492  const auto& it = m_cached_spks.find(script);
3493  if (it != m_cached_spks.end()) {
3494  spk_mans.insert(it->second.begin(), it->second.end());
3495  }
3496  SignatureData sigdata;
3497  Assume(std::all_of(spk_mans.begin(), spk_mans.end(), [&script, &sigdata](ScriptPubKeyMan* spkm) { return spkm->CanProvide(script, sigdata); }));
3498 
3499  // Legacy wallet
3500  if (IsLegacy() && GetLegacyScriptPubKeyMan()->CanProvide(script, sigdata)) spk_mans.insert(GetLegacyScriptPubKeyMan());
3501 
3502  return spk_mans;
3503 }
3504 
3506 {
3507  if (m_spk_managers.count(id) > 0) {
3508  return m_spk_managers.at(id).get();
3509  }
3510  return nullptr;
3511 }
3512 
3513 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script) const
3514 {
3515  SignatureData sigdata;
3516  return GetSolvingProvider(script, sigdata);
3517 }
3518 
3519 std::unique_ptr<SigningProvider> CWallet::GetSolvingProvider(const CScript& script, SignatureData& sigdata) const
3520 {
3521  // Search the cache for relevant SPKMs instead of iterating m_spk_managers
3522  const auto& it = m_cached_spks.find(script);
3523  if (it != m_cached_spks.end()) {
3524  // All spkms for a given script must already be able to make a SigningProvider for the script, so just return the first one.
3525  Assume(it->second.at(0)->CanProvide(script, sigdata));
3526  return it->second.at(0)->GetSolvingProvider(script);
3527  }
3528 
3529  // Legacy wallet
3530  if (IsLegacy() && GetLegacyScriptPubKeyMan()->CanProvide(script, sigdata)) return GetLegacyScriptPubKeyMan()->GetSolvingProvider(script);
3531 
3532  return nullptr;
3533 }
3534 
3535 std::vector<WalletDescriptor> CWallet::GetWalletDescriptors(const CScript& script) const
3536 {
3537  std::vector<WalletDescriptor> descs;
3538  for (const auto spk_man: GetScriptPubKeyMans(script)) {
3539  if (const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man)) {
3540  LOCK(desc_spk_man->cs_desc_man);
3541  descs.push_back(desc_spk_man->GetWalletDescriptor());
3542  }
3543  }
3544  return descs;
3545 }
3546 
3548 {
3550  return nullptr;
3551  }
3552  // Legacy wallets only have one ScriptPubKeyMan which is a LegacyScriptPubKeyMan.
3553  // Everything in m_internal_spk_managers and m_external_spk_managers point to the same legacyScriptPubKeyMan.
3555  if (it == m_internal_spk_managers.end()) return nullptr;
3556  return dynamic_cast<LegacyScriptPubKeyMan*>(it->second);
3557 }
3558 
3560 {
3562  return GetLegacyScriptPubKeyMan();
3563 }
3564 
3565 void CWallet::AddScriptPubKeyMan(const uint256& id, std::unique_ptr<ScriptPubKeyMan> spkm_man)
3566 {
3567  // Add spkm_man to m_spk_managers before calling any method
3568  // that might access it.
3569  const auto& spkm = m_spk_managers[id] = std::move(spkm_man);
3570 
3571  // Update birth time if needed
3572  MaybeUpdateBirthTime(spkm->GetTimeFirstKey());
3573 }
3574 
3576 {
3578  return;
3579  }
3580 
3581  auto spk_manager = std::unique_ptr<ScriptPubKeyMan>(new LegacyScriptPubKeyMan(*this, m_keypool_size));
3582  for (const auto& type : LEGACY_OUTPUT_TYPES) {
3583  m_internal_spk_managers[type] = spk_manager.get();
3584  m_external_spk_managers[type] = spk_manager.get();
3585  }
3586  uint256 id = spk_manager->GetID();
3587  AddScriptPubKeyMan(id, std::move(spk_manager));
3588 }
3589 
3590 bool CWallet::WithEncryptionKey(std::function<bool (const CKeyingMaterial&)> cb) const
3591 {
3592  LOCK(cs_wallet);
3593  return cb(vMasterKey);
3594 }
3595 
3597 {
3598  return !mapMasterKeys.empty();
3599 }
3600 
3602 {
3603  for (const auto& spk_man : GetActiveScriptPubKeyMans()) {
3604  spk_man->NotifyWatchonlyChanged.connect(NotifyWatchonlyChanged);
3605  spk_man->NotifyCanGetAddressesChanged.connect(NotifyCanGetAddressesChanged);
3606  spk_man->NotifyFirstKeyTimeChanged.connect(std::bind(&CWallet::MaybeUpdateBirthTime, this, std::placeholders::_2));
3607  }
3608 }
3609 
3611 {
3612  DescriptorScriptPubKeyMan* spk_manager;
3614  spk_manager = new ExternalSignerScriptPubKeyMan(*this, desc, m_keypool_size);
3615  } else {
3616  spk_manager = new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size);
3617  }
3618  AddScriptPubKeyMan(id, std::unique_ptr<ScriptPubKeyMan>(spk_manager));
3619  return *spk_manager;
3620 }
3621 
3623 {
3625 
3626  // Create single batch txn
3627  WalletBatch batch(GetDatabase());
3628  if (!batch.TxnBegin()) throw std::runtime_error("Error: cannot create db transaction for descriptors setup");
3629 
3630  for (bool internal : {false, true}) {
3631  for (OutputType t : OUTPUT_TYPES) {
3632  auto spk_manager = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, m_keypool_size));
3633  if (IsCrypted()) {
3634  if (IsLocked()) {
3635  throw std::runtime_error(std::string(__func__) + ": Wallet is locked, cannot setup new descriptors");
3636  }
3637  if (!spk_manager->CheckDecryptionKey(vMasterKey) && !spk_manager->Encrypt(vMasterKey, &batch)) {
3638  throw std::runtime_error(std::string(__func__) + ": Could not encrypt new descriptors");
3639  }
3640  }
3641  spk_manager->SetupDescriptorGeneration(batch, master_key, t, internal);
3642  uint256 id = spk_manager->GetID();
3643  AddScriptPubKeyMan(id, std::move(spk_manager));
3644  AddActiveScriptPubKeyManWithDb(batch, id, t, internal);
3645  }
3646  }
3647 
3648  // Ensure information is committed to disk
3649  if (!batch.TxnCommit()) throw std::runtime_error("Error: cannot commit db transaction for descriptors setup");
3650 }
3651 
3653 {
3655 
3657  // Make a seed
3658  CKey seed_key = GenerateRandomKey();
3659  CPubKey seed = seed_key.GetPubKey();
3660  assert(seed_key.VerifyPubKey(seed));
3661 
3662  // Get the extended key
3663  CExtKey master_key;
3664  master_key.SetSeed(seed_key);
3665 
3666  SetupDescriptorScriptPubKeyMans(master_key);
3667  } else {
3669 
3670  // TODO: add account parameter
3671  int account = 0;
3672  UniValue signer_res = signer.GetDescriptors(account);
3673 
3674  if (!signer_res.isObject()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3675 
3676  WalletBatch batch(GetDatabase());
3677  if (!batch.TxnBegin()) throw std::runtime_error("Error: cannot create db transaction for descriptors import");
3678 
3679  for (bool internal : {false, true}) {
3680  const UniValue& descriptor_vals = signer_res.find_value(internal ? "internal" : "receive");
3681  if (!descriptor_vals.isArray()) throw std::runtime_error(std::string(__func__) + ": Unexpected result");
3682  for (const UniValue& desc_val : descriptor_vals.get_array().getValues()) {
3683  const std::string& desc_str = desc_val.getValStr();
3684  FlatSigningProvider keys;
3685  std::string desc_error;
3686  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, desc_error, false);
3687  if (desc == nullptr) {
3688  throw std::runtime_error(std::string(__func__) + ": Invalid descriptor \"" + desc_str + "\" (" + desc_error + ")");
3689  }
3690  if (!desc->GetOutputType()) {
3691  continue;
3692  }
3693  OutputType t = *desc->GetOutputType();
3694  auto spk_manager = std::unique_ptr<ExternalSignerScriptPubKeyMan>(new ExternalSignerScriptPubKeyMan(*this, m_keypool_size));
3695  spk_manager->SetupDescriptor(batch, std::move(desc));
3696  uint256 id = spk_manager->GetID();
3697  AddScriptPubKeyMan(id, std::move(spk_manager));
3698  AddActiveScriptPubKeyManWithDb(batch, id, t, internal);
3699  }
3700  }
3701 
3702  // Ensure imported descriptors are committed to disk
3703  if (!batch.TxnCommit()) throw std::runtime_error("Error: cannot commit db transaction for descriptors import");
3704  }
3705 }
3706 
3708 {
3709  WalletBatch batch(GetDatabase());
3710  return AddActiveScriptPubKeyManWithDb(batch, id, type, internal);
3711 }
3712 
3714 {
3715  if (!batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(type), id, internal)) {
3716  throw std::runtime_error(std::string(__func__) + ": writing active ScriptPubKeyMan id failed");
3717  }
3718  LoadActiveScriptPubKeyMan(id, type, internal);
3719 }
3720 
3722 {
3723  // Activating ScriptPubKeyManager for a given output and change type is incompatible with legacy wallets.
3724  // Legacy wallets have only one ScriptPubKeyManager and it's active for all output and change types.
3726 
3727  WalletLogPrintf("Setting spkMan to active: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3728  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3729  auto& spk_mans_other = internal ? m_external_spk_managers : m_internal_spk_managers;
3730  auto spk_man = m_spk_managers.at(id).get();
3731  spk_mans[type] = spk_man;
3732 
3733  const auto it = spk_mans_other.find(type);
3734  if (it != spk_mans_other.end() && it->second == spk_man) {
3735  spk_mans_other.erase(type);
3736  }
3737 
3739 }
3740 
3742 {
3743  auto spk_man = GetScriptPubKeyMan(type, internal);
3744  if (spk_man != nullptr && spk_man->GetID() == id) {
3745  WalletLogPrintf("Deactivate spkMan: id = %s, type = %s, internal = %s\n", id.ToString(), FormatOutputType(type), internal ? "true" : "false");
3746  WalletBatch batch(GetDatabase());
3747  if (!batch.EraseActiveScriptPubKeyMan(static_cast<uint8_t>(type), internal)) {
3748  throw std::runtime_error(std::string(__func__) + ": erasing active ScriptPubKeyMan id failed");
3749  }
3750 
3751  auto& spk_mans = internal ? m_internal_spk_managers : m_external_spk_managers;
3752  spk_mans.erase(type);
3753  }
3754 
3756 }
3757 
3758 bool CWallet::IsLegacy() const
3759 {
3760  if (m_internal_spk_managers.count(OutputType::LEGACY) == 0) {
3761  return false;
3762  }
3763  auto spk_man = dynamic_cast<LegacyScriptPubKeyMan*>(m_internal_spk_managers.at(OutputType::LEGACY));
3764  return spk_man != nullptr;
3765 }
3766 
3768 {
3769  for (auto& spk_man_pair : m_spk_managers) {
3770  // Try to downcast to DescriptorScriptPubKeyMan then check if the descriptors match
3771  DescriptorScriptPubKeyMan* spk_manager = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man_pair.second.get());
3772  if (spk_manager != nullptr && spk_manager->HasWalletDescriptor(desc)) {
3773  return spk_manager;
3774  }
3775  }
3776 
3777  return nullptr;
3778 }
3779 
3780 std::optional<bool> CWallet::IsInternalScriptPubKeyMan(ScriptPubKeyMan* spk_man) const
3781 {
3782  // Legacy script pubkey man can't be either external or internal
3783  if (IsLegacy()) {
3784  return std::nullopt;
3785  }
3786 
3787  // only active ScriptPubKeyMan can be internal
3788  if (!GetActiveScriptPubKeyMans().count(spk_man)) {
3789  return std::nullopt;
3790  }
3791 
3792  const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
3793  if (!desc_spk_man) {
3794  throw std::runtime_error(std::string(__func__) + ": unexpected ScriptPubKeyMan type.");
3795  }
3796 
3797  LOCK(desc_spk_man->cs_desc_man);
3798  const auto& type = desc_spk_man->GetWalletDescriptor().descriptor->GetOutputType();
3799  assert(type.has_value());
3800 
3801  return GetScriptPubKeyMan(*type, /* internal= */ true) == desc_spk_man;
3802 }
3803 
3804 ScriptPubKeyMan* CWallet::AddWalletDescriptor(WalletDescriptor& desc, const FlatSigningProvider& signing_provider, const std::string& label, bool internal)
3805 {
3807 
3809  WalletLogPrintf("Cannot add WalletDescriptor to a non-descriptor wallet\n");
3810  return nullptr;
3811  }
3812 
3813  auto spk_man = GetDescriptorScriptPubKeyMan(desc);
3814  if (spk_man) {
3815  WalletLogPrintf("Update existing descriptor: %s\n", desc.descriptor->ToString());
3816  spk_man->UpdateWalletDescriptor(desc);
3817  } else {
3818  auto new_spk_man = std::unique_ptr<DescriptorScriptPubKeyMan>(new DescriptorScriptPubKeyMan(*this, desc, m_keypool_size));
3819  spk_man = new_spk_man.get();
3820 
3821  // Save the descriptor to memory
3822  uint256 id = new_spk_man->GetID();
3823  AddScriptPubKeyMan(id, std::move(new_spk_man));
3824  }
3825 
3826  // Add the private keys to the descriptor
3827  for (const auto& entry : signing_provider.keys) {
3828  const CKey& key = entry.second;
3829  spk_man->AddDescriptorKey(key, key.GetPubKey());
3830  }
3831 
3832  // Top up key pool, the manager will generate new scriptPubKeys internally
3833  if (!spk_man->TopUp()) {
3834  WalletLogPrintf("Could not top up scriptPubKeys\n");
3835  return nullptr;
3836  }
3837 
3838  // Apply the label if necessary
3839  // Note: we disable labels for ranged descriptors
3840  if (!desc.descriptor->IsRange()) {
3841  auto script_pub_keys = spk_man->GetScriptPubKeys();
3842  if (script_pub_keys.empty()) {
3843  WalletLogPrintf("Could not generate scriptPubKeys (cache is empty)\n");
3844  return nullptr;
3845  }
3846 
3847  if (!internal) {
3848  for (const auto& script : script_pub_keys) {
3849  CTxDestination dest;
3850  if (ExtractDestination(script, dest)) {
3852  }
3853  }
3854  }
3855  }
3856 
3857  // Save the descriptor to DB
3858  spk_man->WriteDescriptor();
3859 
3860  return spk_man;
3861 }
3862 
3864 {
3866 
3867  WalletLogPrintf("Migrating wallet storage database from BerkeleyDB to SQLite.\n");
3868 
3869  if (m_database->Format() == "sqlite") {
3870  error = _("Error: This wallet already uses SQLite");
3871  return false;
3872  }
3873 
3874  // Get all of the records for DB type migration
3875  std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();
3876  std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();
3877  std::vector<std::pair<SerializeData, SerializeData>> records;
3878  if (!cursor) {
3879  error = _("Error: Unable to begin reading all records in the database");
3880  return false;
3881  }
3883  while (true) {
3884  DataStream ss_key{};
3885  DataStream ss_value{};
3886  status = cursor->Next(ss_key, ss_value);
3887  if (status != DatabaseCursor::Status::MORE) {
3888  break;
3889  }
3890  SerializeData key(ss_key.begin(), ss_key.end());
3891  SerializeData value(ss_value.begin(), ss_value.end());
3892  records.emplace_back(key, value);
3893  }
3894  cursor.reset();
3895  batch.reset();
3896  if (status != DatabaseCursor::Status::DONE) {
3897  error = _("Error: Unable to read all records in the database");
3898  return false;
3899  }
3900 
3901  // Close this database and delete the file
3902  fs::path db_path = fs::PathFromString(m_database->Filename());
3903  m_database->Close();
3904  fs::remove(db_path);
3905 
3906  // Generate the path for the location of the migrated wallet
3907  // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.
3909 
3910  // Make new DB
3911  DatabaseOptions opts;
3912  opts.require_create = true;
3914  DatabaseStatus db_status;
3915  std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);
3916  assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.
3917  m_database.reset();
3918  m_database = std::move(new_db);
3919 
3920  // Write existing records into the new DB
3921  batch = m_database->MakeBatch();
3922  bool began = batch->TxnBegin();
3923  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.
3924  for (const auto& [key, value] : records) {
3925  if (!batch->Write(Span{key}, Span{value})) {
3926  batch->TxnAbort();
3927  m_database->Close();
3928  fs::remove(m_database->Filename());
3929  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.
3930  }
3931  }
3932  bool committed = batch->TxnCommit();
3933  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.
3934  return true;
3935 }
3936 
3937 std::optional<MigrationData> CWallet::GetDescriptorsForLegacy(bilingual_str& error) const
3938 {
3940 
3942  if (!Assume(legacy_spkm)) {
3943  // This shouldn't happen
3944  error = Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"));
3945  return std::nullopt;
3946  }
3947 
3948  std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();
3949  if (res == std::nullopt) {
3950  error = _("Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.");
3951  return std::nullopt;
3952  }
3953  return res;
3954 }
3955 
3957 {
3959 
3961  if (!Assume(legacy_spkm)) {
3962  // This shouldn't happen
3963  error = Untranslated(STR_INTERNAL_BUG("Error: Legacy wallet data missing"));
3964  return false;
3965  }
3966 
3967  // Get all invalid or non-watched scripts that will not be migrated
3968  std::set<CTxDestination> not_migrated_dests;
3969  for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {
3970  CTxDestination dest;
3971  if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);
3972  }
3973 
3974  Assume(!m_cached_spks.empty());
3975 
3976  for (auto& desc_spkm : data.desc_spkms) {
3977  if (m_spk_managers.count(desc_spkm->GetID()) > 0) {
3978  error = _("Error: Duplicate descriptors created during migration. Your wallet may be corrupted.");
3979  return false;
3980  }
3981  uint256 id = desc_spkm->GetID();
3982  AddScriptPubKeyMan(id, std::move(desc_spkm));
3983  }
3984 
3985  // Remove the LegacyScriptPubKeyMan from disk
3986  if (!legacy_spkm->DeleteRecords()) {
3987  return false;
3988  }
3989 
3990  // Remove the LegacyScriptPubKeyMan from memory
3991  m_spk_managers.erase(legacy_spkm->GetID());
3992  m_external_spk_managers.clear();
3993  m_internal_spk_managers.clear();
3994 
3995  // Setup new descriptors
3996  SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
3998  // Use the existing master key if we have it
3999  if (data.master_key.key.IsValid()) {
4001  } else {
4002  // Setup with a new seed if we don't.
4004  }
4005  }
4006 
4007  // Get best block locator so that we can copy it to the watchonly and solvables
4008  CBlockLocator best_block_locator;
4009  if (!WalletBatch(GetDatabase()).ReadBestBlock(best_block_locator)) {
4010  error = _("Error: Unable to read wallet's best block locator record");
4011  return false;
4012  }
4013 
4014  // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.
4015  // We need to go through these in the tx insertion order so that lookups to spends works.
4016  std::vector<uint256> txids_to_delete;
4017  std::unique_ptr<WalletBatch> watchonly_batch;
4018  if (data.watchonly_wallet) {
4019  watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());
4020  // Copy the next tx order pos to the watchonly wallet
4021  LOCK(data.watchonly_wallet->cs_wallet);
4022  data.watchonly_wallet->nOrderPosNext = nOrderPosNext;
4023  watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);
4024  // Write the best block locator to avoid rescanning on reload
4025  if (!watchonly_batch->WriteBestBlock(best_block_locator)) {
4026  error = _("Error: Unable to write watchonly wallet best block locator record");
4027  return false;
4028  }
4029  }
4030  if (data.solvable_wallet) {
4031  // Write the best block locator to avoid rescanning on reload
4032  if (!WalletBatch(data.solvable_wallet->GetDatabase()).WriteBestBlock(best_block_locator)) {
4033  error = _("Error: Unable to write solvable wallet best block locator record");
4034  return false;
4035  }
4036  }
4037  for (const auto& [_pos, wtx] : wtxOrdered) {
4038  // Check it is the watchonly wallet's
4039  // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for
4040  bool is_mine = IsMine(*wtx->tx) || IsFromMe(*wtx->tx);
4041  if (data.watchonly_wallet) {
4042  LOCK(data.watchonly_wallet->cs_wallet);
4043  if (data.watchonly_wallet->IsMine(*wtx->tx) || data.watchonly_wallet->IsFromMe(*wtx->tx)) {
4044  // Add to watchonly wallet
4045  const uint256& hash = wtx->GetHash();
4046  const CWalletTx& to_copy_wtx = *wtx;
4047  if (!data.watchonly_wallet->LoadToWallet(hash, [&](CWalletTx& ins_wtx, bool new_tx) EXCLUSIVE_LOCKS_REQUIRED(data.watchonly_wallet->cs_wallet) {
4048  if (!new_tx) return false;
4049  ins_wtx.SetTx(to_copy_wtx.tx);
4050  ins_wtx.CopyFrom(to_copy_wtx);
4051  return true;
4052  })) {
4053  error = strprintf(_("Error: Could not add watchonly tx %s to watchonly wallet"), wtx->GetHash().GetHex());
4054  return false;
4055  }
4056  watchonly_batch->WriteTx(data.watchonly_wallet->mapWallet.at(hash));
4057  // Mark as to remove from the migrated wallet only if it does not also belong to it
4058  if (!is_mine) {
4059  txids_to_delete.push_back(hash);
4060  }
4061  continue;
4062  }
4063  }
4064  if (!is_mine) {
4065  // Both not ours and not in the watchonly wallet
4066  error = strprintf(_("Error: Transaction %s in wallet cannot be identified to belong to migrated wallets"), wtx->GetHash().GetHex());
4067  return false;
4068  }
4069  }
4070  watchonly_batch.reset(); // Flush
4071  // Do the removes
4072  if (txids_to_delete.size() > 0) {
4073  if (auto res = RemoveTxs(txids_to_delete); !res) {
4074  error = _("Error: Could not delete watchonly transactions. ") + util::ErrorString(res);
4075  return false;
4076  }
4077  }
4078 
4079  // Pair external wallets with their corresponding db handler
4080  std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;
4081  for (const auto& ext_wallet : {data.watchonly_wallet, data.solvable_wallet}) {
4082  if (!ext_wallet) continue;
4083 
4084  std::unique_ptr<WalletBatch> batch = std::make_unique<WalletBatch>(ext_wallet->GetDatabase());
4085  if (!batch->TxnBegin()) {
4086  error = strprintf(_("Error: database transaction cannot be executed for wallet %s"), ext_wallet->GetName());
4087  return false;
4088  }
4089  wallets_vec.emplace_back(ext_wallet, std::move(batch));
4090  }
4091 
4092  // Write address book entry to disk
4093  auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {
4094  auto address{EncodeDestination(dest)};
4095  if (entry.purpose) batch.WritePurpose(address, PurposeToString(*entry.purpose));
4096  if (entry.label) batch.WriteName(address, *entry.label);
4097  for (const auto& [id, request] : entry.receive_requests) {
4098  batch.WriteAddressReceiveRequest(dest, id, request);
4099  }
4100  if (entry.previously_spent) batch.WriteAddressPreviouslySpent(dest, true);
4101  };
4102 
4103  // Check the address book data in the same way we did for transactions
4104  std::vector<CTxDestination> dests_to_delete;
4105  for (const auto& [dest, record] : m_address_book) {
4106  // Ensure "receive" entries that are no longer part of the original wallet are transferred to another wallet
4107  // Entries for everything else ("send") will be cloned to all wallets.
4108  bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);
4109  bool copied = false;
4110  for (auto& [wallet, batch] : wallets_vec) {
4111  LOCK(wallet->cs_wallet);
4112  if (require_transfer && !wallet->IsMine(dest)) continue;
4113 
4114  // Copy the entire address book entry
4115  wallet->m_address_book[dest] = record;
4116  func_store_addr(*batch, dest, record);
4117 
4118  copied = true;
4119  // Only delete 'receive' records that are no longer part of the original wallet
4120  if (require_transfer) {
4121  dests_to_delete.push_back(dest);
4122  break;
4123  }
4124  }
4125 
4126  // Fail immediately if we ever found an entry that was ours and cannot be transferred
4127  // to any of the created wallets (watch-only, solvable).
4128  // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.
4129  if (require_transfer && !copied) {
4130 
4131  // Skip invalid/non-watched scripts that will not be migrated
4132  if (not_migrated_dests.count(dest) > 0) {
4133  dests_to_delete.push_back(dest);
4134  continue;
4135  }
4136 
4137  error = _("Error: Address book data in wallet cannot be identified to belong to migrated wallets");
4138  return false;
4139  }
4140  }
4141 
4142  // Persist external wallets address book entries
4143  for (auto& [wallet, batch] : wallets_vec) {
4144  if (!batch->TxnCommit()) {
4145  error = strprintf(_("Error: address book copy failed for wallet %s"), wallet->GetName());
4146  return false;
4147  }
4148  }
4149 
4150  // Remove the things to delete in this wallet
4151  WalletBatch local_wallet_batch(GetDatabase());
4152  local_wallet_batch.TxnBegin();
4153  if (dests_to_delete.size() > 0) {
4154  for (const auto& dest : dests_to_delete) {
4155  if (!DelAddressBookWithDB(local_wallet_batch, dest)) {
4156  error = _("Error: Unable to remove watchonly address book data");
4157  return false;
4158  }
4159  }
4160  }
4161  local_wallet_batch.TxnCommit();
4162 
4163  // Connect the SPKM signals
4166 
4167  WalletLogPrintf("Wallet migration complete.\n");
4168 
4169  return true;
4170 }
4171 
4173 {
4175 }
4176 
4178 {
4179  AssertLockHeld(wallet.cs_wallet);
4180 
4181  // Get all of the descriptors from the legacy wallet
4182  std::optional<MigrationData> data = wallet.GetDescriptorsForLegacy(error);
4183  if (data == std::nullopt) return false;
4184 
4185  // Create the watchonly and solvable wallets if necessary
4186  if (data->watch_descs.size() > 0 || data->solvable_descs.size() > 0) {
4187  DatabaseOptions options;
4188  options.require_existing = false;
4189  options.require_create = true;
4191 
4192  WalletContext empty_context;
4193  empty_context.args = context.args;
4194 
4195  // Make the wallets
4197  if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
4199  }
4200  if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
4202  }
4203  if (data->watch_descs.size() > 0) {
4204  wallet.WalletLogPrintf("Making a new watchonly wallet containing the watched scripts\n");
4205 
4206  DatabaseStatus status;
4207  std::vector<bilingual_str> warnings;
4208  std::string wallet_name = wallet.GetName() + "_watchonly";
4209  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4210  if (!database) {
4211  error = strprintf(_("Wallet file creation failed: %s"), error);
4212  return false;
4213  }
4214 
4215  data->watchonly_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4216  if (!data->watchonly_wallet) {
4217  error = _("Error: Failed to create new watchonly wallet");
4218  return false;
4219  }
4220  res.watchonly_wallet = data->watchonly_wallet;
4221  LOCK(data->watchonly_wallet->cs_wallet);
4222 
4223  // Parse the descriptors and add them to the new wallet
4224  for (const auto& [desc_str, creation_time] : data->watch_descs) {
4225  // Parse the descriptor
4226  FlatSigningProvider keys;
4227  std::string parse_err;
4228  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, parse_err, /* require_checksum */ true);
4229  assert(desc); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor
4230  assert(!desc->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4231 
4232  // Add to the wallet
4233  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
4234  data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, "", false);
4235  }
4236 
4237  // Add the wallet to settings
4238  UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4239  }
4240  if (data->solvable_descs.size() > 0) {
4241  wallet.WalletLogPrintf("Making a new watchonly wallet containing the unwatched solvable scripts\n");
4242 
4243  DatabaseStatus status;
4244  std::vector<bilingual_str> warnings;
4245  std::string wallet_name = wallet.GetName() + "_solvables";
4246  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4247  if (!database) {
4248  error = strprintf(_("Wallet file creation failed: %s"), error);
4249  return false;
4250  }
4251 
4252  data->solvable_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4253  if (!data->solvable_wallet) {
4254  error = _("Error: Failed to create new watchonly wallet");
4255  return false;
4256  }
4257  res.solvables_wallet = data->solvable_wallet;
4258  LOCK(data->solvable_wallet->cs_wallet);
4259 
4260  // Parse the descriptors and add them to the new wallet
4261  for (const auto& [desc_str, creation_time] : data->solvable_descs) {
4262  // Parse the descriptor
4263  FlatSigningProvider keys;
4264  std::string parse_err;
4265  std::unique_ptr<Descriptor> desc = Parse(desc_str, keys, parse_err, /* require_checksum */ true);
4266  assert(desc); // It shouldn't be possible to have the LegacyScriptPubKeyMan make an invalid descriptor
4267  assert(!desc->IsRange()); // It shouldn't be possible to have LegacyScriptPubKeyMan make a ranged watchonly descriptor
4268 
4269  // Add to the wallet
4270  WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0);
4271  data->solvable_wallet->AddWalletDescriptor(w_desc, keys, "", false);
4272  }
4273 
4274  // Add the wallet to settings
4275  UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/true, warnings);
4276  }
4277  }
4278 
4279  // Add the descriptors to wallet, remove LegacyScriptPubKeyMan, and cleanup txs and address book data
4280  if (!wallet.ApplyMigrationData(*data, error)) {
4281  return false;
4282  }
4283  return true;
4284 }
4285 
4286 util::Result<MigrationResult> MigrateLegacyToDescriptor(const std::string& wallet_name, const SecureString& passphrase, WalletContext& context)
4287 {
4288  MigrationResult res;
4290  std::vector<bilingual_str> warnings;
4291 
4292  // If the wallet is still loaded, unload it so that nothing else tries to use it while we're changing it
4293  bool was_loaded = false;
4294  if (auto wallet = GetWallet(context, wallet_name)) {
4295  if (!RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt, warnings)) {
4296  return util::Error{_("Unable to unload the wallet before migrating")};
4297  }
4298  UnloadWallet(std::move(wallet));
4299  was_loaded = true;
4300  }
4301 
4302  // Load the wallet but only in the context of this function.
4303  // No signals should be connected nor should anything else be aware of this wallet
4304  WalletContext empty_context;
4305  empty_context.args = context.args;
4306  DatabaseOptions options;
4307  options.require_existing = true;
4308  DatabaseStatus status;
4309  std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);
4310  if (!database) {
4311  return util::Error{Untranslated("Wallet file verification failed.") + Untranslated(" ") + error};
4312  }
4313 
4314  // Make the local wallet
4315  std::shared_ptr<CWallet> local_wallet = CWallet::Create(empty_context, wallet_name, std::move(database), options.create_flags, error, warnings);
4316  if (!local_wallet) {
4317  return util::Error{Untranslated("Wallet loading failed.") + Untranslated(" ") + error};
4318  }
4319 
4320  // Helper to reload as normal for some of our exit scenarios
4321  const auto& reload_wallet = [&](std::shared_ptr<CWallet>& to_reload) {
4322  assert(to_reload.use_count() == 1);
4323  std::string name = to_reload->GetName();
4324  to_reload.reset();
4325  to_reload = LoadWallet(context, name, /*load_on_start=*/std::nullopt, options, status, error, warnings);
4326  return to_reload != nullptr;
4327  };
4328 
4329  // Before anything else, check if there is something to migrate.
4330  if (local_wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
4331  if (was_loaded) {
4332  reload_wallet(local_wallet);
4333  }
4334  return util::Error{_("Error: This wallet is already a descriptor wallet")};
4335  }
4336 
4337  // Make a backup of the DB
4338  fs::path this_wallet_dir = fs::absolute(fs::PathFromString(local_wallet->GetDatabase().Filename())).parent_path();
4339  fs::path backup_filename = fs::PathFromString(strprintf("%s-%d.legacy.bak", wallet_name, GetTime()));
4340  fs::path backup_path = this_wallet_dir / backup_filename;
4341  if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {
4342  if (was_loaded) {
4343  reload_wallet(local_wallet);
4344  }
4345  return util::Error{_("Error: Unable to make a backup of your wallet")};
4346  }
4347  res.backup_path = backup_path;
4348 
4349  bool success = false;
4350 
4351  // Unlock the wallet if needed
4352  if (local_wallet->IsLocked() && !local_wallet->Unlock(passphrase)) {
4353  if (was_loaded) {
4354  reload_wallet(local_wallet);
4355  }
4356  if (passphrase.find('\0') == std::string::npos) {
4357  return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase was not provided or was incorrect.")};
4358  } else {
4359  return util::Error{Untranslated("Error: Wallet decryption failed, the wallet passphrase entered was incorrect. "
4360  "The passphrase contains a null character (ie - a zero byte). "
4361  "If this passphrase was set with a version of this software prior to 25.0, "
4362  "please try again with only the characters up to — but not including — "
4363  "the first null character.")};
4364  }
4365  }
4366 
4367  {
4368  LOCK(local_wallet->cs_wallet);
4369  // First change to using SQLite
4370  if (!local_wallet->MigrateToSQLite(error)) return util::Error{error};
4371 
4372  // Do the migration of keys and scripts for non-blank wallets, and cleanup if it fails
4373  success = local_wallet->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
4374  if (!success) {
4375  success = DoMigration(*local_wallet, context, error, res);
4376  } else {
4377  // Make sure that descriptors flag is actually set
4378  local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);
4379  }
4380  }
4381 
4382  // In case of reloading failure, we need to remember the wallet dirs to remove
4383  // Set is used as it may be populated with the same wallet directory paths multiple times,
4384  // both before and after reloading. This ensures the set is complete even if one of the wallets
4385  // fails to reload.
4386  std::set<fs::path> wallet_dirs;
4387  if (success) {
4388  // Migration successful, unload all wallets locally, then reload them.
4389  // Reload the main wallet
4390  wallet_dirs.insert(fs::PathFromString(local_wallet->GetDatabase().Filename()).parent_path());
4391  success = reload_wallet(local_wallet);
4392  res.wallet = local_wallet;
4393  res.wallet_name = wallet_name;
4394  if (success && res.watchonly_wallet) {
4395  // Reload watchonly
4396  wallet_dirs.insert(fs::PathFromString(res.watchonly_wallet->GetDatabase().Filename()).parent_path());
4397  success = reload_wallet(res.watchonly_wallet);
4398  }
4399  if (success && res.solvables_wallet) {
4400  // Reload solvables
4401  wallet_dirs.insert(fs::PathFromString(res.solvables_wallet->GetDatabase().Filename()).parent_path());
4402  success = reload_wallet(res.solvables_wallet);
4403  }
4404  }
4405  if (!success) {
4406  // Migration failed, cleanup
4407  // Copy the backup to the actual wallet dir
4408  fs::path temp_backup_location = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);
4409  fs::copy_file(backup_path, temp_backup_location, fs::copy_options::none);
4410 
4411  // Make list of wallets to cleanup
4412  std::vector<std::shared_ptr<CWallet>> created_wallets;
4413  if (local_wallet) created_wallets.push_back(std::move(local_wallet));
4414  if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));
4415  if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));
4416 
4417  // Get the directories to remove after unloading
4418  for (std::shared_ptr<CWallet>& w : created_wallets) {
4419  wallet_dirs.emplace(fs::PathFromString(w->GetDatabase().Filename()).parent_path());
4420  }
4421 
4422  // Unload the wallets
4423  for (std::shared_ptr<CWallet>& w : created_wallets) {
4424  if (w->HaveChain()) {
4425  // Unloading for wallets that were loaded for normal use
4426  if (!RemoveWallet(context, w, /*load_on_start=*/false)) {
4427  error += _("\nUnable to cleanup failed migration");
4428  return util::Error{error};
4429  }
4430  UnloadWallet(std::move(w));
4431  } else {
4432  // Unloading for wallets in local context
4433  assert(w.use_count() == 1);
4434  w.reset();
4435  }
4436  }
4437 
4438  // Delete the wallet directories
4439  for (const fs::path& dir : wallet_dirs) {
4440  fs::remove_all(dir);
4441  }
4442 
4443  // Restore the backup
4444  DatabaseStatus status;
4445  std::vector<bilingual_str> warnings;
4446  if (!RestoreWallet(context, temp_backup_location, wallet_name, /*load_on_start=*/std::nullopt, status, error, warnings)) {
4447  error += _("\nUnable to restore backup of wallet.");
4448  return util::Error{error};
4449  }
4450 
4451  // Move the backup to the wallet dir
4452  fs::copy_file(temp_backup_location, backup_path, fs::copy_options::none);
4453  fs::remove(temp_backup_location);
4454 
4455  return util::Error{error};
4456  }
4457  return res;
4458 }
4459 
4460 void CWallet::CacheNewScriptPubKeys(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
4461 {
4462  for (const auto& script : spks) {
4463  m_cached_spks[script].push_back(spkm);
4464  }
4465 }
4466 
4467 void CWallet::TopUpCallback(const std::set<CScript>& spks, ScriptPubKeyMan* spkm)
4468 {
4469  // Update scriptPubKey cache
4470  CacheNewScriptPubKeys(spks, spkm);
4471 }
4472 } // namespace wallet
std::unique_ptr< WalletDatabase > MakeDatabase(const fs::path &path, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error)
Definition: walletdb.cpp:1350
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:633
void ReturnDestination()
Return reserved address.
Definition: wallet.cpp:2629
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:1402
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:273
bool UpgradeWallet(int version, bilingual_str &error)
Upgrade the wallet.
Definition: wallet.cpp:3311
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:53
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:185
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:174
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:311
void MaybeUpdateBirthTime(int64_t time)
Updates wallet birth time if &#39;time&#39; is below it.
Definition: wallet.cpp:1768
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:927
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:369
bool CanSupportFeature(enum WalletFeature wf) const override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we support the named feature
Definition: wallet.h:536
std::atomic< bool > fAbortRescan
Definition: wallet.h:307
State of transaction added to mempool.
Definition: transaction.h:41
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:2571
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:501
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:36
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:204
AssertLockHeld(pool.cs)
void MarkDirty()
make sure balances are recalculated
Definition: transaction.h:313
bool EraseAddressReceiveRequest(WalletBatch &batch, const CTxDestination &dest, const std::string &id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2884
bool EraseAddressData(const CTxDestination &dest)
Definition: walletdb.cpp:1309
const std::vector< UniValue > & getValues() const
bool CanGetAddresses(bool internal=false) const
Definition: wallet.cpp:1642
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:1715
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:3596
const T * state() const
Definition: transaction.h:330
#define LogPrint(category,...)
Definition: logging.h:264
assert(!tx.IsCoinBase())
isminetype IsMine(const CScript &script) const override
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:153
const CAddressBookData * FindAddressBookEntry(const CTxDestination &, bool allow_change=false) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3301
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:1971
int GetTxBlocksToMaturity(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3388
std::optional< int > last_scanned_height
Definition: wallet.h:627
CKey key
Definition: key.h:215
bool DoMigration(CWallet &wallet, WalletContext &context, bilingual_str &error, MigrationResult &res) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: wallet.cpp:4177
std::optional< AddressPurpose > purpose
Address purpose which was originally recorded for payment protocol support but now serves as a cached...
Definition: wallet.h:245
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:1565
Bilingual messages:
Definition: translation.h:18
bool IsAddressPreviouslySpent(const CTxDestination &dest) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2860
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:3956
virtual CBlockLocator getActiveChainLocator(const uint256 &block_hash)=0
Return a locator that refers to a block in the active chain.
bool empty() const
Definition: translation.h:29
#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:626
RecursiveMutex cs_KeyStore
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:149
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:2855
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:2877
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:379
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:739
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:3863
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:1745
bool WithEncryptionKey(std::function< bool(const CKeyingMaterial &)> cb) const override
Pass the encryption key to cb().
Definition: wallet.cpp:3590
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:205
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:452
void transactionAddedToMempool(const CTransactionRef &tx) override
Definition: wallet.cpp:1413
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:210
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:73
void updateState(interfaces::Chain &chain)
Update transaction state when attaching to a chain, filling in heights of conflicted and confirmed bl...
Definition: transaction.cpp:32
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:1299
util::Result< void > RemoveTxs(std::vector< uint256 > &txs_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Erases the provided transactions from the wallet.
Definition: wallet.cpp:2334
bool IsLegacy() const
Determine if we are a legacy wallet.
Definition: wallet.cpp:3758
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:153
bool m_is_cache_empty
This flag is true if all m_amounts caches are empty.
Definition: transaction.h:236
Removed for conflict with in-block transaction.
MasterKeyMap mapMasterKeys
Definition: wallet.h:455
WalletDatabase & GetDatabase() const override
Definition: wallet.h:444
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:1345
bool fInternal
Whether this is from the internal (change output) keypool.
Definition: wallet.h:201
std::optional< int64_t > GetOldestKeyPoolTime() const
Definition: wallet.cpp:2534
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:2194
void DeactivateScriptPubKeyMan(uint256 id, OutputType type, bool internal)
Remove specified ScriptPubKeyMan from set of active SPK managers.
Definition: wallet.cpp:3741
std::string TxStateString(const T &state)
Return TxState or SyncTxState as a string for logging or debugging.
Definition: transaction.h:124
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:2423
CTxDestination address
The destination.
Definition: wallet.h:199
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:442
#define PACKAGE_NAME
bool SignTransaction(CMutableTransaction &tx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Fetch the inputs and sign with SIGHASH_ALL.
Definition: wallet.cpp:2106
void CacheNewScriptPubKeys(const std::set< CScript > &spks, ScriptPubKeyMan *spkm)
Add scriptPubKeys for this ScriptPubKeyMan into the scriptPubKey cache.
Definition: wallet.cpp:4460
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:58
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:81
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1065
std::unique_ptr< Wallet > MakeWallet(wallet::WalletContext &context, const std::shared_ptr< wallet::CWallet > &wallet)
Return implementation of Wallet interface.
Definition: interfaces.cpp:688
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:483
bool WriteLockedUTXO(const COutPoint &output)
Definition: walletdb.cpp:296
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:338
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:211
std::vector< std::string > GetAddressReceiveRequests() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2866
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:1076
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:505
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:3477
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:582
boost::signals2::signal< void(const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
Definition: wallet.h:848
State of transaction confirmed in a block.
Definition: transaction.h:31
bool IsEquivalentTo(const CWalletTx &tx) const
True if only scriptSigs are different.
Definition: transaction.cpp:12
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:1212
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:191
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:768
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
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:3547
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:2702
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:37
std::set< ScriptPubKeyMan * > GetAllScriptPubKeyMans() const
Returns all unique ScriptPubKeyMans.
Definition: wallet.cpp:3468
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:2028
bool isAbandoned() const
Definition: transaction.h:337
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:1526
const std::vector< CTxIn > vin
Definition: transaction.h:306
std::optional< bool > IsInternalScriptPubKeyMan(ScriptPubKeyMan *spk_man) const
Returns whether the provided ScriptPubKeyMan is internal.
Definition: wallet.cpp:3780
int64_t GetTxTime() const
Definition: transaction.cpp:26
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:2652
constexpr unsigned char * begin()
Definition: uint256.h:68
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:179
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:2091
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:2587
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE
Default for -spendzeroconfchange.
Definition: wallet.h:127
CKey GenerateRandomKey(bool compressed) noexcept
Definition: key.cpp:372
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:854
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:2638
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
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:90
const uint256 & hash
Definition: chain.h:85
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:176
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:459
void LoadAddressPreviouslySpent(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks destination as previously spent.
Definition: wallet.cpp:2850
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:80
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:3767
bool SetAddressPreviouslySpent(WalletBatch &batch, const CTxDestination &dest, bool used) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2836
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:84
bool IsLocked() const override
Definition: wallet.cpp:3413
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:3575
#define LOCK2(cs1, cs2)
Definition: sync.h:258
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:1150
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:90
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:3707
bool ShouldResend() const
Return true if all conditions for periodically resending transactions are met.
Definition: wallet.cpp:2011
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:3454
virtual bool isInMempool(const uint256 &txid)=0
Check if transaction is in mempool.
std::shared_ptr< CWallet > wallet
Definition: wallet.h:1115
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:1340
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
SecureString create_passphrase
Definition: db.h:187
ArgsManager & args
Definition: bitcoind.cpp:268
bool WriteActiveScriptPubKeyMan(uint8_t type, const uint256 &id, bool internal)
Definition: walletdb.cpp:216
std::string wallet_name
Definition: wallet.h:1114
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
Definition: addresstype.cpp:49
CPubKey vchPubKey
The public key.
bool Unlock(const CKeyingMaterial &vMasterKeyIn)
Definition: wallet.cpp:3439
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: transaction.h:225
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:736
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:86
uint64_t create_flags
Definition: db.h:186
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:866
bool WriteAddressPreviouslySpent(const CTxDestination &dest, bool previously_spent)
Definition: walletdb.cpp:1293
An input of a transaction.
Definition: transaction.h:66
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:976
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:37
#define LOCK(cs)
Definition: sync.h:257
const char * name
Definition: rest.cpp:49
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:146
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:1285
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:97
std::map< OutputType, ScriptPubKeyMan * > m_internal_spk_managers
Definition: wallet.h:412
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:2601
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:1482
bilingual_str AmountHighWarn(const std::string &optname)
Definition: error.cpp:59
Fast randomness source.
Definition: random.h:144
void blockConnected(ChainstateRole role, const interfaces::BlockInfo &block) override
Definition: wallet.cpp:1460
Txid hash
Definition: transaction.h:31
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:733
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:1614
void NotifyWalletLoaded(WalletContext &context, const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:207
uint32_t n
Definition: transaction.h:32
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1784
const std::vector< CTxOut > vout
Definition: transaction.h:307
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:1295
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:2785
std::string ToString() const
virtual bool findBlock(const uint256 &hash, const FoundBlock &block={})=0
Return whether node has the block and optionally return block metadata or contents.
void AddActiveScriptPubKeyManWithDb(WalletBatch &batch, uint256 id, OutputType type, bool internal)
Definition: wallet.cpp:3713
bool IsHDEnabled() const
Definition: wallet.cpp:1631
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:1360
bool BackupWallet(const std::string &strDest) const
Definition: wallet.cpp:3354
static int TxStateSerializedIndex(const TxState &state)
Get TxState serialized block index. Inverse of TxStateInterpretSerialized.
Definition: transaction.h:111
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:2001
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:1423
A structure for PSBTs which contain per-input information.
Definition: psbt.h:193
unsigned int GetKeyPoolSize() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2486
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:1321
#define WAIT_LOCK(cs, name)
Definition: sync.h:262
An output of a transaction.
Definition: transaction.h:149
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:2309
std::string ToString() const
Definition: uint256.cpp:55
bool IsTxImmatureCoinBase(const CWalletTx &wtx) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3400
bool UnlockCoin(const COutPoint &output, WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2662
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:1682
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
void UnsetBlankWalletFlag(WalletBatch &batch) override
Unset the blank wallet flag and saves it to disk.
Definition: wallet.cpp:1677
TxItems wtxOrdered
Definition: wallet.h:484
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:1828
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:4286
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:851
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:301
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
void ForEachAddrBookEntry(const ListAddrBookFunc &func) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2562
std::shared_ptr< CWallet > solvables_wallet
Definition: wallet.h:1117
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:92
void TopUpCallback(const std::set< CScript > &spks, ScriptPubKeyMan *spkm) override
Callback function for after TopUp completes containing any scripts that were added by a SPKMan...
Definition: wallet.cpp:4467
static uint256 TxStateSerializedBlockHash(const TxState &state)
Get TxState serialized block hash. Inverse of TxStateInterpretSerialized.
Definition: transaction.h:99
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:424
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:3344
static void ReleaseWallet(CWallet *wallet)
Definition: wallet.cpp:222
ArgsManager gArgs
Definition: args.cpp:41
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::unordered_map< CScript, std::vector< ScriptPubKeyMan * >, SaltedSipHasher > m_cached_spks
Cache of descriptor ScriptPubKeys used for IsMine. Maps ScriptPubKey to set of spkms.
Definition: wallet.h:426
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:131
if(!SetupNetworking())
int flags
Definition: bitcoin-tx.cpp:530
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:196
bool ImportPrivKeys(const std::map< CKeyID, CKey > &privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1725
256-bit opaque blob.
Definition: uint256.h:106
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:342
static time_point now() noexcept
Return current system time or mocked time, if set.
Definition: time.cpp:70
unsigned int fTimeReceivedIsTxTime
Definition: transaction.h:206
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:935
#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:2054
std::vector< std::shared_ptr< CWallet > > GetWallets(WalletContext &context)
Definition: wallet.cpp:178
void SetSeed(Span< const std::byte > seed)
Definition: key.cpp:388
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1278
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:2497
bool CanGrindR() const
Whether the (external) signer performs R-value signature grinding.
Definition: wallet.cpp:4172
bool SetAddressBookWithDB(WalletBatch &batch, const CTxDestination &address, const std::string &strName, const std::optional< AddressPurpose > &strPurpose)
Definition: wallet.cpp:2381
constexpr void SetNull()
Definition: uint256.h:49
bool IsLockedCoin(const COutPoint &output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2684
State of rejected transaction that conflicts with a confirmed block.
Definition: transaction.h:46
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:123
void KeepDestination()
Keep the address. Do not return its key to the keypool when this object goes out of scope...
Definition: wallet.cpp:2620
bool error(const char *fmt, const Args &... args)
Definition: logging.h:267
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:606
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
static transaction_identifier FromUint256(const uint256 &id)
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:3721
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:480
bool fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: transaction.h:223
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:1699
void AddScriptPubKeyMan(const uint256 &id, std::unique_ptr< ScriptPubKeyMan > spkm_man)
Definition: wallet.cpp:3565
std::shared_ptr< CWallet > watchonly_wallet
Definition: wallet.h:1116
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:455
bool EraseAddressReceiveRequest(const CTxDestination &dest, const std::string &id)
Definition: walletdb.cpp:1304
std::set< ScriptPubKeyMan * > GetScriptPubKeyMans(const CScript &script) const
Get all the ScriptPubKeyMans for a script.
Definition: wallet.cpp:3487
size_t KeypoolCountExternalKeys() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2469
boost::signals2::signal< void(CWallet *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
Definition: wallet.h:863
CTransactionRef non_witness_utxo
Definition: psbt.h:195
bool InMempool() const
Definition: transaction.cpp:21
std::optional< std::string > m_op_label
Definition: wallet.h:749
static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status)
bool IsCrypted() const
Definition: wallet.cpp:3408
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:217
std::unique_ptr< interfaces::Handler > HandleLoadWallet(WalletContext &context, LoadWalletFn load_wallet)
Definition: wallet.cpp:200
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:1335
bool EraseTx(uint256 hash)
Definition: walletdb.cpp:102
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:36
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:477
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:1687
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
void SetLabel(std::string name)
Definition: wallet.h:268
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const override
#define AssertLockNotHeld(cs)
Definition: sync.h:147
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:3937
bool require_existing
Definition: db.h:183
static int count
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:81
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:37
std::vector< WalletDescriptor > GetWalletDescriptors(const CScript &script) const
Get the wallet descriptors for a script.
Definition: wallet.cpp:3535
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:75
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:287
A mutable version of CTransaction.
Definition: transaction.h:377
std::shared_ptr< CWallet > watchonly_wallet
uint256 GetLastBlockHash() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:982
bool UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2672
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
enum wallet::CWallet::ScanResult::@19 status
Tp rand_uniform_delay(const Tp &time, typename Tp::duration range)
Return the time point advanced by a uniform random duration.
Definition: random.h:232
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1663
bool IsCoinBase() const
Definition: transaction.h:344
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:818
static auto quoted(const std::string &s)
Definition: fs.h:95
#define STR_INTERNAL_BUG(msg)
Definition: check.h:60
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:2548
FoundBlock & height(int &height)
Definition: chain.h:57
virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination &addr)
unsigned int nTimeReceived
time received by this node
Definition: transaction.h:207
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:295
Different type to mark Mutex at global scope.
Definition: sync.h:140
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:224
OutputType m_default_address_type
Definition: wallet.h:724
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:301
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:2417
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:1735
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:89
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:842
bool EraseActiveScriptPubKeyMan(uint8_t type, bool internal)
Definition: walletdb.cpp:222
static path u8path(const std::string &utf8_str)
Definition: fs.h:75
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:2507
unsigned int nMasterKeyMaxID
Definition: wallet.h:456
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
bool DelAddressBookWithDB(WalletBatch &batch, const CTxDestination &address)
Definition: wallet.cpp:2430
unsigned int chain_time_max
Definition: chain.h:94
COutPoint prevout
Definition: transaction.h:69
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:32
static bool RunWithinTxn(WalletBatch &batch, std::string_view process_desc, const std::function< bool(WalletBatch &)> &func)
Definition: walletdb.cpp:1237
static path absolute(const path &p)
Definition: fs.h:82
ArgsManager * args
Definition: context.h:39
bool isInactive() const
Definition: transaction.h:339
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:87
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:1330
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)
DescriptorScriptPubKeyMan & LoadDescriptorScriptPubKeyMan(uint256 id, WalletDescriptor &desc)
Instantiate a descriptor ScriptPubKeyMan from the WalletDescriptor and load it.
Definition: wallet.cpp:3610
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
void SetTx(CTransactionRef arg)
Definition: transaction.h:307
bool isArray() const
Definition: univalue.h:84
CTransactionRef tx
Definition: transaction.h:258
void ConnectScriptPubKeyManNotifiers()
Connect the signals from ScriptPubKeyMans to the signals in CWallet.
Definition: wallet.cpp:3601
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:2690
bool HasWalletDescriptor(const WalletDescriptor &desc) const
std::variant< TxStateConfirmed, TxStateInMempool, TxStateConflicted, TxStateInactive, TxStateUnrecognized > TxState
All possible CWalletTx states.
Definition: transaction.h:78
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:2140
#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:857
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:2268
virtual bool havePruned()=0
Check if any block has been pruned.
util::Result< CTxDestination > GetNewChangeDestination(const OutputType type)
Definition: wallet.cpp:2523
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:1669
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:3804
Clock::time_point now() const
Definition: wallet.h:1094
std::unique_ptr< WalletDatabase > MakeWalletDatabase(const std::string &name, const DatabaseOptions &options, DatabaseStatus &status, bilingual_str &error_string)
Definition: wallet.cpp:2891
#define Assert(val)
Identity function.
Definition: check.h:77
std::function< void(std::unique_ptr< interfaces::Wallet > wallet)> LoadWalletFn
Definition: context.h:24
bool IsSpentKey(const CScript &scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1021
std::vector< std::unique_ptr< DescriptorScriptPubKeyMan > > desc_spkms
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
static bool copy_file(const path &from, const path &to, copy_options options)
Definition: fs.h:128
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:639
OutputType TransactionChangeType(const std::optional< OutputType > &change_type, const std::vector< CRecipient > &vecSend) const
Definition: wallet.cpp:2207
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:2915
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:3179
LegacyScriptPubKeyMan * GetOrCreateLegacyScriptPubKeyMan()
Definition: wallet.cpp:3559
void SetupDescriptorScriptPubKeyMans() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3652
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:1543
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
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:3374
std::unique_ptr< SigningProvider > GetSolvingProvider(const CScript &script) const
Get the SigningProvider for a script.
Definition: wallet.cpp:3513