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