Bitcoin Core  0.18.99
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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/consensus.h>
10 #include <consensus/validation.h>
11 #include <fs.h>
12 #include <interfaces/chain.h>
13 #include <interfaces/wallet.h>
14 #include <key.h>
15 #include <key_io.h>
16 #include <keystore.h>
17 #include <net.h>
18 #include <policy/fees.h>
19 #include <policy/policy.h>
20 #include <policy/rbf.h>
21 #include <primitives/block.h>
22 #include <primitives/transaction.h>
23 #include <script/descriptor.h>
24 #include <script/script.h>
25 #include <shutdown.h>
26 #include <timedata.h>
27 #include <txmempool.h>
28 #include <util/bip32.h>
29 #include <util/error.h>
30 #include <util/fees.h>
31 #include <util/moneystr.h>
32 #include <util/rbf.h>
33 #include <util/validation.h>
34 #include <validation.h>
35 #include <wallet/coincontrol.h>
36 #include <wallet/fees.h>
37 
38 #include <algorithm>
39 #include <assert.h>
40 #include <future>
41 
42 #include <boost/algorithm/string/replace.hpp>
43 
44 static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
45 
46 static CCriticalSection cs_wallets;
47 static std::vector<std::shared_ptr<CWallet>> vpwallets GUARDED_BY(cs_wallets);
48 
49 bool AddWallet(const std::shared_ptr<CWallet>& wallet)
50 {
51  LOCK(cs_wallets);
52  assert(wallet);
53  std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
54  if (i != vpwallets.end()) return false;
55  vpwallets.push_back(wallet);
56  return true;
57 }
58 
59 bool RemoveWallet(const std::shared_ptr<CWallet>& wallet)
60 {
61  LOCK(cs_wallets);
62  assert(wallet);
63  std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
64  if (i == vpwallets.end()) return false;
65  vpwallets.erase(i);
66  return true;
67 }
68 
69 bool HasWallets()
70 {
71  LOCK(cs_wallets);
72  return !vpwallets.empty();
73 }
74 
75 std::vector<std::shared_ptr<CWallet>> GetWallets()
76 {
77  LOCK(cs_wallets);
78  return vpwallets;
79 }
80 
81 std::shared_ptr<CWallet> GetWallet(const std::string& name)
82 {
83  LOCK(cs_wallets);
84  for (const std::shared_ptr<CWallet>& wallet : vpwallets) {
85  if (wallet->GetName() == name) return wallet;
86  }
87  return nullptr;
88 }
89 
90 static Mutex g_wallet_release_mutex;
91 static std::condition_variable g_wallet_release_cv;
92 static std::set<CWallet*> g_unloading_wallet_set;
93 
94 // Custom deleter for shared_ptr<CWallet>.
95 static void ReleaseWallet(CWallet* wallet)
96 {
97  // Unregister and delete the wallet right after BlockUntilSyncedToCurrentChain
98  // so that it's in sync with the current chainstate.
99  wallet->WalletLogPrintf("Releasing wallet\n");
101  wallet->Flush();
102  wallet->m_chain_notifications_handler.reset();
103  delete wallet;
104  // Wallet is now released, notify UnloadWallet, if any.
105  {
106  LOCK(g_wallet_release_mutex);
107  if (g_unloading_wallet_set.erase(wallet) == 0) {
108  // UnloadWallet was not called for this wallet, all done.
109  return;
110  }
111  }
112  g_wallet_release_cv.notify_all();
113 }
114 
115 void UnloadWallet(std::shared_ptr<CWallet>&& wallet)
116 {
117  // Mark wallet for unloading.
118  CWallet* pwallet = wallet.get();
119  {
120  LOCK(g_wallet_release_mutex);
121  auto it = g_unloading_wallet_set.insert(pwallet);
122  assert(it.second);
123  }
124  // The wallet can be in use so it's not possible to explicitly unload here.
125  // Notify the unload intent so that all remaining shared pointers are
126  // released.
127  pwallet->NotifyUnload();
128  // Time to ditch our shared_ptr and wait for ReleaseWallet call.
129  wallet.reset();
130  {
131  WAIT_LOCK(g_wallet_release_mutex, lock);
132  while (g_unloading_wallet_set.count(pwallet) == 1) {
133  g_wallet_release_cv.wait(lock);
134  }
135  }
136 }
137 
138 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const WalletLocation& location, std::string& error, std::string& warning)
139 {
140  if (!CWallet::Verify(chain, location, false, error, warning)) {
141  error = "Wallet file verification failed: " + error;
142  return nullptr;
143  }
144 
145  std::shared_ptr<CWallet> wallet = CWallet::CreateWalletFromFile(chain, location);
146  if (!wallet) {
147  error = "Wallet loading failed.";
148  return nullptr;
149  }
150  AddWallet(wallet);
151  wallet->postInitProcess();
152  return wallet;
153 }
154 
155 std::shared_ptr<CWallet> LoadWallet(interfaces::Chain& chain, const std::string& name, std::string& error, std::string& warning)
156 {
157  return LoadWallet(chain, WalletLocation(name), error, warning);
158 }
159 
160 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
161 
162 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
163 
169 std::string COutput::ToString() const
170 {
171  return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
172 }
173 
174 std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider)
175 {
176  std::vector<CScript> dummy;
178  InferDescriptor(spk, provider)->Expand(0, DUMMY_SIGNING_PROVIDER, dummy, out);
179  std::vector<CKeyID> ret;
180  for (const auto& entry : out.pubkeys) {
181  ret.push_back(entry.first);
182  }
183  return ret;
184 }
185 
186 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
187 {
188  LOCK(cs_wallet);
189  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
190  if (it == mapWallet.end())
191  return nullptr;
192  return &(it->second);
193 }
194 
196 {
197  assert(!IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
198  assert(!IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET));
199  AssertLockHeld(cs_wallet);
200  bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
201 
202  CKey secret;
203 
204  // Create new metadata
205  int64_t nCreationTime = GetTime();
206  CKeyMetadata metadata(nCreationTime);
207 
208  // use HD key derivation if HD was enabled during wallet creation and a seed is present
209  if (IsHDEnabled()) {
210  DeriveNewChildKey(batch, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
211  } else {
212  secret.MakeNewKey(fCompressed);
213  }
214 
215  // Compressed public keys were introduced in version 0.6.0
216  if (fCompressed) {
217  SetMinVersion(FEATURE_COMPRPUBKEY);
218  }
219 
220  CPubKey pubkey = secret.GetPubKey();
221  assert(secret.VerifyPubKey(pubkey));
222 
223  mapKeyMetadata[pubkey.GetID()] = metadata;
224  UpdateTimeFirstKey(nCreationTime);
225 
226  if (!AddKeyPubKeyWithDB(batch, secret, pubkey)) {
227  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
228  }
229  return pubkey;
230 }
231 
232 void CWallet::DeriveNewChildKey(WalletBatch &batch, CKeyMetadata& metadata, CKey& secret, bool internal)
233 {
234  // for now we use a fixed keypath scheme of m/0'/0'/k
235  CKey seed; //seed (256bit)
236  CExtKey masterKey; //hd master key
237  CExtKey accountKey; //key at m/0'
238  CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
239  CExtKey childKey; //key at m/0'/0'/<n>'
240 
241  // try to get the seed
242  if (!GetKey(hdChain.seed_id, seed))
243  throw std::runtime_error(std::string(__func__) + ": seed not found");
244 
245  masterKey.SetSeed(seed.begin(), seed.size());
246 
247  // derive m/0'
248  // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
249  masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
250 
251  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
252  assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
253  accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
254 
255  // derive child key at next index, skip keys already known to the wallet
256  do {
257  // always derive hardened keys
258  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
259  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
260  if (internal) {
261  chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
262  metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
263  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
264  metadata.key_origin.path.push_back(1 | BIP32_HARDENED_KEY_LIMIT);
265  metadata.key_origin.path.push_back(hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
266  hdChain.nInternalChainCounter++;
267  }
268  else {
269  chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
270  metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
271  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
272  metadata.key_origin.path.push_back(0 | BIP32_HARDENED_KEY_LIMIT);
273  metadata.key_origin.path.push_back(hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
274  hdChain.nExternalChainCounter++;
275  }
276  } while (HaveKey(childKey.key.GetPubKey().GetID()));
277  secret = childKey.key;
278  metadata.hd_seed_id = hdChain.seed_id;
279  CKeyID master_id = masterKey.key.GetPubKey().GetID();
280  std::copy(master_id.begin(), master_id.begin() + 4, metadata.key_origin.fingerprint);
281  metadata.has_key_origin = true;
282  // update the chain model in the database
283  if (!batch.WriteHDChain(hdChain))
284  throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
285 }
286 
287 bool CWallet::AddKeyPubKeyWithDB(WalletBatch& batch, const CKey& secret, const CPubKey& pubkey)
288 {
289  AssertLockHeld(cs_wallet);
290 
291  // Make sure we aren't adding private keys to private key disabled wallets
292  assert(!IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
293 
294  // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
295  // which is overridden below. To avoid flushes, the database handle is
296  // tunneled through to it.
297  bool needsDB = !encrypted_batch;
298  if (needsDB) {
299  encrypted_batch = &batch;
300  }
301  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
302  if (needsDB) encrypted_batch = nullptr;
303  return false;
304  }
305  if (needsDB) encrypted_batch = nullptr;
306 
307  // check if we need to remove from watch-only
308  CScript script;
309  script = GetScriptForDestination(PKHash(pubkey));
310  if (HaveWatchOnly(script)) {
311  RemoveWatchOnly(script);
312  }
313  script = GetScriptForRawPubKey(pubkey);
314  if (HaveWatchOnly(script)) {
315  RemoveWatchOnly(script);
316  }
317 
318  if (!IsCrypted()) {
319  return batch.WriteKey(pubkey,
320  secret.GetPrivKey(),
321  mapKeyMetadata[pubkey.GetID()]);
322  }
323  UnsetWalletFlag(WALLET_FLAG_BLANK_WALLET);
324  return true;
325 }
326 
327 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
328 {
329  WalletBatch batch(*database);
330  return CWallet::AddKeyPubKeyWithDB(batch, secret, pubkey);
331 }
332 
333 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
334  const std::vector<unsigned char> &vchCryptedSecret)
335 {
336  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
337  return false;
338  {
339  LOCK(cs_wallet);
340  if (encrypted_batch)
341  return encrypted_batch->WriteCryptedKey(vchPubKey,
342  vchCryptedSecret,
343  mapKeyMetadata[vchPubKey.GetID()]);
344  else
345  return WalletBatch(*database).WriteCryptedKey(vchPubKey,
346  vchCryptedSecret,
347  mapKeyMetadata[vchPubKey.GetID()]);
348  }
349 }
350 
351 void CWallet::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata& meta)
352 {
353  AssertLockHeld(cs_wallet);
354  UpdateTimeFirstKey(meta.nCreateTime);
355  mapKeyMetadata[keyID] = meta;
356 }
357 
358 void CWallet::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata& meta)
359 {
360  AssertLockHeld(cs_wallet);
361  UpdateTimeFirstKey(meta.nCreateTime);
362  m_script_metadata[script_id] = meta;
363 }
364 
365 // Writes a keymetadata for a public key. overwrite specifies whether to overwrite an existing metadata for that key if there exists one.
366 bool CWallet::WriteKeyMetadata(const CKeyMetadata& meta, const CPubKey& pubkey, const bool overwrite)
367 {
368  return WalletBatch(*database).WriteKeyMetadata(meta, pubkey, overwrite);
369 }
370 
372 {
373  AssertLockHeld(cs_wallet);
374  if (IsLocked() || IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {
375  return;
376  }
377 
378  std::unique_ptr<WalletBatch> batch = MakeUnique<WalletBatch>(*database);
379  size_t cnt = 0;
380  for (auto& meta_pair : mapKeyMetadata) {
381  CKeyMetadata& meta = meta_pair.second;
382  if (!meta.hd_seed_id.IsNull() && !meta.has_key_origin && meta.hdKeypath != "s") { // If the hdKeypath is "s", that's the seed and it doesn't have a key origin
383  CKey key;
384  GetKey(meta.hd_seed_id, key);
385  CExtKey masterKey;
386  masterKey.SetSeed(key.begin(), key.size());
387  // Add to map
388  CKeyID master_id = masterKey.key.GetPubKey().GetID();
389  std::copy(master_id.begin(), master_id.begin() + 4, meta.key_origin.fingerprint);
390  if (!ParseHDKeypath(meta.hdKeypath, meta.key_origin.path)) {
391  throw std::runtime_error("Invalid stored hdKeypath");
392  }
393  meta.has_key_origin = true;
396  }
397 
398  // Write meta to wallet
399  CPubKey pubkey;
400  if (GetPubKey(meta_pair.first, pubkey)) {
401  batch->WriteKeyMetadata(meta, pubkey, true);
402  if (++cnt % 1000 == 0) {
403  // avoid creating overlarge in-memory batches in case the wallet contains large amounts of keys
404  batch.reset(new WalletBatch(*database));
405  }
406  }
407  }
408  }
409  batch.reset(); //write before setting the flag
410  SetWalletFlag(WALLET_FLAG_KEY_ORIGIN_METADATA);
411 }
412 
413 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
414 {
415  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
416 }
417 
422 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
423 {
424  AssertLockHeld(cs_wallet);
425  if (nCreateTime <= 1) {
426  // Cannot determine birthday information, so set the wallet birthday to
427  // the beginning of time.
428  nTimeFirstKey = 1;
429  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
430  nTimeFirstKey = nCreateTime;
431  }
432 }
433 
434 bool CWallet::AddCScript(const CScript& redeemScript)
435 {
436  if (!CCryptoKeyStore::AddCScript(redeemScript))
437  return false;
438  if (WalletBatch(*database).WriteCScript(Hash160(redeemScript), redeemScript)) {
439  UnsetWalletFlag(WALLET_FLAG_BLANK_WALLET);
440  return true;
441  }
442  return false;
443 }
444 
445 bool CWallet::LoadCScript(const CScript& redeemScript)
446 {
447  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
448  * that never can be redeemed. However, old wallets may still contain
449  * these. Do not add them to the wallet and warn. */
450  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
451  {
452  std::string strAddr = EncodeDestination(ScriptHash(redeemScript));
453  WalletLogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
454  return true;
455  }
456 
457  return CCryptoKeyStore::AddCScript(redeemScript);
458 }
459 
461 {
463  return false;
464  const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
465  UpdateTimeFirstKey(meta.nCreateTime);
466  NotifyWatchonlyChanged(true);
467  if (WalletBatch(*database).WriteWatchOnly(dest, meta)) {
468  UnsetWalletFlag(WALLET_FLAG_BLANK_WALLET);
469  return true;
470  }
471  return false;
472 }
473 
474 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
475 {
476  m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
477  return AddWatchOnly(dest);
478 }
479 
481 {
482  AssertLockHeld(cs_wallet);
484  return false;
485  if (!HaveWatchOnly())
486  NotifyWatchonlyChanged(false);
487  if (!WalletBatch(*database).EraseWatchOnly(dest))
488  return false;
489 
490  return true;
491 }
492 
494 {
495  return CCryptoKeyStore::AddWatchOnly(dest);
496 }
497 
498 bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool accept_no_keys)
499 {
500  CCrypter crypter;
501  CKeyingMaterial _vMasterKey;
502 
503  {
504  LOCK(cs_wallet);
505  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
506  {
507  if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
508  return false;
509  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
510  continue; // try another master key
511  if (CCryptoKeyStore::Unlock(_vMasterKey, accept_no_keys)) {
512  // Now that we've unlocked, upgrade the key metadata
513  UpgradeKeyMetadata();
514  return true;
515  }
516  }
517  }
518  return false;
519 }
520 
521 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
522 {
523  bool fWasLocked = IsLocked();
524 
525  {
526  LOCK(cs_wallet);
527  Lock();
528 
529  CCrypter crypter;
530  CKeyingMaterial _vMasterKey;
531  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
532  {
533  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
534  return false;
535  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
536  return false;
537  if (CCryptoKeyStore::Unlock(_vMasterKey))
538  {
539  int64_t nStartTime = GetTimeMillis();
540  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
541  pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
542 
543  nStartTime = GetTimeMillis();
544  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
545  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
546 
547  if (pMasterKey.second.nDeriveIterations < 25000)
548  pMasterKey.second.nDeriveIterations = 25000;
549 
550  WalletLogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
551 
552  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
553  return false;
554  if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
555  return false;
556  WalletBatch(*database).WriteMasterKey(pMasterKey.first, pMasterKey.second);
557  if (fWasLocked)
558  Lock();
559  return true;
560  }
561  }
562  }
563 
564  return false;
565 }
566 
568 {
569  WalletBatch batch(*database);
570  batch.WriteBestBlock(loc);
571 }
572 
573 void CWallet::SetMinVersion(enum WalletFeature nVersion, WalletBatch* batch_in, bool fExplicit)
574 {
575  LOCK(cs_wallet);
576  if (nWalletVersion >= nVersion)
577  return;
578 
579  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
580  if (fExplicit && nVersion > nWalletMaxVersion)
581  nVersion = FEATURE_LATEST;
582 
583  nWalletVersion = nVersion;
584 
585  if (nVersion > nWalletMaxVersion)
586  nWalletMaxVersion = nVersion;
587 
588  {
589  WalletBatch* batch = batch_in ? batch_in : new WalletBatch(*database);
590  if (nWalletVersion > 40000)
591  batch->WriteMinVersion(nWalletVersion);
592  if (!batch_in)
593  delete batch;
594  }
595 }
596 
597 bool CWallet::SetMaxVersion(int nVersion)
598 {
599  LOCK(cs_wallet);
600  // cannot downgrade below current version
601  if (nWalletVersion > nVersion)
602  return false;
603 
604  nWalletMaxVersion = nVersion;
605 
606  return true;
607 }
608 
609 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
610 {
611  std::set<uint256> result;
612  AssertLockHeld(cs_wallet);
613 
614  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
615  if (it == mapWallet.end())
616  return result;
617  const CWalletTx& wtx = it->second;
618 
619  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
620 
621  for (const CTxIn& txin : wtx.tx->vin)
622  {
623  if (mapTxSpends.count(txin.prevout) <= 1)
624  continue; // No conflict if zero or one spends
625  range = mapTxSpends.equal_range(txin.prevout);
626  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
627  result.insert(_it->second);
628  }
629  return result;
630 }
631 
632 bool CWallet::HasWalletSpend(const uint256& txid) const
633 {
634  AssertLockHeld(cs_wallet);
635  auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
636  return (iter != mapTxSpends.end() && iter->first.hash == txid);
637 }
638 
639 void CWallet::Flush(bool shutdown)
640 {
641  database->Flush(shutdown);
642 }
643 
644 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
645 {
646  // We want all the wallet transactions in range to have the same metadata as
647  // the oldest (smallest nOrderPos).
648  // So: find smallest nOrderPos:
649 
650  int nMinOrderPos = std::numeric_limits<int>::max();
651  const CWalletTx* copyFrom = nullptr;
652  for (TxSpends::iterator it = range.first; it != range.second; ++it) {
653  const CWalletTx* wtx = &mapWallet.at(it->second);
654  if (wtx->nOrderPos < nMinOrderPos) {
655  nMinOrderPos = wtx->nOrderPos;
656  copyFrom = wtx;
657  }
658  }
659 
660  if (!copyFrom) {
661  return;
662  }
663 
664  // Now copy data from copyFrom to rest:
665  for (TxSpends::iterator it = range.first; it != range.second; ++it)
666  {
667  const uint256& hash = it->second;
668  CWalletTx* copyTo = &mapWallet.at(hash);
669  if (copyFrom == copyTo) continue;
670  assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
671  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
672  copyTo->mapValue = copyFrom->mapValue;
673  copyTo->vOrderForm = copyFrom->vOrderForm;
674  // fTimeReceivedIsTxTime not copied on purpose
675  // nTimeReceived not copied on purpose
676  copyTo->nTimeSmart = copyFrom->nTimeSmart;
677  copyTo->fFromMe = copyFrom->fFromMe;
678  // nOrderPos not copied on purpose
679  // cached members not copied on purpose
680  }
681 }
682 
687 bool CWallet::IsSpent(interfaces::Chain::Lock& locked_chain, const uint256& hash, unsigned int n) const
688 {
689  const COutPoint outpoint(hash, n);
690  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
691  range = mapTxSpends.equal_range(outpoint);
692 
693  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
694  {
695  const uint256& wtxid = it->second;
696  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
697  if (mit != mapWallet.end()) {
698  int depth = mit->second.GetDepthInMainChain(locked_chain);
699  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
700  return true; // Spent
701  }
702  }
703  return false;
704 }
705 
706 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
707 {
708  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
709 
710  setLockedCoins.erase(outpoint);
711 
712  std::pair<TxSpends::iterator, TxSpends::iterator> range;
713  range = mapTxSpends.equal_range(outpoint);
714  SyncMetaData(range);
715 }
716 
717 
718 void CWallet::AddToSpends(const uint256& wtxid)
719 {
720  auto it = mapWallet.find(wtxid);
721  assert(it != mapWallet.end());
722  CWalletTx& thisTx = it->second;
723  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
724  return;
725 
726  for (const CTxIn& txin : thisTx.tx->vin)
727  AddToSpends(txin.prevout, wtxid);
728 }
729 
730 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
731 {
732  if (IsCrypted())
733  return false;
734 
735  CKeyingMaterial _vMasterKey;
736 
737  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
738  GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
739 
740  CMasterKey kMasterKey;
741 
742  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
744 
745  CCrypter crypter;
746  int64_t nStartTime = GetTimeMillis();
747  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
748  kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
749 
750  nStartTime = GetTimeMillis();
751  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
752  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
753 
754  if (kMasterKey.nDeriveIterations < 25000)
755  kMasterKey.nDeriveIterations = 25000;
756 
757  WalletLogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
758 
759  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
760  return false;
761  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
762  return false;
763 
764  {
765  LOCK(cs_wallet);
766  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
767  assert(!encrypted_batch);
768  encrypted_batch = new WalletBatch(*database);
769  if (!encrypted_batch->TxnBegin()) {
770  delete encrypted_batch;
771  encrypted_batch = nullptr;
772  return false;
773  }
774  encrypted_batch->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
775 
776  if (!EncryptKeys(_vMasterKey))
777  {
778  encrypted_batch->TxnAbort();
779  delete encrypted_batch;
780  encrypted_batch = nullptr;
781  // We now probably have half of our keys encrypted in memory, and half not...
782  // die and let the user reload the unencrypted wallet.
783  assert(false);
784  }
785 
786  // Encryption was introduced in version 0.4.0
787  SetMinVersion(FEATURE_WALLETCRYPT, encrypted_batch, true);
788 
789  if (!encrypted_batch->TxnCommit()) {
790  delete encrypted_batch;
791  encrypted_batch = nullptr;
792  // We now have keys encrypted in memory, but not on disk...
793  // die to avoid confusion and let the user reload the unencrypted wallet.
794  assert(false);
795  }
796 
797  delete encrypted_batch;
798  encrypted_batch = nullptr;
799 
800  Lock();
801  Unlock(strWalletPassphrase);
802 
803  // if we are using HD, replace the HD seed with a new one
804  if (IsHDEnabled()) {
805  SetHDSeed(GenerateNewSeed());
806  }
807 
808  NewKeyPool();
809  Lock();
810 
811  // Need to completely rewrite the wallet file; if we don't, bdb might keep
812  // bits of the unencrypted private key in slack space in the database file.
813  database->Rewrite();
814 
815  // BDB seems to have a bad habit of writing old data into
816  // slack space in .dat files; that is bad if the old data is
817  // unencrypted private keys. So:
818  database->ReloadDbEnv();
819 
820  }
821  NotifyStatusChanged(this);
822 
823  return true;
824 }
825 
827 {
828  LOCK(cs_wallet);
829  WalletBatch batch(*database);
830 
831  // Old wallets didn't have any defined order for transactions
832  // Probably a bad idea to change the output of this
833 
834  // First: get all CWalletTx into a sorted-by-time multimap.
835  typedef std::multimap<int64_t, CWalletTx*> TxItems;
836  TxItems txByTime;
837 
838  for (auto& entry : mapWallet)
839  {
840  CWalletTx* wtx = &entry.second;
841  txByTime.insert(std::make_pair(wtx->nTimeReceived, wtx));
842  }
843 
844  nOrderPosNext = 0;
845  std::vector<int64_t> nOrderPosOffsets;
846  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
847  {
848  CWalletTx *const pwtx = (*it).second;
849  int64_t& nOrderPos = pwtx->nOrderPos;
850 
851  if (nOrderPos == -1)
852  {
853  nOrderPos = nOrderPosNext++;
854  nOrderPosOffsets.push_back(nOrderPos);
855 
856  if (!batch.WriteTx(*pwtx))
857  return DBErrors::LOAD_FAIL;
858  }
859  else
860  {
861  int64_t nOrderPosOff = 0;
862  for (const int64_t& nOffsetStart : nOrderPosOffsets)
863  {
864  if (nOrderPos >= nOffsetStart)
865  ++nOrderPosOff;
866  }
867  nOrderPos += nOrderPosOff;
868  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
869 
870  if (!nOrderPosOff)
871  continue;
872 
873  // Since we're changing the order, write it back
874  if (!batch.WriteTx(*pwtx))
875  return DBErrors::LOAD_FAIL;
876  }
877  }
878  batch.WriteOrderPosNext(nOrderPosNext);
879 
880  return DBErrors::LOAD_OK;
881 }
882 
884 {
885  AssertLockHeld(cs_wallet);
886  int64_t nRet = nOrderPosNext++;
887  if (batch) {
888  batch->WriteOrderPosNext(nOrderPosNext);
889  } else {
890  WalletBatch(*database).WriteOrderPosNext(nOrderPosNext);
891  }
892  return nRet;
893 }
894 
896 {
897  {
898  LOCK(cs_wallet);
899  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
900  item.second.MarkDirty();
901  }
902 }
903 
904 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
905 {
906  LOCK(cs_wallet);
907 
908  auto mi = mapWallet.find(originalHash);
909 
910  // There is a bug if MarkReplaced is not called on an existing wallet transaction.
911  assert(mi != mapWallet.end());
912 
913  CWalletTx& wtx = (*mi).second;
914 
915  // Ensure for now that we're not overwriting data
916  assert(wtx.mapValue.count("replaced_by_txid") == 0);
917 
918  wtx.mapValue["replaced_by_txid"] = newHash.ToString();
919 
920  WalletBatch batch(*database, "r+");
921 
922  bool success = true;
923  if (!batch.WriteTx(wtx)) {
924  WalletLogPrintf("%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
925  success = false;
926  }
927 
928  NotifyTransactionChanged(this, originalHash, CT_UPDATED);
929 
930  return success;
931 }
932 
933 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
934 {
935  LOCK(cs_wallet);
936 
937  WalletBatch batch(*database, "r+", fFlushOnClose);
938 
939  uint256 hash = wtxIn.GetHash();
940 
941  // Inserts only if not already there, returns tx inserted or tx found
942  std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
943  CWalletTx& wtx = (*ret.first).second;
944  wtx.BindWallet(this);
945  bool fInsertedNew = ret.second;
946  if (fInsertedNew) {
947  wtx.nTimeReceived = chain().getAdjustedTime();
948  wtx.nOrderPos = IncOrderPosNext(&batch);
949  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
950  wtx.nTimeSmart = ComputeTimeSmart(wtx);
951  AddToSpends(hash);
952  }
953 
954  bool fUpdated = false;
955  if (!fInsertedNew)
956  {
957  // Merge
958  if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
959  {
960  wtx.hashBlock = wtxIn.hashBlock;
961  fUpdated = true;
962  }
963  // If no longer abandoned, update
964  if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
965  {
966  wtx.hashBlock = wtxIn.hashBlock;
967  fUpdated = true;
968  }
969  if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
970  {
971  wtx.nIndex = wtxIn.nIndex;
972  fUpdated = true;
973  }
974  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
975  {
976  wtx.fFromMe = wtxIn.fFromMe;
977  fUpdated = true;
978  }
979  // If we have a witness-stripped version of this transaction, and we
980  // see a new version with a witness, then we must be upgrading a pre-segwit
981  // wallet. Store the new version of the transaction with the witness,
982  // as the stripped-version must be invalid.
983  // TODO: Store all versions of the transaction, instead of just one.
984  if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
985  wtx.SetTx(wtxIn.tx);
986  fUpdated = true;
987  }
988  }
989 
991  WalletLogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
992 
993  // Write to disk
994  if (fInsertedNew || fUpdated)
995  if (!batch.WriteTx(wtx))
996  return false;
997 
998  // Break debit/credit balance caches:
999  wtx.MarkDirty();
1000 
1001  // Notify UI of new or updated transaction
1002  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1003 
1004  // notify an external script when a wallet transaction comes in or is updated
1005  std::string strCmd = gArgs.GetArg("-walletnotify", "");
1006 
1007  if (!strCmd.empty())
1008  {
1009  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1010  std::thread t(runCommand, strCmd);
1011  t.detach(); // thread runs free
1012  }
1013 
1014  return true;
1015 }
1016 
1018 {
1019  uint256 hash = wtxIn.GetHash();
1020  const auto& ins = mapWallet.emplace(hash, wtxIn);
1021  CWalletTx& wtx = ins.first->second;
1022  wtx.BindWallet(this);
1023  if (/* insertion took place */ ins.second) {
1024  wtx.m_it_wtxOrdered = wtxOrdered.insert(std::make_pair(wtx.nOrderPos, &wtx));
1025  }
1026  AddToSpends(hash);
1027  for (const CTxIn& txin : wtx.tx->vin) {
1028  auto it = mapWallet.find(txin.prevout.hash);
1029  if (it != mapWallet.end()) {
1030  CWalletTx& prevtx = it->second;
1031  if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1032  MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1033  }
1034  }
1035  }
1036 }
1037 
1038 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const uint256& block_hash, int posInBlock, bool fUpdate)
1039 {
1040  const CTransaction& tx = *ptx;
1041  {
1042  AssertLockHeld(cs_wallet);
1043 
1044  if (!block_hash.IsNull()) {
1045  for (const CTxIn& txin : tx.vin) {
1046  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1047  while (range.first != range.second) {
1048  if (range.first->second != tx.GetHash()) {
1049  WalletLogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), block_hash.ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1050  MarkConflicted(block_hash, range.first->second);
1051  }
1052  range.first++;
1053  }
1054  }
1055  }
1056 
1057  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1058  if (fExisted && !fUpdate) return false;
1059  if (fExisted || IsMine(tx) || IsFromMe(tx))
1060  {
1061  /* Check if any keys in the wallet keypool that were supposed to be unused
1062  * have appeared in a new transaction. If so, remove those keys from the keypool.
1063  * This can happen when restoring an old wallet backup that does not contain
1064  * the mostly recently created transactions from newer versions of the wallet.
1065  */
1066 
1067  // loop though all outputs
1068  for (const CTxOut& txout: tx.vout) {
1069  // extract addresses and check if they match with an unused keypool key
1070  for (const auto& keyid : GetAffectedKeys(txout.scriptPubKey, *this)) {
1071  std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1072  if (mi != m_pool_key_to_index.end()) {
1073  WalletLogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1074  MarkReserveKeysAsUsed(mi->second);
1075 
1076  if (!TopUpKeyPool()) {
1077  WalletLogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1078  }
1079  }
1080  }
1081  }
1082 
1083  CWalletTx wtx(this, ptx);
1084 
1085  // Get merkle branch if transaction was found in a block
1086  if (!block_hash.IsNull())
1087  wtx.SetMerkleBranch(block_hash, posInBlock);
1088 
1089  return AddToWallet(wtx, false);
1090  }
1091  }
1092  return false;
1093 }
1094 
1096 {
1097  auto locked_chain = chain().lock();
1098  LOCK(cs_wallet);
1099  const CWalletTx* wtx = GetWalletTx(hashTx);
1100  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain(*locked_chain) == 0 && !wtx->InMempool();
1101 }
1102 
1104 {
1105  for (const CTxIn& txin : tx->vin) {
1106  auto it = mapWallet.find(txin.prevout.hash);
1107  if (it != mapWallet.end()) {
1108  it->second.MarkDirty();
1109  }
1110  }
1111 }
1112 
1114 {
1115  auto locked_chain_recursive = chain().lock(); // Temporary. Removed in upcoming lock cleanup
1116  LOCK(cs_wallet);
1117 
1118  WalletBatch batch(*database, "r+");
1119 
1120  std::set<uint256> todo;
1121  std::set<uint256> done;
1122 
1123  // Can't mark abandoned if confirmed or in mempool
1124  auto it = mapWallet.find(hashTx);
1125  assert(it != mapWallet.end());
1126  CWalletTx& origtx = it->second;
1127  if (origtx.GetDepthInMainChain(locked_chain) != 0 || origtx.InMempool()) {
1128  return false;
1129  }
1130 
1131  todo.insert(hashTx);
1132 
1133  while (!todo.empty()) {
1134  uint256 now = *todo.begin();
1135  todo.erase(now);
1136  done.insert(now);
1137  auto it = mapWallet.find(now);
1138  assert(it != mapWallet.end());
1139  CWalletTx& wtx = it->second;
1140  int currentconfirm = wtx.GetDepthInMainChain(locked_chain);
1141  // If the orig tx was not in block, none of its spends can be
1142  assert(currentconfirm <= 0);
1143  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1144  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1145  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1146  assert(!wtx.InMempool());
1147  wtx.nIndex = -1;
1148  wtx.setAbandoned();
1149  wtx.MarkDirty();
1150  batch.WriteTx(wtx);
1151  NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1152  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1153  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1154  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1155  if (!done.count(iter->second)) {
1156  todo.insert(iter->second);
1157  }
1158  iter++;
1159  }
1160  // If a transaction changes 'conflicted' state, that changes the balance
1161  // available of the outputs it spends. So force those to be recomputed
1162  MarkInputsDirty(wtx.tx);
1163  }
1164  }
1165 
1166  return true;
1167 }
1168 
1169 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1170 {
1171  auto locked_chain = chain().lock();
1172  LOCK(cs_wallet);
1173 
1174  int conflictconfirms = -locked_chain->getBlockDepth(hashBlock);
1175  // If number of conflict confirms cannot be determined, this means
1176  // that the block is still unknown or not yet part of the main chain,
1177  // for example when loading the wallet during a reindex. Do nothing in that
1178  // case.
1179  if (conflictconfirms >= 0)
1180  return;
1181 
1182  // Do not flush the wallet here for performance reasons
1183  WalletBatch batch(*database, "r+", false);
1184 
1185  std::set<uint256> todo;
1186  std::set<uint256> done;
1187 
1188  todo.insert(hashTx);
1189 
1190  while (!todo.empty()) {
1191  uint256 now = *todo.begin();
1192  todo.erase(now);
1193  done.insert(now);
1194  auto it = mapWallet.find(now);
1195  assert(it != mapWallet.end());
1196  CWalletTx& wtx = it->second;
1197  int currentconfirm = wtx.GetDepthInMainChain(*locked_chain);
1198  if (conflictconfirms < currentconfirm) {
1199  // Block is 'more conflicted' than current confirm; update.
1200  // Mark transaction as conflicted with this block.
1201  wtx.nIndex = -1;
1202  wtx.hashBlock = hashBlock;
1203  wtx.MarkDirty();
1204  batch.WriteTx(wtx);
1205  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1206  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1207  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1208  if (!done.count(iter->second)) {
1209  todo.insert(iter->second);
1210  }
1211  iter++;
1212  }
1213  // If a transaction changes 'conflicted' state, that changes the balance
1214  // available of the outputs it spends. So force those to be recomputed
1215  MarkInputsDirty(wtx.tx);
1216  }
1217  }
1218 }
1219 
1220 void CWallet::SyncTransaction(const CTransactionRef& ptx, const uint256& block_hash, int posInBlock, bool update_tx) {
1221  if (!AddToWalletIfInvolvingMe(ptx, block_hash, posInBlock, update_tx))
1222  return; // Not one of ours
1223 
1224  // If a transaction changes 'conflicted' state, that changes the balance
1225  // available of the outputs it spends. So force those to be
1226  // recomputed, also:
1227  MarkInputsDirty(ptx);
1228 }
1229 
1231  auto locked_chain = chain().lock();
1232  LOCK(cs_wallet);
1233  SyncTransaction(ptx, {} /* block hash */, 0 /* position in block */);
1234 
1235  auto it = mapWallet.find(ptx->GetHash());
1236  if (it != mapWallet.end()) {
1237  it->second.fInMempool = true;
1238  }
1239 }
1240 
1242  LOCK(cs_wallet);
1243  auto it = mapWallet.find(ptx->GetHash());
1244  if (it != mapWallet.end()) {
1245  it->second.fInMempool = false;
1246  }
1247 }
1248 
1249 void CWallet::BlockConnected(const CBlock& block, const std::vector<CTransactionRef>& vtxConflicted) {
1250  const uint256& block_hash = block.GetHash();
1251  auto locked_chain = chain().lock();
1252  LOCK(cs_wallet);
1253  // TODO: Temporarily ensure that mempool removals are notified before
1254  // connected transactions. This shouldn't matter, but the abandoned
1255  // state of transactions in our wallet is currently cleared when we
1256  // receive another notification and there is a race condition where
1257  // notification of a connected conflict might cause an outside process
1258  // to abandon a transaction and then have it inadvertently cleared by
1259  // the notification that the conflicted transaction was evicted.
1260 
1261  for (const CTransactionRef& ptx : vtxConflicted) {
1262  SyncTransaction(ptx, {} /* block hash */, 0 /* position in block */);
1263  TransactionRemovedFromMempool(ptx);
1264  }
1265  for (size_t i = 0; i < block.vtx.size(); i++) {
1266  SyncTransaction(block.vtx[i], block_hash, i);
1267  TransactionRemovedFromMempool(block.vtx[i]);
1268  }
1269 
1270  m_last_block_processed = block_hash;
1271 }
1272 
1274  auto locked_chain = chain().lock();
1275  LOCK(cs_wallet);
1276 
1277  for (const CTransactionRef& ptx : block.vtx) {
1278  SyncTransaction(ptx, {} /* block hash */, 0 /* position in block */);
1279  }
1280 }
1281 
1283 {
1284  m_best_block_time = GetTime();
1285 }
1286 
1287 
1289  AssertLockNotHeld(cs_wallet);
1290  // Skip the queue-draining stuff if we know we're caught up with
1291  // ::ChainActive().Tip(), otherwise put a callback in the validation interface queue and wait
1292  // for the queue to drain enough to execute it (indicating we are caught up
1293  // at least with the time we entered this function).
1294  uint256 last_block_hash = WITH_LOCK(cs_wallet, return m_last_block_processed);
1295  chain().waitForNotificationsIfNewBlocksConnected(last_block_hash);
1296 }
1297 
1298 
1300 {
1301  {
1302  LOCK(cs_wallet);
1303  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1304  if (mi != mapWallet.end())
1305  {
1306  const CWalletTx& prev = (*mi).second;
1307  if (txin.prevout.n < prev.tx->vout.size())
1308  return IsMine(prev.tx->vout[txin.prevout.n]);
1309  }
1310  }
1311  return ISMINE_NO;
1312 }
1313 
1314 // Note that this function doesn't distinguish between a 0-valued input,
1315 // and a not-"is mine" (according to the filter) input.
1316 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1317 {
1318  {
1319  LOCK(cs_wallet);
1320  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1321  if (mi != mapWallet.end())
1322  {
1323  const CWalletTx& prev = (*mi).second;
1324  if (txin.prevout.n < prev.tx->vout.size())
1325  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1326  return prev.tx->vout[txin.prevout.n].nValue;
1327  }
1328  }
1329  return 0;
1330 }
1331 
1332 isminetype CWallet::IsMine(const CTxOut& txout) const
1333 {
1334  return ::IsMine(*this, txout.scriptPubKey);
1335 }
1336 
1337 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1338 {
1339  if (!MoneyRange(txout.nValue))
1340  throw std::runtime_error(std::string(__func__) + ": value out of range");
1341  return ((IsMine(txout) & filter) ? txout.nValue : 0);
1342 }
1343 
1344 bool CWallet::IsChange(const CTxOut& txout) const
1345 {
1346  return IsChange(txout.scriptPubKey);
1347 }
1348 
1349 bool CWallet::IsChange(const CScript& script) const
1350 {
1351  // TODO: fix handling of 'change' outputs. The assumption is that any
1352  // payment to a script that is ours, but is not in the address book
1353  // is change. That assumption is likely to break when we implement multisignature
1354  // wallets that return change back into a multi-signature-protected address;
1355  // a better way of identifying which outputs are 'the send' and which are
1356  // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1357  // which output, if any, was change).
1358  if (::IsMine(*this, script))
1359  {
1360  CTxDestination address;
1361  if (!ExtractDestination(script, address))
1362  return true;
1363 
1364  LOCK(cs_wallet);
1365  if (!mapAddressBook.count(address))
1366  return true;
1367  }
1368  return false;
1369 }
1370 
1371 CAmount CWallet::GetChange(const CTxOut& txout) const
1372 {
1373  if (!MoneyRange(txout.nValue))
1374  throw std::runtime_error(std::string(__func__) + ": value out of range");
1375  return (IsChange(txout) ? txout.nValue : 0);
1376 }
1377 
1378 bool CWallet::IsMine(const CTransaction& tx) const
1379 {
1380  for (const CTxOut& txout : tx.vout)
1381  if (IsMine(txout))
1382  return true;
1383  return false;
1384 }
1385 
1387 {
1388  return (GetDebit(tx, ISMINE_ALL) > 0);
1389 }
1390 
1392 {
1393  CAmount nDebit = 0;
1394  for (const CTxIn& txin : tx.vin)
1395  {
1396  nDebit += GetDebit(txin, filter);
1397  if (!MoneyRange(nDebit))
1398  throw std::runtime_error(std::string(__func__) + ": value out of range");
1399  }
1400  return nDebit;
1401 }
1402 
1403 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1404 {
1405  LOCK(cs_wallet);
1406 
1407  for (const CTxIn& txin : tx.vin)
1408  {
1409  auto mi = mapWallet.find(txin.prevout.hash);
1410  if (mi == mapWallet.end())
1411  return false; // any unknown inputs can't be from us
1412 
1413  const CWalletTx& prev = (*mi).second;
1414 
1415  if (txin.prevout.n >= prev.tx->vout.size())
1416  return false; // invalid input!
1417 
1418  if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1419  return false;
1420  }
1421  return true;
1422 }
1423 
1425 {
1426  CAmount nCredit = 0;
1427  for (const CTxOut& txout : tx.vout)
1428  {
1429  nCredit += GetCredit(txout, filter);
1430  if (!MoneyRange(nCredit))
1431  throw std::runtime_error(std::string(__func__) + ": value out of range");
1432  }
1433  return nCredit;
1434 }
1435 
1437 {
1438  CAmount nChange = 0;
1439  for (const CTxOut& txout : tx.vout)
1440  {
1441  nChange += GetChange(txout);
1442  if (!MoneyRange(nChange))
1443  throw std::runtime_error(std::string(__func__) + ": value out of range");
1444  }
1445  return nChange;
1446 }
1447 
1449 {
1450  assert(!IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
1451  CKey key;
1452  key.MakeNewKey(true);
1453  return DeriveNewSeed(key);
1454 }
1455 
1457 {
1458  int64_t nCreationTime = GetTime();
1459  CKeyMetadata metadata(nCreationTime);
1460 
1461  // calculate the seed
1462  CPubKey seed = key.GetPubKey();
1463  assert(key.VerifyPubKey(seed));
1464 
1465  // set the hd keypath to "s" -> Seed, refers the seed to itself
1466  metadata.hdKeypath = "s";
1467  metadata.has_key_origin = false;
1468  metadata.hd_seed_id = seed.GetID();
1469 
1470  {
1471  LOCK(cs_wallet);
1472 
1473  // mem store the metadata
1474  mapKeyMetadata[seed.GetID()] = metadata;
1475 
1476  // write the key&metadata to the database
1477  if (!AddKeyPubKey(key, seed))
1478  throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1479  }
1480 
1481  return seed;
1482 }
1483 
1484 void CWallet::SetHDSeed(const CPubKey& seed)
1485 {
1486  LOCK(cs_wallet);
1487  // store the keyid (hash160) together with
1488  // the child index counter in the database
1489  // as a hdchain object
1490  CHDChain newHdChain;
1492  newHdChain.seed_id = seed.GetID();
1493  SetHDChain(newHdChain, false);
1494  NotifyCanGetAddressesChanged();
1495  UnsetWalletFlag(WALLET_FLAG_BLANK_WALLET);
1496 }
1497 
1498 void CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1499 {
1500  LOCK(cs_wallet);
1501  if (!memonly && !WalletBatch(*database).WriteHDChain(chain))
1502  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1503 
1504  hdChain = chain;
1505 }
1506 
1508 {
1509  return !hdChain.seed_id.IsNull();
1510 }
1511 
1513 {
1514  // A wallet can generate keys if it has an HD seed (IsHDEnabled) or it is a non-HD wallet (pre FEATURE_HD)
1515  LOCK(cs_wallet);
1516  return IsHDEnabled() || !CanSupportFeature(FEATURE_HD);
1517 }
1518 
1519 bool CWallet::CanGetAddresses(bool internal)
1520 {
1521  LOCK(cs_wallet);
1522  // Check if the keypool has keys
1523  bool keypool_has_keys;
1524  if (internal && CanSupportFeature(FEATURE_HD_SPLIT)) {
1525  keypool_has_keys = setInternalKeyPool.size() > 0;
1526  } else {
1527  keypool_has_keys = KeypoolCountExternalKeys() > 0;
1528  }
1529  // If the keypool doesn't have keys, check if we can generate them
1530  if (!keypool_has_keys) {
1531  return CanGenerateKeys();
1532  }
1533  return keypool_has_keys;
1534 }
1535 
1537 {
1538  LOCK(cs_wallet);
1539  m_wallet_flags |= flags;
1540  if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags))
1541  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1542 }
1543 
1544 void CWallet::UnsetWalletFlag(uint64_t flag)
1545 {
1546  LOCK(cs_wallet);
1547  m_wallet_flags &= ~flag;
1548  if (!WalletBatch(*database).WriteWalletFlags(m_wallet_flags))
1549  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1550 }
1551 
1552 bool CWallet::IsWalletFlagSet(uint64_t flag)
1553 {
1554  return (m_wallet_flags & flag);
1555 }
1556 
1557 bool CWallet::SetWalletFlags(uint64_t overwriteFlags, bool memonly)
1558 {
1559  LOCK(cs_wallet);
1560  m_wallet_flags = overwriteFlags;
1561  if (((overwriteFlags & g_known_wallet_flags) >> 32) ^ (overwriteFlags >> 32)) {
1562  // contains unknown non-tolerable wallet flags
1563  return false;
1564  }
1565  if (!memonly && !WalletBatch(*database).WriteWalletFlags(m_wallet_flags)) {
1566  throw std::runtime_error(std::string(__func__) + ": writing wallet flags failed");
1567  }
1568 
1569  return true;
1570 }
1571 
1572 int64_t CWalletTx::GetTxTime() const
1573 {
1574  int64_t n = nTimeSmart;
1575  return n ? n : nTimeReceived;
1576 }
1577 
1578 // Helper for producing a max-sized low-S low-R signature (eg 71 bytes)
1579 // or a max-sized low-S signature (e.g. 72 bytes) if use_max_sig is true
1580 bool CWallet::DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig) const
1581 {
1582  // Fill in dummy signatures for fee calculation.
1583  const CScript& scriptPubKey = txout.scriptPubKey;
1584  SignatureData sigdata;
1585 
1586  if (!ProduceSignature(*this, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigdata)) {
1587  return false;
1588  }
1589  UpdateInput(tx_in, sigdata);
1590  return true;
1591 }
1592 
1593 // Helper for producing a bunch of max-sized low-S low-R signatures (eg 71 bytes)
1594 bool CWallet::DummySignTx(CMutableTransaction &txNew, const std::vector<CTxOut> &txouts, bool use_max_sig) const
1595 {
1596  // Fill in dummy signatures for fee calculation.
1597  int nIn = 0;
1598  for (const auto& txout : txouts)
1599  {
1600  if (!DummySignInput(txNew.vin[nIn], txout, use_max_sig)) {
1601  return false;
1602  }
1603 
1604  nIn++;
1605  }
1606  return true;
1607 }
1608 
1610 {
1611  std::vector<CTxOut> txouts;
1612  // Look up the inputs. We should have already checked that this transaction
1613  // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
1614  // wallet, with a valid index into the vout array, and the ability to sign.
1615  for (const CTxIn& input : tx.vin) {
1616  const auto mi = wallet->mapWallet.find(input.prevout.hash);
1617  if (mi == wallet->mapWallet.end()) {
1618  return -1;
1619  }
1620  assert(input.prevout.n < mi->second.tx->vout.size());
1621  txouts.emplace_back(mi->second.tx->vout[input.prevout.n]);
1622  }
1623  return CalculateMaximumSignedTxSize(tx, wallet, txouts, use_max_sig);
1624 }
1625 
1626 // txouts needs to be in the order of tx.vin
1627 int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector<CTxOut>& txouts, bool use_max_sig)
1628 {
1629  CMutableTransaction txNew(tx);
1630  if (!wallet->DummySignTx(txNew, txouts, use_max_sig)) {
1631  // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
1632  // implies that we can sign for every input.
1633  return -1;
1634  }
1635  return GetVirtualTransactionSize(CTransaction(txNew));
1636 }
1637 
1638 int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* wallet, bool use_max_sig)
1639 {
1640  CMutableTransaction txn;
1641  txn.vin.push_back(CTxIn(COutPoint()));
1642  if (!wallet->DummySignInput(txn.vin[0], txout, use_max_sig)) {
1643  return -1;
1644  }
1645  return GetVirtualTransactionInputSize(txn.vin[0]);
1646 }
1647 
1648 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1649  std::list<COutputEntry>& listSent, CAmount& nFee, const isminefilter& filter) const
1650 {
1651  nFee = 0;
1652  listReceived.clear();
1653  listSent.clear();
1654 
1655  // Compute fee:
1656  CAmount nDebit = GetDebit(filter);
1657  if (nDebit > 0) // debit>0 means we signed/sent this transaction
1658  {
1659  CAmount nValueOut = tx->GetValueOut();
1660  nFee = nDebit - nValueOut;
1661  }
1662 
1663  // Sent/received.
1664  for (unsigned int i = 0; i < tx->vout.size(); ++i)
1665  {
1666  const CTxOut& txout = tx->vout[i];
1667  isminetype fIsMine = pwallet->IsMine(txout);
1668  // Only need to handle txouts if AT LEAST one of these is true:
1669  // 1) they debit from us (sent)
1670  // 2) the output is to us (received)
1671  if (nDebit > 0)
1672  {
1673  // Don't report 'change' txouts
1674  if (pwallet->IsChange(txout))
1675  continue;
1676  }
1677  else if (!(fIsMine & filter))
1678  continue;
1679 
1680  // In either case, we need to get the destination address
1681  CTxDestination address;
1682 
1683  if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1684  {
1685  pwallet->WalletLogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1686  this->GetHash().ToString());
1687  address = CNoDestination();
1688  }
1689 
1690  COutputEntry output = {address, txout.nValue, (int)i};
1691 
1692  // If we are debited by the transaction, add the output as a "sent" entry
1693  if (nDebit > 0)
1694  listSent.push_back(output);
1695 
1696  // If we are receiving the output, add it as a "received" entry
1697  if (fIsMine & filter)
1698  listReceived.push_back(output);
1699  }
1700 
1701 }
1702 
1711 int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& reserver, bool update)
1712 {
1713  // Find starting block. May be null if nCreateTime is greater than the
1714  // highest blockchain timestamp, in which case there is nothing that needs
1715  // to be scanned.
1716  uint256 start_block;
1717  {
1718  auto locked_chain = chain().lock();
1719  const Optional<int> start_height = locked_chain->findFirstBlockWithTimeAndHeight(startTime - TIMESTAMP_WINDOW, 0, &start_block);
1720  const Optional<int> tip_height = locked_chain->getHeight();
1721  WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, tip_height && start_height ? *tip_height - *start_height + 1 : 0);
1722  }
1723 
1724  if (!start_block.IsNull()) {
1725  // TODO: this should take into account failure by ScanResult::USER_ABORT
1726  ScanResult result = ScanForWalletTransactions(start_block, {} /* stop_block */, reserver, update);
1727  if (result.status == ScanResult::FAILURE) {
1728  int64_t time_max;
1729  if (!chain().findBlock(result.last_failed_block, nullptr /* block */, nullptr /* time */, &time_max)) {
1730  throw std::logic_error("ScanForWalletTransactions returned invalid block hash");
1731  }
1732  return time_max + TIMESTAMP_WINDOW + 1;
1733  }
1734  }
1735  return startTime;
1736 }
1737 
1759 CWallet::ScanResult CWallet::ScanForWalletTransactions(const uint256& start_block, const uint256& stop_block, const WalletRescanReserver& reserver, bool fUpdate)
1760 {
1761  int64_t nNow = GetTime();
1762  int64_t start_time = GetTimeMillis();
1763 
1764  assert(reserver.isReserved());
1765 
1766  uint256 block_hash = start_block;
1767  ScanResult result;
1768 
1769  WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
1770 
1771  fAbortRescan = false;
1772  ShowProgress(strprintf("%s " + _("Rescanning..."), GetDisplayName()), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1773  uint256 tip_hash;
1774  // The way the 'block_height' is initialized is just a workaround for the gcc bug #47679 since version 4.6.0.
1775  Optional<int> block_height = MakeOptional(false, int());
1776  double progress_begin;
1777  double progress_end;
1778  {
1779  auto locked_chain = chain().lock();
1780  if (Optional<int> tip_height = locked_chain->getHeight()) {
1781  tip_hash = locked_chain->getBlockHash(*tip_height);
1782  }
1783  block_height = locked_chain->getBlockHeight(block_hash);
1784  progress_begin = chain().guessVerificationProgress(block_hash);
1785  progress_end = chain().guessVerificationProgress(stop_block.IsNull() ? tip_hash : stop_block);
1786  }
1787  double progress_current = progress_begin;
1788  while (block_height && !fAbortRescan && !chain().shutdownRequested()) {
1789  m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);
1790  if (*block_height % 100 == 0 && progress_end - progress_begin > 0.0) {
1791  ShowProgress(strprintf("%s " + _("Rescanning..."), GetDisplayName()), std::max(1, std::min(99, (int)(m_scanning_progress * 100))));
1792  }
1793  if (GetTime() >= nNow + 60) {
1794  nNow = GetTime();
1795  WalletLogPrintf("Still rescanning. At block %d. Progress=%f\n", *block_height, progress_current);
1796  }
1797 
1798  CBlock block;
1799  if (chain().findBlock(block_hash, &block) && !block.IsNull()) {
1800  auto locked_chain = chain().lock();
1801  LOCK(cs_wallet);
1802  if (!locked_chain->getBlockHeight(block_hash)) {
1803  // Abort scan if current block is no longer active, to prevent
1804  // marking transactions as coming from the wrong block.
1805  // TODO: This should return success instead of failure, see
1806  // https://github.com/bitcoin/bitcoin/pull/14711#issuecomment-458342518
1807  result.last_failed_block = block_hash;
1808  result.status = ScanResult::FAILURE;
1809  break;
1810  }
1811  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1812  SyncTransaction(block.vtx[posInBlock], block_hash, posInBlock, fUpdate);
1813  }
1814  // scan succeeded, record block as most recent successfully scanned
1815  result.last_scanned_block = block_hash;
1816  result.last_scanned_height = *block_height;
1817  } else {
1818  // could not scan block, keep scanning but record this block as the most recent failure
1819  result.last_failed_block = block_hash;
1820  result.status = ScanResult::FAILURE;
1821  }
1822  if (block_hash == stop_block) {
1823  break;
1824  }
1825  {
1826  auto locked_chain = chain().lock();
1827  Optional<int> tip_height = locked_chain->getHeight();
1828  if (!tip_height || *tip_height <= block_height || !locked_chain->getBlockHeight(block_hash)) {
1829  // break successfully when rescan has reached the tip, or
1830  // previous block is no longer on the chain due to a reorg
1831  break;
1832  }
1833 
1834  // increment block and verification progress
1835  block_hash = locked_chain->getBlockHash(++*block_height);
1836  progress_current = chain().guessVerificationProgress(block_hash);
1837 
1838  // handle updated tip hash
1839  const uint256 prev_tip_hash = tip_hash;
1840  tip_hash = locked_chain->getBlockHash(*tip_height);
1841  if (stop_block.IsNull() && prev_tip_hash != tip_hash) {
1842  // in case the tip has changed, update progress max
1843  progress_end = chain().guessVerificationProgress(tip_hash);
1844  }
1845  }
1846  }
1847  ShowProgress(strprintf("%s " + _("Rescanning..."), GetDisplayName()), 100); // hide progress dialog in GUI
1848  if (block_height && fAbortRescan) {
1849  WalletLogPrintf("Rescan aborted at block %d. Progress=%f\n", *block_height, progress_current);
1850  result.status = ScanResult::USER_ABORT;
1851  } else if (block_height && chain().shutdownRequested()) {
1852  WalletLogPrintf("Rescan interrupted by shutdown request at block %d. Progress=%f\n", *block_height, progress_current);
1853  result.status = ScanResult::USER_ABORT;
1854  } else {
1855  WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - start_time);
1856  }
1857  return result;
1858 }
1859 
1861 {
1862  // If transactions aren't being broadcasted, don't let them into local mempool either
1863  if (!fBroadcastTransactions)
1864  return;
1865  std::map<int64_t, CWalletTx*> mapSorted;
1866 
1867  // Sort pending wallet transactions based on their initial wallet insertion order
1868  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1869  {
1870  const uint256& wtxid = item.first;
1871  CWalletTx& wtx = item.second;
1872  assert(wtx.GetHash() == wtxid);
1873 
1874  int nDepth = wtx.GetDepthInMainChain(locked_chain);
1875 
1876  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1877  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1878  }
1879  }
1880 
1881  // Try to add wallet transactions to memory pool
1882  for (const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1883  CWalletTx& wtx = *(item.second);
1884  CValidationState state;
1885  wtx.AcceptToMemoryPool(locked_chain, state);
1886  }
1887 }
1888 
1890 {
1891  // Can't relay if wallet is not broadcasting
1892  if (!pwallet->GetBroadcastTransactions()) return false;
1893  // Don't relay coinbase transactions outside blocks
1894  if (IsCoinBase()) return false;
1895  // Don't relay abandoned transactions
1896  if (isAbandoned()) return false;
1897  // Don't relay conflicted or already confirmed transactions
1898  if (GetDepthInMainChain(locked_chain) != 0) return false;
1899  // Don't relay transactions that aren't accepted to the mempool
1900  CValidationState unused_state;
1901  if (!InMempool() && !AcceptToMemoryPool(locked_chain, unused_state)) return false;
1902  // Don't try to relay if the node is not connected to the p2p network
1903  if (!pwallet->chain().p2pEnabled()) return false;
1904 
1905  // Try to relay the transaction
1906  pwallet->WalletLogPrintf("Relaying wtx %s\n", GetHash().ToString());
1907  pwallet->chain().relayTransaction(GetHash());
1908 
1909  return true;
1910 }
1911 
1912 std::set<uint256> CWalletTx::GetConflicts() const
1913 {
1914  std::set<uint256> result;
1915  if (pwallet != nullptr)
1916  {
1917  uint256 myHash = GetHash();
1918  result = pwallet->GetConflicts(myHash);
1919  result.erase(myHash);
1920  }
1921  return result;
1922 }
1923 
1924 CAmount CWalletTx::GetCachableAmount(AmountType type, const isminefilter& filter, bool recalculate) const
1925 {
1926  auto& amount = m_amounts[type];
1927  if (recalculate || !amount.m_cached[filter]) {
1928  amount.Set(filter, type == DEBIT ? pwallet->GetDebit(*tx, filter) : pwallet->GetCredit(*tx, filter));
1929  }
1930  return amount.m_value[filter];
1931 }
1932 
1934 {
1935  if (tx->vin.empty())
1936  return 0;
1937 
1938  CAmount debit = 0;
1939  if (filter & ISMINE_SPENDABLE) {
1940  debit += GetCachableAmount(DEBIT, ISMINE_SPENDABLE);
1941  }
1942  if (filter & ISMINE_WATCH_ONLY) {
1943  debit += GetCachableAmount(DEBIT, ISMINE_WATCH_ONLY);
1944  }
1945  return debit;
1946 }
1947 
1949 {
1950  // Must wait until coinbase is safely deep enough in the chain before valuing it
1951  if (IsImmatureCoinBase(locked_chain))
1952  return 0;
1953 
1954  CAmount credit = 0;
1955  if (filter & ISMINE_SPENDABLE) {
1956  // GetBalance can assume transactions in mapWallet won't change
1957  credit += GetCachableAmount(CREDIT, ISMINE_SPENDABLE);
1958  }
1959  if (filter & ISMINE_WATCH_ONLY) {
1960  credit += GetCachableAmount(CREDIT, ISMINE_WATCH_ONLY);
1961  }
1962  return credit;
1963 }
1964 
1966 {
1967  if (IsImmatureCoinBase(locked_chain) && IsInMainChain(locked_chain)) {
1968  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_SPENDABLE, !fUseCache);
1969  }
1970 
1971  return 0;
1972 }
1973 
1974 CAmount CWalletTx::GetAvailableCredit(interfaces::Chain::Lock& locked_chain, bool fUseCache, const isminefilter& filter) const
1975 {
1976  if (pwallet == nullptr)
1977  return 0;
1978 
1979  // Avoid caching ismine for NO or ALL cases (could remove this check and simplify in the future).
1980  bool allow_cache = filter == ISMINE_SPENDABLE || filter == ISMINE_WATCH_ONLY;
1981 
1982  // Must wait until coinbase is safely deep enough in the chain before valuing it
1983  if (IsImmatureCoinBase(locked_chain))
1984  return 0;
1985 
1986  if (fUseCache && allow_cache && m_amounts[AVAILABLE_CREDIT].m_cached[filter]) {
1987  return m_amounts[AVAILABLE_CREDIT].m_value[filter];
1988  }
1989 
1990  CAmount nCredit = 0;
1991  uint256 hashTx = GetHash();
1992  for (unsigned int i = 0; i < tx->vout.size(); i++)
1993  {
1994  if (!pwallet->IsSpent(locked_chain, hashTx, i))
1995  {
1996  const CTxOut &txout = tx->vout[i];
1997  nCredit += pwallet->GetCredit(txout, filter);
1998  if (!MoneyRange(nCredit))
1999  throw std::runtime_error(std::string(__func__) + " : value out of range");
2000  }
2001  }
2002 
2003  if (allow_cache) {
2004  m_amounts[AVAILABLE_CREDIT].Set(filter, nCredit);
2005  }
2006 
2007  return nCredit;
2008 }
2009 
2011 {
2012  if (IsImmatureCoinBase(locked_chain) && IsInMainChain(locked_chain)) {
2013  return GetCachableAmount(IMMATURE_CREDIT, ISMINE_WATCH_ONLY, !fUseCache);
2014  }
2015 
2016  return 0;
2017 }
2018 
2020 {
2021  if (fChangeCached)
2022  return nChangeCached;
2023  nChangeCached = pwallet->GetChange(*tx);
2024  fChangeCached = true;
2025  return nChangeCached;
2026 }
2027 
2029 {
2030  return fInMempool;
2031 }
2032 
2034 {
2035  // Quick answer in most cases
2036  if (!locked_chain.checkFinalTx(*tx)) {
2037  return false;
2038  }
2039  int nDepth = GetDepthInMainChain(locked_chain);
2040  if (nDepth >= 1)
2041  return true;
2042  if (nDepth < 0)
2043  return false;
2044  if (!pwallet->m_spend_zero_conf_change || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
2045  return false;
2046 
2047  // Don't trust unconfirmed transactions from us unless they are in the mempool.
2048  if (!InMempool())
2049  return false;
2050 
2051  // Trusted if all inputs are from us and are in the mempool:
2052  for (const CTxIn& txin : tx->vin)
2053  {
2054  // Transactions not sent by us: not trusted
2055  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
2056  if (parent == nullptr)
2057  return false;
2058  const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
2059  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
2060  return false;
2061  }
2062  return true;
2063 }
2064 
2065 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
2066 {
2067  CMutableTransaction tx1 {*this->tx};
2068  CMutableTransaction tx2 {*_tx.tx};
2069  for (auto& txin : tx1.vin) txin.scriptSig = CScript();
2070  for (auto& txin : tx2.vin) txin.scriptSig = CScript();
2071  return CTransaction(tx1) == CTransaction(tx2);
2072 }
2073 
2074 // Rebroadcast transactions from the wallet. We do this on a random timer
2075 // to slightly obfuscate which transactions come from our wallet.
2076 //
2077 // Ideally, we'd only resend transactions that we think should have been
2078 // mined in the most recent block. Any transaction that wasn't in the top
2079 // blockweight of transactions in the mempool shouldn't have been mined,
2080 // and so is probably just sitting in the mempool waiting to be confirmed.
2081 // Rebroadcasting does nothing to speed up confirmation and only damages
2082 // privacy.
2084 {
2085  // During reindex, importing and IBD, old wallet transactions become
2086  // unconfirmed. Don't resend them as that would spam other nodes.
2087  if (!chain().isReadyToBroadcast()) return;
2088 
2089  // Do this infrequently and randomly to avoid giving away
2090  // that these are our transactions.
2091  if (GetTime() < nNextResend || !fBroadcastTransactions) return;
2092  bool fFirst = (nNextResend == 0);
2093  nNextResend = GetTime() + GetRand(30 * 60);
2094  if (fFirst) return;
2095 
2096  // Only do it if there's been a new block since last time
2097  if (m_best_block_time < nLastResend) return;
2098  nLastResend = GetTime();
2099 
2100  int relayed_tx_count = 0;
2101 
2102  { // locked_chain and cs_wallet scope
2103  auto locked_chain = chain().lock();
2104  LOCK(cs_wallet);
2105 
2106  // Relay transactions
2107  for (std::pair<const uint256, CWalletTx>& item : mapWallet) {
2108  CWalletTx& wtx = item.second;
2109  // only rebroadcast unconfirmed txes older than 5 minutes before the
2110  // last block was found
2111  if (wtx.nTimeReceived > m_best_block_time - 5 * 60) continue;
2112  if (wtx.RelayWalletTransaction(*locked_chain)) ++relayed_tx_count;
2113  }
2114  } // locked_chain and cs_wallet
2115 
2116  if (relayed_tx_count > 0) {
2117  WalletLogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed_tx_count);
2118  }
2119 }
2120  // end of mapWallet
2122 
2124 {
2125  for (const std::shared_ptr<CWallet>& pwallet : GetWallets()) {
2126  pwallet->ResendWalletTransactions();
2127  }
2128 }
2129 
2130 
2137 CWallet::Balance CWallet::GetBalance(const int min_depth) const
2138 {
2139  Balance ret;
2140  {
2141  auto locked_chain = chain().lock();
2142  LOCK(cs_wallet);
2143  for (const auto& entry : mapWallet)
2144  {
2145  const CWalletTx& wtx = entry.second;
2146  const bool is_trusted{wtx.IsTrusted(*locked_chain)};
2147  const int tx_depth{wtx.GetDepthInMainChain(*locked_chain)};
2148  const CAmount tx_credit_mine{wtx.GetAvailableCredit(*locked_chain, /* fUseCache */ true, ISMINE_SPENDABLE)};
2149  const CAmount tx_credit_watchonly{wtx.GetAvailableCredit(*locked_chain, /* fUseCache */ true, ISMINE_WATCH_ONLY)};
2150  if (is_trusted && tx_depth >= min_depth) {
2151  ret.m_mine_trusted += tx_credit_mine;
2152  ret.m_watchonly_trusted += tx_credit_watchonly;
2153  }
2154  if (!is_trusted && tx_depth == 0 && wtx.InMempool()) {
2155  ret.m_mine_untrusted_pending += tx_credit_mine;
2156  ret.m_watchonly_untrusted_pending += tx_credit_watchonly;
2157  }
2158  ret.m_mine_immature += wtx.GetImmatureCredit(*locked_chain);
2159  ret.m_watchonly_immature += wtx.GetImmatureWatchOnlyCredit(*locked_chain);
2160  }
2161  }
2162  return ret;
2163 }
2164 
2166 {
2167  auto locked_chain = chain().lock();
2168  LOCK(cs_wallet);
2169 
2170  CAmount balance = 0;
2171  std::vector<COutput> vCoins;
2172  AvailableCoins(*locked_chain, vCoins, true, coinControl);
2173  for (const COutput& out : vCoins) {
2174  if (out.fSpendable) {
2175  balance += out.tx->tx->vout[out.i].nValue;
2176  }
2177  }
2178  return balance;
2179 }
2180 
2181 void CWallet::AvailableCoins(interfaces::Chain::Lock& locked_chain, std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount, const int nMinDepth, const int nMaxDepth) const
2182 {
2183  AssertLockHeld(cs_wallet);
2184 
2185  vCoins.clear();
2186  CAmount nTotal = 0;
2187 
2188  for (const auto& entry : mapWallet)
2189  {
2190  const uint256& wtxid = entry.first;
2191  const CWalletTx& wtx = entry.second;
2192 
2193  if (!locked_chain.checkFinalTx(*wtx.tx)) {
2194  continue;
2195  }
2196 
2197  if (wtx.IsImmatureCoinBase(locked_chain))
2198  continue;
2199 
2200  int nDepth = wtx.GetDepthInMainChain(locked_chain);
2201  if (nDepth < 0)
2202  continue;
2203 
2204  // We should not consider coins which aren't at least in our mempool
2205  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2206  if (nDepth == 0 && !wtx.InMempool())
2207  continue;
2208 
2209  bool safeTx = wtx.IsTrusted(locked_chain);
2210 
2211  // We should not consider coins from transactions that are replacing
2212  // other transactions.
2213  //
2214  // Example: There is a transaction A which is replaced by bumpfee
2215  // transaction B. In this case, we want to prevent creation of
2216  // a transaction B' which spends an output of B.
2217  //
2218  // Reason: If transaction A were initially confirmed, transactions B
2219  // and B' would no longer be valid, so the user would have to create
2220  // a new transaction C to replace B'. However, in the case of a
2221  // one-block reorg, transactions B' and C might BOTH be accepted,
2222  // when the user only wanted one of them. Specifically, there could
2223  // be a 1-block reorg away from the chain where transactions A and C
2224  // were accepted to another chain where B, B', and C were all
2225  // accepted.
2226  if (nDepth == 0 && wtx.mapValue.count("replaces_txid")) {
2227  safeTx = false;
2228  }
2229 
2230  // Similarly, we should not consider coins from transactions that
2231  // have been replaced. In the example above, we would want to prevent
2232  // creation of a transaction A' spending an output of A, because if
2233  // transaction B were initially confirmed, conflicting with A and
2234  // A', we wouldn't want to the user to create a transaction D
2235  // intending to replace A', but potentially resulting in a scenario
2236  // where A, A', and D could all be accepted (instead of just B and
2237  // D, or just A and A' like the user would want).
2238  if (nDepth == 0 && wtx.mapValue.count("replaced_by_txid")) {
2239  safeTx = false;
2240  }
2241 
2242  if (fOnlySafe && !safeTx) {
2243  continue;
2244  }
2245 
2246  if (nDepth < nMinDepth || nDepth > nMaxDepth)
2247  continue;
2248 
2249  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++) {
2250  if (wtx.tx->vout[i].nValue < nMinimumAmount || wtx.tx->vout[i].nValue > nMaximumAmount)
2251  continue;
2252 
2253  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2254  continue;
2255 
2256  if (IsLockedCoin(entry.first, i))
2257  continue;
2258 
2259  if (IsSpent(locked_chain, wtxid, i))
2260  continue;
2261 
2262  isminetype mine = IsMine(wtx.tx->vout[i]);
2263 
2264  if (mine == ISMINE_NO) {
2265  continue;
2266  }
2267 
2268  bool solvable = IsSolvable(*this, wtx.tx->vout[i].scriptPubKey);
2269  bool spendable = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (((mine & ISMINE_WATCH_ONLY) != ISMINE_NO) && (coinControl && coinControl->fAllowWatchOnly && solvable));
2270 
2271  vCoins.push_back(COutput(&wtx, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->fAllowWatchOnly)));
2272 
2273  // Checks the sum amount of all UTXO's.
2274  if (nMinimumSumAmount != MAX_MONEY) {
2275  nTotal += wtx.tx->vout[i].nValue;
2276 
2277  if (nTotal >= nMinimumSumAmount) {
2278  return;
2279  }
2280  }
2281 
2282  // Checks the maximum number of UTXO's.
2283  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2284  return;
2285  }
2286  }
2287  }
2288 }
2289 
2290 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins(interfaces::Chain::Lock& locked_chain) const
2291 {
2292  AssertLockHeld(cs_wallet);
2293 
2294  std::map<CTxDestination, std::vector<COutput>> result;
2295  std::vector<COutput> availableCoins;
2296 
2297  AvailableCoins(locked_chain, availableCoins);
2298 
2299  for (const COutput& coin : availableCoins) {
2300  CTxDestination address;
2301  if (coin.fSpendable &&
2302  ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2303  result[address].emplace_back(std::move(coin));
2304  }
2305  }
2306 
2307  std::vector<COutPoint> lockedCoins;
2308  ListLockedCoins(lockedCoins);
2309  for (const COutPoint& output : lockedCoins) {
2310  auto it = mapWallet.find(output.hash);
2311  if (it != mapWallet.end()) {
2312  int depth = it->second.GetDepthInMainChain(locked_chain);
2313  if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2314  IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2315  CTxDestination address;
2316  if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2317  result[address].emplace_back(
2318  &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2319  }
2320  }
2321  }
2322  }
2323 
2324  return result;
2325 }
2326 
2328 {
2329  const CTransaction* ptx = &tx;
2330  int n = output;
2331  while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2332  const COutPoint& prevout = ptx->vin[0].prevout;
2333  auto it = mapWallet.find(prevout.hash);
2334  if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2335  !IsMine(it->second.tx->vout[prevout.n])) {
2336  break;
2337  }
2338  ptx = it->second.tx.get();
2339  n = prevout.n;
2340  }
2341  return ptx->vout[n];
2342 }
2343 
2344 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, std::vector<OutputGroup> groups,
2345  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CoinSelectionParams& coin_selection_params, bool& bnb_used) const
2346 {
2347  setCoinsRet.clear();
2348  nValueRet = 0;
2349 
2350  std::vector<OutputGroup> utxo_pool;
2351  if (coin_selection_params.use_bnb) {
2352  // Get long term estimate
2353  FeeCalculation feeCalc;
2354  CCoinControl temp;
2355  temp.m_confirm_target = 1008;
2356  CFeeRate long_term_feerate = GetMinimumFeeRate(*this, temp, &feeCalc);
2357 
2358  // Calculate cost of change
2359  CAmount cost_of_change = GetDiscardRate(*this).GetFee(coin_selection_params.change_spend_size) + coin_selection_params.effective_fee.GetFee(coin_selection_params.change_output_size);
2360 
2361  // Filter by the min conf specs and add to utxo_pool and calculate effective value
2362  for (OutputGroup& group : groups) {
2363  if (!group.EligibleForSpending(eligibility_filter)) continue;
2364 
2365  group.fee = 0;
2366  group.long_term_fee = 0;
2367  group.effective_value = 0;
2368  for (auto it = group.m_outputs.begin(); it != group.m_outputs.end(); ) {
2369  const CInputCoin& coin = *it;
2370  CAmount effective_value = coin.txout.nValue - (coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes));
2371  // Only include outputs that are positive effective value (i.e. not dust)
2372  if (effective_value > 0) {
2373  group.fee += coin.m_input_bytes < 0 ? 0 : coin_selection_params.effective_fee.GetFee(coin.m_input_bytes);
2374  group.long_term_fee += coin.m_input_bytes < 0 ? 0 : long_term_feerate.GetFee(coin.m_input_bytes);
2375  group.effective_value += effective_value;
2376  ++it;
2377  } else {
2378  it = group.Discard(coin);
2379  }
2380  }
2381  if (group.effective_value > 0) utxo_pool.push_back(group);
2382  }
2383  // Calculate the fees for things that aren't inputs
2384  CAmount not_input_fees = coin_selection_params.effective_fee.GetFee(coin_selection_params.tx_noinputs_size);
2385  bnb_used = true;
2386  return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
2387  } else {
2388  // Filter by the min conf specs and add to utxo_pool
2389  for (const OutputGroup& group : groups) {
2390  if (!group.EligibleForSpending(eligibility_filter)) continue;
2391  utxo_pool.push_back(group);
2392  }
2393  bnb_used = false;
2394  return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
2395  }
2396 }
2397 
2398 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl& coin_control, CoinSelectionParams& coin_selection_params, bool& bnb_used) const
2399 {
2400  std::vector<COutput> vCoins(vAvailableCoins);
2401 
2402  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2403  if (coin_control.HasSelected() && !coin_control.fAllowOtherInputs)
2404  {
2405  // We didn't use BnB here, so set it to false.
2406  bnb_used = false;
2407 
2408  for (const COutput& out : vCoins)
2409  {
2410  if (!out.fSpendable)
2411  continue;
2412  nValueRet += out.tx->tx->vout[out.i].nValue;
2413  setCoinsRet.insert(out.GetInputCoin());
2414  }
2415  return (nValueRet >= nTargetValue);
2416  }
2417 
2418  // calculate value from preset inputs and store them
2419  std::set<CInputCoin> setPresetCoins;
2420  CAmount nValueFromPresetInputs = 0;
2421 
2422  std::vector<COutPoint> vPresetInputs;
2423  coin_control.ListSelected(vPresetInputs);
2424  for (const COutPoint& outpoint : vPresetInputs)
2425  {
2426  // For now, don't use BnB if preset inputs are selected. TODO: Enable this later
2427  bnb_used = false;
2428  coin_selection_params.use_bnb = false;
2429 
2430  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2431  if (it != mapWallet.end())
2432  {
2433  const CWalletTx& wtx = it->second;
2434  // Clearly invalid input, fail
2435  if (wtx.tx->vout.size() <= outpoint.n)
2436  return false;
2437  // Just to calculate the marginal byte size
2438  nValueFromPresetInputs += wtx.tx->vout[outpoint.n].nValue;
2439  setPresetCoins.insert(CInputCoin(wtx.tx, outpoint.n));
2440  } else
2441  return false; // TODO: Allow non-wallet inputs
2442  }
2443 
2444  // remove preset inputs from vCoins
2445  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.HasSelected();)
2446  {
2447  if (setPresetCoins.count(it->GetInputCoin()))
2448  it = vCoins.erase(it);
2449  else
2450  ++it;
2451  }
2452 
2453  // form groups from remaining coins; note that preset coins will not
2454  // automatically have their associated (same address) coins included
2455  if (coin_control.m_avoid_partial_spends && vCoins.size() > OUTPUT_GROUP_MAX_ENTRIES) {
2456  // Cases where we have 11+ outputs all pointing to the same destination may result in
2457  // privacy leaks as they will potentially be deterministically sorted. We solve that by
2458  // explicitly shuffling the outputs before processing
2459  Shuffle(vCoins.begin(), vCoins.end(), FastRandomContext());
2460  }
2461  std::vector<OutputGroup> groups = GroupOutputs(vCoins, !coin_control.m_avoid_partial_spends);
2462 
2463  size_t max_ancestors = (size_t)std::max<int64_t>(1, gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT));
2464  size_t max_descendants = (size_t)std::max<int64_t>(1, gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2465  bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2466 
2467  bool res = nTargetValue <= nValueFromPresetInputs ||
2468  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 6, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2469  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(1, 1, 0), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used) ||
2470  (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, 2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2471  (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::min((size_t)4, max_ancestors/3), std::min((size_t)4, max_descendants/3)), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2472  (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors/2, max_descendants/2), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2473  (m_spend_zero_conf_change && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, max_ancestors-1, max_descendants-1), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used)) ||
2474  (m_spend_zero_conf_change && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, CoinEligibilityFilter(0, 1, std::numeric_limits<uint64_t>::max()), groups, setCoinsRet, nValueRet, coin_selection_params, bnb_used));
2475 
2476  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2477  util::insert(setCoinsRet, setPresetCoins);
2478 
2479  // add preset inputs to the total value selected
2480  nValueRet += nValueFromPresetInputs;
2481 
2482  return res;
2483 }
2484 
2486 {
2487  AssertLockHeld(cs_wallet);
2488 
2489  // sign the new tx
2490  int nIn = 0;
2491  for (auto& input : tx.vin) {
2492  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2493  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2494  return false;
2495  }
2496  const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2497  const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2498  SignatureData sigdata;
2499  if (!ProduceSignature(*this, MutableTransactionSignatureCreator(&tx, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2500  return false;
2501  }
2502  UpdateInput(input, sigdata);
2503  nIn++;
2504  }
2505  return true;
2506 }
2507 
2508 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2509 {
2510  std::vector<CRecipient> vecSend;
2511 
2512  // Turn the txout set into a CRecipient vector.
2513  for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2514  const CTxOut& txOut = tx.vout[idx];
2515  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2516  vecSend.push_back(recipient);
2517  }
2518 
2519  coinControl.fAllowOtherInputs = true;
2520 
2521  for (const CTxIn& txin : tx.vin) {
2522  coinControl.Select(txin.prevout);
2523  }
2524 
2525  // Acquire the locks to prevent races to the new locked unspents between the
2526  // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2527  auto locked_chain = chain().lock();
2528  LOCK(cs_wallet);
2529 
2530  CReserveKey reservekey(this);
2531  CTransactionRef tx_new;
2532  if (!CreateTransaction(*locked_chain, vecSend, tx_new, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2533  return false;
2534  }
2535 
2536  if (nChangePosInOut != -1) {
2537  tx.vout.insert(tx.vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
2538  // We don't have the normal Create/Commit cycle, and don't want to risk
2539  // reusing change, so just remove the key from the keypool here.
2540  reservekey.KeepKey();
2541  }
2542 
2543  // Copy output sizes from new transaction; they may have had the fee
2544  // subtracted from them.
2545  for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
2546  tx.vout[idx].nValue = tx_new->vout[idx].nValue;
2547  }
2548 
2549  // Add new txins while keeping original txin scriptSig/order.
2550  for (const CTxIn& txin : tx_new->vin) {
2551  if (!coinControl.IsSelected(txin.prevout)) {
2552  tx.vin.push_back(txin);
2553 
2554  if (lockUnspents) {
2555  LockCoin(txin.prevout);
2556  }
2557  }
2558  }
2559 
2560  return true;
2561 }
2562 
2563 static bool IsCurrentForAntiFeeSniping(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain)
2564 {
2565  if (chain.isInitialBlockDownload()) {
2566  return false;
2567  }
2568  constexpr int64_t MAX_ANTI_FEE_SNIPING_TIP_AGE = 8 * 60 * 60; // in seconds
2569  if (locked_chain.getBlockTime(*locked_chain.getHeight()) < (GetTime() - MAX_ANTI_FEE_SNIPING_TIP_AGE)) {
2570  return false;
2571  }
2572  return true;
2573 }
2574 
2579 static uint32_t GetLocktimeForNewTransaction(interfaces::Chain& chain, interfaces::Chain::Lock& locked_chain)
2580 {
2581  uint32_t const height = locked_chain.getHeight().get_value_or(-1);
2582  uint32_t locktime;
2583  // Discourage fee sniping.
2584  //
2585  // For a large miner the value of the transactions in the best block and
2586  // the mempool can exceed the cost of deliberately attempting to mine two
2587  // blocks to orphan the current best block. By setting nLockTime such that
2588  // only the next block can include the transaction, we discourage this
2589  // practice as the height restricted and limited blocksize gives miners
2590  // considering fee sniping fewer options for pulling off this attack.
2591  //
2592  // A simple way to think about this is from the wallet's point of view we
2593  // always want the blockchain to move forward. By setting nLockTime this
2594  // way we're basically making the statement that we only want this
2595  // transaction to appear in the next block; we don't want to potentially
2596  // encourage reorgs by allowing transactions to appear at lower heights
2597  // than the next block in forks of the best chain.
2598  //
2599  // Of course, the subsidy is high enough, and transaction volume low
2600  // enough, that fee sniping isn't a problem yet, but by implementing a fix
2601  // now we ensure code won't be written that makes assumptions about
2602  // nLockTime that preclude a fix later.
2603  if (IsCurrentForAntiFeeSniping(chain, locked_chain)) {
2604  locktime = height;
2605 
2606  // Secondly occasionally randomly pick a nLockTime even further back, so
2607  // that transactions that are delayed after signing for whatever reason,
2608  // e.g. high-latency mix networks and some CoinJoin implementations, have
2609  // better privacy.
2610  if (GetRandInt(10) == 0)
2611  locktime = std::max(0, (int)locktime - GetRandInt(100));
2612  } else {
2613  // If our chain is lagging behind, we can't discourage fee sniping nor help
2614  // the privacy of high-latency transactions. To avoid leaking a potentially
2615  // unique "nLockTime fingerprint", set nLockTime to a constant.
2616  locktime = 0;
2617  }
2618  assert(locktime <= height);
2619  assert(locktime < LOCKTIME_THRESHOLD);
2620  return locktime;
2621 }
2622 
2623 OutputType CWallet::TransactionChangeType(OutputType change_type, const std::vector<CRecipient>& vecSend)
2624 {
2625  // If -changetype is specified, always use that change type.
2626  if (change_type != OutputType::CHANGE_AUTO) {
2627  return change_type;
2628  }
2629 
2630  // if m_default_address_type is legacy, use legacy address as change (even
2631  // if some of the outputs are P2WPKH or P2WSH).
2632  if (m_default_address_type == OutputType::LEGACY) {
2633  return OutputType::LEGACY;
2634  }
2635 
2636  // if any destination is P2WPKH or P2WSH, use P2WPKH for the change
2637  // output.
2638  for (const auto& recipient : vecSend) {
2639  // Check if any destination contains a witness program:
2640  int witnessversion = 0;
2641  std::vector<unsigned char> witnessprogram;
2642  if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2643  return OutputType::BECH32;
2644  }
2645  }
2646 
2647  // else use m_default_address_type for change
2648  return m_default_address_type;
2649 }
2650 
2651 bool CWallet::CreateTransaction(interfaces::Chain::Lock& locked_chain, const std::vector<CRecipient>& vecSend, CTransactionRef& tx, CReserveKey& reservekey, CAmount& nFeeRet,
2652  int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2653 {
2654  CAmount nValue = 0;
2655  int nChangePosRequest = nChangePosInOut;
2656  unsigned int nSubtractFeeFromAmount = 0;
2657  for (const auto& recipient : vecSend)
2658  {
2659  if (nValue < 0 || recipient.nAmount < 0)
2660  {
2661  strFailReason = _("Transaction amounts must not be negative");
2662  return false;
2663  }
2664  nValue += recipient.nAmount;
2665 
2666  if (recipient.fSubtractFeeFromAmount)
2667  nSubtractFeeFromAmount++;
2668  }
2669  if (vecSend.empty())
2670  {
2671  strFailReason = _("Transaction must have at least one recipient");
2672  return false;
2673  }
2674 
2675  CMutableTransaction txNew;
2676 
2677  txNew.nLockTime = GetLocktimeForNewTransaction(chain(), locked_chain);
2678 
2679  FeeCalculation feeCalc;
2680  CAmount nFeeNeeded;
2681  int nBytes;
2682  {
2683  std::set<CInputCoin> setCoins;
2684  auto locked_chain = chain().lock();
2685  LOCK(cs_wallet);
2686  {
2687  std::vector<COutput> vAvailableCoins;
2688  AvailableCoins(*locked_chain, vAvailableCoins, true, &coin_control, 1, MAX_MONEY, MAX_MONEY, 0, coin_control.m_min_depth);
2689  CoinSelectionParams coin_selection_params; // Parameters for coin selection, init with dummy
2690 
2691  // Create change script that will be used if we need change
2692  // TODO: pass in scriptChange instead of reservekey so
2693  // change transaction isn't always pay-to-bitcoin-address
2694  CScript scriptChange;
2695 
2696  // coin control: send change to custom address
2697  if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2698  scriptChange = GetScriptForDestination(coin_control.destChange);
2699  } else { // no coin control: send change to newly generated address
2700  // Note: We use a new key here to keep it from being obvious which side is the change.
2701  // The drawback is that by not reusing a previous key, the change may be lost if a
2702  // backup is restored, if the backup doesn't have the new private key for the change.
2703  // If we reused the old key, it would be possible to add code to look for and
2704  // rediscover unknown transactions that were written with keys of ours to recover
2705  // post-backup change.
2706 
2707  // Reserve a new key pair from key pool
2708  if (!CanGetAddresses(true)) {
2709  strFailReason = _("Can't generate a change-address key. No keys in the internal keypool and can't generate any keys.");
2710  return false;
2711  }
2712  CPubKey vchPubKey;
2713  bool ret;
2714  ret = reservekey.GetReservedKey(vchPubKey, true);
2715  if (!ret)
2716  {
2717  strFailReason = _("Keypool ran out, please call keypoolrefill first");
2718  return false;
2719  }
2720 
2721  const OutputType change_type = TransactionChangeType(coin_control.m_change_type ? *coin_control.m_change_type : m_default_change_type, vecSend);
2722 
2723  LearnRelatedScripts(vchPubKey, change_type);
2724  scriptChange = GetScriptForDestination(GetDestinationForKey(vchPubKey, change_type));
2725  }
2726  CTxOut change_prototype_txout(0, scriptChange);
2727  coin_selection_params.change_output_size = GetSerializeSize(change_prototype_txout);
2728 
2729  CFeeRate discard_rate = GetDiscardRate(*this);
2730 
2731  // Get the fee rate to use effective values in coin selection
2732  CFeeRate nFeeRateNeeded = GetMinimumFeeRate(*this, coin_control, &feeCalc);
2733 
2734  nFeeRet = 0;
2735  bool pick_new_inputs = true;
2736  CAmount nValueIn = 0;
2737 
2738  // BnB selector is the only selector used when this is true.
2739  // That should only happen on the first pass through the loop.
2740  coin_selection_params.use_bnb = nSubtractFeeFromAmount == 0; // If we are doing subtract fee from recipient, then don't use BnB
2741  // Start with no fee and loop until there is enough fee
2742  while (true)
2743  {
2744  nChangePosInOut = nChangePosRequest;
2745  txNew.vin.clear();
2746  txNew.vout.clear();
2747  bool fFirst = true;
2748 
2749  CAmount nValueToSelect = nValue;
2750  if (nSubtractFeeFromAmount == 0)
2751  nValueToSelect += nFeeRet;
2752 
2753  // vouts to the payees
2754  coin_selection_params.tx_noinputs_size = 11; // Static vsize overhead + outputs vsize. 4 nVersion, 4 nLocktime, 1 input count, 1 output count, 1 witness overhead (dummy, flag, stack size)
2755  for (const auto& recipient : vecSend)
2756  {
2757  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2758 
2759  if (recipient.fSubtractFeeFromAmount)
2760  {
2761  assert(nSubtractFeeFromAmount != 0);
2762  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2763 
2764  if (fFirst) // first receiver pays the remainder not divisible by output count
2765  {
2766  fFirst = false;
2767  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2768  }
2769  }
2770  // Include the fee cost for outputs. Note this is only used for BnB right now
2771  coin_selection_params.tx_noinputs_size += ::GetSerializeSize(txout, PROTOCOL_VERSION);
2772 
2773  if (IsDust(txout, chain().relayDustFee()))
2774  {
2775  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2776  {
2777  if (txout.nValue < 0)
2778  strFailReason = _("The transaction amount is too small to pay the fee");
2779  else
2780  strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2781  }
2782  else
2783  strFailReason = _("Transaction amount too small");
2784  return false;
2785  }
2786  txNew.vout.push_back(txout);
2787  }
2788 
2789  // Choose coins to use
2790  bool bnb_used;
2791  if (pick_new_inputs) {
2792  nValueIn = 0;
2793  setCoins.clear();
2794  int change_spend_size = CalculateMaximumSignedInputSize(change_prototype_txout, this);
2795  // If the wallet doesn't know how to sign change output, assume p2sh-p2wpkh
2796  // as lower-bound to allow BnB to do it's thing
2797  if (change_spend_size == -1) {
2798  coin_selection_params.change_spend_size = DUMMY_NESTED_P2WPKH_INPUT_SIZE;
2799  } else {
2800  coin_selection_params.change_spend_size = (size_t)change_spend_size;
2801  }
2802  coin_selection_params.effective_fee = nFeeRateNeeded;
2803  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coin_control, coin_selection_params, bnb_used))
2804  {
2805  // If BnB was used, it was the first pass. No longer the first pass and continue loop with knapsack.
2806  if (bnb_used) {
2807  coin_selection_params.use_bnb = false;
2808  continue;
2809  }
2810  else {
2811  strFailReason = _("Insufficient funds");
2812  return false;
2813  }
2814  }
2815  } else {
2816  bnb_used = false;
2817  }
2818 
2819  const CAmount nChange = nValueIn - nValueToSelect;
2820  if (nChange > 0)
2821  {
2822  // Fill a vout to ourself
2823  CTxOut newTxOut(nChange, scriptChange);
2824 
2825  // Never create dust outputs; if we would, just
2826  // add the dust to the fee.
2827  // The nChange when BnB is used is always going to go to fees.
2828  if (IsDust(newTxOut, discard_rate) || bnb_used)
2829  {
2830  nChangePosInOut = -1;
2831  nFeeRet += nChange;
2832  }
2833  else
2834  {
2835  if (nChangePosInOut == -1)
2836  {
2837  // Insert change txn at random position:
2838  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2839  }
2840  else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2841  {
2842  strFailReason = _("Change index out of range");
2843  return false;
2844  }
2845 
2846  std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2847  txNew.vout.insert(position, newTxOut);
2848  }
2849  } else {
2850  nChangePosInOut = -1;
2851  }
2852 
2853  // Dummy fill vin for maximum size estimation
2854  //
2855  for (const auto& coin : setCoins) {
2856  txNew.vin.push_back(CTxIn(coin.outpoint,CScript()));
2857  }
2858 
2859  nBytes = CalculateMaximumSignedTxSize(CTransaction(txNew), this, coin_control.fAllowWatchOnly);
2860  if (nBytes < 0) {
2861  strFailReason = _("Signing transaction failed");
2862  return false;
2863  }
2864 
2865  nFeeNeeded = GetMinimumFee(*this, nBytes, coin_control, &feeCalc);
2866  if (feeCalc.reason == FeeReason::FALLBACK && !m_allow_fallback_fee) {
2867  // eventually allow a fallback fee
2868  strFailReason = _("Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
2869  return false;
2870  }
2871 
2872  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2873  // because we must be at the maximum allowed fee.
2874  if (nFeeNeeded < chain().relayMinFee().GetFee(nBytes))
2875  {
2876  strFailReason = _("Transaction too large for fee policy");
2877  return false;
2878  }
2879 
2880  if (nFeeRet >= nFeeNeeded) {
2881  // Reduce fee to only the needed amount if possible. This
2882  // prevents potential overpayment in fees if the coins
2883  // selected to meet nFeeNeeded result in a transaction that
2884  // requires less fee than the prior iteration.
2885 
2886  // If we have no change and a big enough excess fee, then
2887  // try to construct transaction again only without picking
2888  // new inputs. We now know we only need the smaller fee
2889  // (because of reduced tx size) and so we should add a
2890  // change output. Only try this once.
2891  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2892  unsigned int tx_size_with_change = nBytes + coin_selection_params.change_output_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2893  CAmount fee_needed_with_change = GetMinimumFee(*this, tx_size_with_change, coin_control, nullptr);
2894  CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2895  if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2896  pick_new_inputs = false;
2897  nFeeRet = fee_needed_with_change;
2898  continue;
2899  }
2900  }
2901 
2902  // If we have change output already, just increase it
2903  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2904  CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2905  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2906  change_position->nValue += extraFeePaid;
2907  nFeeRet -= extraFeePaid;
2908  }
2909  break; // Done, enough fee included.
2910  }
2911  else if (!pick_new_inputs) {
2912  // This shouldn't happen, we should have had enough excess
2913  // fee to pay for the new output and still meet nFeeNeeded
2914  // Or we should have just subtracted fee from recipients and
2915  // nFeeNeeded should not have changed
2916  strFailReason = _("Transaction fee and change calculation failed");
2917  return false;
2918  }
2919 
2920  // Try to reduce change to include necessary fee
2921  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2922  CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2923  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2924  // Only reduce change if remaining amount is still a large enough output.
2925  if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2926  change_position->nValue -= additionalFeeNeeded;
2927  nFeeRet += additionalFeeNeeded;
2928  break; // Done, able to increase fee from change
2929  }
2930  }
2931 
2932  // If subtracting fee from recipients, we now know what fee we
2933  // need to subtract, we have no reason to reselect inputs
2934  if (nSubtractFeeFromAmount > 0) {
2935  pick_new_inputs = false;
2936  }
2937 
2938  // Include more fee and try again.
2939  nFeeRet = nFeeNeeded;
2940  coin_selection_params.use_bnb = false;
2941  continue;
2942  }
2943  }
2944 
2945  if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2946 
2947  // Shuffle selected coins and fill in final vin
2948  txNew.vin.clear();
2949  std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
2950  Shuffle(selected_coins.begin(), selected_coins.end(), FastRandomContext());
2951 
2952  // Note how the sequence number is set to non-maxint so that
2953  // the nLockTime set above actually works.
2954  //
2955  // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2956  // we use the highest possible value in that range (maxint-2)
2957  // to avoid conflicting with other possible uses of nSequence,
2958  // and in the spirit of "smallest possible change from prior
2959  // behavior."
2960  const uint32_t nSequence = coin_control.m_signal_bip125_rbf.get_value_or(m_signal_rbf) ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2961  for (const auto& coin : selected_coins) {
2962  txNew.vin.push_back(CTxIn(coin.outpoint, CScript(), nSequence));
2963  }
2964 
2965  if (sign)
2966  {
2967  int nIn = 0;
2968  for (const auto& coin : selected_coins)
2969  {
2970  const CScript& scriptPubKey = coin.txout.scriptPubKey;
2971  SignatureData sigdata;
2972 
2973  if (!ProduceSignature(*this, MutableTransactionSignatureCreator(&txNew, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2974  {
2975  strFailReason = _("Signing transaction failed");
2976  return false;
2977  } else {
2978  UpdateInput(txNew.vin.at(nIn), sigdata);
2979  }
2980 
2981  nIn++;
2982  }
2983  }
2984 
2985  // Return the constructed transaction data.
2986  tx = MakeTransactionRef(std::move(txNew));
2987 
2988  // Limit size
2989  if (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT)
2990  {
2991  strFailReason = _("Transaction too large");
2992  return false;
2993  }
2994  }
2995 
2996  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2997  // Lastly, ensure this tx will pass the mempool's chain limits
2998  if (!chain().checkChainLimits(tx)) {
2999  strFailReason = _("Transaction has too long of a mempool chain");
3000  return false;
3001  }
3002  }
3003 
3004  WalletLogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
3005  nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
3006  feeCalc.est.pass.start, feeCalc.est.pass.end,
3007  100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
3008  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
3009  feeCalc.est.fail.start, feeCalc.est.fail.end,
3010  100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
3011  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3012  return true;
3013 }
3014 
3018 bool CWallet::CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector<std::pair<std::string, std::string>> orderForm, CReserveKey& reservekey, CValidationState& state)
3019 {
3020  {
3021  auto locked_chain = chain().lock();
3022  LOCK(cs_wallet);
3023 
3024  CWalletTx wtxNew(this, std::move(tx));
3025  wtxNew.mapValue = std::move(mapValue);
3026  wtxNew.vOrderForm = std::move(orderForm);
3027  wtxNew.fTimeReceivedIsTxTime = true;
3028  wtxNew.fFromMe = true;
3029 
3030  WalletLogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString()); /* Continued */
3031  {
3032  // Take key pair from key pool so it won't be used again
3033  reservekey.KeepKey();
3034 
3035  // Add tx to wallet, because if it has change it's also ours,
3036  // otherwise just for transaction history.
3037  AddToWallet(wtxNew);
3038 
3039  // Notify that old coins are spent
3040  for (const CTxIn& txin : wtxNew.tx->vin)
3041  {
3042  CWalletTx &coin = mapWallet.at(txin.prevout.hash);
3043  coin.BindWallet(this);
3044  NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3045  }
3046  }
3047 
3048  // Get the inserted-CWalletTx from mapWallet so that the
3049  // fInMempool flag is cached properly
3050  CWalletTx& wtx = mapWallet.at(wtxNew.GetHash());
3051 
3052  if (fBroadcastTransactions)
3053  {
3054  // Broadcast
3055  if (!wtx.AcceptToMemoryPool(*locked_chain, state)) {
3056  WalletLogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", FormatStateMessage(state));
3057  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3058  } else {
3059  wtx.RelayWalletTransaction(*locked_chain);
3060  }
3061  }
3062  }
3063  return true;
3064 }
3065 
3066 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3067 {
3068  LOCK(cs_wallet);
3069 
3070  fFirstRunRet = false;
3071  DBErrors nLoadWalletRet = WalletBatch(*database,"cr+").LoadWallet(this);
3072  if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3073  {
3074  if (database->Rewrite("\x04pool"))
3075  {
3076  setInternalKeyPool.clear();
3077  setExternalKeyPool.clear();
3078  m_pool_key_to_index.clear();
3079  // Note: can't top-up keypool here, because wallet is locked.
3080  // User will be prompted to unlock wallet the next operation
3081  // that requires a new key.
3082  }
3083  }
3084 
3085  {
3086  LOCK(cs_KeyStore);
3087  // This wallet is in its first run if all of these are empty
3088  fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty()
3089  && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET);
3090  }
3091 
3092  if (nLoadWalletRet != DBErrors::LOAD_OK)
3093  return nLoadWalletRet;
3094 
3095  return DBErrors::LOAD_OK;
3096 }
3097 
3098 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3099 {
3100  AssertLockHeld(cs_wallet);
3101  DBErrors nZapSelectTxRet = WalletBatch(*database, "cr+").ZapSelectTx(vHashIn, vHashOut);
3102  for (uint256 hash : vHashOut) {
3103  const auto& it = mapWallet.find(hash);
3104  wtxOrdered.erase(it->second.m_it_wtxOrdered);
3105  mapWallet.erase(it);
3106  }
3107 
3108  if (nZapSelectTxRet == DBErrors::NEED_REWRITE)
3109  {
3110  if (database->Rewrite("\x04pool"))
3111  {
3112  setInternalKeyPool.clear();
3113  setExternalKeyPool.clear();
3114  m_pool_key_to_index.clear();
3115  // Note: can't top-up keypool here, because wallet is locked.
3116  // User will be prompted to unlock wallet the next operation
3117  // that requires a new key.
3118  }
3119  }
3120 
3121  if (nZapSelectTxRet != DBErrors::LOAD_OK)
3122  return nZapSelectTxRet;
3123 
3124  MarkDirty();
3125 
3126  return DBErrors::LOAD_OK;
3127 }
3128 
3129 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3130 {
3131  DBErrors nZapWalletTxRet = WalletBatch(*database,"cr+").ZapWalletTx(vWtx);
3132  if (nZapWalletTxRet == DBErrors::NEED_REWRITE)
3133  {
3134  if (database->Rewrite("\x04pool"))
3135  {
3136  LOCK(cs_wallet);
3137  setInternalKeyPool.clear();
3138  setExternalKeyPool.clear();
3139  m_pool_key_to_index.clear();
3140  // Note: can't top-up keypool here, because wallet is locked.
3141  // User will be prompted to unlock wallet the next operation
3142  // that requires a new key.
3143  }
3144  }
3145 
3146  if (nZapWalletTxRet != DBErrors::LOAD_OK)
3147  return nZapWalletTxRet;
3148 
3149  return DBErrors::LOAD_OK;
3150 }
3151 
3152 
3153 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3154 {
3155  bool fUpdated = false;
3156  {
3157  LOCK(cs_wallet);
3158  std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3159  fUpdated = mi != mapAddressBook.end();
3160  mapAddressBook[address].name = strName;
3161  if (!strPurpose.empty()) /* update purpose only if requested */
3162  mapAddressBook[address].purpose = strPurpose;
3163  }
3164  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3165  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3166  if (!strPurpose.empty() && !WalletBatch(*database).WritePurpose(EncodeDestination(address), strPurpose))
3167  return false;
3168  return WalletBatch(*database).WriteName(EncodeDestination(address), strName);
3169 }
3170 
3172 {
3173  {
3174  LOCK(cs_wallet);
3175 
3176  // Delete destdata tuples associated with address
3177  std::string strAddress = EncodeDestination(address);
3178  for (const std::pair<const std::string, std::string> &item : mapAddressBook[address].destdata)
3179  {
3180  WalletBatch(*database).EraseDestData(strAddress, item.first);
3181  }
3182  mapAddressBook.erase(address);
3183  }
3184 
3185  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3186 
3187  WalletBatch(*database).ErasePurpose(EncodeDestination(address));
3188  return WalletBatch(*database).EraseName(EncodeDestination(address));
3189 }
3190 
3191 const std::string& CWallet::GetLabelName(const CScript& scriptPubKey) const
3192 {
3193  CTxDestination address;
3194  if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3195  auto mi = mapAddressBook.find(address);
3196  if (mi != mapAddressBook.end()) {
3197  return mi->second.name;
3198  }
3199  }
3200  // A scriptPubKey that doesn't have an entry in the address book is
3201  // associated with the default label ("").
3202  const static std::string DEFAULT_LABEL_NAME;
3203  return DEFAULT_LABEL_NAME;
3204 }
3205 
3211 {
3212  if (IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3213  return false;
3214  }
3215  {
3216  LOCK(cs_wallet);
3217  WalletBatch batch(*database);
3218 
3219  for (const int64_t nIndex : setInternalKeyPool) {
3220  batch.ErasePool(nIndex);
3221  }
3222  setInternalKeyPool.clear();
3223 
3224  for (const int64_t nIndex : setExternalKeyPool) {
3225  batch.ErasePool(nIndex);
3226  }
3227  setExternalKeyPool.clear();
3228 
3229  for (const int64_t nIndex : set_pre_split_keypool) {
3230  batch.ErasePool(nIndex);
3231  }
3232  set_pre_split_keypool.clear();
3233 
3234  m_pool_key_to_index.clear();
3235 
3236  if (!TopUpKeyPool()) {
3237  return false;
3238  }
3239  WalletLogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3240  }
3241  return true;
3242 }
3243 
3245 {
3246  AssertLockHeld(cs_wallet);
3247  return setExternalKeyPool.size() + set_pre_split_keypool.size();
3248 }
3249 
3250 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3251 {
3252  AssertLockHeld(cs_wallet);
3253  if (keypool.m_pre_split) {
3254  set_pre_split_keypool.insert(nIndex);
3255  } else if (keypool.fInternal) {
3256  setInternalKeyPool.insert(nIndex);
3257  } else {
3258  setExternalKeyPool.insert(nIndex);
3259  }
3260  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3261  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3262 
3263  // If no metadata exists yet, create a default with the pool key's
3264  // creation time. Note that this may be overwritten by actually
3265  // stored metadata for that key later, which is fine.
3266  CKeyID keyid = keypool.vchPubKey.GetID();
3267  if (mapKeyMetadata.count(keyid) == 0)
3268  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3269 }
3270 
3271 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3272 {
3273  if (!CanGenerateKeys()) {
3274  return false;
3275  }
3276  {
3277  LOCK(cs_wallet);
3278 
3279  if (IsLocked())
3280  return false;
3281 
3282  // Top up key pool
3283  unsigned int nTargetSize;
3284  if (kpSize > 0)
3285  nTargetSize = kpSize;
3286  else
3287  nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3288 
3289  // count amount of available keys (internal, external)
3290  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3291  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3292  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3293 
3294  if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3295  {
3296  // don't create extra internal keys
3297  missingInternal = 0;
3298  }
3299  bool internal = false;
3300  WalletBatch batch(*database);
3301  for (int64_t i = missingInternal + missingExternal; i--;)
3302  {
3303  if (i < missingInternal) {
3304  internal = true;
3305  }
3306 
3307  CPubKey pubkey(GenerateNewKey(batch, internal));
3308  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
3309  }
3310  if (missingInternal + missingExternal > 0) {
3311  WalletLogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size() + set_pre_split_keypool.size(), setInternalKeyPool.size());
3312  }
3313  }
3314  NotifyCanGetAddressesChanged();
3315  return true;
3316 }
3317 
3318 void CWallet::AddKeypoolPubkey(const CPubKey& pubkey, const bool internal)
3319 {
3320  WalletBatch batch(*database);
3321  AddKeypoolPubkeyWithDB(pubkey, internal, batch);
3322  NotifyCanGetAddressesChanged();
3323 }
3324 
3325 void CWallet::AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch)
3326 {
3327  LOCK(cs_wallet);
3328  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3329  int64_t index = ++m_max_keypool_index;
3330  if (!batch.WritePool(index, CKeyPool(pubkey, internal))) {
3331  throw std::runtime_error(std::string(__func__) + ": writing imported pubkey failed");
3332  }
3333  if (internal) {
3334  setInternalKeyPool.insert(index);
3335  } else {
3336  setExternalKeyPool.insert(index);
3337  }
3338  m_pool_key_to_index[pubkey.GetID()] = index;
3339 }
3340 
3341 bool CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3342 {
3343  nIndex = -1;
3344  keypool.vchPubKey = CPubKey();
3345  {
3346  LOCK(cs_wallet);
3347 
3348  if (!IsLocked())
3349  TopUpKeyPool();
3350 
3351  bool fReturningInternal = fRequestedInternal;
3352  fReturningInternal &= (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) || IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
3353  bool use_split_keypool = set_pre_split_keypool.empty();
3354  std::set<int64_t>& setKeyPool = use_split_keypool ? (fReturningInternal ? setInternalKeyPool : setExternalKeyPool) : set_pre_split_keypool;
3355 
3356  // Get the oldest key
3357  if (setKeyPool.empty()) {
3358  return false;
3359  }
3360 
3361  WalletBatch batch(*database);
3362 
3363  auto it = setKeyPool.begin();
3364  nIndex = *it;
3365  setKeyPool.erase(it);
3366  if (!batch.ReadPool(nIndex, keypool)) {
3367  throw std::runtime_error(std::string(__func__) + ": read failed");
3368  }
3369  CPubKey pk;
3370  if (!GetPubKey(keypool.vchPubKey.GetID(), pk)) {
3371  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3372  }
3373  // If the key was pre-split keypool, we don't care about what type it is
3374  if (use_split_keypool && keypool.fInternal != fReturningInternal) {
3375  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3376  }
3377  if (!keypool.vchPubKey.IsValid()) {
3378  throw std::runtime_error(std::string(__func__) + ": keypool entry invalid");
3379  }
3380 
3381  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3382  WalletLogPrintf("keypool reserve %d\n", nIndex);
3383  }
3384  NotifyCanGetAddressesChanged();
3385  return true;
3386 }
3387 
3388 void CWallet::KeepKey(int64_t nIndex)
3389 {
3390  // Remove from key pool
3391  WalletBatch batch(*database);
3392  batch.ErasePool(nIndex);
3393  WalletLogPrintf("keypool keep %d\n", nIndex);
3394 }
3395 
3396 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3397 {
3398  // Return to key pool
3399  {
3400  LOCK(cs_wallet);
3401  if (fInternal) {
3402  setInternalKeyPool.insert(nIndex);
3403  } else if (!set_pre_split_keypool.empty()) {
3404  set_pre_split_keypool.insert(nIndex);
3405  } else {
3406  setExternalKeyPool.insert(nIndex);
3407  }
3408  m_pool_key_to_index[pubkey.GetID()] = nIndex;
3409  NotifyCanGetAddressesChanged();
3410  }
3411  WalletLogPrintf("keypool return %d\n", nIndex);
3412 }
3413 
3414 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3415 {
3416  if (!CanGetAddresses(internal)) {
3417  return false;
3418  }
3419 
3420  CKeyPool keypool;
3421  {
3422  LOCK(cs_wallet);
3423  int64_t nIndex;
3424  if (!ReserveKeyFromKeyPool(nIndex, keypool, internal) && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
3425  if (IsLocked()) return false;
3426  WalletBatch batch(*database);
3427  result = GenerateNewKey(batch, internal);
3428  return true;
3429  }
3430  KeepKey(nIndex);
3431  result = keypool.vchPubKey;
3432  }
3433  return true;
3434 }
3435 
3436 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, WalletBatch& batch) {
3437  if (setKeyPool.empty()) {
3438  return GetTime();
3439  }
3440 
3441  CKeyPool keypool;
3442  int64_t nIndex = *(setKeyPool.begin());
3443  if (!batch.ReadPool(nIndex, keypool)) {
3444  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3445  }
3446  assert(keypool.vchPubKey.IsValid());
3447  return keypool.nTime;
3448 }
3449 
3451 {
3452  LOCK(cs_wallet);
3453 
3454  WalletBatch batch(*database);
3455 
3456  // load oldest key from keypool, get time and return
3457  int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
3458  if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3459  oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, batch), oldestKey);
3460  if (!set_pre_split_keypool.empty()) {
3461  oldestKey = std::max(GetOldestKeyTimeInPool(set_pre_split_keypool, batch), oldestKey);
3462  }
3463  }
3464 
3465  return oldestKey;
3466 }
3467 
3468 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances(interfaces::Chain::Lock& locked_chain)
3469 {
3470  std::map<CTxDestination, CAmount> balances;
3471 
3472  {
3473  LOCK(cs_wallet);
3474  for (const auto& walletEntry : mapWallet)
3475  {
3476  const CWalletTx& wtx = walletEntry.second;
3477 
3478  if (!wtx.IsTrusted(locked_chain))
3479  continue;
3480 
3481  if (wtx.IsImmatureCoinBase(locked_chain))
3482  continue;
3483 
3484  int nDepth = wtx.GetDepthInMainChain(locked_chain);
3485  if (nDepth < (wtx.IsFromMe(ISMINE_ALL) ? 0 : 1))
3486  continue;
3487 
3488  for (unsigned int i = 0; i < wtx.tx->vout.size(); i++)
3489  {
3490  CTxDestination addr;
3491  if (!IsMine(wtx.tx->vout[i]))
3492  continue;
3493  if(!ExtractDestination(wtx.tx->vout[i].scriptPubKey, addr))
3494  continue;
3495 
3496  CAmount n = IsSpent(locked_chain, walletEntry.first, i) ? 0 : wtx.tx->vout[i].nValue;
3497 
3498  if (!balances.count(addr))
3499  balances[addr] = 0;
3500  balances[addr] += n;
3501  }
3502  }
3503  }
3504 
3505  return balances;
3506 }
3507 
3508 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3509 {
3510  AssertLockHeld(cs_wallet);
3511  std::set< std::set<CTxDestination> > groupings;
3512  std::set<CTxDestination> grouping;
3513 
3514  for (const auto& walletEntry : mapWallet)
3515  {
3516  const CWalletTx& wtx = walletEntry.second;
3517 
3518  if (wtx.tx->vin.size() > 0)
3519  {
3520  bool any_mine = false;
3521  // group all input addresses with each other
3522  for (const CTxIn& txin : wtx.tx->vin)
3523  {
3524  CTxDestination address;
3525  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3526  continue;
3527  if(!ExtractDestination(mapWallet.at(txin.prevout.hash).tx->vout[txin.prevout.n].scriptPubKey, address))
3528  continue;
3529  grouping.insert(address);
3530  any_mine = true;
3531  }
3532 
3533  // group change with input addresses
3534  if (any_mine)
3535  {
3536  for (const CTxOut& txout : wtx.tx->vout)
3537  if (IsChange(txout))
3538  {
3539  CTxDestination txoutAddr;
3540  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3541  continue;
3542  grouping.insert(txoutAddr);
3543  }
3544  }
3545  if (grouping.size() > 0)
3546  {
3547  groupings.insert(grouping);
3548  grouping.clear();
3549  }
3550  }
3551 
3552  // group lone addrs by themselves
3553  for (const auto& txout : wtx.tx->vout)
3554  if (IsMine(txout))
3555  {
3556  CTxDestination address;
3557  if(!ExtractDestination(txout.scriptPubKey, address))
3558  continue;
3559  grouping.insert(address);
3560  groupings.insert(grouping);
3561  grouping.clear();
3562  }
3563  }
3564 
3565  std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3566  std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3567  for (std::set<CTxDestination> _grouping : groupings)
3568  {
3569  // make a set of all the groups hit by this new group
3570  std::set< std::set<CTxDestination>* > hits;
3571  std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3572  for (const CTxDestination& address : _grouping)
3573  if ((it = setmap.find(address)) != setmap.end())
3574  hits.insert((*it).second);
3575 
3576  // merge all hit groups into a new single group and delete old groups
3577  std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3578  for (std::set<CTxDestination>* hit : hits)
3579  {
3580  merged->insert(hit->begin(), hit->end());
3581  uniqueGroupings.erase(hit);
3582  delete hit;
3583  }
3584  uniqueGroupings.insert(merged);
3585 
3586  // update setmap
3587  for (const CTxDestination& element : *merged)
3588  setmap[element] = merged;
3589  }
3590 
3591  std::set< std::set<CTxDestination> > ret;
3592  for (const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3593  {
3594  ret.insert(*uniqueGrouping);
3595  delete uniqueGrouping;
3596  }
3597 
3598  return ret;
3599 }
3600 
3601 std::set<CTxDestination> CWallet::GetLabelAddresses(const std::string& label) const
3602 {
3603  LOCK(cs_wallet);
3604  std::set<CTxDestination> result;
3605  for (const std::pair<const CTxDestination, CAddressBookData>& item : mapAddressBook)
3606  {
3607  const CTxDestination& address = item.first;
3608  const std::string& strName = item.second.name;
3609  if (strName == label)
3610  result.insert(address);
3611  }
3612  return result;
3613 }
3614 
3615 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3616 {
3617  if (!pwallet->CanGetAddresses(internal)) {
3618  return false;
3619  }
3620 
3621  if (nIndex == -1)
3622  {
3623  CKeyPool keypool;
3624  if (!pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal)) {
3625  return false;
3626  }
3627  vchPubKey = keypool.vchPubKey;
3628  fInternal = keypool.fInternal;
3629  }
3630  assert(vchPubKey.IsValid());
3631  pubkey = vchPubKey;
3632  return true;
3633 }
3634 
3636 {
3637  if (nIndex != -1)
3638  pwallet->KeepKey(nIndex);
3639  nIndex = -1;
3640  vchPubKey = CPubKey();
3641 }
3642 
3644 {
3645  if (nIndex != -1) {
3646  pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3647  }
3648  nIndex = -1;
3649  vchPubKey = CPubKey();
3650 }
3651 
3652 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3653 {
3654  AssertLockHeld(cs_wallet);
3655  bool internal = setInternalKeyPool.count(keypool_id);
3656  if (!internal) assert(setExternalKeyPool.count(keypool_id) || set_pre_split_keypool.count(keypool_id));
3657  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : (set_pre_split_keypool.empty() ? &setExternalKeyPool : &set_pre_split_keypool);
3658  auto it = setKeyPool->begin();
3659 
3660  WalletBatch batch(*database);
3661  while (it != std::end(*setKeyPool)) {
3662  const int64_t& index = *(it);
3663  if (index > keypool_id) break; // set*KeyPool is ordered
3664 
3665  CKeyPool keypool;
3666  if (batch.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3667  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3668  }
3669  LearnAllRelatedScripts(keypool.vchPubKey);
3670  batch.ErasePool(index);
3671  WalletLogPrintf("keypool index %d removed\n", index);
3672  it = setKeyPool->erase(it);
3673  }
3674 }
3675 
3676 void CWallet::LockCoin(const COutPoint& output)
3677 {
3678  AssertLockHeld(cs_wallet);
3679  setLockedCoins.insert(output);
3680 }
3681 
3682 void CWallet::UnlockCoin(const COutPoint& output)
3683 {
3684  AssertLockHeld(cs_wallet);
3685  setLockedCoins.erase(output);
3686 }
3687 
3689 {
3690  AssertLockHeld(cs_wallet);
3691  setLockedCoins.clear();
3692 }
3693 
3694 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3695 {
3696  AssertLockHeld(cs_wallet);
3697  COutPoint outpt(hash, n);
3698 
3699  return (setLockedCoins.count(outpt) > 0);
3700 }
3701 
3702 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3703 {
3704  AssertLockHeld(cs_wallet);
3705  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3706  it != setLockedCoins.end(); it++) {
3707  COutPoint outpt = (*it);
3708  vOutpts.push_back(outpt);
3709  }
3710 }
3711  // end of Actions
3713 
3714 void CWallet::GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map<CKeyID, int64_t>& mapKeyBirth) const {
3715  AssertLockHeld(cs_wallet);
3716  mapKeyBirth.clear();
3717 
3718  // get birth times for keys with metadata
3719  for (const auto& entry : mapKeyMetadata) {
3720  if (entry.second.nCreateTime) {
3721  mapKeyBirth[entry.first] = entry.second.nCreateTime;
3722  }
3723  }
3724 
3725  // map in which we'll infer heights of other keys
3726  const Optional<int> tip_height = locked_chain.getHeight();
3727  const int max_height = tip_height && *tip_height > 144 ? *tip_height - 144 : 0; // the tip can be reorganized; use a 144-block safety margin
3728  std::map<CKeyID, int> mapKeyFirstBlock;
3729  for (const CKeyID &keyid : GetKeys()) {
3730  if (mapKeyBirth.count(keyid) == 0)
3731  mapKeyFirstBlock[keyid] = max_height;
3732  }
3733 
3734  // if there are no such keys, we're done
3735  if (mapKeyFirstBlock.empty())
3736  return;
3737 
3738  // find first block that affects those keys, if there are any left
3739  for (const auto& entry : mapWallet) {
3740  // iterate over all wallet transactions...
3741  const CWalletTx &wtx = entry.second;
3742  if (Optional<int> height = locked_chain.getBlockHeight(wtx.hashBlock)) {
3743  // ... which are already in a block
3744  for (const CTxOut &txout : wtx.tx->vout) {
3745  // iterate over all their outputs
3746  for (const auto &keyid : GetAffectedKeys(txout.scriptPubKey, *this)) {
3747  // ... and all their affected keys
3748  std::map<CKeyID, int>::iterator rit = mapKeyFirstBlock.find(keyid);
3749  if (rit != mapKeyFirstBlock.end() && *height < rit->second)
3750  rit->second = *height;
3751  }
3752  }
3753  }
3754  }
3755 
3756  // Extract block timestamps for those keys
3757  for (const auto& entry : mapKeyFirstBlock)
3758  mapKeyBirth[entry.first] = locked_chain.getBlockTime(entry.second) - TIMESTAMP_WINDOW; // block times can be 2h off
3759 }
3760 
3782 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3783 {
3784  unsigned int nTimeSmart = wtx.nTimeReceived;
3785  if (!wtx.hashUnset()) {
3786  int64_t blocktime;
3787  if (chain().findBlock(wtx.hashBlock, nullptr /* block */, &blocktime)) {
3788  int64_t latestNow = wtx.nTimeReceived;
3789  int64_t latestEntry = 0;
3790 
3791  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3792  int64_t latestTolerated = latestNow + 300;
3793  const TxItems& txOrdered = wtxOrdered;
3794  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3795  CWalletTx* const pwtx = it->second;
3796  if (pwtx == &wtx) {
3797  continue;
3798  }
3799  int64_t nSmartTime;
3800  nSmartTime = pwtx->nTimeSmart;
3801  if (!nSmartTime) {
3802  nSmartTime = pwtx->nTimeReceived;
3803  }
3804  if (nSmartTime <= latestTolerated) {
3805  latestEntry = nSmartTime;
3806  if (nSmartTime > latestNow) {
3807  latestNow = nSmartTime;
3808  }
3809  break;
3810  }
3811  }
3812 
3813  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3814  } else {
3815  WalletLogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3816  }
3817  }
3818  return nTimeSmart;
3819 }
3820 
3821 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3822 {
3823  if (boost::get<CNoDestination>(&dest))
3824  return false;
3825 
3826  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3827  return WalletBatch(*database).WriteDestData(EncodeDestination(dest), key, value);
3828 }
3829 
3830 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3831 {
3832  if (!mapAddressBook[dest].destdata.erase(key))
3833  return false;
3834  return WalletBatch(*database).EraseDestData(EncodeDestination(dest), key);
3835 }
3836 
3837 void CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3838 {
3839  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3840 }
3841 
3842 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3843 {
3844  std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3845  if(i != mapAddressBook.end())
3846  {
3847  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3848  if(j != i->second.destdata.end())
3849  {
3850  if(value)
3851  *value = j->second;
3852  return true;
3853  }
3854  }
3855  return false;
3856 }
3857 
3858 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3859 {
3860  std::vector<std::string> values;
3861  for (const auto& address : mapAddressBook) {
3862  for (const auto& data : address.second.destdata) {
3863  if (!data.first.compare(0, prefix.size(), prefix)) {
3864  values.emplace_back(data.second);
3865  }
3866  }
3867  }
3868  return values;
3869 }
3870 
3872 {
3873  WalletBatch batch(*database);
3874  for (auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
3875  int64_t index = *it;
3876  CKeyPool keypool;
3877  if (!batch.ReadPool(index, keypool)) {
3878  throw std::runtime_error(std::string(__func__) + ": read keypool entry failed");
3879  }
3880  keypool.m_pre_split = true;
3881  if (!batch.WritePool(index, keypool)) {
3882  throw std::runtime_error(std::string(__func__) + ": writing modified keypool entry failed");
3883  }
3884  set_pre_split_keypool.insert(index);
3885  it = setExternalKeyPool.erase(it);
3886  }
3887 }
3888 
3889 bool CWallet::Verify(interfaces::Chain& chain, const WalletLocation& location, bool salvage_wallet, std::string& error_string, std::string& warning_string)
3890 {
3891  // Do some checking on wallet path. It should be either a:
3892  //
3893  // 1. Path where a directory can be created.
3894  // 2. Path to an existing directory.
3895  // 3. Path to a symlink to a directory.
3896  // 4. For backwards compatibility, the name of a data file in -walletdir.
3897  LOCK(cs_wallets);
3898  const fs::path& wallet_path = location.GetPath();
3899  fs::file_type path_type = fs::symlink_status(wallet_path).type();
3900  if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
3901  (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
3902  (path_type == fs::regular_file && fs::path(location.GetName()).filename() == location.GetName()))) {
3903  error_string = strprintf(
3904  "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and "
3905  "database/log.?????????? files can be stored, a location where such a directory could be created, "
3906  "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
3907  location.GetName(), GetWalletDir());
3908  return false;
3909  }
3910 
3911  // Make sure that the wallet path doesn't clash with an existing wallet path
3912  if (IsWalletLoaded(wallet_path)) {
3913  error_string = strprintf("Error loading wallet %s. Duplicate -wallet filename specified.", location.GetName());
3914  return false;
3915  }
3916 
3917  // Keep same database environment instance across Verify/Recover calls below.
3918  std::unique_ptr<WalletDatabase> database = WalletDatabase::Create(wallet_path);
3919 
3920  try {
3921  if (!WalletBatch::VerifyEnvironment(wallet_path, error_string)) {
3922  return false;
3923  }
3924  } catch (const fs::filesystem_error& e) {
3925  error_string = strprintf("Error loading wallet %s. %s", location.GetName(), fsbridge::get_filesystem_error_message(e));
3926  return false;
3927  }
3928 
3929  if (salvage_wallet) {
3930  // Recover readable keypairs:
3931  CWallet dummyWallet(&chain, WalletLocation(), WalletDatabase::CreateDummy());
3932  std::string backup_filename;
3933  if (!WalletBatch::Recover(wallet_path, (void *)&dummyWallet, WalletBatch::RecoverKeysOnlyFilter, backup_filename)) {
3934  return false;
3935  }
3936  }
3937 
3938  return WalletBatch::VerifyDatabaseFile(wallet_path, warning_string, error_string);
3939 }
3940 
3941 std::shared_ptr<CWallet> CWallet::CreateWalletFromFile(interfaces::Chain& chain, const WalletLocation& location, uint64_t wallet_creation_flags)
3942 {
3943  const std::string& walletFile = WalletDataFilePath(location.GetPath()).string();
3944 
3945  // needed to restore wallet transaction meta data after -zapwallettxes
3946  std::vector<CWalletTx> vWtx;
3947 
3948  if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3949  chain.initMessage(_("Zapping all transactions from wallet..."));
3950 
3951  std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(&chain, location, WalletDatabase::Create(location.GetPath()));
3952  DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3953  if (nZapWalletRet != DBErrors::LOAD_OK) {
3954  chain.initError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3955  return nullptr;
3956  }
3957  }
3958 
3959  chain.initMessage(_("Loading wallet..."));
3960 
3961  int64_t nStart = GetTimeMillis();
3962  bool fFirstRun = true;
3963  // TODO: Can't use std::make_shared because we need a custom deleter but
3964  // should be possible to use std::allocate_shared.
3965  std::shared_ptr<CWallet> walletInstance(new CWallet(&chain, location, WalletDatabase::Create(location.GetPath())), ReleaseWallet);
3966  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3967  if (nLoadWalletRet != DBErrors::LOAD_OK)
3968  {
3969  if (nLoadWalletRet == DBErrors::CORRUPT) {
3970  chain.initError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3971  return nullptr;
3972  }
3973  else if (nLoadWalletRet == DBErrors::NONCRITICAL_ERROR)
3974  {
3975  chain.initWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3976  " or address book entries might be missing or incorrect."),
3977  walletFile));
3978  }
3979  else if (nLoadWalletRet == DBErrors::TOO_NEW) {
3980  chain.initError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3981  return nullptr;
3982  }
3983  else if (nLoadWalletRet == DBErrors::NEED_REWRITE)
3984  {
3985  chain.initError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3986  return nullptr;
3987  }
3988  else {
3989  chain.initError(strprintf(_("Error loading %s"), walletFile));
3990  return nullptr;
3991  }
3992  }
3993 
3994  int prev_version = walletInstance->GetVersion();
3995  if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3996  {
3997  int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3998  if (nMaxVersion == 0) // the -upgradewallet without argument case
3999  {
4000  walletInstance->WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4001  nMaxVersion = FEATURE_LATEST;
4002  walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
4003  }
4004  else
4005  walletInstance->WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
4006  if (nMaxVersion < walletInstance->GetVersion())
4007  {
4008  chain.initError(_("Cannot downgrade wallet"));
4009  return nullptr;
4010  }
4011  walletInstance->SetMaxVersion(nMaxVersion);
4012  }
4013 
4014  // Upgrade to HD if explicit upgrade
4015  if (gArgs.GetBoolArg("-upgradewallet", false)) {
4016  LOCK(walletInstance->cs_wallet);
4017 
4018  // Do not upgrade versions to any version between HD_SPLIT and FEATURE_PRE_SPLIT_KEYPOOL unless already supporting HD_SPLIT
4019  int max_version = walletInstance->GetVersion();
4020  if (!walletInstance->CanSupportFeature(FEATURE_HD_SPLIT) && max_version >= FEATURE_HD_SPLIT && max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
4021  chain.initError(_("Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified."));
4022  return nullptr;
4023  }
4024 
4025  bool hd_upgrade = false;
4026  bool split_upgrade = false;
4027  if (walletInstance->CanSupportFeature(FEATURE_HD) && !walletInstance->IsHDEnabled()) {
4028  walletInstance->WalletLogPrintf("Upgrading wallet to HD\n");
4029  walletInstance->SetMinVersion(FEATURE_HD);
4030 
4031  // generate a new master key
4032  CPubKey masterPubKey = walletInstance->GenerateNewSeed();
4033  walletInstance->SetHDSeed(masterPubKey);
4034  hd_upgrade = true;
4035  }
4036  // Upgrade to HD chain split if necessary
4037  if (walletInstance->CanSupportFeature(FEATURE_HD_SPLIT)) {
4038  walletInstance->WalletLogPrintf("Upgrading wallet to use HD chain split\n");
4039  walletInstance->SetMinVersion(FEATURE_PRE_SPLIT_KEYPOOL);
4040  split_upgrade = FEATURE_HD_SPLIT > prev_version;
4041  }
4042  // Mark all keys currently in the keypool as pre-split
4043  if (split_upgrade) {
4044  walletInstance->MarkPreSplitKeys();
4045  }
4046  // Regenerate the keypool if upgraded to HD
4047  if (hd_upgrade) {
4048  if (!walletInstance->TopUpKeyPool()) {
4049  chain.initError(_("Unable to generate keys"));
4050  return nullptr;
4051  }
4052  }
4053  }
4054 
4055  if (fFirstRun)
4056  {
4057  // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
4058  walletInstance->SetMinVersion(FEATURE_LATEST);
4059 
4060  if ((wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
4061  //selective allow to set flags
4062  walletInstance->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
4063  } else if (wallet_creation_flags & WALLET_FLAG_BLANK_WALLET) {
4064  walletInstance->SetWalletFlag(WALLET_FLAG_BLANK_WALLET);
4065  } else {
4066  // generate a new seed
4067  CPubKey seed = walletInstance->GenerateNewSeed();
4068  walletInstance->SetHDSeed(seed);
4069  } // Otherwise, do not generate a new seed
4070 
4071  // Top up the keypool
4072  if (walletInstance->CanGenerateKeys() && !walletInstance->TopUpKeyPool()) {
4073  chain.initError(_("Unable to generate initial keys"));
4074  return nullptr;
4075  }
4076 
4077  auto locked_chain = chain.lock();
4078  walletInstance->ChainStateFlushed(locked_chain->getTipLocator());
4079  } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) {
4080  // Make it impossible to disable private keys after creation
4081  chain.initError(strprintf(_("Error loading %s: Private keys can only be disabled during creation"), walletFile));
4082  return NULL;
4083  } else if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
4084  LOCK(walletInstance->cs_KeyStore);
4085  if (!walletInstance->mapKeys.empty() || !walletInstance->mapCryptedKeys.empty()) {
4086  chain.initWarning(strprintf(_("Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
4087  }
4088  }
4089 
4090  if (!gArgs.GetArg("-addresstype", "").empty() && !ParseOutputType(gArgs.GetArg("-addresstype", ""), walletInstance->m_default_address_type)) {
4091  chain.initError(strprintf("Unknown address type '%s'", gArgs.GetArg("-addresstype", "")));
4092  return nullptr;
4093  }
4094 
4095  if (!gArgs.GetArg("-changetype", "").empty() && !ParseOutputType(gArgs.GetArg("-changetype", ""), walletInstance->m_default_change_type)) {
4096  chain.initError(strprintf("Unknown change type '%s'", gArgs.GetArg("-changetype", "")));
4097  return nullptr;
4098  }
4099 
4100  if (gArgs.IsArgSet("-mintxfee")) {
4101  CAmount n = 0;
4102  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) {
4103  chain.initError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
4104  return nullptr;
4105  }
4106  if (n > HIGH_TX_FEE_PER_KB) {
4107  chain.initWarning(AmountHighWarn("-mintxfee") + " " +
4108  _("This is the minimum transaction fee you pay on every transaction."));
4109  }
4110  walletInstance->m_min_fee = CFeeRate(n);
4111  }
4112 
4113  walletInstance->m_allow_fallback_fee = Params().IsFallbackFeeEnabled();
4114  if (gArgs.IsArgSet("-fallbackfee")) {
4115  CAmount nFeePerK = 0;
4116  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) {
4117  chain.initError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
4118  return nullptr;
4119  }
4120  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4121  chain.initWarning(AmountHighWarn("-fallbackfee") + " " +
4122  _("This is the transaction fee you may pay when fee estimates are not available."));
4123  }
4124  walletInstance->m_fallback_fee = CFeeRate(nFeePerK);
4125  walletInstance->m_allow_fallback_fee = nFeePerK != 0; //disable fallback fee in case value was set to 0, enable if non-null value
4126  }
4127  if (gArgs.IsArgSet("-discardfee")) {
4128  CAmount nFeePerK = 0;
4129  if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) {
4130  chain.initError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
4131  return nullptr;
4132  }
4133  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4134  chain.initWarning(AmountHighWarn("-discardfee") + " " +
4135  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4136  }
4137  walletInstance->m_discard_rate = CFeeRate(nFeePerK);
4138  }
4139  if (gArgs.IsArgSet("-paytxfee")) {
4140  CAmount nFeePerK = 0;
4141  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) {
4142  chain.initError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
4143  return nullptr;
4144  }
4145  if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4146  chain.initWarning(AmountHighWarn("-paytxfee") + " " +
4147  _("This is the transaction fee you will pay if you send a transaction."));
4148  }
4149  walletInstance->m_pay_tx_fee = CFeeRate(nFeePerK, 1000);
4150  if (walletInstance->m_pay_tx_fee < chain.relayMinFee()) {
4151  chain.initError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4152  gArgs.GetArg("-paytxfee", ""), chain.relayMinFee().ToString()));
4153  return nullptr;
4154  }
4155  }
4156 
4157  if (gArgs.IsArgSet("-maxtxfee"))
4158  {
4159  CAmount nMaxFee = 0;
4160  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) {
4161  chain.initError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
4162  return nullptr;
4163  }
4164  if (nMaxFee > HIGH_MAX_TX_FEE) {
4165  chain.initWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4166  }
4167  if (CFeeRate(nMaxFee, 1000) < chain.relayMinFee()) {
4168  chain.initError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4169  gArgs.GetArg("-maxtxfee", ""), chain.relayMinFee().ToString()));
4170  return nullptr;
4171  }
4172  walletInstance->m_default_max_tx_fee = nMaxFee;
4173  }
4174 
4175  if (chain.relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB)
4176  chain.initWarning(AmountHighWarn("-minrelaytxfee") + " " +
4177  _("The wallet will avoid paying less than the minimum relay fee."));
4178 
4179  walletInstance->m_confirm_target = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4180  walletInstance->m_spend_zero_conf_change = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4181  walletInstance->m_signal_rbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4182 
4183  walletInstance->WalletLogPrintf("Wallet completed loading in %15dms\n", GetTimeMillis() - nStart);
4184 
4185  // Try to top up keypool. No-op if the wallet is locked.
4186  walletInstance->TopUpKeyPool();
4187 
4188  auto locked_chain = chain.lock();
4189  LOCK(walletInstance->cs_wallet);
4190 
4191  int rescan_height = 0;
4192  if (!gArgs.GetBoolArg("-rescan", false))
4193  {
4194  WalletBatch batch(*walletInstance->database);
4195  CBlockLocator locator;
4196  if (batch.ReadBestBlock(locator)) {
4197  if (const Optional<int> fork_height = locked_chain->findLocatorFork(locator)) {
4198  rescan_height = *fork_height;
4199  }
4200  }
4201  }
4202 
4203  const Optional<int> tip_height = locked_chain->getHeight();
4204  if (tip_height) {
4205  walletInstance->m_last_block_processed = locked_chain->getBlockHash(*tip_height);
4206  } else {
4207  walletInstance->m_last_block_processed.SetNull();
4208  }
4209 
4210  if (tip_height && *tip_height != rescan_height)
4211  {
4212  // We can't rescan beyond non-pruned blocks, stop and throw an error.
4213  // This might happen if a user uses an old wallet within a pruned node
4214  // or if they ran -disablewallet for a longer time, then decided to re-enable
4215  if (chain.havePruned()) {
4216  // Exit early and print an error.
4217  // If a block is pruned after this check, we will load the wallet,
4218  // but fail the rescan with a generic error.
4219  int block_height = *tip_height;
4220  while (block_height > 0 && locked_chain->haveBlockOnDisk(block_height - 1) && rescan_height != block_height) {
4221  --block_height;
4222  }
4223 
4224  if (rescan_height != block_height) {
4225  chain.initError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4226  return nullptr;
4227  }
4228  }
4229 
4230  chain.initMessage(_("Rescanning..."));
4231  walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", *tip_height - rescan_height, rescan_height);
4232 
4233  // No need to read and scan block if block was created before
4234  // our wallet birthday (as adjusted for block time variability)
4235  if (walletInstance->nTimeFirstKey) {
4236  if (Optional<int> first_block = locked_chain->findFirstBlockWithTimeAndHeight(walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW, rescan_height, nullptr)) {
4237  rescan_height = *first_block;
4238  }
4239  }
4240 
4241  {
4242  WalletRescanReserver reserver(walletInstance.get());
4243  if (!reserver.reserve() || (ScanResult::SUCCESS != walletInstance->ScanForWalletTransactions(locked_chain->getBlockHash(rescan_height), {} /* stop block */, reserver, true /* update */).status)) {
4244  chain.initError(_("Failed to rescan the wallet during initialization"));
4245  return nullptr;
4246  }
4247  }
4248  walletInstance->ChainStateFlushed(locked_chain->getTipLocator());
4249  walletInstance->database->IncrementUpdateCounter();
4250 
4251  // Restore wallet transaction metadata after -zapwallettxes=1
4252  if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4253  {
4254  WalletBatch batch(*walletInstance->database);
4255 
4256  for (const CWalletTx& wtxOld : vWtx)
4257  {
4258  uint256 hash = wtxOld.GetHash();
4259  std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4260  if (mi != walletInstance->mapWallet.end())
4261  {
4262  const CWalletTx* copyFrom = &wtxOld;
4263  CWalletTx* copyTo = &mi->second;
4264  copyTo->mapValue = copyFrom->mapValue;
4265  copyTo->vOrderForm = copyFrom->vOrderForm;
4266  copyTo->nTimeReceived = copyFrom->nTimeReceived;
4267  copyTo->nTimeSmart = copyFrom->nTimeSmart;
4268  copyTo->fFromMe = copyFrom->fFromMe;
4269  copyTo->nOrderPos = copyFrom->nOrderPos;
4270  batch.WriteTx(*copyTo);
4271  }
4272  }
4273  }
4274  }
4275 
4276  chain.loadWallet(interfaces::MakeWallet(walletInstance));
4277 
4278  // Register with the validation interface. It's ok to do this after rescan since we're still holding locked_chain.
4279  walletInstance->handleNotifications();
4280 
4281  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4282 
4283  {
4284  walletInstance->WalletLogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4285  walletInstance->WalletLogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4286  walletInstance->WalletLogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4287  }
4288 
4289  return walletInstance;
4290 }
4291 
4293 {
4294  m_chain_notifications_handler = m_chain->handleNotifications(*this);
4295 }
4296 
4298 {
4299  auto locked_chain = chain().lock();
4300  LOCK(cs_wallet);
4301 
4302  // Add wallet transactions that aren't already in a block to mempool
4303  // Do this here as mempool requires genesis block to be loaded
4304  ReacceptWalletTransactions(*locked_chain);
4305 
4306  // Update wallet transactions with current mempool transactions.
4307  chain().requestMempoolTransactions(*this);
4308 }
4309 
4310 bool CWallet::BackupWallet(const std::string& strDest)
4311 {
4312  return database->Backup(strDest);
4313 }
4314 
4316 {
4317  nTime = GetTime();
4318  fInternal = false;
4319  m_pre_split = false;
4320 }
4321 
4322 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4323 {
4324  nTime = GetTime();
4325  vchPubKey = vchPubKeyIn;
4326  fInternal = internalIn;
4327  m_pre_split = false;
4328 }
4329 
4330 CWalletKey::CWalletKey(int64_t nExpires)
4331 {
4332  nTimeCreated = (nExpires ? GetTime() : 0);
4333  nTimeExpires = nExpires;
4334 }
4335 
4336 void CMerkleTx::SetMerkleBranch(const uint256& block_hash, int posInBlock)
4337 {
4338  // Update the tx's hashBlock
4339  hashBlock = block_hash;
4340 
4341  // set the position of the transaction in the block
4342  nIndex = posInBlock;
4343 }
4344 
4346 {
4347  if (hashUnset())
4348  return 0;
4349 
4350  return locked_chain.getBlockDepth(hashBlock) * (nIndex == -1 ? -1 : 1);
4351 }
4352 
4354 {
4355  if (!IsCoinBase())
4356  return 0;
4357  int chain_depth = GetDepthInMainChain(locked_chain);
4358  assert(chain_depth >= 0); // coinbase tx should not be conflicted
4359  return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
4360 }
4361 
4363 {
4364  // note GetBlocksToMaturity is 0 for non-coinbase tx
4365  return GetBlocksToMaturity(locked_chain) > 0;
4366 }
4367 
4369 {
4370  // We must set fInMempool here - while it will be re-set to true by the
4371  // entered-mempool callback, if we did not there would be a race where a
4372  // user could call sendmoney in a loop and hit spurious out of funds errors
4373  // because we think that this newly generated transaction's change is
4374  // unavailable as we're not yet aware that it is in the mempool.
4375  bool ret = locked_chain.submitToMemoryPool(tx, pwallet->m_default_max_tx_fee, state);
4376  fInMempool |= ret;
4377  return ret;
4378 }
4379 
4381 {
4382  if (key.IsCompressed() && (type == OutputType::P2SH_SEGWIT || type == OutputType::BECH32)) {
4383  CTxDestination witdest = WitnessV0KeyHash(key.GetID());
4384  CScript witprog = GetScriptForDestination(witdest);
4385  // Make sure the resulting program is solvable.
4386  assert(IsSolvable(*this, witprog));
4387  AddCScript(witprog);
4388  }
4389 }
4390 
4392 {
4393  // OutputType::P2SH_SEGWIT always adds all necessary scripts for all types.
4394  LearnRelatedScripts(key, OutputType::P2SH_SEGWIT);
4395 }
4396 
4397 std::vector<OutputGroup> CWallet::GroupOutputs(const std::vector<COutput>& outputs, bool single_coin) const {
4398  std::vector<OutputGroup> groups;
4399  std::map<CTxDestination, OutputGroup> gmap;
4400  CTxDestination dst;
4401  for (const auto& output : outputs) {
4402  if (output.fSpendable) {
4403  CInputCoin input_coin = output.GetInputCoin();
4404 
4405  size_t ancestors, descendants;
4406  chain().getTransactionAncestry(output.tx->GetHash(), ancestors, descendants);
4407  if (!single_coin && ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) {
4408  // Limit output groups to no more than 10 entries, to protect
4409  // against inadvertently creating a too-large transaction
4410  // when using -avoidpartialspends
4411  if (gmap[dst].m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
4412  groups.push_back(gmap[dst]);
4413  gmap.erase(dst);
4414  }
4415  gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
4416  } else {
4417  groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(ISMINE_ALL), ancestors, descendants);
4418  }
4419  }
4420  }
4421  if (!single_coin) {
4422  for (const auto& it : gmap) groups.push_back(it.second);
4423  }
4424  return groups;
4425 }
4426 
4427 bool CWallet::GetKeyOrigin(const CKeyID& keyID, KeyOriginInfo& info) const
4428 {
4429  CKeyMetadata meta;
4430  {
4431  LOCK(cs_wallet);
4432  auto it = mapKeyMetadata.find(keyID);
4433  if (it != mapKeyMetadata.end()) {
4434  meta = it->second;
4435  }
4436  }
4437  if (meta.has_key_origin) {
4438  std::copy(meta.key_origin.fingerprint, meta.key_origin.fingerprint + 4, info.fingerprint);
4439  info.path = meta.key_origin.path;
4440  } else { // Single pubkeys get the master fingerprint of themselves
4441  std::copy(keyID.begin(), keyID.begin() + 4, info.fingerprint);
4442  }
4443  return true;
4444 }
4445 
4446 bool CWallet::AddKeyOrigin(const CPubKey& pubkey, const KeyOriginInfo& info)
4447 {
4448  LOCK(cs_wallet);
4449  std::copy(info.fingerprint, info.fingerprint + 4, mapKeyMetadata[pubkey.GetID()].key_origin.fingerprint);
4450  mapKeyMetadata[pubkey.GetID()].key_origin.path = info.path;
4451  mapKeyMetadata[pubkey.GetID()].has_key_origin = true;
4452  mapKeyMetadata[pubkey.GetID()].hdKeypath = WriteHDKeypath(info.path);
4453  return WriteKeyMetadata(mapKeyMetadata[pubkey.GetID()], pubkey, true);
4454 }
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:2065
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:408
AmountType
Definition: wallet.h:476
void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks all keys in the keypool up to and including reserve_key as used.
Definition: wallet.cpp:3652
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
Definition: db.h:145
CAmount nValue
Definition: transaction.h:136
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:28
void AddKeypoolPubkeyWithDB(const CPubKey &pubkey, const bool internal, WalletBatch &batch)
Definition: wallet.cpp:3325
void AddKeypoolPubkey(const CPubKey &pubkey, const bool internal)
Definition: wallet.cpp:3318
const fs::path & GetPath() const
Get wallet absolute path.
Definition: walletutil.h:32
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:752
EstimatorBucket pass
Definition: fees.h:70
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:42
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3250
void SetTx(CTransactionRef arg)
Definition: wallet.h:372
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
Definition: wallet.h:341
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: sign.h:25
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:472
bool ParseMoney(const std::string &str, CAmount &nRet)
Definition: moneystr.cpp:34
int i
Definition: wallet.h:608
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:665
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:172
std::string hdKeypath
Definition: walletdb.h:101
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:549
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:41
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:45
std::set< std::set< CTxDestination > > GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3508
std::unique_ptr< interfaces::Handler > m_chain_notifications_handler
Registered interfaces::Chain::Notifications handler.
Definition: wallet.h:871
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const uint256 &block_hash, int posInBlock, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1038
bool CreateTransaction(interfaces::Chain::Lock &locked_chain, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl &coin_control, bool sign=true)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:2651
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:186
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:159
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3450
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:26
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:128
EstimationResult est
Definition: fees.h:78
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:308
void SetNull()
Definition: uint256.h:39
bool CanGetAddresses(bool internal=false)
Definition: wallet.cpp:1519
int returnedTarget
Definition: fees.h:81
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:126
CScript scriptPubKey
Definition: transaction.h:137
void UpgradeKeyMetadata() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo.
Definition: wallet.cpp:371
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:80
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:14
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:74
constexpr CAmount HIGH_MAX_TX_FEE
-maxtxfee will warn if called with a higher fee than this amount (in satoshis)
Definition: wallet.h:81
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3682
void UnloadWallet(std::shared_ptr< CWallet > &&wallet)
Explicitly unload and delete the wallet.
Definition: wallet.cpp:115
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:81
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:4297
CKey key
Definition: key.h:149
CAmount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2165
virtual bool haveBlockOnDisk(int height)=0
Check that the block is available on disk (i.e.
char fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
Definition: wallet.h:471
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:294
size_t change_output_size
Definition: wallet.h:678
bool HaveKey(const CKeyStore &store, const CKey &key)
Checks if a CKey is in the given CKeyStore compressed or otherwise.
Definition: keystore.cpp:200
Definition: block.h:72
boost::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:32
void SetHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1498
int64_t GetTimeMillis()
Definition: time.cpp:40
Optional< T > MakeOptional(bool condition, T &&value)
Substitute for C++17 std::make_optional.
Definition: optional.h:18
virtual int getBlockDepth(const uint256 &hash)=0
Get block depth.
#define strprintf
Definition: tinyformat.h:1066
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:49
Encryption/decryption context with key information.
Definition: crypter.h:76
const uint256 & GetHash() const
Definition: wallet.h:409
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:576
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:233
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Find non-change parent output.
Definition: wallet.cpp:2327
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:185
CAmount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
Definition: wallet.h:1016
double start
Definition: fees.h:59
virtual int64_t getBlockTime(int height)=0
Get block time. Height must be valid or this function will abort.
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1386
int nIndex
Definition: wallet.h:352
bool EraseDestData(const CTxDestination &dest, const std::string &key) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:3830
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
Definition: wallet.h:1043
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:37
Flag set when a wallet contains no HD seed and no private keys, scripts, addresses, and other watch only things, and is therefore "blank.".
Definition: wallet.h:139
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:614
std::vector< CTxIn > vin
Definition: transaction.h:368
uint256 last_scanned_block
Hash and height of most recent block that was successfully scanned.
Definition: wallet.h:1001
bool use_max_sig
Whether to use the maximum sized, 72 byte signature when calculating the size of the input spend...
Definition: wallet.h:621
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:154
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:758
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &target_value, const CAmount &cost_of_change, std::set< CInputCoin > &out_set, CAmount &value_ret, CAmount not_input_fees)
static const uint32_t SEQUENCE_FINAL
Definition: transaction.h:73
const char * prefix
Definition: rest.cpp:625
bool SelectCoinsMinConf(const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< OutputGroup > groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:2344
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1933
Definition: key.h:144
Balance GetBalance(int min_depth=0) const
Definition: wallet.cpp:2137
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:34
virtual bool isInitialBlockDownload()=0
Check if in IBD.
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:74
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:26
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: wallet.cpp:2508
uint256 hashBlock
Definition: wallet.h:345
FeeReason reason
Definition: fees.h:79
CAmount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
Definition: fees.cpp:21
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:106
size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3244
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
Definition: sign.cpp:439
Interface for querying locked chain state, used by legacy code that assumes state won&#39;t change betwee...
Definition: chain.h:68
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:60
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:300
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:472
void LoadToWallet(const CWalletTx &wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1017
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
Definition: wallet.h:473
CFeeRate GetDiscardRate(const CWallet &wallet)
Return the maximum feerate for discarding change.
Definition: fees.cpp:93
static bool VerifyDatabaseFile(const fs::path &wallet_path, std::string &warningStr, std::string &errorStr)
Definition: walletdb.cpp:742
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:86
bool HasSelected() const
Definition: coincontrol.h:49
bool RemoveWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:480
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: crypter.h:68
virtual Optional< int > getBlockHeight(const uint256 &hash)=0
Get block height above genesis block.
bool SetMaxVersion(int nVersion)
change which version we&#39;re allowed to upgrade to (note that this does not immediately imply upgrading...
Definition: wallet.cpp:597
#define PACKAGE_NAME
boost::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:22
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
Definition: sign.cpp:440
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
Definition: wallet.h:1015
CAmount m_watchonly_untrusted_pending
Definition: wallet.h:1019
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:371
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:27
int m_min_depth
Minimum chain depth value for coin availability.
Definition: coincontrol.h:40
int m_input_bytes
Pre-computed estimated size of this output as a fully-signed input in a transaction.
Definition: coinselection.h:41
CAmount m_watchonly_immature
Definition: wallet.h:1020
bool IsWalletFlagSet(uint64_t flag)
check if a certain wallet flag is set
Definition: wallet.cpp:1552
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:95
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:540
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: wallet.cpp:75
void MaybeResendWalletTxs()
Called periodically by the schedule thread.
Definition: wallet.cpp:2123
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:512
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:242
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:92
bool IsSpent(interfaces::Chain::Lock &locked_chain, 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:687
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
Implement lookup of key origin information through wallet key metadata.
Definition: wallet.cpp:4427
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:3837
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:652
A signature creator for transactions.
Definition: sign.h:102
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
Definition: moneystr.cpp:12
CWalletKey(int64_t nExpires=0)
Definition: wallet.cpp:4330
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:50
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:94
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:445
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:240
const unsigned char * begin() const
Definition: key.h:89
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
Definition: wallet.cpp:904
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:48
virtual Optional< int > findFirstBlockWithTimeAndHeight(int64_t time, int height, uint256 *hash)=0
Return height of the first block in the chain with timestamp equal or greater than the given time and...
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:730
bool IsWalletLoaded(const fs::path &wallet_path)
Return whether a wallet database is currently loaded.
Definition: db.cpp:75
unsigned char * begin()
Definition: uint256.h:55
virtual void initError(const std::string &message)=0
Send init error.
double withinTarget
Definition: fees.h:61
bool WriteWalletFlags(const uint64_t flags)
Definition: walletdb.cpp:763
CAmount m_watchonly_trusted
Definition: wallet.h:1018
CAmount GetImmatureWatchOnlyCredit(interfaces::Chain::Lock &locked_chain, const bool fUseCache=true) const
Definition: wallet.cpp:2010
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1344
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:155
bool IsNull() const
Definition: uint256.h:31
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:232
OutputType
Definition: outputtype.h:16
static bool Recover(const fs::path &wallet_path, void *callbackDataIn, bool(*recoverKVcallback)(void *callbackData, CDataStream ssKey, CDataStream ssValue), std::string &out_backup_filename)
Definition: walletdb.cpp:702
Coin Control Features.
Definition: coincontrol.h:16
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:38
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) ...
Definition: wallet.cpp:413
const std::vector< CTxIn > vin
Definition: transaction.h:287
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:992
std::string ToString() const
Definition: wallet.cpp:169
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:999
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:114
int desiredTarget
Definition: fees.h:80
bool IsTrusted(interfaces::Chain::Lock &locked_chain) const
Definition: wallet.cpp:2033
Access to the wallet database.
Definition: walletdb.h:150
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:555
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:452
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3098
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:3388
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
virtual bool submitToMemoryPool(const CTransactionRef &tx, CAmount absurd_fee, CValidationState &state)=0
Add transaction to memory pool if the transaction fee is below the amount specified by absurd_fee...
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:36
boost::signals2::signal< void()> NotifyUnload
Wallet is about to be unloaded.
Definition: wallet.h:1162
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:122
size_t change_spend_size
Definition: wallet.h:679
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
Definition: crypter.cpp:216
void BlockDisconnected(const CBlock &block) override
Definition: wallet.cpp:1273
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3153
bool done
const uint32_t BIP32_HARDENED_KEY_LIMIT
Definition: wallet.cpp:160
void MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx)
Definition: wallet.cpp:1169
std::vector< CKeyID > GetAffectedKeys(const CScript &spk, const SigningProvider &provider)
Definition: wallet.cpp:174
void MarkDirty()
Definition: wallet.cpp:895
DBErrors ReorderTransactions()
Definition: wallet.cpp:826
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn, bool fSafeIn, bool use_max_sig_in=false)
Definition: wallet.h:630
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3694
void UnsetWalletFlag(uint64_t flag)
Unsets a single wallet flag.
Definition: wallet.cpp:1544
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3171
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:747
std::string AmountHighWarn(const std::string &optname)
Definition: error.cpp:35
bool SelectCoins(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CCoinControl &coin_control, CoinSelectionParams &coin_selection_params, bool &bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coinControl are...
Definition: wallet.cpp:2398
int64_t nTime
The time at which the key was generated. Set in AddKeypoolPubKeyWithDB.
Definition: wallet.h:192
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
Definition: wallet.cpp:1580
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:3782
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1648
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost, unsigned int bytes_per_sigop)
Definition: policy.cpp:252
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3066
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:287
CAmount m_mine_immature
Immature coinbases in the main chain.
Definition: wallet.h:1017
int nDepth
Definition: wallet.h:609
const std::string & GetName() const
Get wallet name.
Definition: walletutil.h:29
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:101
CAmount GetCredit(interfaces::Chain::Lock &locked_chain, const isminefilter &filter) const
Definition: wallet.cpp:1948
void ReacceptWalletTransactions(interfaces::Chain::Lock &locked_chain) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1860
void TransactionAddedToMempool(const CTransactionRef &tx) override
Definition: wallet.cpp:1230
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:1285
double end
Definition: fees.h:60
CTransactionRef tx
Definition: wallet.h:344
EstimatorBucket fail
Definition: fees.h:71
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
Definition: wallet.cpp:3210
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Update wallet first key creation time.
Definition: wallet.cpp:422
void AvailableCoins(interfaces::Chain::Lock &locked_chain, std::vector< COutput > &vCoins, bool fOnlySafe=true, const CCoinControl *coinControl=nullptr, const CAmount &nMinimumAmount=1, const CAmount &nMaximumAmount=MAX_MONEY, const CAmount &nMinimumSumAmount=MAX_MONEY, const uint64_t nMaximumCount=0, const int nMinDepth=0, const int nMaxDepth=9999999) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2181
static bool VerifyEnvironment(const fs::path &wallet_path, std::string &errorStr)
Definition: walletdb.cpp:737
isminetype
IsMine() return codes.
Definition: ismine.h:18
An input of a transaction.
Definition: transaction.h:63
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:434
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
Definition: wallet.cpp:1638
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:660
bool IsHDEnabled() const
Definition: wallet.cpp:1507
#define LOCK(cs)
Definition: sync.h:182
const char * name
Definition: rest.cpp:38
bool InMempool() const
Definition: wallet.cpp:2028
const uint256 & GetHash() const
Definition: transaction.h:322
std::shared_ptr< CWallet > LoadWallet(interfaces::Chain &chain, const WalletLocation &location, std::string &error, std::string &warning)
Definition: wallet.cpp:138
CKeyPool()
Definition: wallet.cpp:4315
virtual Optional< int > getHeight()=0
Get current chain height, not including genesis block (returns 0 if chain only contains genesis block...
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:632
void runCommand(const std::string &strCommand)
Definition: system.cpp:1125
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:351
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:20
Chain & m_chain
Definition: wallet.cpp:527
bool IsValid() const
Definition: pubkey.h:171
Fast randomness source.
Definition: random.h:98
std::set< uint256 > GetConflicts() const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:1912
void Select(const COutPoint &output)
Definition: coincontrol.h:59
uint256 uint256S(const char *str)
Definition: uint256.h:131
An encapsulated public key.
Definition: pubkey.h:30
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:24
CAmount GetImmatureCredit(interfaces::Chain::Lock &locked_chain, bool fUseCache=true) const
Definition: wallet.cpp:1965
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1095
std::vector< OutputGroup > GroupOutputs(const std::vector< COutput > &outputs, bool single_coin) const
Definition: wallet.cpp:4397
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a destination data tuple to the store, and saves it to disk.
Definition: wallet.cpp:3821
std::map< CKeyID, CPubKey > pubkeys
Definition: sign.h:79
uint32_t n
Definition: transaction.h:22
fs::path WalletDataFilePath(const fs::path &wallet_path)
Given a wallet directory path or legacy file path, return path to main data file in the wallet databa...
Definition: db.cpp:87
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3688
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:158
const std::vector< CTxOut > vout
Definition: transaction.h:288
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:327
bool IsCoinBase() const
Definition: wallet.h:410
double inMempool
Definition: fees.h:63
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:96
virtual CBlockLocator getTipLocator()=0
Get locator for the current chain tip.
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:639
static std::shared_ptr< CWallet > CreateWalletFromFile(interfaces::Chain &chain, const WalletLocation &location, uint64_t wallet_creation_flags=0)
Definition: wallet.cpp:3941
bool m_pre_split
Whether this key was generated for a keypool before the wallet was upgraded to HD-split.
Definition: wallet.h:198
bool IsImmatureCoinBase(interfaces::Chain::Lock &locked_chain) const
Definition: wallet.cpp:4362
void ChainStateFlushed(const CBlockLocator &loc) override
Definition: wallet.cpp:567
virtual void requestMempoolTransactions(Notifications &notifications)=0
Synchronously send TransactionAddedToMempool notifications about all current mempool transactions to ...
bool GetReservedKey(CPubKey &pubkey, bool internal=false)
Reserve a key from the keypool.
Definition: wallet.cpp:3615
ScanResult ScanForWalletTransactions(const uint256 &first_block, const uint256 &last_block, const WalletRescanReserver &reserver, bool fUpdate)
Scan the block chain (starting in start_block) for transactions from or to us.
Definition: wallet.cpp:1759
bool SignTransaction(CMutableTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:2485
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:88
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:134
void handleNotifications()
Register the wallet for chain notifications.
Definition: wallet.cpp:4292
#define WAIT_LOCK(cs, name)
Definition: sync.h:187
An output of a transaction.
Definition: transaction.h:133
std::string ToString() const
Definition: uint256.cpp:62
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:292
bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly)
overwrite all flags by the given uint64_t returns false if unknown, non-tolerable flags are present ...
Definition: wallet.cpp:1557
virtual std::unique_ptr< Lock > lock(bool try_lock=false)=0
Return Lock interface.
virtual void getTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants)=0
Calculate mempool ancestor and descendant counts for the given transaction.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
static bool Verify(interfaces::Chain &chain, const WalletLocation &location, bool salvage_wallet, std::string &error_string, std::string &warning_string)
Verify wallet naming and perform salvage on the wallet if required.
Definition: wallet.cpp:3889
KeyOriginInfo key_origin
Definition: walletdb.h:103
int64_t nCreateTime
Definition: walletdb.h:100
size_t tx_noinputs_size
Definition: wallet.h:681
std::vector< CTxOut > vout
Definition: transaction.h:369
void TransactionRemovedFromMempool(const CTransactionRef &ptx) override
Definition: wallet.cpp:1241
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:454
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
Definition: wallet.cpp:1403
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:18
bool has_key_origin
Definition: walletdb.h:104
Special output type for change outputs only.
bool RemoveWatchOnly(const CScript &dest) override
Definition: keystore.cpp:152
void SetSeed(const unsigned char *seed, unsigned int nSeedLen)
Definition: key.cpp:302
boost::optional< bool > m_signal_bip125_rbf
Override the wallet&#39;s m_signal_rbf if set.
Definition: coincontrol.h:34
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:209
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:933
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
Definition: db.h:138
CAmount GetAvailableCredit(interfaces::Chain::Lock &locked_chain, bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS
Definition: wallet.cpp:1974
std::unique_ptr< Wallet > MakeWallet(const std::shared_ptr< CWallet > &wallet)
Return implementation of Wallet interface.
Definition: dummywallet.cpp:81
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:706
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:644
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1303
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:421
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, const bool overwrite)
Definition: walletdb.cpp:60
CAmount GetCachableAmount(AmountType type, const isminefilter &filter, bool recalculate=false) const
Definition: wallet.cpp:1924
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:443
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3702
int nVersion
Definition: walletdb.h:99
void UpdatedBlockTip() override
Definition: wallet.cpp:1282
bool AddWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
Definition: wallet.cpp:460
void KeepKey()
Keep the key. Do not return it to the keypool when this object goes out of scope. ...
Definition: wallet.cpp:3635
std::string _(const char *psz)
Translation function.
Definition: system.h:52
void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1288
int flags
Definition: bitcoin-tx.cpp:507
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:149
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
Definition: wallet.cpp:883
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3676
CPubKey DeriveNewSeed(const CKey &key)
Definition: wallet.cpp:1456
uint256 GetHash() const
Definition: block.cpp:13
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:144
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:103
Capture information about block/transaction validation.
Definition: validation.h:98
256-bit opaque blob.
Definition: uint256.h:121
CPubKey vchPubKey
The public key.
Definition: wallet.h:194
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:15
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
Definition: random.h:205
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:573
virtual bool checkChainLimits(const CTransactionRef &tx)=0
Check if transaction will pass the mempool&#39;s chain limits.
std::vector< CTransactionRef > vtx
Definition: block.h:76
bool AcceptToMemoryPool(interfaces::Chain::Lock &locked_chain, CValidationState &state)
Pass this transaction to the mempool.
Definition: wallet.cpp:4368
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
bool HasWallets()
Definition: wallet.cpp:69
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
Definition: descriptor.cpp:902
An interface to be implemented by keystores that support signing.
Definition: sign.h:49
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3129
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:1316
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:521
void SetWalletFlag(uint64_t flags)
set a single wallet flag
Definition: wallet.cpp:1536
int64_t GetTxTime() const
Definition: wallet.cpp:1572
A wrapper to reserve a key from a wallet keypool.
Definition: wallet.h:252
Interface giving clients (wallet processes, maybe other analysis tools in the future) ability to acce...
Definition: chain.h:58
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0&#39;/2000".
Definition: bip32.cpp:12
void ResendWalletTransactions()
Definition: wallet.cpp:2083
const CChainParams & Params()
Return the currently selected parameters.
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3601
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:390
bool IsNull() const
Definition: block.h:58
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:54
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3271
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret) override
Adds an encrypted key to the store, and saves it to disk.
Definition: wallet.cpp:333
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:465
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:63
void SetHDSeed(const CPubKey &key)
Definition: wallet.cpp:1484
bool Unlock(const CKeyingMaterial &vMasterKeyIn, bool accept_no_keys=false)
Definition: crypter.cpp:178
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:496
bool WriteKeyMetadata(const CKeyMetadata &meta, const CPubKey &pubkey, bool overwrite)
Definition: wallet.cpp:366
virtual void initWarning(const std::string &message)=0
Send init warning.
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey)
Definition: ismine.cpp:175
double leftMempool
Definition: fees.h:64
bool AddKeyOrigin(const CPubKey &pubkey, const KeyOriginInfo &info)
Add a KeyOriginInfo to the wallet.
Definition: wallet.cpp:4446
virtual void initMessage(const std::string &message)=0
Send init message.
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:20
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:348
const CWalletTx * tx
Definition: wallet.h:607
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
Definition: wallet.cpp:4380
std::string GetHex() const
Definition: uint256.cpp:21
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:609
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:59
bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm, CReserveKey &reservekey, CValidationState &state)
Call after CreateTransaction unless you want to abort.
Definition: wallet.cpp:3018
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:692
ArgsManager gArgs
Definition: system.cpp:74
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1103
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:40
virtual 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...
const std::string & GetLabelName(const CScript &scriptPubKey) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3191
#define AssertLockNotHeld(cs)
Definition: sync.h:71
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:445
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: dummywallet.cpp:57
bool KnapsackSolver(const CAmount &nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet)
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:190
std::map< CTxDestination, CAmount > GetAddressBalances(interfaces::Chain::Lock &locked_chain)
Definition: wallet.cpp:3468
void SyncTransaction(const CTransactionRef &tx, const uint256 &block_hash, int posInBlock=0, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:1220
std::vector< unsigned char > vchSalt
Definition: crypter.h:38
static const int VERSION_WITH_KEY_ORIGIN
Definition: walletdb.h:97
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:45
Definition: wallet.h:329
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3871
#define GUARDED_BY(x)
Definition: threadsafety.h:38
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:139
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
Definition: wallet.cpp:3341
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:67
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
bool GetKeyFromPool(CPubKey &key, bool internal=false)
Definition: wallet.cpp:3414
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:211
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:52
Optional< int > last_scanned_height
Definition: wallet.h:1002
A mutable version of CTransaction.
Definition: transaction.h:366
uint256 last_failed_block
Height of the most recent block that could not be scanned due to read errors or pruning.
Definition: wallet.h:1008
size_type size() const
Definition: prevector.h:277
double totalConfirmed
Definition: fees.h:62
bool Unlock(const SecureString &strWalletPassphrase, bool accept_no_keys=false)
Definition: wallet.cpp:498
void ReturnKey()
Return a key to the keypool.
Definition: wallet.cpp:3643
The WalletLocation class provides wallet information.
Definition: walletutil.h:19
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:65
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: time.cpp:20
virtual void loadWallet(std::unique_ptr< Wallet > wallet)=0
Send wallet load notification to the GUI.
std::string ToString() const
Definition: feerate.cpp:40
CFeeRate effective_fee
Definition: wallet.h:680
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:455
An encapsulated private key.
Definition: key.h:27
bool IsFallbackFeeEnabled() const
Return true if the fallback fee is by default enabled for this network.
Definition: chainparams.h:79
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
Definition: error.cpp:40
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
Definition: wallet.cpp:4391
const SigningProvider & DUMMY_SIGNING_PROVIDER
Definition: sign.cpp:441
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:358
CKeyID hd_seed_id
Definition: walletdb.h:102
std::vector< std::string > GetDestValues(const std::string &prefix) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get all destination values matching a prefix.
Definition: wallet.cpp:3858
bool isReserved() const
Definition: wallet.h:1325
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:1337
bool AbandonTransaction(interfaces::Chain::Lock &locked_chain, const uint256 &hashTx)
Definition: wallet.cpp:1113
unsigned int nDeriveIterations
Definition: crypter.h:42
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1711
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1299
bool hashUnset() const
Definition: wallet.h:405
boost::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:139
virtual bool checkFinalTx(const CTransaction &tx)=0
Check if transaction will be final given chain height current time.
bool CanGenerateKeys()
Definition: wallet.cpp:1512
AssertLockHeld(g_cs_orphans)
CKeyID seed_id
seed hash160
Definition: walletdb.h:64
bool BackupWallet(const std::string &strDest)
Definition: wallet.cpp:4310
bool RelayWalletTransaction(interfaces::Chain::Lock &locked_chain)
Definition: wallet.cpp:1889
COutPoint prevout
Definition: transaction.h:66
std::vector< uint32_t > path
Definition: sign.h:26
void GetKeyBirthTimes(interfaces::Chain::Lock &locked_chain, std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3714
int GetDepthInMainChain(interfaces::Chain::Lock &locked_chain) const
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:4345
int GetRandInt(int nMax) noexcept
Definition: random.cpp:670
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:860
void SetMerkleBranch(const uint256 &block_hash, int posInBlock)
Definition: wallet.cpp:4336
bool ParseOutputType(const std::string &type, OutputType &output_type)
Definition: outputtype.cpp:20
bool error(const char *fmt, const Args &... args)
Definition: system.h:61
void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey &pubkey)
Definition: wallet.cpp:3396
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:10
int nVersion
Definition: walletdb.h:69
virtual CFeeRate relayMinFee()=0
Relay current minimum fee (from -minrelaytxfee and -incrementalrelayfee settings).
OutputType TransactionChangeType(OutputType change_type, const std::vector< CRecipient > &vecSend)
Definition: wallet.cpp:2623
static bool RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
Definition: walletdb.cpp:714
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
enum CWallet::ScanResult::@16 status
virtual uint256 getBlockHash(int height)=0
Get block hash. Height must be valid or this function will abort.
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:12
bool fInternal
Whether this keypool entry is in the internal keypool (for change outputs)
Definition: wallet.h:196
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig)
Definition: wallet.cpp:1609
virtual bool findBlock(const uint256 &hash, CBlock *block=nullptr, int64_t *time=nullptr, int64_t *max_time=nullptr)=0
Return whether node has the block and optionally return block metadata or contents.
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
Definition: wallet.cpp:493
static const int VERSION_HD_BASE
Definition: walletdb.h:66
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Look up a destination data tuple in the store, return true if found false otherwise.
Definition: wallet.cpp:3842
virtual bool havePruned()=0
Check if any block has been pruned.
CAmount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:1371
std::map< CTxDestination, std::vector< COutput > > ListCoins(interfaces::Chain::Lock &locked_chain) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Return list of available coins and locked coins grouped by non-change output address.
Definition: wallet.cpp:2290
CTxOut txout
Definition: coinselection.h:37
CPubKey GenerateNewKey(WalletBatch &batch, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
keystore implementation Generate a new key
Definition: wallet.cpp:195
CAmount GetChange() const
Definition: wallet.cpp:2019
CPubKey GenerateNewSeed()
Definition: wallet.cpp:1448
void BlockConnected(const CBlock &block, const std::vector< CTransactionRef > &vtxConflicted) override
Definition: wallet.cpp:1249
bool AddWatchOnly(const CScript &dest) override
Support for Watch-only addresses.
Definition: keystore.cpp:140
A key from a CWallet&#39;s keypool.
Definition: wallet.h:188
int GetBlocksToMaturity(interfaces::Chain::Lock &locked_chain) const
Definition: wallet.cpp:4353
constexpr CAmount HIGH_TX_FEE_PER_KB
Discourage users to set fees higher than this amount (in satoshis) per kB.
Definition: wallet.h:79
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:33
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:453
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
Definition: feerate.cpp:23
bool isAbandoned() const
Definition: wallet.h:406
uint256 hash
Definition: transaction.h:21
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:180
double decay
Definition: fees.h:72