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