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