Fabcoin Core  0.16.2
P2P Digital Currency
wallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 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 <base58.h>
9 #include <checkpoints.h>
10 #include <chain.h>
11 #include <wallet/coincontrol.h>
12 #include <consensus/consensus.h>
13 #include <consensus/validation.h>
14 #include <fs.h>
15 #include <init.h>
16 #include <key.h>
17 #include <keystore.h>
18 #include <validation.h>
19 #include <net.h>
20 #include <policy/fees.h>
21 #include <policy/policy.h>
22 #include <policy/rbf.h>
23 #include <primitives/block.h>
24 #include <primitives/transaction.h>
25 #include <script/script.h>
26 #include <script/sign.h>
27 #include <scheduler.h>
28 #include <timedata.h>
29 #include <txmempool.h>
30 #include <util.h>
31 #include <ui_interface.h>
32 #include <utilmoneystr.h>
33 
34 #include <assert.h>
35 
36 #include <boost/algorithm/string/replace.hpp>
37 #include <boost/filesystem.hpp>
38 #include <boost/thread.hpp>
39 #include <miner.h>
40 
41 std::vector<CWalletRef> vpwallets;
43 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
44 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
45 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
46 bool bZeroBalanceAddressToken = DEFAULT_ZERO_BALANCE_ADDRESS_TOKEN;
47 bool fWalletRbf = DEFAULT_WALLET_RBF;
48 bool fNotUseChangeAddress = DEFAULT_NOT_USE_CHANGE_ADDRESS;
49 bool fCheckForUpdates = DEFAULT_CHECK_FOR_UPDATES;
50 bool fBatchProcessingMode = false;
51 
52 const char * DEFAULT_WALLET_DAT = "wallet.dat";
53 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
54 
56 
60 };
61 
66 std::map<int, ScriptsElement> scriptsMap;
67 
72 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
73 
79 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
80 
81 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
82 
83 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
84 
85 
86 
87 
94 {
95  bool operator()(const CInputCoin& t1,
96  const CInputCoin& t2) const
97  {
98  return t1.txout.nValue < t2.txout.nValue;
99  }
100 };
101 
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 
107 class CAffectedKeysVisitor : public boost::static_visitor<void> {
108 private:
110  std::vector<CKeyID> &vKeys;
111 
112 public:
113  CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
114 
115  void Process(const CScript &script) {
117  std::vector<CTxDestination> vDest;
118  int nRequired;
119  if (ExtractDestinations(script, type, vDest, nRequired)) {
120  for (const CTxDestination &dest : vDest)
121  boost::apply_visitor(*this, dest);
122  }
123  }
124 
125  void operator()(const CKeyID &keyId) {
126  if (keystore.HaveKey(keyId))
127  vKeys.push_back(keyId);
128  }
129 
130  void operator()(const CScriptID &scriptId) {
131  CScript script;
132  if (keystore.GetCScript(scriptId, script))
133  Process(script);
134  }
135 
136  void operator()(const CNoDestination &none) {}
137 };
138 
140 {
141  LOCK(cs_wallet);
142  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
143  if (it == mapWallet.end())
144  return nullptr;
145  return &(it->second);
146 }
147 
148 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
149 {
150  AssertLockHeld(cs_wallet); // mapKeyMetadata
151  bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
152 
153  CKey secret;
154 
155  // Create new metadata
156  int64_t nCreationTime = GetTime();
157  CKeyMetadata metadata(nCreationTime);
158 
159  // use HD key derivation if HD was enabled during wallet creation
160  if (IsHDEnabled()) {
161  DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
162  } else {
163  secret.MakeNewKey(fCompressed);
164  }
165 
166  // Compressed public keys were introduced in version 0.6.0
167  if (fCompressed) {
168  SetMinVersion(FEATURE_COMPRPUBKEY);
169  }
170 
171  CPubKey pubkey = secret.GetPubKey();
172  assert(secret.VerifyPubKey(pubkey));
173 
174  mapKeyMetadata[pubkey.GetID()] = metadata;
175  UpdateTimeFirstKey(nCreationTime);
176 
177  if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
178  throw std::runtime_error(std::string(__func__) + ": AddKey failed");
179  }
180  return pubkey;
181 }
182 
183 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
184 {
185  // for now we use a fixed keypath scheme of m/0'/0'/k
186  CKey key; //master key seed (256bit)
187  CExtKey masterKey; //hd master key
188  CExtKey accountKey; //key at m/0'
189  CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
190  CExtKey childKey; //key at m/0'/0'/<n>'
191 
192  // try to get the master key
193  if (!GetKey(hdChain.masterKeyID, key))
194  throw std::runtime_error(std::string(__func__) + ": Master key not found");
195 
196  masterKey.SetMaster(key.begin(), key.size());
197 
198  // derive m/0'
199  // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
200  masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
201 
202  // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
203  assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
204  accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
205 
206  // derive child key at next index, skip keys already known to the wallet
207  do {
208  // always derive hardened keys
209  // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
210  // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
211  if (internal) {
212  chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
213  metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
214  hdChain.nInternalChainCounter++;
215  }
216  else {
217  chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
218  metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
219  hdChain.nExternalChainCounter++;
220  }
221  } while (HaveKey(childKey.key.GetPubKey().GetID()));
222  secret = childKey.key;
223  metadata.hdMasterKeyID = hdChain.masterKeyID;
224  // update the chain model in the database
225  if (!walletdb.WriteHDChain(hdChain))
226  throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
227 }
228 
229 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
230 {
231  AssertLockHeld(cs_wallet); // mapKeyMetadata
232 
233  // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
234  // which is overridden below. To avoid flushes, the database handle is
235  // tunneled through to it.
236  bool needsDB = !pwalletdbEncryption;
237  if (needsDB) {
238  pwalletdbEncryption = &walletdb;
239  }
240  if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
241  if (needsDB) pwalletdbEncryption = nullptr;
242  return false;
243  }
244  if (needsDB) pwalletdbEncryption = nullptr;
245 
246  // check if we need to remove from watch-only
247  CScript script;
248  script = GetScriptForDestination(pubkey.GetID());
249  if (HaveWatchOnly(script)) {
250  RemoveWatchOnly(script);
251  }
252  script = GetScriptForRawPubKey(pubkey);
253  if (HaveWatchOnly(script)) {
254  RemoveWatchOnly(script);
255  }
256 
257  if (!IsCrypted()) {
258  return walletdb.WriteKey(pubkey,
259  secret.GetPrivKey(),
260  mapKeyMetadata[pubkey.GetID()]);
261  }
262  return true;
263 }
264 
265 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
266 {
267  CWalletDB walletdb(*dbw);
268  return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
269 }
270 
271 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
272  const std::vector<unsigned char> &vchCryptedSecret)
273 {
274  if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
275  return false;
276  {
277  LOCK(cs_wallet);
278  if (pwalletdbEncryption)
279  return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
280  vchCryptedSecret,
281  mapKeyMetadata[vchPubKey.GetID()]);
282  else
283  return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
284  vchCryptedSecret,
285  mapKeyMetadata[vchPubKey.GetID()]);
286  }
287 }
288 
289 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
290 {
291  AssertLockHeld(cs_wallet); // mapKeyMetadata
292  UpdateTimeFirstKey(meta.nCreateTime);
293  mapKeyMetadata[keyID] = meta;
294  return true;
295 }
296 
297 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
298 {
299  return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
300 }
301 
306 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
307 {
308  AssertLockHeld(cs_wallet);
309  if (nCreateTime <= 1) {
310  // Cannot determine birthday information, so set the wallet birthday to
311  // the beginning of time.
312  nTimeFirstKey = 1;
313  } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
314  nTimeFirstKey = nCreateTime;
315  }
316 }
317 
318 bool CWallet::AddCScript(const CScript& redeemScript)
319 {
320  if (!CCryptoKeyStore::AddCScript(redeemScript))
321  return false;
322  return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
323 }
324 
325 // optional setting to unlock wallet for staking only
326 // serves to disable the trivial sendmoney when OS account compromised
327 // provides no real security
329 
330 bool CWallet::LoadCScript(const CScript& redeemScript)
331 {
332  /* A sanity check was added in pull #3843 to avoid adding redeemScripts
333  * that never can be redeemed. However, old wallets may still contain
334  * these. Do not add them to the wallet and warn. */
335  if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
336  {
337  std::string strAddr = CFabcoinAddress(CScriptID(redeemScript)).ToString();
338  LogPrintf("%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",
339  __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
340  return true;
341  }
342 
343  return CCryptoKeyStore::AddCScript(redeemScript);
344 }
345 
347 {
349  return false;
350  const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
351  UpdateTimeFirstKey(meta.nCreateTime);
352  NotifyWatchonlyChanged(true);
353  return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
354 }
355 
356 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
357 {
358  mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
359  return AddWatchOnly(dest);
360 }
361 
363 {
364  AssertLockHeld(cs_wallet);
366  return false;
367  if (!HaveWatchOnly())
368  NotifyWatchonlyChanged(false);
369  if (!CWalletDB(*dbw).EraseWatchOnly(dest))
370  return false;
371 
372  return true;
373 }
374 
376 {
377  return CCryptoKeyStore::AddWatchOnly(dest);
378 }
379 
380 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
381 {
382  CCrypter crypter;
383  CKeyingMaterial _vMasterKey;
384 
385  {
386  LOCK(cs_wallet);
387  for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
388  {
389  if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
390  return false;
391  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
392  continue; // try another master key
393  if (CCryptoKeyStore::Unlock(_vMasterKey))
394  return true;
395  }
396  }
397  return false;
398 }
399 
400 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
401 {
402  bool fWasLocked = IsLocked();
403 
404  {
405  LOCK(cs_wallet);
406  Lock();
407 
408  CCrypter crypter;
409  CKeyingMaterial _vMasterKey;
410  for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
411  {
412  if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
413  return false;
414  if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
415  return false;
416  if (CCryptoKeyStore::Unlock(_vMasterKey))
417  {
418  int64_t nStartTime = GetTimeMillis();
419  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
420  pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
421 
422  nStartTime = GetTimeMillis();
423  crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
424  pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
425 
426  if (pMasterKey.second.nDeriveIterations < 25000)
427  pMasterKey.second.nDeriveIterations = 25000;
428 
429  LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
430 
431  if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
432  return false;
433  if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
434  return false;
435  CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
436  if (fWasLocked)
437  Lock();
438  return true;
439  }
440  }
441  }
442 
443  return false;
444 }
445 
447 {
448  CWalletDB walletdb(*dbw);
449  walletdb.WriteBestBlock(loc);
450 }
451 
452 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
453 {
454  LOCK(cs_wallet); // nWalletVersion
455  if (nWalletVersion >= nVersion)
456  return true;
457 
458  // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
459  if (fExplicit && nVersion > nWalletMaxVersion)
460  nVersion = FEATURE_LATEST;
461 
462  nWalletVersion = nVersion;
463 
464  if (nVersion > nWalletMaxVersion)
465  nWalletMaxVersion = nVersion;
466 
467  {
468  CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
469  if (nWalletVersion > 40000)
470  pwalletdb->WriteMinVersion(nWalletVersion);
471  if (!pwalletdbIn)
472  delete pwalletdb;
473  }
474 
475  return true;
476 }
477 
478 bool CWallet::SetMaxVersion(int nVersion)
479 {
480  LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
481  // cannot downgrade below current version
482  if (nWalletVersion > nVersion)
483  return false;
484 
485  nWalletMaxVersion = nVersion;
486 
487  return true;
488 }
489 
490 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
491 {
492  std::set<uint256> result;
493  AssertLockHeld(cs_wallet);
494 
495  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
496  if (it == mapWallet.end())
497  return result;
498  const CWalletTx& wtx = it->second;
499 
500  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
501 
502  for (const CTxIn& txin : wtx.tx->vin)
503  {
504  if (mapTxSpends.count(txin.prevout) <= 1)
505  continue; // No conflict if zero or one spends
506  range = mapTxSpends.equal_range(txin.prevout);
507  for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
508  result.insert(_it->second);
509  }
510  return result;
511 }
512 
513 bool CWallet::HasWalletSpend(const uint256& txid) const
514 {
515  AssertLockHeld(cs_wallet);
516  auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
517  return (iter != mapTxSpends.end() && iter->first.hash == txid);
518 }
519 
520 void CWallet::Flush(bool shutdown)
521 {
522  dbw->Flush(shutdown);
523 }
524 
526 {
527  if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
528  return true;
529 
530  uiInterface.InitMessage(_("Verifying wallet(s)..."));
531 
532  // Keep track of each wallet absolute path to detect duplicates.
533  std::set<fs::path> wallet_paths;
534 
535  for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
536  if (boost::filesystem::path(walletFile).filename() != walletFile) {
537  return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
538  }
539 
540  if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
541  return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
542  }
543 
544  fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
545 
546  if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
547  return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
548  }
549 
550  if (!wallet_paths.insert(wallet_path).second) {
551  return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
552  }
553 
554  std::string strError;
555  if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
556  return InitError(strError);
557  }
558 
559  if (gArgs.GetBoolArg("-salvagewallet", false)) {
560  // Recover readable keypairs:
561  CWallet dummyWallet;
562  std::string backup_filename;
563  if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
564  return false;
565  }
566  }
567 
568  std::string strWarning;
569  bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
570  if (!strWarning.empty()) {
571  InitWarning(strWarning);
572  }
573  if (!dbV) {
574  InitError(strError);
575  return false;
576  }
577  }
578 
579  return true;
580 }
581 
582 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
583 {
584  // We want all the wallet transactions in range to have the same metadata as
585  // the oldest (smallest nOrderPos).
586  // So: find smallest nOrderPos:
587 
588  int nMinOrderPos = std::numeric_limits<int>::max();
589  const CWalletTx* copyFrom = nullptr;
590  for (TxSpends::iterator it = range.first; it != range.second; ++it)
591  {
592  const uint256& hash = it->second;
593  int n = mapWallet[hash].nOrderPos;
594  if (n < nMinOrderPos)
595  {
596  nMinOrderPos = n;
597  copyFrom = &mapWallet[hash];
598  }
599  }
600  // Now copy data from copyFrom to rest:
601  for (TxSpends::iterator it = range.first; it != range.second; ++it)
602  {
603  const uint256& hash = it->second;
604  CWalletTx* copyTo = &mapWallet[hash];
605  if (copyFrom == copyTo) continue;
606  if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
607  copyTo->mapValue = copyFrom->mapValue;
608  copyTo->vOrderForm = copyFrom->vOrderForm;
609  // fTimeReceivedIsTxTime not copied on purpose
610  // nTimeReceived not copied on purpose
611  copyTo->nTimeSmart = copyFrom->nTimeSmart;
612  copyTo->fFromMe = copyFrom->fFromMe;
613  copyTo->strFromAccount = copyFrom->strFromAccount;
614  // nOrderPos not copied on purpose
615  // cached members not copied on purpose
616  }
617 }
618 
623 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
624 {
625  const COutPoint outpoint(hash, n);
626  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
627  range = mapTxSpends.equal_range(outpoint);
628 
629  for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
630  {
631  const uint256& wtxid = it->second;
632  std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
633  if (mit != mapWallet.end()) {
634  int depth = mit->second.GetDepthInMainChain();
635  if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
636  return true; // Spent
637  }
638  }
639  return false;
640 }
641 
642 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
643 {
644  mapTxSpends.insert(std::make_pair(outpoint, wtxid));
645 
646  std::pair<TxSpends::iterator, TxSpends::iterator> range;
647  range = mapTxSpends.equal_range(outpoint);
648  SyncMetaData(range);
649 }
650 
651 
652 void CWallet::AddToSpends(const uint256& wtxid)
653 {
654  assert(mapWallet.count(wtxid));
655  CWalletTx& thisTx = mapWallet[wtxid];
656  if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
657  return;
658 
659  for (const CTxIn& txin : thisTx.tx->vin)
660  AddToSpends(txin.prevout, wtxid);
661 }
662 
663 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
664 {
665  if (IsCrypted())
666  return false;
667 
668  CKeyingMaterial _vMasterKey;
669 
670  _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
671  GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
672 
673  CMasterKey kMasterKey;
674 
675  kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
677 
678  CCrypter crypter;
679  int64_t nStartTime = GetTimeMillis();
680  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
681  kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
682 
683  nStartTime = GetTimeMillis();
684  crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
685  kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
686 
687  if (kMasterKey.nDeriveIterations < 25000)
688  kMasterKey.nDeriveIterations = 25000;
689 
690  LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
691 
692  if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
693  return false;
694  if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
695  return false;
696 
697  {
698  LOCK(cs_wallet);
699  mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
700  assert(!pwalletdbEncryption);
701  pwalletdbEncryption = new CWalletDB(*dbw);
702  if (!pwalletdbEncryption->TxnBegin()) {
703  delete pwalletdbEncryption;
704  pwalletdbEncryption = nullptr;
705  return false;
706  }
707  pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
708 
709  if (!EncryptKeys(_vMasterKey))
710  {
711  pwalletdbEncryption->TxnAbort();
712  delete pwalletdbEncryption;
713  // We now probably have half of our keys encrypted in memory, and half not...
714  // die and let the user reload the unencrypted wallet.
715  assert(false);
716  }
717 
718  // Encryption was introduced in version 0.4.0
719  SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
720 
721  if (!pwalletdbEncryption->TxnCommit()) {
722  delete pwalletdbEncryption;
723  // We now have keys encrypted in memory, but not on disk...
724  // die to avoid confusion and let the user reload the unencrypted wallet.
725  assert(false);
726  }
727 
728  delete pwalletdbEncryption;
729  pwalletdbEncryption = nullptr;
730 
731  Lock();
732  Unlock(strWalletPassphrase);
733 
734  // if we are using HD, replace the HD master key (seed) with a new one
735  if (IsHDEnabled()) {
736  if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
737  return false;
738  }
739  }
740 
741  NewKeyPool();
742  Lock();
743 
744  // Need to completely rewrite the wallet file; if we don't, bdb might keep
745  // bits of the unencrypted private key in slack space in the database file.
746  dbw->Rewrite();
747 
748  }
749  NotifyStatusChanged(this);
750 
751  return true;
752 }
753 
755 {
756  LOCK(cs_wallet);
757  CWalletDB walletdb(*dbw);
758 
759  // Old wallets didn't have any defined order for transactions
760  // Probably a bad idea to change the output of this
761 
762  // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
763  typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
764  typedef std::multimap<int64_t, TxPair > TxItems;
765  TxItems txByTime;
766 
767  for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
768  {
769  CWalletTx* wtx = &((*it).second);
770  txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
771  }
772  std::list<CAccountingEntry> acentries;
773  walletdb.ListAccountCreditDebit("", acentries);
774  for (CAccountingEntry& entry : acentries)
775  {
776  txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
777  }
778 
779  nOrderPosNext = 0;
780  std::vector<int64_t> nOrderPosOffsets;
781  for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
782  {
783  CWalletTx *const pwtx = (*it).second.first;
784  CAccountingEntry *const pacentry = (*it).second.second;
785  int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
786 
787  if (nOrderPos == -1)
788  {
789  nOrderPos = nOrderPosNext++;
790  nOrderPosOffsets.push_back(nOrderPos);
791 
792  if (pwtx)
793  {
794  if (!walletdb.WriteTx(*pwtx))
795  return DB_LOAD_FAIL;
796  }
797  else
798  if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
799  return DB_LOAD_FAIL;
800  }
801  else
802  {
803  int64_t nOrderPosOff = 0;
804  for (const int64_t& nOffsetStart : nOrderPosOffsets)
805  {
806  if (nOrderPos >= nOffsetStart)
807  ++nOrderPosOff;
808  }
809  nOrderPos += nOrderPosOff;
810  nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
811 
812  if (!nOrderPosOff)
813  continue;
814 
815  // Since we're changing the order, write it back
816  if (pwtx)
817  {
818  if (!walletdb.WriteTx(*pwtx))
819  return DB_LOAD_FAIL;
820  }
821  else
822  if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
823  return DB_LOAD_FAIL;
824  }
825  }
826  walletdb.WriteOrderPosNext(nOrderPosNext);
827 
828  return DB_LOAD_OK;
829 }
830 
832 {
833  AssertLockHeld(cs_wallet); // nOrderPosNext
834  int64_t nRet = nOrderPosNext++;
835  if (pwalletdb) {
836  pwalletdb->WriteOrderPosNext(nOrderPosNext);
837  } else {
838  CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
839  }
840  return nRet;
841 }
842 
843 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
844 {
845  CWalletDB walletdb(*dbw);
846  if (!walletdb.TxnBegin())
847  return false;
848 
849  int64_t nNow = GetAdjustedTime();
850 
851  // Debit
852  CAccountingEntry debit;
853  debit.nOrderPos = IncOrderPosNext(&walletdb);
854  debit.strAccount = strFrom;
855  debit.nCreditDebit = -nAmount;
856  debit.nTime = nNow;
857  debit.strOtherAccount = strTo;
858  debit.strComment = strComment;
859  AddAccountingEntry(debit, &walletdb);
860 
861  // Credit
862  CAccountingEntry credit;
863  credit.nOrderPos = IncOrderPosNext(&walletdb);
864  credit.strAccount = strTo;
865  credit.nCreditDebit = nAmount;
866  credit.nTime = nNow;
867  credit.strOtherAccount = strFrom;
868  credit.strComment = strComment;
869  AddAccountingEntry(credit, &walletdb);
870 
871  if (!walletdb.TxnCommit())
872  return false;
873 
874  return true;
875 }
876 
877 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
878 {
879  CWalletDB walletdb(*dbw);
880 
881  CAccount account;
882  walletdb.ReadAccount(strAccount, account);
883 
884  if (!bForceNew) {
885  if (!account.vchPubKey.IsValid())
886  bForceNew = true;
887  else {
888  // Check if the current key has been used
889  CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
890  for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
891  it != mapWallet.end() && account.vchPubKey.IsValid();
892  ++it)
893  for (const CTxOut& txout : (*it).second.tx->vout)
894  if (txout.scriptPubKey == scriptPubKey) {
895  bForceNew = true;
896  break;
897  }
898  }
899  }
900 
901  // Generate a new key
902  if (bForceNew) {
903  if (!GetKeyFromPool(account.vchPubKey, false))
904  return false;
905 
906  SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
907  walletdb.WriteAccount(strAccount, account);
908  }
909 
910  pubKey = account.vchPubKey;
911 
912  return true;
913 }
914 
916 {
917  {
918  LOCK(cs_wallet);
919  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
920  item.second.MarkDirty();
921  }
922 }
923 
924 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
925 {
926  LOCK(cs_wallet);
927 
928  auto mi = mapWallet.find(originalHash);
929 
930  // There is a bug if MarkReplaced is not called on an existing wallet transaction.
931  assert(mi != mapWallet.end());
932 
933  CWalletTx& wtx = (*mi).second;
934 
935  // Ensure for now that we're not overwriting data
936  assert(wtx.mapValue.count("replaced_by_txid") == 0);
937 
938  wtx.mapValue["replaced_by_txid"] = newHash.ToString();
939 
940  CWalletDB walletdb(*dbw, "r+");
941 
942  bool success = true;
943  if (!walletdb.WriteTx(wtx)) {
944  LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
945  success = false;
946  }
947 
948  NotifyTransactionChanged(this, originalHash, CT_UPDATED);
949 
950  return success;
951 }
952 
953 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
954 {
955  LOCK(cs_wallet);
956 
957  CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
958 
959  uint256 hash = wtxIn.GetHash();
960 
961  // Inserts only if not already there, returns tx inserted or tx found
962  std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
963  CWalletTx& wtx = (*ret.first).second;
964  wtx.BindWallet(this);
965  bool fInsertedNew = ret.second;
966  if (fInsertedNew)
967  {
969  wtx.nOrderPos = IncOrderPosNext(&walletdb);
970  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
971  wtx.nTimeSmart = ComputeTimeSmart(wtx);
972  AddToSpends(hash);
973  }
974 
975  bool fUpdated = false;
976  if (!fInsertedNew)
977  {
978  // Merge
979  if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
980  {
981  wtx.hashBlock = wtxIn.hashBlock;
982  fUpdated = true;
983  }
984  // If no longer abandoned, update
985  if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
986  {
987  wtx.hashBlock = wtxIn.hashBlock;
988  fUpdated = true;
989  }
990  if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
991  {
992  wtx.nIndex = wtxIn.nIndex;
993  fUpdated = true;
994  }
995  if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
996  {
997  wtx.fFromMe = wtxIn.fFromMe;
998  fUpdated = true;
999  }
1000  // If we have a witness-stripped version of this transaction, and we
1001  // see a new version with a witness, then we must be upgrading a pre-segwit
1002  // wallet. Store the new version of the transaction with the witness,
1003  // as the stripped-version must be invalid.
1004  // TODO: Store all versions of the transaction, instead of just one.
1005  if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
1006  wtx.SetTx(wtxIn.tx);
1007  fUpdated = true;
1008  }
1009  }
1010 
1012  LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
1013 
1014  // Write to disk
1015  if (fInsertedNew || fUpdated)
1016  if (!walletdb.WriteTx(wtx))
1017  return false;
1018 
1019  // Break debit/credit balance caches:
1020  wtx.MarkDirty();
1021 
1022  // Notify UI of new or updated transaction
1023  NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
1024 
1025  // notify an external script when a wallet transaction comes in or is updated
1026  std::string strCmd = gArgs.GetArg("-walletnotify", "");
1027 
1028  if ( !strCmd.empty())
1029  {
1030  boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
1031  boost::thread t(runCommand, strCmd); // thread runs free
1032  }
1033 
1034  return true;
1035 }
1036 
1038 {
1039  uint256 hash = wtxIn.GetHash();
1040 
1041  mapWallet[hash] = wtxIn;
1042  CWalletTx& wtx = mapWallet[hash];
1043  wtx.BindWallet(this);
1044  wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1045  AddToSpends(hash);
1046  for (const CTxIn& txin : wtx.tx->vin) {
1047  if (mapWallet.count(txin.prevout.hash)) {
1048  CWalletTx& prevtx = mapWallet[txin.prevout.hash];
1049  if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1050  MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1051  }
1052  }
1053  }
1054 
1055  return true;
1056 }
1057 
1071 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1072 {
1073  const CTransaction& tx = *ptx;
1074  {
1075  AssertLockHeld(cs_wallet);
1076 
1077  if (pIndex != nullptr) {
1078  for (const CTxIn& txin : tx.vin) {
1079  std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1080  while (range.first != range.second) {
1081  if (range.first->second != tx.GetHash()) {
1082  LogPrintf("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);
1083  MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1084  }
1085  range.first++;
1086  }
1087  }
1088  }
1089 
1090  bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1091  if (fExisted && !fUpdate) return false;
1092  if (fExisted || IsMine(tx) || IsFromMe(tx))
1093  {
1094  /* Check if any keys in the wallet keypool that were supposed to be unused
1095  * have appeared in a new transaction. If so, remove those keys from the keypool.
1096  * This can happen when restoring an old wallet backup that does not contain
1097  * the mostly recently created transactions from newer versions of the wallet.
1098  */
1099 
1100  // loop though all outputs
1101  for (const CTxOut& txout: tx.vout) {
1102  // extract addresses and check if they match with an unused keypool key
1103  std::vector<CKeyID> vAffected;
1104  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1105  for (const CKeyID &keyid : vAffected) {
1106  std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1107  if (mi != m_pool_key_to_index.end()) {
1108  LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1109  MarkReserveKeysAsUsed(mi->second);
1110 
1111  if (!TopUpKeyPool()) {
1112  LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1113  }
1114  }
1115  }
1116  }
1117 
1118  CWalletTx wtx(this, ptx);
1119 
1120  // Get merkle branch if transaction was found in a block
1121  if (pIndex != nullptr)
1122  wtx.SetMerkleBranch(pIndex, posInBlock);
1123 
1124  return AddToWallet(wtx, false);
1125  }
1126  }
1127  return false;
1128 }
1129 
1131 {
1132  LOCK2(cs_main, cs_wallet);
1133  const CWalletTx* wtx = GetWalletTx(hashTx);
1134  return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1135 }
1136 
1138 {
1139  LOCK2(cs_main, cs_wallet);
1140 
1141  CWalletDB walletdb(*dbw, "r+");
1142 
1143  std::set<uint256> todo;
1144  std::set<uint256> done;
1145 
1146  // Can't mark abandoned if confirmed or in mempool
1147  assert(mapWallet.count(hashTx));
1148  CWalletTx& origtx = mapWallet[hashTx];
1149  if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1150  return false;
1151  }
1152 
1153  todo.insert(hashTx);
1154 
1155  while (!todo.empty()) {
1156  uint256 now = *todo.begin();
1157  todo.erase(now);
1158  done.insert(now);
1159  assert(mapWallet.count(now));
1160  CWalletTx& wtx = mapWallet[now];
1161  int currentconfirm = wtx.GetDepthInMainChain();
1162  // If the orig tx was not in block, none of its spends can be
1163  assert(currentconfirm <= 0);
1164  // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1165  if (currentconfirm == 0 && !wtx.isAbandoned()) {
1166  // If the orig tx was not in block/mempool, none of its spends can be in mempool
1167  assert(!wtx.InMempool());
1168  wtx.nIndex = -1;
1169  wtx.setAbandoned();
1170  wtx.MarkDirty();
1171  walletdb.WriteTx(wtx);
1172  NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1173  // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1174  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1175  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1176  if (!done.count(iter->second)) {
1177  todo.insert(iter->second);
1178  }
1179  iter++;
1180  }
1181  // If a transaction changes 'conflicted' state, that changes the balance
1182  // available of the outputs it spends. So force those to be recomputed
1183  for (const CTxIn& txin : wtx.tx->vin)
1184  {
1185  if (mapWallet.count(txin.prevout.hash))
1186  mapWallet[txin.prevout.hash].MarkDirty();
1187  }
1188  }
1189  }
1190 
1191  return true;
1192 }
1193 
1194 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1195 {
1196  LOCK2(cs_main, cs_wallet);
1197 
1198  int conflictconfirms = 0;
1199  if (mapBlockIndex.count(hashBlock)) {
1200  CBlockIndex* pindex = mapBlockIndex[hashBlock];
1201  if (chainActive.Contains(pindex)) {
1202  conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1203  }
1204  }
1205  // If number of conflict confirms cannot be determined, this means
1206  // that the block is still unknown or not yet part of the main chain,
1207  // for example when loading the wallet during a reindex. Do nothing in that
1208  // case.
1209  if (conflictconfirms >= 0)
1210  return;
1211 
1212  // Do not flush the wallet here for performance reasons
1213  CWalletDB walletdb(*dbw, "r+", false);
1214 
1215  std::set<uint256> todo;
1216  std::set<uint256> done;
1217 
1218  todo.insert(hashTx);
1219 
1220  while (!todo.empty()) {
1221  uint256 now = *todo.begin();
1222  todo.erase(now);
1223  done.insert(now);
1224  assert(mapWallet.count(now));
1225  CWalletTx& wtx = mapWallet[now];
1226  int currentconfirm = wtx.GetDepthInMainChain();
1227  if (conflictconfirms < currentconfirm) {
1228  // Block is 'more conflicted' than current confirm; update.
1229  // Mark transaction as conflicted with this block.
1230  wtx.nIndex = -1;
1231  wtx.hashBlock = hashBlock;
1232  wtx.MarkDirty();
1233  walletdb.WriteTx(wtx);
1234  // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1235  TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1236  while (iter != mapTxSpends.end() && iter->first.hash == now) {
1237  if (!done.count(iter->second)) {
1238  todo.insert(iter->second);
1239  }
1240  iter++;
1241  }
1242  // If a transaction changes 'conflicted' state, that changes the balance
1243  // available of the outputs it spends. So force those to be recomputed
1244  for (const CTxIn& txin : wtx.tx->vin)
1245  {
1246  if (mapWallet.count(txin.prevout.hash))
1247  mapWallet[txin.prevout.hash].MarkDirty();
1248  }
1249  }
1250  }
1251 }
1252 
1253 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1254  const CTransaction& tx = *ptx;
1255 
1256  if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1257  return; // Not one of ours
1258 
1259  // If a transaction changes 'conflicted' state, that changes the balance
1260  // available of the outputs it spends. So force those to be
1261  // recomputed, also:
1262  for (const CTxIn& txin : tx.vin)
1263  {
1264  if (mapWallet.count(txin.prevout.hash))
1265  mapWallet[txin.prevout.hash].MarkDirty();
1266  }
1267 }
1268 
1270  LOCK2(cs_main, cs_wallet);
1271  SyncTransaction(ptx);
1272 }
1273 
1274 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1275  LOCK2(cs_main, cs_wallet);
1276  // TODO: Temporarily ensure that mempool removals are notified before
1277  // connected transactions. This shouldn't matter, but the abandoned
1278  // state of transactions in our wallet is currently cleared when we
1279  // receive another notification and there is a race condition where
1280  // notification of a connected conflict might cause an outside process
1281  // to abandon a transaction and then have it inadvertently cleared by
1282  // the notification that the conflicted transaction was evicted.
1283 
1284  for (const CTransactionRef& ptx : vtxConflicted) {
1285  SyncTransaction(ptx);
1286  }
1287  for (size_t i = 0; i < pblock->vtx.size(); i++) {
1288  SyncTransaction(pblock->vtx[i], pindex, i);
1289  }
1290 }
1291 
1292 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1293  LOCK2(cs_main, cs_wallet);
1294 
1295  for (const CTransactionRef& ptx : pblock->vtx) {
1296  SyncTransaction(ptx);
1297  }
1298 }
1299 
1300 
1301 
1303 {
1304  {
1305  LOCK(cs_wallet);
1306  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1307  if (mi != mapWallet.end())
1308  {
1309  const CWalletTx& prev = (*mi).second;
1310  if (txin.prevout.n < prev.tx->vout.size())
1311  return IsMine(prev.tx->vout[txin.prevout.n]);
1312  }
1313  }
1314  return ISMINE_NO;
1315 }
1316 
1317 // Note that this function doesn't distinguish between a 0-valued input,
1318 // and a not-"is mine" (according to the filter) input.
1319 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1320 {
1321  {
1322  LOCK(cs_wallet);
1323  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1324  if (mi != mapWallet.end())
1325  {
1326  const CWalletTx& prev = (*mi).second;
1327  if (txin.prevout.n < prev.tx->vout.size())
1328  if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1329  return prev.tx->vout[txin.prevout.n].nValue;
1330  }
1331  }
1332  return 0;
1333 }
1334 
1335 isminetype CWallet::IsMine(const CTxOut& txout) const
1336 {
1337  return ::IsMine(*this, txout.scriptPubKey);
1338 }
1339 
1340 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1341 {
1342  if (!MoneyRange(txout.nValue))
1343  throw std::runtime_error(std::string(__func__) + ": value out of range");
1344  return ((IsMine(txout) & filter) ? txout.nValue : 0);
1345 }
1346 
1347 bool CWallet::IsChange(const CTxOut& txout) const
1348 {
1349  // TODO: fix handling of 'change' outputs. The assumption is that any
1350  // payment to a script that is ours, but is not in the address book
1351  // is change. That assumption is likely to break when we implement multisignature
1352  // wallets that return change back into a multi-signature-protected address;
1353  // a better way of identifying which outputs are 'the send' and which are
1354  // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1355  // which output, if any, was change).
1356  if (::IsMine(*this, txout.scriptPubKey))
1357  {
1359  if (!ExtractDestination(txout.scriptPubKey, address))
1360  return true;
1361 
1362  LOCK(cs_wallet);
1363  if (!mapAddressBook.count(address))
1364  return true;
1365  }
1366  return false;
1367 }
1368 
1369 CAmount CWallet::GetChange(const CTxOut& txout) const
1370 {
1371  if (!MoneyRange(txout.nValue))
1372  throw std::runtime_error(std::string(__func__) + ": value out of range");
1373  return (IsChange(txout) ? txout.nValue : 0);
1374 }
1375 
1376 bool CWallet::IsMine(const CTransaction& tx) const
1377 {
1378  for (const CTxOut& txout : tx.vout)
1379  if (IsMine(txout))
1380  return true;
1381  return false;
1382 }
1383 
1384 bool CWallet::IsFromMe(const CTransaction& tx) const
1385 {
1386  return (GetDebit(tx, ISMINE_ALL) > 0);
1387 }
1388 
1389 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1390 {
1391  CAmount nDebit = 0;
1392  for (const CTxIn& txin : tx.vin)
1393  {
1394  nDebit += GetDebit(txin, filter);
1395  if (!MoneyRange(nDebit))
1396  throw std::runtime_error(std::string(__func__) + ": value out of range");
1397  }
1398  return nDebit;
1399 }
1400 
1401 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1402 {
1403  LOCK(cs_wallet);
1404 
1405  for (const CTxIn& txin : tx.vin)
1406  {
1407  auto mi = mapWallet.find(txin.prevout.hash);
1408  if (mi == mapWallet.end())
1409  return false; // any unknown inputs can't be from us
1410 
1411  const CWalletTx& prev = (*mi).second;
1412 
1413  if (txin.prevout.n >= prev.tx->vout.size())
1414  return false; // invalid input!
1415 
1416  if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1417  return false;
1418  }
1419  return true;
1420 }
1421 
1422 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1423 {
1424  CAmount nCredit = 0;
1425  for (const CTxOut& txout : tx.vout)
1426  {
1427  nCredit += GetCredit(txout, filter);
1428  if (!MoneyRange(nCredit))
1429  throw std::runtime_error(std::string(__func__) + ": value out of range");
1430  }
1431  return nCredit;
1432 }
1433 
1435 {
1436  CAmount nChange = 0;
1437  for (const CTxOut& txout : tx.vout)
1438  {
1439  nChange += GetChange(txout);
1440  if (!MoneyRange(nChange))
1441  throw std::runtime_error(std::string(__func__) + ": value out of range");
1442  }
1443  return nChange;
1444 }
1445 
1447 {
1448  CKey key;
1449  key.MakeNewKey(true);
1450 
1451  int64_t nCreationTime = GetTime();
1452  CKeyMetadata metadata(nCreationTime);
1453 
1454  // calculate the pubkey
1455  CPubKey pubkey = key.GetPubKey();
1456  assert(key.VerifyPubKey(pubkey));
1457 
1458  // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1459  metadata.hdKeypath = "m";
1460  metadata.hdMasterKeyID = pubkey.GetID();
1461 
1462  {
1463  LOCK(cs_wallet);
1464 
1465  // mem store the metadata
1466  mapKeyMetadata[pubkey.GetID()] = metadata;
1467 
1468  // write the key&metadata to the database
1469  if (!AddKeyPubKey(key, pubkey))
1470  throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1471  }
1472 
1473  return pubkey;
1474 }
1475 
1477 {
1478  LOCK(cs_wallet);
1479  // store the keyid (hash160) together with
1480  // the child index counter in the database
1481  // as a hdchain object
1482  CHDChain newHdChain;
1484  newHdChain.masterKeyID = pubkey.GetID();
1485  SetHDChain(newHdChain, false);
1486 
1487  return true;
1488 }
1489 
1490 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1491 {
1492  LOCK(cs_wallet);
1493  if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1494  throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1495 
1496  hdChain = chain;
1497  return true;
1498 }
1499 
1501 {
1502  return !hdChain.masterKeyID.IsNull();
1503 }
1504 
1505 int64_t CWalletTx::GetTxTime() const
1506 {
1507  int64_t n = nTimeSmart;
1508  return n ? n : nTimeReceived;
1509 }
1510 
1512 {
1513  // Returns -1 if it wasn't being tracked
1514  int nRequests = -1;
1515  {
1516  LOCK(pwallet->cs_wallet);
1517  if (IsCoinBase())
1518  {
1519  // Generated block
1520  if (!hashUnset())
1521  {
1522  std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1523  if (mi != pwallet->mapRequestCount.end())
1524  nRequests = (*mi).second;
1525  }
1526  }
1527  else
1528  {
1529  // Did anyone request this transaction?
1530  std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1531  if (mi != pwallet->mapRequestCount.end())
1532  {
1533  nRequests = (*mi).second;
1534 
1535  // How about the block it's in?
1536  if (nRequests == 0 && !hashUnset())
1537  {
1538  std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1539  if (_mi != pwallet->mapRequestCount.end())
1540  nRequests = (*_mi).second;
1541  else
1542  nRequests = 1; // If it's in someone else's block it must have got out
1543  }
1544  }
1545  }
1546  }
1547  return nRequests;
1548 }
1549 
1550 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1551  std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1552 {
1553  nFee = 0;
1554  listReceived.clear();
1555  listSent.clear();
1556  strSentAccount = strFromAccount;
1557 
1558  // Compute fee:
1559  CAmount nDebit = GetDebit(filter);
1560  if (nDebit > 0) // debit>0 means we signed/sent this transaction
1561  {
1562  CAmount nValueOut = tx->GetValueOut();
1563  nFee = nDebit - nValueOut;
1564  }
1565 
1566  // Sent/received.
1567  for (unsigned int i = 0; i < tx->vout.size(); ++i)
1568  {
1569  const CTxOut& txout = tx->vout[i];
1570  isminetype fIsMine = pwallet->IsMine(txout);
1571  // Only need to handle txouts if AT LEAST one of these is true:
1572  // 1) they debit from us (sent)
1573  // 2) the output is to us (received)
1574  if (nDebit > 0)
1575  {
1576  // Don't report 'change' txouts
1577  if (pwallet->IsChange(txout))
1578  continue;
1579  }
1580  else if (!(fIsMine & filter))
1581  continue;
1582 
1583  // In either case, we need to get the destination address
1585 
1586  if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1587  {
1588  LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1589  this->GetHash().ToString());
1590  address = CNoDestination();
1591  }
1592 
1593  COutputEntry output = {address, txout.nValue, (int)i};
1594 
1595  // If we are debited by the transaction, add the output as a "sent" entry
1596  if (nDebit > 0)
1597  listSent.push_back(output);
1598 
1599  // If we are receiving the output, add it as a "received" entry
1600  if (fIsMine & filter)
1601  listReceived.push_back(output);
1602  }
1603 
1604 }
1605 
1614 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1615 {
1617  AssertLockHeld(cs_wallet);
1618 
1619  // Find starting block. May be null if nCreateTime is greater than the
1620  // highest blockchain timestamp, in which case there is nothing that needs
1621  // to be scanned.
1622  CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1623  LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1624 
1625  if (startBlock) {
1626  const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1627  if (failedBlock) {
1628  return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1629  }
1630  }
1631  return startTime;
1632 }
1633 
1644 {
1645  int64_t nNow = GetTime();
1646  const CChainParams& chainParams = Params();
1647 
1648  CBlockIndex* pindex = pindexStart;
1649  CBlockIndex* ret = nullptr;
1650  {
1651  LOCK2(cs_main, cs_wallet);
1652  fAbortRescan = false;
1653  fScanningWallet = true;
1654 
1655  ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1656  double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1657  double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1658  while (pindex && !fAbortRescan)
1659  {
1660  if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1661  ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1662  if (GetTime() >= nNow + 60) {
1663  nNow = GetTime();
1664  LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1665  }
1666 
1667  CBlock block;
1668  if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1669  for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1670  AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1671  }
1672  } else {
1673  ret = pindex;
1674  }
1675  pindex = chainActive.Next(pindex);
1676  }
1677  if (pindex && fAbortRescan) {
1678  LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1679  }
1680  ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1681 
1682  fScanningWallet = false;
1683  }
1684  return ret;
1685 }
1686 
1688 {
1689  // If transactions aren't being broadcasted, don't let them into local mempool either
1690  if (!fBroadcastTransactions)
1691  return;
1692  LOCK2(cs_main, cs_wallet);
1693  std::map<int64_t, CWalletTx*> mapSorted;
1694 
1695  // Sort pending wallet transactions based on their initial wallet insertion order
1696  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1697  {
1698  const uint256& wtxid = item.first;
1699  CWalletTx& wtx = item.second;
1700  assert(wtx.GetHash() == wtxid);
1701 
1702  int nDepth = wtx.GetDepthInMainChain();
1703 
1704  if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1705  mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1706  }
1707  }
1708 
1709  // Try to add wallet transactions to memory pool
1710  for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1711  {
1712  CWalletTx& wtx = *(item.second);
1713 
1714  LOCK(mempool.cs);
1715  CValidationState state;
1716  wtx.AcceptToMemoryPool(maxTxFee, state);
1717  }
1718 }
1719 
1721 {
1722  assert(pwallet->GetBroadcastTransactions());
1723  if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1724  {
1725  CValidationState state;
1726  /* GetDepthInMainChain already catches known conflicts. */
1727  if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1728  LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1729  if (connman) {
1730  CInv inv(MSG_TX, GetHash());
1731  connman->ForEachNode([&inv](CNode* pnode)
1732  {
1733  pnode->PushInventory(inv);
1734  });
1735  return true;
1736  }
1737  }
1738  }
1739  return false;
1740 }
1741 
1742 std::set<uint256> CWalletTx::GetConflicts() const
1743 {
1744  std::set<uint256> result;
1745  if (pwallet != nullptr)
1746  {
1747  uint256 myHash = GetHash();
1748  result = pwallet->GetConflicts(myHash);
1749  result.erase(myHash);
1750  }
1751  return result;
1752 }
1753 
1755 {
1756  if (tx->vin.empty())
1757  return 0;
1758 
1759  CAmount debit = 0;
1760  if(filter & ISMINE_SPENDABLE)
1761  {
1762  if (fDebitCached)
1763  debit += nDebitCached;
1764  else
1765  {
1766  nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1767  fDebitCached = true;
1768  debit += nDebitCached;
1769  }
1770  }
1771  if(filter & ISMINE_WATCH_ONLY)
1772  {
1773  if(fWatchDebitCached)
1774  debit += nWatchDebitCached;
1775  else
1776  {
1777  nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1778  fWatchDebitCached = true;
1779  debit += nWatchDebitCached;
1780  }
1781  }
1782  return debit;
1783 }
1784 
1786 {
1787  // Must wait until coinbase is safely deep enough in the chain before valuing it
1788  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1789  return 0;
1790 
1791  CAmount credit = 0;
1792  if (filter & ISMINE_SPENDABLE)
1793  {
1794  // GetBalance can assume transactions in mapWallet won't change
1795  if (fCreditCached)
1796  credit += nCreditCached;
1797  else
1798  {
1799  nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1800  fCreditCached = true;
1801  credit += nCreditCached;
1802  }
1803  }
1804  if (filter & ISMINE_WATCH_ONLY)
1805  {
1806  if (fWatchCreditCached)
1807  credit += nWatchCreditCached;
1808  else
1809  {
1810  nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1811  fWatchCreditCached = true;
1812  credit += nWatchCreditCached;
1813  }
1814  }
1815  return credit;
1816 }
1817 
1819 {
1820  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1821  {
1822  if (fUseCache && fImmatureCreditCached)
1823  return nImmatureCreditCached;
1824  nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1825  fImmatureCreditCached = true;
1826  return nImmatureCreditCached;
1827  }
1828 
1829  return 0;
1830 }
1831 
1833 {
1834  if (pwallet == 0)
1835  return 0;
1836 
1837  // Must wait until coinbase is safely deep enough in the chain before valuing it
1838  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1839  return 0;
1840 
1841  if (fUseCache && fAvailableCreditCached)
1842  return nAvailableCreditCached;
1843 
1844  CAmount nCredit = 0;
1845  uint256 hashTx = GetHash();
1846  for (unsigned int i = 0; i < tx->vout.size(); i++)
1847  {
1848  if (!pwallet->IsSpent(hashTx, i))
1849  {
1850  const CTxOut &txout = tx->vout[i];
1851  nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1852  if (!MoneyRange(nCredit))
1853  throw std::runtime_error(std::string(__func__) + " : value out of range");
1854  }
1855  }
1856 
1857  nAvailableCreditCached = nCredit;
1858  fAvailableCreditCached = true;
1859  return nCredit;
1860 }
1861 
1863 {
1864  if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1865  {
1866  if (fUseCache && fImmatureWatchCreditCached)
1867  return nImmatureWatchCreditCached;
1868  nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1869  fImmatureWatchCreditCached = true;
1870  return nImmatureWatchCreditCached;
1871  }
1872 
1873  return 0;
1874 }
1875 
1877 {
1878  if (pwallet == 0)
1879  return 0;
1880 
1881  // Must wait until coinbase is safely deep enough in the chain before valuing it
1882  if (IsCoinBase() && GetBlocksToMaturity() > 0)
1883  return 0;
1884 
1885  if (fUseCache && fAvailableWatchCreditCached)
1886  return nAvailableWatchCreditCached;
1887 
1888  CAmount nCredit = 0;
1889  for (unsigned int i = 0; i < tx->vout.size(); i++)
1890  {
1891  if (!pwallet->IsSpent(GetHash(), i))
1892  {
1893  const CTxOut &txout = tx->vout[i];
1894  nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1895  if (!MoneyRange(nCredit))
1896  throw std::runtime_error(std::string(__func__) + ": value out of range");
1897  }
1898  }
1899 
1900  nAvailableWatchCreditCached = nCredit;
1901  fAvailableWatchCreditCached = true;
1902  return nCredit;
1903 }
1904 
1906 {
1907  if (fChangeCached)
1908  return nChangeCached;
1909  nChangeCached = pwallet->GetChange(*this);
1910  fChangeCached = true;
1911  return nChangeCached;
1912 }
1913 
1915 {
1916  LOCK(mempool.cs);
1917  return mempool.exists(GetHash());
1918 }
1919 
1921 {
1922  // Quick answer in most cases
1923  if (!CheckFinalTx(*this))
1924  return false;
1925  int nDepth = GetDepthInMainChain();
1926  if (nDepth >= 1)
1927  return true;
1928  if (nDepth < 0)
1929  return false;
1930  if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1931  return false;
1932 
1933  // Don't trust unconfirmed transactions from us unless they are in the mempool.
1934  if (!InMempool())
1935  return false;
1936 
1937  // Trusted if all inputs are from us and are in the mempool:
1938  for (const CTxIn& txin : tx->vin)
1939  {
1940  // Transactions not sent by us: not trusted
1941  const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1942  if (parent == nullptr)
1943  return false;
1944  const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1945  if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1946  return false;
1947  }
1948  return true;
1949 }
1950 
1951 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1952 {
1953  CMutableTransaction tx1 = *this->tx;
1954  CMutableTransaction tx2 = *_tx.tx;
1955  for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1956  for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1957  return CTransaction(tx1) == CTransaction(tx2);
1958 }
1959 
1960 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1961 {
1962  std::vector<uint256> result;
1963 
1964  LOCK(cs_wallet);
1965 
1966  // Sort them in chronological order
1967  std::multimap<unsigned int, CWalletTx*> mapSorted;
1968  for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1969  {
1970  CWalletTx& wtx = item.second;
1971  // Don't rebroadcast if newer than nTime:
1972  if (wtx.nTimeReceived > nTime)
1973  continue;
1974  mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1975  }
1976  for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1977  {
1978  CWalletTx& wtx = *item.second;
1979  if (wtx.RelayWalletTransaction(connman))
1980  result.push_back(wtx.GetHash());
1981  }
1982  return result;
1983 }
1984 
1985 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1986 {
1987  // Do this infrequently and randomly to avoid giving away
1988  // that these are our transactions.
1989  if (GetTime() < nNextResend || !fBroadcastTransactions)
1990  return;
1991  bool fFirst = (nNextResend == 0);
1992  nNextResend = GetTime() + GetRand(30 * 60);
1993  if (fFirst)
1994  return;
1995 
1996  // Only do it if there's been a new block since last time
1997  if (nBestBlockTime < nLastResend)
1998  return;
1999  nLastResend = GetTime();
2000 
2001  // Rebroadcast unconfirmed txes older than 5 minutes before the last
2002  // block was found:
2003  std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2004  if (!relayed.empty())
2005  LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2006 }
2007  // end of mapWallet
2009 
2010 
2011 
2012 
2020 {
2021  CAmount nTotal = 0;
2022  {
2023  LOCK2(cs_main, cs_wallet);
2024  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2025  {
2026  const CWalletTx* pcoin = &(*it).second;
2027  if (pcoin->IsTrusted())
2028  nTotal += pcoin->GetAvailableCredit();
2029  }
2030  }
2031 
2032  return nTotal;
2033 }
2034 
2036 {
2037  CAmount nTotal = 0;
2038  {
2039  LOCK2(cs_main, cs_wallet);
2040  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2041  {
2042  const CWalletTx* pcoin = &(*it).second;
2043  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2044  nTotal += pcoin->GetAvailableCredit();
2045  }
2046  }
2047  return nTotal;
2048 }
2049 
2051 {
2052  CAmount nTotal = 0;
2053  {
2054  LOCK2(cs_main, cs_wallet);
2055  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2056  {
2057  const CWalletTx* pcoin = &(*it).second;
2058  nTotal += pcoin->GetImmatureCredit();
2059  }
2060  }
2061  return nTotal;
2062 }
2063 
2065 {
2066  CAmount nTotal = 0;
2067  {
2068  LOCK2(cs_main, cs_wallet);
2069  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2070  {
2071  const CWalletTx* pcoin = &(*it).second;
2072  if (pcoin->IsTrusted())
2073  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2074  }
2075  }
2076 
2077  return nTotal;
2078 }
2079 
2081 {
2082  CAmount nTotal = 0;
2083  {
2084  LOCK2(cs_main, cs_wallet);
2085  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2086  {
2087  const CWalletTx* pcoin = &(*it).second;
2088  if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2089  nTotal += pcoin->GetAvailableWatchOnlyCredit();
2090  }
2091  }
2092  return nTotal;
2093 }
2094 
2096 {
2097  CAmount nTotal = 0;
2098  {
2099  LOCK2(cs_main, cs_wallet);
2100  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2101  {
2102  const CWalletTx* pcoin = &(*it).second;
2103  nTotal += pcoin->GetImmatureWatchOnlyCredit();
2104  }
2105  }
2106  return nTotal;
2107 }
2108 
2109 // Calculate total balance in a different way from GetBalance. The biggest
2110 // difference is that GetBalance sums up all unspent TxOuts paying to the
2111 // wallet, while this sums up both spent and unspent TxOuts paying to the
2112 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2113 // also has fewer restrictions on which unconfirmed transactions are considered
2114 // trusted.
2115 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2116 {
2117  LOCK2(cs_main, cs_wallet);
2118 
2119  CAmount balance = 0;
2120  for (const auto& entry : mapWallet) {
2121  const CWalletTx& wtx = entry.second;
2122  const int depth = wtx.GetDepthInMainChain();
2123  if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2124  continue;
2125  }
2126 
2127  // Loop through tx outputs and add incoming payments. For outgoing txs,
2128  // treat change outputs specially, as part of the amount debited.
2129  CAmount debit = wtx.GetDebit(filter);
2130  const bool outgoing = debit > 0;
2131  for (const CTxOut& out : wtx.tx->vout) {
2132  if (outgoing && IsChange(out)) {
2133  debit -= out.nValue;
2134  } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2135  balance += out.nValue;
2136  }
2137  }
2138 
2139  // For outgoing txs, subtract amount debited.
2140  if (outgoing && (!account || *account == wtx.strFromAccount)) {
2141  balance -= debit;
2142  }
2143  }
2144 
2145  if (account) {
2146  balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2147  }
2148 
2149  return balance;
2150 }
2151 
2153 {
2154  LOCK2(cs_main, cs_wallet);
2155 
2156  CAmount balance = 0;
2157  std::vector<COutput> vCoins;
2158  AvailableCoins(vCoins, true, coinControl);
2159  for (const COutput& out : vCoins) {
2160  if (out.fSpendable) {
2161  balance += out.tx->tx->vout[out.i].nValue;
2162  }
2163  }
2164  return balance;
2165 }
2166 
2167 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
2168 {
2169  vCoins.clear();
2170 
2171  {
2172  LOCK2(cs_main, cs_wallet);
2173 
2174  CAmount nTotal = 0;
2175 
2176  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2177  {
2178  const uint256& wtxid = it->first;
2179  const CWalletTx* pcoin = &(*it).second;
2180 
2181  if (!CheckFinalTx(*pcoin))
2182  continue;
2183 
2184  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2185  continue;
2186 
2187  int nDepth = pcoin->GetDepthInMainChain();
2188  if (nDepth < 0)
2189  continue;
2190 
2191  // We should not consider coins which aren't at least in our mempool
2192  // It's possible for these to be conflicted via ancestors which we may never be able to detect
2193  if (nDepth == 0 && !pcoin->InMempool())
2194  continue;
2195 
2196  bool safeTx = pcoin->IsTrusted();
2197 
2198  // We should not consider coins from transactions that are replacing
2199  // other transactions.
2200  //
2201  // Example: There is a transaction A which is replaced by bumpfee
2202  // transaction B. In this case, we want to prevent creation of
2203  // a transaction B' which spends an output of B.
2204  //
2205  // Reason: If transaction A were initially confirmed, transactions B
2206  // and B' would no longer be valid, so the user would have to create
2207  // a new transaction C to replace B'. However, in the case of a
2208  // one-block reorg, transactions B' and C might BOTH be accepted,
2209  // when the user only wanted one of them. Specifically, there could
2210  // be a 1-block reorg away from the chain where transactions A and C
2211  // were accepted to another chain where B, B', and C were all
2212  // accepted.
2213  if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2214  safeTx = false;
2215  }
2216 
2217  // Similarly, we should not consider coins from transactions that
2218  // have been replaced. In the example above, we would want to prevent
2219  // creation of a transaction A' spending an output of A, because if
2220  // transaction B were initially confirmed, conflicting with A and
2221  // A', we wouldn't want to the user to create a transaction D
2222  // intending to replace A', but potentially resulting in a scenario
2223  // where A, A', and D could all be accepted (instead of just B and
2224  // D, or just A and A' like the user would want).
2225  if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2226  safeTx = false;
2227  }
2228 
2229  if (fOnlySafe && !safeTx) {
2230  continue;
2231  }
2232 
2233  if (nDepth < nMinDepth || nDepth > nMaxDepth)
2234  continue;
2235 
2236  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2237  if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2238  continue;
2239 
2240  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2241  continue;
2242 
2243  if (IsLockedCoin((*it).first, i))
2244  continue;
2245 
2246  if (IsSpent(wtxid, i))
2247  continue;
2248 
2249  isminetype mine = IsMine(pcoin->tx->vout[i]);
2250 
2251  if (mine == ISMINE_NO) {
2252  continue;
2253  }
2254 
2255  bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2256  bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2257 
2258  vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2259 
2260  // Checks the sum amount of all UTXO's.
2261  if (nMinimumSumAmount != MAX_MONEY) {
2262  nTotal += pcoin->tx->vout[i].nValue;
2263 
2264  if (nTotal >= nMinimumSumAmount) {
2265  return;
2266  }
2267  }
2268 
2269  // Checks the maximum number of UTXO's.
2270  if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2271  return;
2272  }
2273  }
2274  }
2275  }
2276 }
2277 
2278 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2279 {
2280  // TODO: Add AssertLockHeld(cs_wallet) here.
2281  //
2282  // Because the return value from this function contains pointers to
2283  // CWalletTx objects, callers to this function really should acquire the
2284  // cs_wallet lock before calling it. However, the current caller doesn't
2285  // acquire this lock yet. There was an attempt to add the missing lock in
2286  // https://github.com/blockchaingate/fabcoin/pull/10340, but that change has been
2287  // postponed until after https://github.com/blockchaingate/fabcoin/pull/10244 to
2288  // avoid adding some extra complexity to the Qt code.
2289 
2290  std::map<CTxDestination, std::vector<COutput>> result;
2291 
2292  std::vector<COutput> availableCoins;
2293  AvailableCoins(availableCoins);
2294 
2295  LOCK2(cs_main, cs_wallet);
2296  for (auto& coin : availableCoins) {
2298  if (coin.fSpendable &&
2299  ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2300  result[address].emplace_back(std::move(coin));
2301  }
2302  }
2303 
2304  std::vector<COutPoint> lockedCoins;
2305  ListLockedCoins(lockedCoins);
2306  for (const auto& output : lockedCoins) {
2307  auto it = mapWallet.find(output.hash);
2308  if (it != mapWallet.end()) {
2309  int depth = it->second.GetDepthInMainChain();
2310  if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2311  IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2313  if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2314  result[address].emplace_back(
2315  &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2316  }
2317  }
2318  }
2319  }
2320 
2321  return result;
2322 }
2323 
2324 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2325 {
2326  const CTransaction* ptx = &tx;
2327  int n = output;
2328  while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2329  const COutPoint& prevout = ptx->vin[0].prevout;
2330  auto it = mapWallet.find(prevout.hash);
2331  if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2332  !IsMine(it->second.tx->vout[prevout.n])) {
2333  break;
2334  }
2335  ptx = it->second.tx.get();
2336  n = prevout.n;
2337  }
2338  return ptx->vout[n];
2339 }
2340 
2341 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2342  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2343 {
2344  std::vector<char> vfIncluded;
2345 
2346  vfBest.assign(vValue.size(), true);
2347  nBest = nTotalLower;
2348 
2349  FastRandomContext insecure_rand;
2350 
2351  for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2352  {
2353  vfIncluded.assign(vValue.size(), false);
2354  CAmount nTotal = 0;
2355  bool fReachedTarget = false;
2356  for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2357  {
2358  for (unsigned int i = 0; i < vValue.size(); i++)
2359  {
2360  //The solver here uses a randomized algorithm,
2361  //the randomness serves no real security purpose but is just
2362  //needed to prevent degenerate behavior and it is important
2363  //that the rng is fast. We do not use a constant random sequence,
2364  //because there may be some privacy improvement by making
2365  //the selection random.
2366  if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2367  {
2368  nTotal += vValue[i].txout.nValue;
2369  vfIncluded[i] = true;
2370  if (nTotal >= nTargetValue)
2371  {
2372  fReachedTarget = true;
2373  if (nTotal < nBest)
2374  {
2375  nBest = nTotal;
2376  vfBest = vfIncluded;
2377  }
2378  nTotal -= vValue[i].txout.nValue;
2379  vfIncluded[i] = false;
2380  }
2381  }
2382  }
2383  }
2384  }
2385 }
2386 
2387 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2388  std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2389 {
2390  setCoinsRet.clear();
2391  nValueRet = 0;
2392 
2393  // List of values less than target
2394  boost::optional<CInputCoin> coinLowestLarger;
2395  std::vector<CInputCoin> vValue;
2396  CAmount nTotalLower = 0;
2397 
2398  random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2399 
2400  for (const COutput &output : vCoins)
2401  {
2402  if (!output.fSpendable)
2403  continue;
2404 
2405  const CWalletTx *pcoin = output.tx;
2406 
2407  if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2408  continue;
2409 
2410  if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2411  continue;
2412 
2413  int i = output.i;
2414 
2415  CInputCoin coin = CInputCoin(pcoin, i);
2416 
2417  if (coin.txout.nValue == nTargetValue)
2418  {
2419  setCoinsRet.insert(coin);
2420  nValueRet += coin.txout.nValue;
2421  return true;
2422  }
2423  else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2424  {
2425  vValue.push_back(coin);
2426  nTotalLower += coin.txout.nValue;
2427  }
2428  else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2429  {
2430  coinLowestLarger = coin;
2431  }
2432  }
2433 
2434  if (nTotalLower == nTargetValue)
2435  {
2436  for (const auto& input : vValue)
2437  {
2438  setCoinsRet.insert(input);
2439  nValueRet += input.txout.nValue;
2440  }
2441  return true;
2442  }
2443 
2444  if (nTotalLower < nTargetValue)
2445  {
2446  if (!coinLowestLarger)
2447  return false;
2448  setCoinsRet.insert(coinLowestLarger.get());
2449  nValueRet += coinLowestLarger->txout.nValue;
2450  return true;
2451  }
2452 
2453  // Solve subset sum by stochastic approximation
2454  std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2455  std::reverse(vValue.begin(), vValue.end());
2456  std::vector<char> vfBest;
2457  CAmount nBest;
2458 
2459  ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2460  if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2461  ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2462 
2463  // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2464  // or the next bigger coin is closer), return the bigger coin
2465  if (coinLowestLarger &&
2466  ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2467  {
2468  setCoinsRet.insert(coinLowestLarger.get());
2469  nValueRet += coinLowestLarger->txout.nValue;
2470  }
2471  else {
2472  for (unsigned int i = 0; i < vValue.size(); i++)
2473  if (vfBest[i])
2474  {
2475  setCoinsRet.insert(vValue[i]);
2476  nValueRet += vValue[i].txout.nValue;
2477  }
2478 
2479  if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2480  LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2481  for (unsigned int i = 0; i < vValue.size(); i++) {
2482  if (vfBest[i]) {
2483  LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2484  }
2485  }
2486  LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2487  }
2488  }
2489 
2490  return true;
2491 }
2492 
2493 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2494 {
2495  std::vector<COutput> vCoins(vAvailableCoins);
2496 
2497  // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2498  if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2499  {
2500  for (const COutput& out : vCoins)
2501  {
2502  if (!out.fSpendable)
2503  continue;
2504  nValueRet += out.tx->tx->vout[out.i].nValue;
2505  setCoinsRet.insert(CInputCoin(out.tx, out.i));
2506  }
2507  return (nValueRet >= nTargetValue);
2508  }
2509 
2510  // calculate value from preset inputs and store them
2511  std::set<CInputCoin> setPresetCoins;
2512  CAmount nValueFromPresetInputs = 0;
2513 
2514  std::vector<COutPoint> vPresetInputs;
2515  if (coinControl)
2516  coinControl->ListSelected(vPresetInputs);
2517  for (const COutPoint& outpoint : vPresetInputs)
2518  {
2519  std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2520  if (it != mapWallet.end())
2521  {
2522  const CWalletTx* pcoin = &it->second;
2523  // Clearly invalid input, fail
2524  if (pcoin->tx->vout.size() <= outpoint.n)
2525  return false;
2526  nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2527  setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2528  } else
2529  return false; // TODO: Allow non-wallet inputs
2530  }
2531 
2532  // remove preset inputs from vCoins
2533  for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2534  {
2535  if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2536  it = vCoins.erase(it);
2537  else
2538  ++it;
2539  }
2540 
2541  size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2542  bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2543 
2544  bool res = nTargetValue <= nValueFromPresetInputs ||
2545  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2546  SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2547  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2548  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2549  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2550  (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2551  (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2552 
2553  // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2554  setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2555 
2556  // add preset inputs to the total value selected
2557  nValueRet += nValueFromPresetInputs;
2558 
2559  return res;
2560 }
2561 
2563 {
2564  AssertLockHeld(cs_wallet); // mapWallet
2565 
2566  // sign the new tx
2567  CTransaction txNewConst(tx);
2568  int nIn = 0;
2569  for (const auto& input : tx.vin) {
2570  std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2571  if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2572  return false;
2573  }
2574  const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2575  const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2576  SignatureData sigdata;
2577  if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2578  return false;
2579  }
2580  UpdateTransaction(tx, nIn, sigdata);
2581  nIn++;
2582  }
2583  return true;
2584 }
2585 
2586 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2587 {
2588  std::vector<CRecipient> vecSend;
2589 
2590  // Turn the txout set into a CRecipient vector
2591  for (size_t idx = 0; idx < tx.vout.size(); idx++)
2592  {
2593  const CTxOut& txOut = tx.vout[idx];
2594  CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2595  vecSend.push_back(recipient);
2596  }
2597 
2598  coinControl.fAllowOtherInputs = true;
2599 
2600  for (const CTxIn& txin : tx.vin)
2601  coinControl.Select(txin.prevout);
2602 
2603  CReserveKey reservekey(this);
2604  CWalletTx wtx;
2605  if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2606  return false;
2607  }
2608 
2609  if (nChangePosInOut != -1) {
2610  tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2611  // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
2612  // so just remove the key from the keypool here.
2613  reservekey.KeepKey();
2614  }
2615 
2616  // Copy output sizes from new transaction; they may have had the fee subtracted from them
2617  for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2618  tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2619 
2620  // Add new txins (keeping original txin scriptSig/order)
2621  for (const CTxIn& txin : wtx.tx->vin)
2622  {
2623  if (!coinControl.IsSelected(txin.prevout))
2624  {
2625  tx.vin.push_back(txin);
2626 
2627  if (lockUnspents)
2628  {
2629  LOCK2(cs_main, cs_wallet);
2630  LockCoin(txin.prevout);
2631  }
2632  }
2633  }
2634 
2635 
2636  return true;
2637 }
2638 
2639 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2640 {
2641  unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2642  CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2643  // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2644  discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2645  // Discard rate must be at least dustRelayFee
2646  discard_rate = std::max(discard_rate, ::dustRelayFee);
2647  return discard_rate;
2648 }
2649 
2650 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2651  int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign, CAmount nGasFee, bool hasSender)
2652 {
2653  CAmount nValue = 0;
2654  int nChangePosRequest = nChangePosInOut;
2655  unsigned int nSubtractFeeFromAmount = 0;
2656  COutPoint senderInput;
2657  if(hasSender && coin_control.HasSelected()){
2658  std::vector<COutPoint> vSenderInputs;
2659  coin_control.ListSelected(vSenderInputs);
2660  senderInput=vSenderInputs[0];
2661  }
2662  for (const auto& recipient : vecSend)
2663  {
2664  if (nValue < 0 || recipient.nAmount < 0)
2665  {
2666  strFailReason = _("Transaction amounts must not be negative");
2667  return false;
2668  }
2669  nValue += recipient.nAmount;
2670 
2671  if (recipient.fSubtractFeeFromAmount)
2672  nSubtractFeeFromAmount++;
2673  }
2674  if (vecSend.empty())
2675  {
2676  strFailReason = _("Transaction must have at least one recipient");
2677  return false;
2678  }
2679 
2680  wtxNew.fTimeReceivedIsTxTime = true;
2681  wtxNew.BindWallet(this);
2682  CMutableTransaction txNew;
2683 
2684  // Discourage fee sniping.
2685  //
2686  // For a large miner the value of the transactions in the best block and
2687  // the mempool can exceed the cost of deliberately attempting to mine two
2688  // blocks to orphan the current best block. By setting nLockTime such that
2689  // only the next block can include the transaction, we discourage this
2690  // practice as the height restricted and limited blocksize gives miners
2691  // considering fee sniping fewer options for pulling off this attack.
2692  //
2693  // A simple way to think about this is from the wallet's point of view we
2694  // always want the blockchain to move forward. By setting nLockTime this
2695  // way we're basically making the statement that we only want this
2696  // transaction to appear in the next block; we don't want to potentially
2697  // encourage reorgs by allowing transactions to appear at lower heights
2698  // than the next block in forks of the best chain.
2699  //
2700  // Of course, the subsidy is high enough, and transaction volume low
2701  // enough, that fee sniping isn't a problem yet, but by implementing a fix
2702  // now we ensure code won't be written that makes assumptions about
2703  // nLockTime that preclude a fix later.
2704  txNew.nLockTime = chainActive.Height();
2705 
2706  // Secondly occasionally randomly pick a nLockTime even further back, so
2707  // that transactions that are delayed after signing for whatever reason,
2708  // e.g. high-latency mix networks and some CoinJoin implementations, have
2709  // better privacy.
2710  if (GetRandInt(10) == 0)
2711  txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2712 
2713  assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2714  assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2715  FeeCalculation feeCalc;
2716  CAmount nFeeNeeded;
2717  unsigned int nBytes;
2718  {
2719  std::set<CInputCoin> setCoins;
2720  std::vector<CInputCoin> vCoins;
2721  LOCK2(cs_main, cs_wallet);
2722  {
2723  std::vector<COutput> vAvailableCoins;
2724  AvailableCoins(vAvailableCoins, true, &coin_control);
2725 
2726  // Create change script that will be used if we need change
2727  // TODO: pass in scriptChange instead of reservekey so
2728  // change transaction isn't always pay-to-fabcoin-address
2729  CScript scriptChange;
2730 
2731  // coin control: send change to custom address
2732  if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2733  scriptChange = GetScriptForDestination(coin_control.destChange);
2734  } else { // no coin control: send change to newly generated address
2735  // Note: We use a new key here to keep it from being obvious which side is the change.
2736  // The drawback is that by not reusing a previous key, the change may be lost if a
2737  // backup is restored, if the backup doesn't have the new private key for the change.
2738  // If we reused the old key, it would be possible to add code to look for and
2739  // rediscover unknown transactions that were written with keys of ours to recover
2740  // post-backup change.
2741 
2742  // Reserve a new key pair from key pool
2743  CPubKey vchPubKey;
2744  bool ret;
2745  ret = reservekey.GetReservedKey(vchPubKey, true);
2746  if (!ret)
2747  {
2748  strFailReason = _("Keypool ran out, please call keypoolrefill first");
2749  return false;
2750  }
2751 
2752  scriptChange = GetScriptForDestination(vchPubKey.GetID());
2753  }
2754  CTxOut change_prototype_txout(0, scriptChange);
2755  size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2756 
2757  CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2758  nFeeRet = 0;
2759  bool pick_new_inputs = true;
2760  CAmount nValueIn = 0;
2761  // Start with no fee and loop until there is enough fee
2762  while (true)
2763  {
2764  nChangePosInOut = nChangePosRequest;
2765  txNew.vin.clear();
2766  txNew.vout.clear();
2767  wtxNew.fFromMe = true;
2768  bool fFirst = true;
2769 
2770  CAmount nValueToSelect = nValue;
2771  if (nSubtractFeeFromAmount == 0)
2772  nValueToSelect += nFeeRet;
2773  // vouts to the payees
2774  for (const auto& recipient : vecSend)
2775  {
2776  CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2777 
2778  if (recipient.fSubtractFeeFromAmount)
2779  {
2780  txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2781 
2782  if (fFirst) // first receiver pays the remainder not divisible by output count
2783  {
2784  fFirst = false;
2785  txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2786  }
2787  }
2788 
2789  if (IsDust(txout, ::dustRelayFee))
2790  {
2791  if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2792  {
2793  if (txout.nValue < 0)
2794  strFailReason = _("The transaction amount is too small to pay the fee");
2795  else
2796  strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2797  }
2798  else
2799  strFailReason = _("Transaction amount too small");
2800  return false;
2801  }
2802  txNew.vout.push_back(txout);
2803  }
2804 
2805  // Choose coins to use
2806  if (pick_new_inputs) {
2807  nValueIn = 0;
2808  setCoins.clear();
2809  if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2810  {
2811  strFailReason = _("Insufficient funds");
2812  return false;
2813  }
2814  }
2815 
2816  const CAmount nChange = nValueIn - nValueToSelect;
2817 
2818  if (nChange > 0)
2819  {
2820  // send change to existing address
2821  if (fNotUseChangeAddress &&
2822  boost::get<CNoDestination>(&coin_control.destChange) &&
2823  setCoins.size() > 0)
2824  {
2825  // setCoins will be added as inputs to the new transaction
2826  // Set the first input script as change script for the new transaction
2827  auto pcoin = setCoins.begin();
2828  scriptChange = pcoin->txout.scriptPubKey;
2829 
2830  change_prototype_txout = CTxOut(0, scriptChange);
2831  change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2832  }
2833 
2834  // Fill a vout to ourself
2835  CTxOut newTxOut(nChange, scriptChange);
2836 
2837  // Never create dust outputs; if we would, just
2838  // add the dust to the fee.
2839  if (IsDust(newTxOut, discard_rate))
2840  {
2841  nChangePosInOut = -1;
2842  nFeeRet += nChange;
2843  }
2844  else
2845  {
2846  if (nChangePosInOut == -1)
2847  {
2848  // Insert change txn at random position:
2849  nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2850  }
2851  else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2852  {
2853  strFailReason = _("Change index out of range");
2854  return false;
2855  }
2856 
2857  std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2858  txNew.vout.insert(position, newTxOut);
2859  }
2860  } else {
2861  nChangePosInOut = -1;
2862  }
2863 
2864  // Move sender input to position 0
2865  vCoins.clear();
2866  std::copy(setCoins.begin(), setCoins.end(), std::back_inserter(vCoins));
2867  if(hasSender && coin_control.HasSelected()){
2868  for (std::vector<CInputCoin>::size_type i = 0 ; i != vCoins.size(); i++){
2869  if(vCoins[i].outpoint==senderInput){
2870  if(i==0)break;
2871  iter_swap(vCoins.begin(),vCoins.begin()+i);
2872  break;
2873  }
2874  }
2875  }
2876 
2877  // Fill vin
2878  //
2879  // Note how the sequence number is set to non-maxint so that
2880  // the nLockTime set above actually works.
2881  //
2882  // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2883  // we use the highest possible value in that range (maxint-2)
2884  // to avoid conflicting with other possible uses of nSequence,
2885  // and in the spirit of "smallest possible change from prior
2886  // behavior."
2887  const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2888  for (const auto& coin : vCoins)
2889  txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2890  nSequence));
2891 
2892  // Fill in dummy signatures for fee calculation.
2893  if (!DummySignTx(txNew, vCoins)) {
2894  strFailReason = _("Signing transaction failed");
2895  return false;
2896  }
2897 
2898  nBytes = GetVirtualTransactionSize(txNew);
2899 
2900  // Remove scriptSigs to eliminate the fee calculation dummy signatures
2901  for (auto& vin : txNew.vin) {
2902  vin.scriptSig = CScript();
2903  vin.scriptWitness.SetNull();
2904  }
2905 
2906  nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc)+nGasFee;
2907 
2908  // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2909  // because we must be at the maximum allowed fee.
2910  if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2911  {
2912  strFailReason = _("Transaction too large for fee policy");
2913  return false;
2914  }
2915 
2916  if (nFeeRet >= nFeeNeeded) {
2917  // Reduce fee to only the needed amount if possible. This
2918  // prevents potential overpayment in fees if the coins
2919  // selected to meet nFeeNeeded result in a transaction that
2920  // requires less fee than the prior iteration.
2921 
2922  // If we have no change and a big enough excess fee, then
2923  // try to construct transaction again only without picking
2924  // new inputs. We now know we only need the smaller fee
2925  // (because of reduced tx size) and so we should add a
2926  // change output. Only try this once.
2927  if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2928  unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2929  CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2930  CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2931  if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2932  pick_new_inputs = false;
2933  nFeeRet = fee_needed_with_change;
2934  continue;
2935  }
2936  }
2937 
2938  // If we have change output already, just increase it
2939  if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2940  CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2941  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2942  change_position->nValue += extraFeePaid;
2943  nFeeRet -= extraFeePaid;
2944  }
2945  break; // Done, enough fee included.
2946  }
2947  else if (!pick_new_inputs) {
2948  // This shouldn't happen, we should have had enough excess
2949  // fee to pay for the new output and still meet nFeeNeeded
2950  // Or we should have just subtracted fee from recipients and
2951  // nFeeNeeded should not have changed
2952  strFailReason = _("Transaction fee and change calculation failed");
2953  return false;
2954  }
2955 
2956  // Try to reduce change to include necessary fee
2957  if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2958  CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2959  std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2960  // Only reduce change if remaining amount is still a large enough output.
2961  if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2962  change_position->nValue -= additionalFeeNeeded;
2963  nFeeRet += additionalFeeNeeded;
2964  break; // Done, able to increase fee from change
2965  }
2966  }
2967 
2968  // If subtracting fee from recipients, we now know what fee we
2969  // need to subtract, we have no reason to reselect inputs
2970  if (nSubtractFeeFromAmount > 0) {
2971  pick_new_inputs = false;
2972  }
2973 
2974  // Include more fee and try again.
2975  nFeeRet = nFeeNeeded;
2976  continue;
2977  }
2978  }
2979 
2980  if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2981 
2982  if (sign)
2983  {
2984  CTransaction txNewConst(txNew);
2985  int nIn = 0;
2986  for (const auto& coin : vCoins)
2987  {
2988  const CScript& scriptPubKey = coin.txout.scriptPubKey;
2989  SignatureData sigdata;
2990 
2991  if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2992  {
2993  strFailReason = _("Signing transaction failed");
2994  return false;
2995  } else {
2996  UpdateTransaction(txNew, nIn, sigdata);
2997  }
2998 
2999  nIn++;
3000  }
3001  }
3002 
3003  // Embed the constructed transaction data in wtxNew.
3004  wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
3005 
3006  // Limit size
3007  if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
3008  {
3009  strFailReason = _("Transaction too large");
3010  return false;
3011  }
3012  }
3013 
3014  if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
3015  // Lastly, ensure this tx will pass the mempool's chain limits
3016  LockPoints lp;
3017  CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
3018  CTxMemPool::setEntries setAncestors;
3019  size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
3020  size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
3021  size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
3022  size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
3023  std::string errString;
3024  if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
3025  strFailReason = _("Transaction has too long of a mempool chain");
3026  return false;
3027  }
3028  }
3029 
3030  /*LogPrintf("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",
3031  nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
3032  feeCalc.est.pass.start, feeCalc.est.pass.end,
3033  100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
3034  feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
3035  feeCalc.est.fail.start, feeCalc.est.fail.end,
3036  100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
3037  feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3038  */
3039  return true;
3040 }
3041 
3045 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3046 {
3047  {
3048  LOCK2(cs_main, cs_wallet);
3049  LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3050  {
3051  // Take key pair from key pool so it won't be used again
3052  reservekey.KeepKey();
3053 
3054  // Add tx to wallet, because if it has change it's also ours,
3055  // otherwise just for transaction history.
3056  AddToWallet(wtxNew);
3057 
3058  // Notify that old coins are spent
3059  for (const CTxIn& txin : wtxNew.tx->vin)
3060  {
3061  CWalletTx &coin = mapWallet[txin.prevout.hash];
3062  coin.BindWallet(this);
3063  NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3064  }
3065  }
3066 
3067  // Track how many getdata requests our transaction gets
3068  mapRequestCount[wtxNew.GetHash()] = 0;
3069 
3070  if (fBroadcastTransactions)
3071  {
3072  // Broadcast
3073  if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
3074  LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3075  // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3076  } else {
3077  wtxNew.RelayWalletTransaction(connman);
3078  }
3079  }
3080  }
3081  return true;
3082 }
3083 
3084 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3085  CWalletDB walletdb(*dbw);
3086  return walletdb.ListAccountCreditDebit(strAccount, entries);
3087 }
3088 
3090 {
3091  CWalletDB walletdb(*dbw);
3092 
3093  return AddAccountingEntry(acentry, &walletdb);
3094 }
3095 
3097 {
3098  if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3099  return false;
3100  }
3101 
3102  laccentries.push_back(acentry);
3103  CAccountingEntry & entry = laccentries.back();
3104  wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
3105 
3106  return true;
3107 }
3108 
3109 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3110 {
3111  return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3112 }
3113 
3114 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
3115 {
3116  /* User control of how to calculate fee uses the following parameter precedence:
3117  1. coin_control.m_feerate
3118  2. coin_control.m_confirm_target
3119  3. payTxFee (user-set global variable)
3120  4. nTxConfirmTarget (user-set global variable)
3121  The first parameter that is set is used.
3122  */
3123  CAmount fee_needed;
3124  if (coin_control.m_feerate) { // 1.
3125  fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
3126  if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3127  // Allow to override automatic min/max check over coin control instance
3128  if (coin_control.fOverrideFeeRate) return fee_needed;
3129  }
3130  else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
3131  fee_needed = ::payTxFee.GetFee(nTxBytes);
3132  if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3133  }
3134  else { // 2. or 4.
3135  // We will use smart fee estimation
3136  unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
3137  // By default estimates are economical iff we are signaling opt-in-RBF
3138  bool conservative_estimate = !coin_control.signalRbf;
3139  // Allow to override the default fee estimate mode over the CoinControl instance
3140  if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3141  else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3142 
3143  fee_needed = 0;
3144  fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3145  if (fee_needed == 0) {
3146  // if we don't have enough data for estimateSmartFee, then use fallbackFee
3147  fee_needed = fallbackFee.GetFee(nTxBytes);
3148  if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3149  }
3150  // Obey mempool min fee when using smart fee estimation
3151  CAmount min_mempool_fee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3152  if (fee_needed < min_mempool_fee) {
3153  fee_needed = min_mempool_fee;
3154  if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3155  }
3156  }
3157 
3158  // prevent user from paying a fee below minRelayTxFee or minTxFee
3159  CAmount required_fee = GetRequiredFee(nTxBytes);
3160  if (required_fee > fee_needed) {
3161  fee_needed = required_fee;
3162  if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3163  }
3164  // But always obey the maximum
3165  if (fee_needed > maxTxFee) {
3166  fee_needed = maxTxFee;
3167  if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3168  }
3169  return fee_needed;
3170 }
3171 
3172 
3173 
3174 
3175 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3176 {
3177  LOCK2(cs_main, cs_wallet);
3178 
3179  fFirstRunRet = false;
3180  DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3181  if (nLoadWalletRet == DB_NEED_REWRITE)
3182  {
3183  if (dbw->Rewrite("\x04pool"))
3184  {
3185  setInternalKeyPool.clear();
3186  setExternalKeyPool.clear();
3187  m_pool_key_to_index.clear();
3188  // Note: can't top-up keypool here, because wallet is locked.
3189  // User will be prompted to unlock wallet the next operation
3190  // that requires a new key.
3191  }
3192  }
3193 
3194  if (nLoadWalletRet != DB_LOAD_OK)
3195  return nLoadWalletRet;
3196  fFirstRunRet = !vchDefaultKey.IsValid();
3197 
3198  uiInterface.LoadWallet(this);
3199 
3200  return DB_LOAD_OK;
3201 }
3202 
3203 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3204 {
3205  AssertLockHeld(cs_wallet); // mapWallet
3206  vchDefaultKey = CPubKey();
3207  DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3208  for (uint256 hash : vHashOut)
3209  mapWallet.erase(hash);
3210 
3211  if (nZapSelectTxRet == DB_NEED_REWRITE)
3212  {
3213  if (dbw->Rewrite("\x04pool"))
3214  {
3215  setInternalKeyPool.clear();
3216  setExternalKeyPool.clear();
3217  m_pool_key_to_index.clear();
3218  // Note: can't top-up keypool here, because wallet is locked.
3219  // User will be prompted to unlock wallet the next operation
3220  // that requires a new key.
3221  }
3222  }
3223 
3224  if (nZapSelectTxRet != DB_LOAD_OK)
3225  return nZapSelectTxRet;
3226 
3227  MarkDirty();
3228 
3229  return DB_LOAD_OK;
3230 
3231 }
3232 
3233 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3234 {
3235  vchDefaultKey = CPubKey();
3236  DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3237  if (nZapWalletTxRet == DB_NEED_REWRITE)
3238  {
3239  if (dbw->Rewrite("\x04pool"))
3240  {
3241  LOCK(cs_wallet);
3242  setInternalKeyPool.clear();
3243  setExternalKeyPool.clear();
3244  m_pool_key_to_index.clear();
3245  // Note: can't top-up keypool here, because wallet is locked.
3246  // User will be prompted to unlock wallet the next operation
3247  // that requires a new key.
3248  }
3249  }
3250 
3251  if (nZapWalletTxRet != DB_LOAD_OK)
3252  return nZapWalletTxRet;
3253 
3254  return DB_LOAD_OK;
3255 }
3256 
3257 
3258 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3259 {
3260  bool fUpdated = false;
3261  {
3262  LOCK(cs_wallet); // mapAddressBook
3263  std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3264  fUpdated = mi != mapAddressBook.end();
3265  mapAddressBook[address].name = strName;
3266  if (!strPurpose.empty()) /* update purpose only if requested */
3267  mapAddressBook[address].purpose = strPurpose;
3268  }
3269  NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3270  strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3271  if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CFabcoinAddress(address).ToString(), strPurpose))
3272  return false;
3273  return CWalletDB(*dbw).WriteName(CFabcoinAddress(address).ToString(), strName);
3274 }
3275 
3277 {
3278  {
3279  LOCK(cs_wallet); // mapAddressBook
3280 
3281  // Delete destdata tuples associated with address
3282  std::string strAddress = CFabcoinAddress(address).ToString();
3283  for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3284  {
3285  CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3286  }
3287  mapAddressBook.erase(address);
3288  }
3289 
3290  NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3291 
3292  CWalletDB(*dbw).ErasePurpose(CFabcoinAddress(address).ToString());
3293  return CWalletDB(*dbw).EraseName(CFabcoinAddress(address).ToString());
3294 }
3295 
3296 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3297 {
3299  if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3300  auto mi = mapAddressBook.find(address);
3301  if (mi != mapAddressBook.end()) {
3302  return mi->second.name;
3303  }
3304  }
3305  // A scriptPubKey that doesn't have an entry in the address book is
3306  // associated with the default account ("").
3307  const static std::string DEFAULT_ACCOUNT_NAME;
3308  return DEFAULT_ACCOUNT_NAME;
3309 }
3310 
3311 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3312 {
3313  if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3314  return false;
3315  vchDefaultKey = vchPubKey;
3316  return true;
3317 }
3318 
3324 {
3325  {
3326  LOCK(cs_wallet);
3327  CWalletDB walletdb(*dbw);
3328 
3329  for (int64_t nIndex : setInternalKeyPool) {
3330  walletdb.ErasePool(nIndex);
3331  }
3332  setInternalKeyPool.clear();
3333 
3334  for (int64_t nIndex : setExternalKeyPool) {
3335  walletdb.ErasePool(nIndex);
3336  }
3337  setExternalKeyPool.clear();
3338 
3339  m_pool_key_to_index.clear();
3340 
3341  if (!TopUpKeyPool()) {
3342  return false;
3343  }
3344  LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3345  }
3346  return true;
3347 }
3348 
3350 {
3351  AssertLockHeld(cs_wallet); // setExternalKeyPool
3352  return setExternalKeyPool.size();
3353 }
3354 
3355 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3356 {
3357  AssertLockHeld(cs_wallet);
3358  if (keypool.fInternal) {
3359  setInternalKeyPool.insert(nIndex);
3360  } else {
3361  setExternalKeyPool.insert(nIndex);
3362  }
3363  m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3364  m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3365 
3366  // If no metadata exists yet, create a default with the pool key's
3367  // creation time. Note that this may be overwritten by actually
3368  // stored metadata for that key later, which is fine.
3369  CKeyID keyid = keypool.vchPubKey.GetID();
3370  if (mapKeyMetadata.count(keyid) == 0)
3371  mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3372 }
3373 
3374 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3375 {
3376  {
3377  LOCK(cs_wallet);
3378 
3379  if (IsLocked())
3380  return false;
3381 
3382  // Top up key pool
3383  unsigned int nTargetSize;
3384  if (kpSize > 0)
3385  nTargetSize = kpSize;
3386  else
3387  nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3388 
3389  // count amount of available keys (internal, external)
3390  // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3391  int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3392  int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3393 
3394  if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3395  {
3396  // don't create extra internal keys
3397  missingInternal = 0;
3398  }
3399  bool internal = false;
3400  CWalletDB walletdb(*dbw);
3401  for (int64_t i = missingInternal + missingExternal; i--;)
3402  {
3403  if (i < missingInternal) {
3404  internal = true;
3405  }
3406 
3407  assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3408  int64_t index = ++m_max_keypool_index;
3409 
3410  CPubKey pubkey(GenerateNewKey(walletdb, internal));
3411  if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3412  throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3413  }
3414 
3415  if (internal) {
3416  setInternalKeyPool.insert(index);
3417  } else {
3418  setExternalKeyPool.insert(index);
3419  }
3420  m_pool_key_to_index[pubkey.GetID()] = index;
3421  }
3422  if (missingInternal + missingExternal > 0) {
3423  LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3424  }
3425  }
3426  return true;
3427 }
3428 
3429 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3430 {
3431  nIndex = -1;
3432  keypool.vchPubKey = CPubKey();
3433  {
3434  LOCK(cs_wallet);
3435 
3436  if (!IsLocked())
3437  TopUpKeyPool();
3438 
3439  bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3440  std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3441 
3442  // Get the oldest key
3443  if(setKeyPool.empty())
3444  return;
3445 
3446  CWalletDB walletdb(*dbw);
3447 
3448  auto it = setKeyPool.begin();
3449  nIndex = *it;
3450  setKeyPool.erase(it);
3451  if (!walletdb.ReadPool(nIndex, keypool)) {
3452  throw std::runtime_error(std::string(__func__) + ": read failed");
3453  }
3454  if (!HaveKey(keypool.vchPubKey.GetID())) {
3455  throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3456  }
3457  if (keypool.fInternal != fReturningInternal) {
3458  throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3459  }
3460 
3461  assert(keypool.vchPubKey.IsValid());
3462  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3463  LogPrintf("keypool reserve %d\n", nIndex);
3464  }
3465 }
3466 
3467 void CWallet::KeepKey(int64_t nIndex)
3468 {
3469  // Remove from key pool
3470  CWalletDB walletdb(*dbw);
3471  walletdb.ErasePool(nIndex);
3472  LogPrintf("keypool keep %d\n", nIndex);
3473 }
3474 
3475 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3476 {
3477  // Return to key pool
3478  {
3479  LOCK(cs_wallet);
3480  if (fInternal) {
3481  setInternalKeyPool.insert(nIndex);
3482  } else {
3483  setExternalKeyPool.insert(nIndex);
3484  }
3485  m_pool_key_to_index[pubkey.GetID()] = nIndex;
3486  }
3487  LogPrintf("keypool return %d\n", nIndex);
3488 }
3489 
3490 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3491 {
3492  CKeyPool keypool;
3493  {
3494  LOCK(cs_wallet);
3495  int64_t nIndex = 0;
3496  ReserveKeyFromKeyPool(nIndex, keypool, internal);
3497  if (nIndex == -1)
3498  {
3499  if (IsLocked()) return false;
3500  CWalletDB walletdb(*dbw);
3501  result = GenerateNewKey(walletdb, internal);
3502  return true;
3503  }
3504  KeepKey(nIndex);
3505  result = keypool.vchPubKey;
3506  }
3507  return true;
3508 }
3509 
3510 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3511  if (setKeyPool.empty()) {
3512  return GetTime();
3513  }
3514 
3515  CKeyPool keypool;
3516  int64_t nIndex = *(setKeyPool.begin());
3517  if (!walletdb.ReadPool(nIndex, keypool)) {
3518  throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3519  }
3520  assert(keypool.vchPubKey.IsValid());
3521  return keypool.nTime;
3522 }
3523 
3525 {
3526  LOCK(cs_wallet);
3527 
3528  CWalletDB walletdb(*dbw);
3529 
3530  // load oldest key from keypool, get time and return
3531  int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3532  if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3533  oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3534  }
3535 
3536  return oldestKey;
3537 }
3538 
3539 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3540 {
3541  std::map<CTxDestination, CAmount> balances;
3542 
3543  {
3544  LOCK(cs_wallet);
3545  for (const auto& walletEntry : mapWallet)
3546  {
3547  const CWalletTx *pcoin = &walletEntry.second;
3548 
3549  if (!pcoin->IsTrusted())
3550  continue;
3551 
3552  if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3553  continue;
3554 
3555  int nDepth = pcoin->GetDepthInMainChain();
3556  if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3557  continue;
3558 
3559  for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3560  {
3561  CTxDestination addr;
3562  if (!IsMine(pcoin->tx->vout[i]))
3563  continue;
3564  if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3565  continue;
3566 
3567  CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3568 
3569  if (!balances.count(addr))
3570  balances[addr] = 0;
3571  balances[addr] += n;
3572  }
3573  }
3574  }
3575 
3576  return balances;
3577 }
3578 
3579 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3580 {
3581  AssertLockHeld(cs_wallet); // mapWallet
3582  std::set< std::set<CTxDestination> > groupings;
3583  std::set<CTxDestination> grouping;
3584 
3585  for (const auto& walletEntry : mapWallet)
3586  {
3587  const CWalletTx *pcoin = &walletEntry.second;
3588 
3589  if (pcoin->tx->vin.size() > 0)
3590  {
3591  bool any_mine = false;
3592  // group all input addresses with each other
3593  for (CTxIn txin : pcoin->tx->vin)
3594  {
3596  if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3597  continue;
3598  if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3599  continue;
3600  grouping.insert(address);
3601  any_mine = true;
3602  }
3603 
3604  // group change with input addresses
3605  if (any_mine)
3606  {
3607  for (CTxOut txout : pcoin->tx->vout)
3608  if (IsChange(txout))
3609  {
3610  CTxDestination txoutAddr;
3611  if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3612  continue;
3613  grouping.insert(txoutAddr);
3614  }
3615  }
3616  if (grouping.size() > 0)
3617  {
3618  groupings.insert(grouping);
3619  grouping.clear();
3620  }
3621  }
3622 
3623  // group lone addrs by themselves
3624  for (const auto& txout : pcoin->tx->vout)
3625  if (IsMine(txout))
3626  {
3628  if(!ExtractDestination(txout.scriptPubKey, address))
3629  continue;
3630  grouping.insert(address);
3631  groupings.insert(grouping);
3632  grouping.clear();
3633  }
3634  }
3635 
3636  std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3637  std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3638  for (std::set<CTxDestination> _grouping : groupings)
3639  {
3640  // make a set of all the groups hit by this new group
3641  std::set< std::set<CTxDestination>* > hits;
3642  std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3643  for (CTxDestination address : _grouping)
3644  if ((it = setmap.find(address)) != setmap.end())
3645  hits.insert((*it).second);
3646 
3647  // merge all hit groups into a new single group and delete old groups
3648  std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3649  for (std::set<CTxDestination>* hit : hits)
3650  {
3651  merged->insert(hit->begin(), hit->end());
3652  uniqueGroupings.erase(hit);
3653  delete hit;
3654  }
3655  uniqueGroupings.insert(merged);
3656 
3657  // update setmap
3658  for (CTxDestination element : *merged)
3659  setmap[element] = merged;
3660  }
3661 
3662  std::set< std::set<CTxDestination> > ret;
3663  for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3664  {
3665  ret.insert(*uniqueGrouping);
3666  delete uniqueGrouping;
3667  }
3668 
3669  return ret;
3670 }
3671 
3672 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3673 {
3674  LOCK(cs_wallet);
3675  std::set<CTxDestination> result;
3676  for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3677  {
3678  const CTxDestination& address = item.first;
3679  const std::string& strName = item.second.name;
3680  if (strName == strAccount)
3681  result.insert(address);
3682  }
3683  return result;
3684 }
3685 
3686 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3687 {
3688  if (nIndex == -1)
3689  {
3690  CKeyPool keypool;
3691  pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3692  if (nIndex != -1)
3693  vchPubKey = keypool.vchPubKey;
3694  else {
3695  return false;
3696  }
3697  fInternal = keypool.fInternal;
3698  }
3699  assert(vchPubKey.IsValid());
3700  pubkey = vchPubKey;
3701  return true;
3702 }
3703 
3705 {
3706  if (nIndex != -1)
3707  pwallet->KeepKey(nIndex);
3708  nIndex = -1;
3709  vchPubKey = CPubKey();
3710 }
3711 
3713 {
3714  if (nIndex != -1) {
3715  pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3716  }
3717  nIndex = -1;
3718  vchPubKey = CPubKey();
3719 }
3720 
3721 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3722 {
3723  AssertLockHeld(cs_wallet);
3724  bool internal = setInternalKeyPool.count(keypool_id);
3725  if (!internal) assert(setExternalKeyPool.count(keypool_id));
3726  std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3727  auto it = setKeyPool->begin();
3728 
3729  CWalletDB walletdb(*dbw);
3730  while (it != std::end(*setKeyPool)) {
3731  const int64_t& index = *(it);
3732  if (index > keypool_id) break; // set*KeyPool is ordered
3733 
3734  CKeyPool keypool;
3735  if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3736  m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3737  }
3738  walletdb.ErasePool(index);
3739  LogPrintf("keypool index %d removed\n", index);
3740  it = setKeyPool->erase(it);
3741  }
3742 }
3743 
3744 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3745 {
3746  std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3747  CPubKey pubkey;
3748  if (!rKey->GetReservedKey(pubkey))
3749  return;
3750 
3751  script = rKey;
3752  script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3753 }
3754 
3755 void CWallet::LockCoin(const COutPoint& output)
3756 {
3757  AssertLockHeld(cs_wallet); // setLockedCoins
3758  setLockedCoins.insert(output);
3759 }
3760 
3761 void CWallet::UnlockCoin(const COutPoint& output)
3762 {
3763  AssertLockHeld(cs_wallet); // setLockedCoins
3764  setLockedCoins.erase(output);
3765 }
3766 
3768 {
3769  AssertLockHeld(cs_wallet); // setLockedCoins
3770  setLockedCoins.clear();
3771 }
3772 
3773 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3774 {
3775  AssertLockHeld(cs_wallet); // setLockedCoins
3776  COutPoint outpt(hash, n);
3777 
3778  return (setLockedCoins.count(outpt) > 0);
3779 }
3780 
3781 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3782 {
3783  AssertLockHeld(cs_wallet); // setLockedCoins
3784  for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3785  it != setLockedCoins.end(); it++) {
3786  COutPoint outpt = (*it);
3787  vOutpts.push_back(outpt);
3788  }
3789 }
3790  // end of Actions
3792 
3793 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3794  AssertLockHeld(cs_wallet); // mapKeyMetadata
3795  mapKeyBirth.clear();
3796 
3797  // get birth times for keys with metadata
3798  for (const auto& entry : mapKeyMetadata) {
3799  if (entry.second.nCreateTime) {
3800  mapKeyBirth[entry.first] = entry.second.nCreateTime;
3801  }
3802  }
3803 
3804  // map in which we'll infer heights of other keys
3805  CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3806  std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3807  std::set<CKeyID> setKeys;
3808  GetKeys(setKeys);
3809  for (const CKeyID &keyid : setKeys) {
3810  if (mapKeyBirth.count(keyid) == 0)
3811  mapKeyFirstBlock[keyid] = pindexMax;
3812  }
3813  setKeys.clear();
3814 
3815  // if there are no such keys, we're done
3816  if (mapKeyFirstBlock.empty())
3817  return;
3818 
3819  // find first block that affects those keys, if there are any left
3820  std::vector<CKeyID> vAffected;
3821  for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3822  // iterate over all wallet transactions...
3823  const CWalletTx &wtx = (*it).second;
3824  BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3825  if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3826  // ... which are already in a block
3827  int nHeight = blit->second->nHeight;
3828  for (const CTxOut &txout : wtx.tx->vout) {
3829  // iterate over all their outputs
3830  CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3831  for (const CKeyID &keyid : vAffected) {
3832  // ... and all their affected keys
3833  std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3834  if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3835  rit->second = blit->second;
3836  }
3837  vAffected.clear();
3838  }
3839  }
3840  }
3841 
3842  // Extract block timestamps for those keys
3843  for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3844  mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3845 }
3846 
3868 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3869 {
3870  unsigned int nTimeSmart = wtx.nTimeReceived;
3871  if (!wtx.hashUnset()) {
3872  if (mapBlockIndex.count(wtx.hashBlock)) {
3873  int64_t latestNow = wtx.nTimeReceived;
3874  int64_t latestEntry = 0;
3875 
3876  // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3877  int64_t latestTolerated = latestNow + 300;
3878  const TxItems& txOrdered = wtxOrdered;
3879  for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3880  CWalletTx* const pwtx = it->second.first;
3881  if (pwtx == &wtx) {
3882  continue;
3883  }
3884  CAccountingEntry* const pacentry = it->second.second;
3885  int64_t nSmartTime;
3886  if (pwtx) {
3887  nSmartTime = pwtx->nTimeSmart;
3888  if (!nSmartTime) {
3889  nSmartTime = pwtx->nTimeReceived;
3890  }
3891  } else {
3892  nSmartTime = pacentry->nTime;
3893  }
3894  if (nSmartTime <= latestTolerated) {
3895  latestEntry = nSmartTime;
3896  if (nSmartTime > latestNow) {
3897  latestNow = nSmartTime;
3898  }
3899  break;
3900  }
3901  }
3902 
3903  int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3904  nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3905  } else {
3906  LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3907  }
3908  }
3909  return nTimeSmart;
3910 }
3911 
3912 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3913 {
3914  if (boost::get<CNoDestination>(&dest))
3915  return false;
3916 
3917  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3918  return CWalletDB(*dbw).WriteDestData(CFabcoinAddress(dest).ToString(), key, value);
3919 }
3920 
3921 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3922 {
3923  if (!mapAddressBook[dest].destdata.erase(key))
3924  return false;
3925  return CWalletDB(*dbw).EraseDestData(CFabcoinAddress(dest).ToString(), key);
3926 }
3927 
3928 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3929 {
3930  mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3931  return true;
3932 }
3933 
3934 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3935 {
3936  std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3937  if(i != mapAddressBook.end())
3938  {
3939  CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3940  if(j != i->second.destdata.end())
3941  {
3942  if(value)
3943  *value = j->second;
3944  return true;
3945  }
3946  }
3947  return false;
3948 }
3949 
3950 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3951 {
3952  LOCK(cs_wallet);
3953  std::vector<std::string> values;
3954  for (const auto& address : mapAddressBook) {
3955  for (const auto& data : address.second.destdata) {
3956  if (!data.first.compare(0, prefix.size(), prefix)) {
3957  values.emplace_back(data.second);
3958  }
3959  }
3960  }
3961  return values;
3962 }
3963 
3964 std::string CWallet::GetWalletHelpString(bool showDebug)
3965 {
3966  std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3967  strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3968  strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3969  strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3970  CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3971  strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
3972  "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"),
3973  CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3974  strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3975  CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3976  strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3978  strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3979  strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3980  strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3981  strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
3982  strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
3983  strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3984  strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3985  strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3986  strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3987  strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3988  strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3989  " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3990  strUsage += HelpMessageOpt("-rpcmaxgasprice", strprintf(_("The max value (in satoshis) for gas price allowed through RPC (default: %u)"), MAX_RPC_GAS_PRICE));
3991 
3992  if (showDebug)
3993  {
3994  strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3995 
3996  strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3997  strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3998  strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3999  strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
4000  }
4001 
4002  return strUsage;
4003 }
4004 
4005 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
4006 {
4007  // needed to restore wallet transaction meta data after -zapwallettxes
4008  std::vector<CWalletTx> vWtx;
4009 
4010  if (gArgs.GetBoolArg("-zapwallettxes", false)) {
4011  uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
4012 
4013  std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
4014  CWallet *tempWallet = new CWallet(std::move(dbw));
4015  DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
4016  if (nZapWalletRet != DB_LOAD_OK) {
4017  InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
4018  return nullptr;
4019  }
4020 
4021  delete tempWallet;
4022  tempWallet = nullptr;
4023  }
4024 
4025  uiInterface.InitMessage(_("Loading wallet..."));
4026 
4027  int64_t nStart = GetTimeMillis();
4028  bool fFirstRun = true;
4029  std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
4030  CWallet *walletInstance = new CWallet(std::move(dbw));
4031  DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
4032  if (nLoadWalletRet != DB_LOAD_OK)
4033  {
4034  if (nLoadWalletRet == DB_CORRUPT) {
4035  InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
4036  return nullptr;
4037  }
4038  else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
4039  {
4040  InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
4041  " or address book entries might be missing or incorrect."),
4042  walletFile));
4043  }
4044  else if (nLoadWalletRet == DB_TOO_NEW) {
4045  InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
4046  return nullptr;
4047  }
4048  else if (nLoadWalletRet == DB_NEED_REWRITE)
4049  {
4050  InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
4051  return nullptr;
4052  }
4053  else {
4054  InitError(strprintf(_("Error loading %s"), walletFile));
4055  return nullptr;
4056  }
4057  }
4058 
4059  if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
4060  {
4061  int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
4062  if (nMaxVersion == 0) // the -upgradewallet without argument case
4063  {
4064  LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
4065  nMaxVersion = CLIENT_VERSION;
4066  walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
4067  }
4068  else
4069  LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
4070  if (nMaxVersion < walletInstance->GetVersion())
4071  {
4072  InitError(_("Cannot downgrade wallet"));
4073  return nullptr;
4074  }
4075  walletInstance->SetMaxVersion(nMaxVersion);
4076  }
4077 
4078  if (fFirstRun)
4079  {
4080  // Create new keyUser and set as default key
4081  if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
4082 
4083  // ensure this wallet.dat can only be opened by clients supporting HD with chain split
4084  walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
4085 
4086  // generate a new master key
4087  CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
4088  if (!walletInstance->SetHDMasterKey(masterPubKey))
4089  throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
4090  }
4091  CPubKey newDefaultKey;
4092  if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
4093  walletInstance->SetDefaultKey(newDefaultKey);
4094  if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
4095  InitError(_("Cannot write default address") += "\n");
4096  return nullptr;
4097  }
4098  }
4099 
4100  walletInstance->SetBestChain(chainActive.GetLocator());
4101  }
4102  else if (gArgs.IsArgSet("-usehd")) {
4103  bool useHD = gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
4104  if (walletInstance->IsHDEnabled() && !useHD) {
4105  InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
4106  return nullptr;
4107  }
4108  if (!walletInstance->IsHDEnabled() && useHD) {
4109  InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
4110  return nullptr;
4111  }
4112  }
4113 
4114  LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
4115 
4116  RegisterValidationInterface(walletInstance);
4117 
4118  // Try to top up keypool. No-op if the wallet is locked.
4119  walletInstance->TopUpKeyPool();
4120 
4121  CBlockIndex *pindexRescan = chainActive.Genesis();
4122  if (!gArgs.GetBoolArg("-rescan", false))
4123  {
4124  CWalletDB walletdb(*walletInstance->dbw);
4125  CBlockLocator locator;
4126  if (walletdb.ReadBestBlock(locator))
4127  pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4128  }
4129  if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
4130  {
4131  //We can't rescan beyond non-pruned blocks, stop and throw an error
4132  //this might happen if a user uses an old wallet within a pruned node
4133  // or if he ran -disablewallet for a longer time, then decided to re-enable
4134  if (fPruneMode)
4135  {
4136  CBlockIndex *block = chainActive.Tip();
4137  while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4138  block = block->pprev;
4139 
4140  if (pindexRescan != block) {
4141  InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4142  return nullptr;
4143  }
4144  }
4145 
4146  uiInterface.InitMessage(_("Rescanning..."));
4147  LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4148 
4149  // No need to read and scan block if block was created before
4150  // our wallet birthday (as adjusted for block time variability)
4151  while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4152  pindexRescan = chainActive.Next(pindexRescan);
4153  }
4154 
4155  nStart = GetTimeMillis();
4156  walletInstance->ScanForWalletTransactions(pindexRescan, true);
4157  LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4158  walletInstance->SetBestChain(chainActive.GetLocator());
4159  walletInstance->dbw->IncrementUpdateCounter();
4160 
4161  // Restore wallet transaction metadata after -zapwallettxes=1
4162  if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4163  {
4164  CWalletDB walletdb(*walletInstance->dbw);
4165 
4166  for (const CWalletTx& wtxOld : vWtx)
4167  {
4168  uint256 hash = wtxOld.GetHash();
4169  std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4170  if (mi != walletInstance->mapWallet.end())
4171  {
4172  const CWalletTx* copyFrom = &wtxOld;
4173  CWalletTx* copyTo = &mi->second;
4174  copyTo->mapValue = copyFrom->mapValue;
4175  copyTo->vOrderForm = copyFrom->vOrderForm;
4176  copyTo->nTimeReceived = copyFrom->nTimeReceived;
4177  copyTo->nTimeSmart = copyFrom->nTimeSmart;
4178  copyTo->fFromMe = copyFrom->fFromMe;
4179  copyTo->strFromAccount = copyFrom->strFromAccount;
4180  copyTo->nOrderPos = copyFrom->nOrderPos;
4181  walletdb.WriteTx(*copyTo);
4182  }
4183  }
4184  }
4185  }
4186  walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4187 
4188  {
4189  LOCK(walletInstance->cs_wallet);
4190  LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4191  LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4192  LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4193  }
4194 
4195  return walletInstance;
4196 }
4197 
4199 {
4200  if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4201  LogPrintf("Wallet disabled!\n");
4202  return true;
4203  }
4204 
4205  for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4206  CWallet * const pwallet = CreateWalletFromFile(walletFile);
4207  if (!pwallet) {
4208  return false;
4209  }
4210  vpwallets.push_back(pwallet);
4211  }
4212 
4213  return true;
4214 }
4215 
4216 std::atomic<bool> CWallet::fFlushScheduled(false);
4217 
4219 {
4220  // Add wallet transactions that aren't already in a block to mempool
4221  // Do this here as mempool requires genesis block to be loaded
4222  ReacceptWalletTransactions();
4223 
4224  // Run a thread to flush wallet periodically
4225  if (!CWallet::fFlushScheduled.exchange(true)) {
4226  scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4227  }
4228 }
4229 
4231 {
4232  gArgs.SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4233  const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4234 
4235  if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4236  return true;
4237 
4238  if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
4239  LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4240  }
4241 
4242  if (gArgs.GetBoolArg("-salvagewallet", false)) {
4243  if (is_multiwallet) {
4244  return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4245  }
4246  // Rewrite just private keys: rescan to find transactions
4247  if (gArgs.SoftSetBoolArg("-rescan", true)) {
4248  LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4249  }
4250  }
4251 
4252  int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
4253  // -zapwallettxes implies dropping the mempool on startup
4254  if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
4255  LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4256  }
4257 
4258  // -zapwallettxes implies a rescan
4259  if (zapwallettxes != 0) {
4260  if (is_multiwallet) {
4261  return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4262  }
4263  if (gArgs.SoftSetBoolArg("-rescan", true)) {
4264  LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4265  }
4266  }
4267 
4268  if (is_multiwallet) {
4269  if (gArgs.GetBoolArg("-upgradewallet", false)) {
4270  return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4271  }
4272  }
4273 
4274  if (gArgs.GetBoolArg("-sysperms", false))
4275  return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4276  if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
4277  return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4278 
4279  if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4280  InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4281  _("The wallet will avoid paying less than the minimum relay fee."));
4282 
4283  if (gArgs.IsArgSet("-mintxfee"))
4284  {
4285  CAmount n = 0;
4286  if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n)
4287  return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
4288  if (n > HIGH_TX_FEE_PER_KB)
4289  InitWarning(AmountHighWarn("-mintxfee") + " " +
4290  _("This is the minimum transaction fee you pay on every transaction."));
4291  CWallet::minTxFee = CFeeRate(n);
4292  }
4293  if (gArgs.IsArgSet("-fallbackfee"))
4294  {
4295  CAmount nFeePerK = 0;
4296  if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK))
4297  return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
4298  if (nFeePerK > HIGH_TX_FEE_PER_KB)
4299  InitWarning(AmountHighWarn("-fallbackfee") + " " +
4300  _("This is the transaction fee you may pay when fee estimates are not available."));
4301  CWallet::fallbackFee = CFeeRate(nFeePerK);
4302  }
4303  if (gArgs.IsArgSet("-discardfee"))
4304  {
4305  CAmount nFeePerK = 0;
4306  if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK))
4307  return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
4308  if (nFeePerK > HIGH_TX_FEE_PER_KB)
4309  InitWarning(AmountHighWarn("-discardfee") + " " +
4310  _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4311  CWallet::m_discard_rate = CFeeRate(nFeePerK);
4312  }
4313  if (gArgs.IsArgSet("-paytxfee"))
4314  {
4315  CAmount nFeePerK = 0;
4316  if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK))
4317  return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
4318  if (nFeePerK > HIGH_TX_FEE_PER_KB)
4319  InitWarning(AmountHighWarn("-paytxfee") + " " +
4320  _("This is the transaction fee you will pay if you send a transaction."));
4321 
4322  payTxFee = CFeeRate(nFeePerK, 1000);
4323  if (payTxFee < ::minRelayTxFee)
4324  {
4325  return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4326  gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4327  }
4328  }
4329  if (gArgs.IsArgSet("-maxtxfee"))
4330  {
4331  CAmount nMaxFee = 0;
4332  if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
4333  return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
4334  if (nMaxFee > HIGH_MAX_TX_FEE)
4335  InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4336  maxTxFee = nMaxFee;
4337  if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4338  {
4339  return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4340  gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4341  }
4342  }
4343  nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4344  bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4345  bZeroBalanceAddressToken = gArgs.GetBoolArg("-zerobalanceaddresstoken", DEFAULT_SPEND_ZEROCONF_CHANGE);
4346  fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4347 
4348  return true;
4349 }
4350 
4351 bool CWallet::BackupWallet(const std::string& strDest)
4352 {
4353  return dbw->Backup(strDest);
4354 }
4355 
4356 bool CWallet::LoadToken(const CTokenInfo &token)
4357 {
4358  uint256 hash = token.GetHash();
4359  mapToken[hash] = token;
4360 
4361  return true;
4362 }
4363 
4364 bool CWallet::LoadTokenTx(const CTokenTx &tokenTx)
4365 {
4366  uint256 hash = tokenTx.GetHash();
4367  mapTokenTx[hash] = tokenTx;
4368 
4369  return true;
4370 }
4371 
4372 bool CWallet::AddTokenEntry(const CTokenInfo &token, bool fFlushOnClose)
4373 {
4374  LOCK2(cs_main, cs_wallet);
4375 
4376  CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
4377 
4378  uint256 hash = token.GetHash();
4379 
4380  bool fInsertedNew = true;
4381 
4382  std::map<uint256, CTokenInfo>::iterator it = mapToken.find(hash);
4383  if(it!=mapToken.end())
4384  {
4385  fInsertedNew = false;
4386  }
4387 
4388  // Write to disk
4389  CTokenInfo wtoken = token;
4390  if(!fInsertedNew)
4391  {
4392  wtoken.nCreateTime = GetAdjustedTime();
4393  }
4394  else
4395  {
4396  wtoken.nCreateTime = it->second.nCreateTime;
4397  }
4398 
4399  if (!walletdb.WriteToken(wtoken))
4400  return false;
4401 
4402  mapToken[hash] = wtoken;
4403 
4404  NotifyTokenChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
4405 
4406  // Refresh token tx
4407  if(fInsertedNew)
4408  {
4409  for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++)
4410  {
4411  uint256 tokenTxHash = it->second.GetHash();
4412  NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED);
4413  }
4414  }
4415 
4416  LogPrintf("AddTokenEntry %s\n", wtoken.GetHash().ToString());
4417 
4418  return true;
4419 }
4420 
4421 bool CWallet::AddTokenTxEntry(const CTokenTx &tokenTx, bool fFlushOnClose)
4422 {
4423  LOCK2(cs_main, cs_wallet);
4424 
4425  CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
4426 
4427  uint256 hash = tokenTx.GetHash();
4428 
4429  bool fInsertedNew = true;
4430 
4431  std::map<uint256, CTokenTx>::iterator it = mapTokenTx.find(hash);
4432  if(it!=mapTokenTx.end())
4433  {
4434  fInsertedNew = false;
4435  }
4436 
4437  // Write to disk
4438  CTokenTx wtokenTx = tokenTx;
4439  if(!fInsertedNew)
4440  {
4441  wtokenTx.strLabel = it->second.strLabel;
4442  }
4443  const CBlockIndex *pIndex = chainActive[wtokenTx.blockNumber];
4444  wtokenTx.nCreateTime = pIndex ? pIndex->GetBlockTime() : GetAdjustedTime();
4445 
4446  if (!walletdb.WriteTokenTx(wtokenTx))
4447  return false;
4448 
4449  mapTokenTx[hash] = wtokenTx;
4450 
4451  NotifyTokenTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
4452 
4453  LogPrintf("AddTokenTxEntry %s\n", wtokenTx.GetHash().ToString());
4454 
4455  return true;
4456 }
4457 
4459 {
4460  nTime = GetTime();
4461  fInternal = false;
4462 }
4463 
4464 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4465 {
4466  nTime = GetTime();
4467  vchPubKey = vchPubKeyIn;
4468  fInternal = internalIn;
4469 }
4470 
4471 CWalletKey::CWalletKey(int64_t nExpires)
4472 {
4473  nTimeCreated = (nExpires ? GetTime() : 0);
4474  nTimeExpires = nExpires;
4475 }
4476 
4477 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4478 {
4479  // Update the tx's hashBlock
4480  hashBlock = pindex->GetBlockHash();
4481 
4482  // set the position of the transaction in the block
4483  nIndex = posInBlock;
4484 }
4485 
4487 {
4488  if (hashUnset())
4489  return 0;
4490 
4492 
4493  // Find the block it claims to be in
4494  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4495  if (mi == mapBlockIndex.end())
4496  return 0;
4497  CBlockIndex* pindex = (*mi).second;
4498  if (!pindex || !chainActive.Contains(pindex))
4499  return 0;
4500 
4501  return pindex->nHeight;
4502 }
4503 
4504 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4505 {
4506  if (hashUnset())
4507  return 0;
4508 
4510 
4511  // Find the block it claims to be in
4512  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4513  if (mi == mapBlockIndex.end())
4514  return 0;
4515  CBlockIndex* pindex = (*mi).second;
4516  if (!pindex || !chainActive.Contains(pindex))
4517  return 0;
4518 
4519  pindexRet = pindex;
4520  return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4521 }
4522 
4524 {
4525  if (!IsCoinBase())
4526  return 0;
4527 
4528  //80000
4529  const Consensus::Params& consensus = Params().GetConsensus();
4530  if( this->GetHeight() < consensus.CoinbaseLock && this->GetHeight() != 2 )
4531  return std::max(0, (consensus.CoinbaseLock+1) - GetDepthInMainChain());
4532  else
4533  return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4534 
4535 }
4536 
4537 
4539 {
4540  return ::AcceptToMemoryPool(mempool, state, tx, true, nullptr, nullptr, false, nAbsurdFee);
4541 }
4542 
4544 {
4545  return SerializeHash(*this, SER_GETHASH, 0);
4546 }
4547 
4548 
4550 {
4551  return SerializeHash(*this, SER_GETHASH, 0);
4552 }
4553 
4554 
4555 bool CWallet::GetTokenTxDetails(const CTokenTx &wtx, uint256 &credit, uint256 &debit, std::string &tokenSymbol, uint8_t &decimals) const
4556 {
4557  LOCK2(cs_main, cs_wallet);
4558  bool ret = false;
4559 
4560  for(auto it = mapToken.begin(); it != mapToken.end(); it++)
4561  {
4562  CTokenInfo info = it->second;
4563  if(wtx.strContractAddress == info.strContractAddress)
4564  {
4565  if(wtx.strSenderAddress == info.strSenderAddress)
4566  {
4567  debit = wtx.nValue;
4568  tokenSymbol = info.strTokenSymbol;
4569  decimals = info.nDecimals;
4570  ret = true;
4571  }
4572 
4573  if(wtx.strReceiverAddress == info.strSenderAddress)
4574  {
4575  credit = wtx.nValue;
4576  tokenSymbol = info.strTokenSymbol;
4577  decimals = info.nDecimals;
4578  ret = true;
4579  }
4580  }
4581  }
4582 
4583  return ret;
4584 }
4585 
4586 bool CWallet::IsTokenTxMine(const CTokenTx &wtx) const
4587 {
4588  LOCK2(cs_main, cs_wallet);
4589  bool ret = false;
4590 
4591  for(auto it = mapToken.begin(); it != mapToken.end(); it++)
4592  {
4593  CTokenInfo info = it->second;
4594  if(wtx.strContractAddress == info.strContractAddress)
4595  {
4596  if(wtx.strSenderAddress == info.strSenderAddress ||
4598  {
4599  ret = true;
4600  }
4601  }
4602  }
4603 
4604  return ret;
4605 }
4606 
4607 bool CWallet::RemoveTokenEntry(const uint256 &tokenHash, bool fFlushOnClose)
4608 {
4609  LOCK2(cs_main, cs_wallet);
4610 
4611  CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
4612 
4613  bool fFound = false;
4614 
4615  std::map<uint256, CTokenInfo>::iterator it = mapToken.find(tokenHash);
4616  if(it!=mapToken.end())
4617  {
4618  fFound = true;
4619  }
4620 
4621  if(fFound)
4622  {
4623  // Remove from disk
4624  if (!walletdb.EraseToken(tokenHash))
4625  return false;
4626 
4627  mapToken.erase(it);
4628 
4629  NotifyTokenChanged(this, tokenHash, CT_DELETED);
4630 
4631  // Refresh token tx
4632  for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++)
4633  {
4634  uint256 tokenTxHash = it->second.GetHash();
4635  NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED);
4636  }
4637  }
4638 
4639  LogPrintf("RemoveTokenEntry %s\n", tokenHash.ToString());
4640 
4641  return true;
4642 }
4643 
4644 bool CWallet::SetContractBook(const std::string &strAddress, const std::string &strName, const std::string &strAbi)
4645 {
4646  bool fUpdated = false;
4647  {
4648  LOCK(cs_wallet); // mapContractBook
4649  auto mi = mapContractBook.find(strAddress);
4650  fUpdated = mi != mapContractBook.end();
4651  mapContractBook[strAddress].name = strName;
4652  mapContractBook[strAddress].abi = strAbi;
4653  }
4654 
4655  NotifyContractBookChanged(this, strAddress, strName, strAbi, (fUpdated ? CT_UPDATED : CT_NEW) );
4656 
4657  CWalletDB walletdb(*dbw, "r+", true);
4658  bool ret = walletdb.WriteContractData(strAddress, "name", strName);
4659  ret &= walletdb.WriteContractData(strAddress, "abi", strAbi);
4660  return ret;
4661 }
4662 
4663 bool CWallet::DelContractBook(const std::string &strAddress)
4664 {
4665  {
4666  LOCK(cs_wallet); // mapContractBook
4667  mapContractBook.erase(strAddress);
4668  }
4669 
4670  NotifyContractBookChanged(this, strAddress, "", "", CT_DELETED);
4671 
4672  CWalletDB walletdb(*dbw, "r+", true);
4673  bool ret = walletdb.EraseContractData(strAddress, "name");
4674  ret &= walletdb.EraseContractData(strAddress, "abi");
4675  return ret;
4676 }
4677 
4678 bool CWallet::LoadContractData(const std::string &address, const std::string &key, const std::string &value)
4679 {
4680  bool ret = true;
4681  if(key == "name")
4682  {
4683  mapContractBook[address].name = value;
4684  }
4685  else if(key == "abi")
4686  {
4687  mapContractBook[address].abi = value;
4688  }
4689  else
4690  {
4691  ret = false;
4692  }
4693  return ret;
4694 }
4695 
CAmount GetImmatureWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1862
uint256 GetHash() const
Definition: wallet.cpp:4543
std::string strTokenSymbol
Definition: wallet.h:1302
CAmount nValue
Definition: transaction.h:134
void postInitProcess(CScheduler &scheduler)
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
Definition: wallet.cpp:4218
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost)
Compute the virtual transaction size (weight reinterpreted as bytes).
Definition: policy.cpp:254
CAmount GetFeePerK() const
Return the fee in liu for a size of 1000 bytes.
Definition: feerate.h:38
bool WriteMinVersion(int nVersion)
Definition: walletdb.cpp:153
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, bool fUpdate=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:1643
CTxMemPool mempool
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: util.cpp:563
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
Definition: crypter.cpp:43
void DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata &metadata, CKey &secret, bool internal=false)
Definition: wallet.cpp:183
CFeeRate GetMinFee(size_t sizelimit) const
The minimum fee to get into the mempool, which may itself not be enough for larger-sized transactions...
Definition: txmempool.cpp:996
std::set< std::set< CTxDestination > > GetAddressGroupings()
Definition: wallet.cpp:3579
const char * DEFAULT_WALLET_DAT
Definition: wallet.cpp:52
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
Definition: sign.cpp:198
void SetTx(CTransactionRef arg)
Definition: wallet.h:243
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
Definition: wallet.h:208
CAmount GetAvailableWatchOnlyCredit(const bool &fUseCache=true) const
Definition: wallet.cpp:1876
bool SignTransaction(CMutableTransaction &tx)
Definition: wallet.cpp:2562
CKeyID masterKeyID
master key hash160
Definition: walletdb.h:67
Account information.
Definition: wallet.h:1244
static std::string GetWalletHelpString(bool showDebug)
Definition: wallet.cpp:3964
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth, const std::string *account) const
Definition: wallet.cpp:2115
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:598
std::string hdKeypath
Definition: walletdb.h:103
bool AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey &key, const CPubKey &pubkey)
Definition: wallet.cpp:229
void SetMerkleBranch(const CBlockIndex *pIndex, int posInBlock)
Definition: wallet.cpp:4477
std::string strReceiverAddress
Definition: wallet.h:1357
void UnlockAllCoins()
Definition: wallet.cpp:3767
void BindWallet(CWallet *pwalletIn)
Definition: wallet.h:459
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
Definition: crypter.h:39
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:79
CAmount GetChange(const CTxOut &txout) const
Definition: wallet.cpp:1369
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:90
std::vector< CWalletRef > vpwallets
Definition: wallet.cpp:41
bool IsHDEnabled() const
Definition: wallet.cpp:1500
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
Definition: wallet.cpp:1384
bool 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:3928
int64_t nCreateTime
Definition: wallet.h:1307
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3524
CAmount GetAvailableCredit(bool fUseCache=true) const
Definition: wallet.cpp:1832
int GetDepthInMainChain(const CBlockIndex *&pindexRet) const
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:4504
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
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2167
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
Definition: wallet.cpp:1340
bool fAllowWatchOnly
Includes watch only addresses which match the ISMINE_WATCH_SOLVABLE criteria.
Definition: coincontrol.h:23
const unsigned char * begin() const
Definition: key.h:88
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
Definition: wallet.cpp:1401
bool WriteAccount(const std::string &strAccount, const CAccount &account)
Definition: walletdb.cpp:164
void Process(const CScript &script)
Definition: wallet.cpp:115
bool AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment="")
Definition: wallet.cpp:843
int64_t GetTransactionWeight(const CTransaction &tx)
CAmount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
Definition: wallet.cpp:2152
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:251
bool DelContractBook(const std::string &strAddress)
Definition: wallet.cpp:4663
CScript scriptPubKey
Definition: transaction.h:135
const unsigned int WALLET_CRYPTO_KEY_SIZE
Definition: crypter.h:12
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:184
int GetRandInt(int nMax)
Definition: random.cpp:367
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
Definition: util.cpp:498
uint256 hash
Definition: wallet.cpp:59
static bool InitLoadWallet()
Definition: wallet.cpp:4198
CKey key
Definition: key.h:145
Force estimateSmartFee to use non-conservative estimates.
struct evm_uint256be balance(struct evm_env *env, struct evm_uint160be address)
Definition: capi.c:7
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn&#39;t already have a value.
Definition: util.cpp:537
#define PACKAGE_NAME
char fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this fabcoin node...
Definition: wallet.h:337
bool WriteTx(const CWalletTx &wtx)
Definition: walletdb.cpp:49
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:175
bool TxnBegin()
Begin a new transaction.
Definition: walletdb.cpp:882
Definition: block.h:155
boost::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:29
CFeeRate estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool &pool)
Estimate feerate needed to get be included in a block within confTarget blocks.
Definition: fees.cpp:736
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:826
CCriticalSection cs_wallet
Definition: wallet.h:748
bool SetContractBook(const std::string &strAddress, const std::string &strName, const std::string &strAbi)
Definition: wallet.cpp:4644
const uint256 & GetHash() const
Definition: wallet.h:278
#define strprintf
Definition: tinyformat.h:1054
std::unique_ptr< CWalletDBWrapper > dbw
Definition: wallet.h:741
Encryption/decryption context with key information.
Definition: crypter.h:74
bool WriteToken(const CTokenInfo &wtoken)
Definition: walletdb.cpp:907
bool GetTokenTxDetails(const CTokenTx &wtx, uint256 &credit, uint256 &debit, std::string &tokenSymbol, uint8_t &decimals) const
Definition: wallet.cpp:4555
CAmount maxTxFee
Absolute maximum transaction fee (in liu) used by wallet and mempool (rejects high fee in sendrawtran...
Definition: validation.cpp:104
int nIndex
Definition: wallet.h:219
CAmount nReserveBalance
Settings.
Definition: wallet.cpp:55
std::vector< unsigned char > vchCryptedKey
Definition: crypter.h:35
inv message data
Definition: protocol.h:338
std::vector< CTxIn > vin
Definition: transaction.h:392
bool bSpendZeroConfChange
Definition: wallet.cpp:45
std::string strFromAccount
Definition: wallet.h:338
WalletFeature
(client) version numbers for particular wallet features
Definition: wallet.h:104
size_t GetSerializeSize(const T &t, int nType, int nVersion=0)
Definition: serialize.h:989
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
Definition: walletdb.cpp:90
bool IsChange(const CTxOut &txout) const
Definition: wallet.cpp:1347
int GetHeight() const
Definition: wallet.cpp:4486
bool TxnCommit()
Commit current transaction.
Definition: walletdb.cpp:887
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:74
static const uint32_t SEQUENCE_FINAL
Only serialized through CTransaction.
Definition: transaction.h:71
int64_t IncOrderPosNext(CWalletDB *pwalletdb=nullptr)
Increment the next transaction order id.
Definition: wallet.cpp:831
const char * prefix
Definition: rest.cpp:623
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:265
Definition: key.h:140
CPubKey vchDefaultKey
Definition: wallet.h:830
std::string GetHex() const
Definition: uint256.cpp:21
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
Definition: crypter.h:32
void ReacceptWalletTransactions()
Definition: wallet.cpp:1687
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:24
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:2586
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
uint256 hashBlock
Definition: wallet.h:212
bool hashUnset() const
Definition: wallet.h:274
FeeReason reason
Definition: fees.h:127
CCriticalSection cs_main
Definition: validation.cpp:77
base58-encoded Fabcoin addresses.
Definition: base58.h:104
CAmount GetUnconfirmedBalance() const
Definition: wallet.cpp:2035
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:56
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Definition: standard.cpp:378
int64_t nOrderPos
position in ordered transaction list
Definition: wallet.h:339
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
Definition: crypter.cpp:93
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
Definition: keystore.h:110
A signature creator for transactions.
Definition: sign.h:35
virtual bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/fabcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:39
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those source fail to pr...
Definition: random.cpp:317
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector< COutput > vCoins, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
Definition: wallet.cpp:2387
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
Definition: wallet.cpp:642
std::string strSenderAddress
Definition: wallet.h:1304
CPubKey GenerateNewHDMasterKey()
Definition: wallet.cpp:1446
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:478
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey, SigVersion sigversion)
Definition: ismine.cpp:29
bool IsTrusted() const
Definition: wallet.cpp:1920
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:534
for(size_t i=trim;i< len;i++) hash[i-trim]
CKeyID hdMasterKeyID
Definition: walletdb.h:104
static bool ParameterInteraction()
Definition: wallet.cpp:4230
void GetKeyBirthTimes(std::map< CTxDestination, int64_t > &mapKeyBirth) const
Definition: wallet.cpp:3793
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:29
int64_t nTimeFirstKey
Definition: wallet.h:728
std::vector< std::string > GetArgs(const std::string &strArg)
Definition: util.cpp:490
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Definition: scheduler.cpp:126
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
A wallet has been loaded.
Definition: ui_interface.h:95
void ListAccountCreditDebit(const std::string &strAccount, std::list< CAccountingEntry > &acentries)
Definition: walletdb.cpp:186
assert(len-trim+(2 *lenIndices)<=WIDTH)
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const
Definition: wallet.cpp:3781
bool AddTokenEntry(const CTokenInfo &token, bool fFlushOnClose=true)
Definition: wallet.cpp:4372
void MarkDirty()
make sure balances are recalculated
Definition: wallet.h:446
CChainParams defines various tweakable parameters of a given instance of the Fabcoin system...
Definition: chainparams.h:47
bool SetMinVersion(enum WalletFeature, CWalletDB *pwalletdbIn=nullptr, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
Definition: wallet.cpp:452
unsigned int GetKeyPoolSize()
Definition: wallet.h:1075
int64_t GetTxTime() const
Definition: wallet.cpp:1505
int64_t blockNumber
Definition: wallet.h:1364
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:4471
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:107
bool ErasePurpose(const std::string &strAddress)
Definition: walletdb.cpp:44
bool WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry &acentry)
This writes directly to the database, and will not update the CWallet&#39;s cached accounting entries! Us...
Definition: walletdb.cpp:169
CAmount GetImmatureCredit(bool fUseCache=true) const
Definition: wallet.cpp:1818
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Definition: coincontrol.h:78
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Definition: crypter.cpp:230
ExecStats::duration min
Definition: ExecStats.cpp:35
CAmount GetCredit(const isminefilter &filter) const
Definition: wallet.cpp:1785
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
Definition: wallet.cpp:924
DBErrors
Error statuses for the wallet database.
Definition: walletdb.h:51
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
Definition: wallet.cpp:3355
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:663
if(a.IndicesBefore(b, len, lenIndices))
Definition: equihash.cpp:243
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn&#39;t already have a value.
Definition: util.cpp:528
unsigned char * begin()
Definition: uint256.h:65
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:437
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:141
void ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Definition: wallet.cpp:3429
double GuessVerificationProgress(const ChainTxData &data, CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index.
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:25
void PushInventory(const CInv &inv)
Definition: net.h:822
void SyncTransaction(const CTransactionRef &tx, const CBlockIndex *pindex=nullptr, int posInBlock=0)
Definition: wallet.cpp:1253
bool AddWatchOnly(const CScript &dest) override
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
Definition: wallet.cpp:346
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:297
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1754
bool LoadContractData(const std::string &address, const std::string &key, const std::string &value)
Adds a contract data tuple to the store, without saving it to disk.
Definition: wallet.cpp:4678
const std::vector< CTxIn > vin
Definition: transaction.h:292
std::map< CTxDestination, CAmount > GetAddressBalances()
Definition: wallet.cpp:3539
bool Derive(CExtKey &out, unsigned int nChild) const
Definition: key.cpp:236
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2050
boost::optional< CFeeRate > m_feerate
Override the default payTxFee if set.
Definition: coincontrol.h:27
bool IsEquivalentTo(const CWalletTx &tx) const
Definition: wallet.cpp:1951
bool WriteOrderPosNext(int64_t nOrderPosNext)
Definition: walletdb.cpp:128
void BlockDisconnected(const std::shared_ptr< const CBlock > &pblock) override
Notifies listeners of a block being disconnected.
Definition: wallet.cpp:1292
bool TransactionWithinChainLimit(const uint256 &txid, size_t chainLimit) const
Returns false if the transaction is in the mempool and not within the chain limit specified...
Definition: txmempool.cpp:1073
bool HasWalletSpend(const uint256 &txid) const
Check if a given transaction has any of its outputs spent by another transaction in the wallet...
Definition: wallet.cpp:513
static bool RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
Definition: walletdb.cpp:833
mapValue_t mapValue
Key/value map with information about the transaction.
Definition: wallet.h:318
std::string ToString() const
Definition: uint256.cpp:95
static CAmount GetRequiredFee(unsigned int nTxBytes)
Return the minimum required fee taking into account the floating relay fee and user set minimum trans...
Definition: wallet.cpp:3109
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
Definition: txmempool.h:66
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:302
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CWalletTx &wtxNew, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl &coin_control, bool sign=true, CAmount nGasFee=0, bool hasSender=false)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:2650
void operator()(const CNoDestination &none)
Definition: wallet.cpp:136
CDBEnv bitdb
Definition: db.cpp:61
CAmount GetUnconfirmedWatchOnlyBalance() const
Definition: wallet.cpp:2080
std::string strContractAddress
Definition: wallet.h:1355
std::set< CTxDestination > GetAccountAddresses(const std::string &strAccount) const
Definition: wallet.cpp:3672
int GetDepthInMainChain() const
Definition: wallet.h:268
void KeepKey(int64_t nIndex)
Definition: wallet.cpp:3467
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
std::multimap< int64_t, TxPair > TxItems
Definition: wallet.h:819
int64_t GetBlockTimeMax() const
Definition: chain.h:334
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
Definition: crypter.cpp:208
void MarkReserveKeysAsUsed(int64_t keypool_id)
Marks all keys in the keypool up to and including reserve_key as used.
Definition: wallet.cpp:3721
bool fBatchProcessingMode
Definition: wallet.cpp:50
size_type size() const
Definition: prevector.h:282
bool ReadBlockFromDisk(Block &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
#define AssertLockHeld(cs)
Definition: sync.h:85
void SetBroadcastTransactions(bool broadcast)
Set whether this wallet broadcasts transactions.
Definition: wallet.h:1147
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3258
CBlockPolicyEstimator feeEstimator
Definition: validation.cpp:106
uint256 SerializeHash(const T &obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
Compute the 256-bit hash of an object&#39;s serialization.
Definition: hash.h:200
void MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx)
Definition: wallet.cpp:1194
int GetBlocksToMaturity() const
Definition: wallet.cpp:4523
void MarkDirty()
Definition: wallet.cpp:915
std::string strComment
Definition: wallet.h:596
bool IsTokenTxMine(const CTokenTx &wtx) const
Definition: wallet.cpp:4586
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:512
DBErrors ReorderTransactions()
Definition: wallet.cpp:754
#define LOCK2(cs1, cs2)
Definition: sync.h:176
size_t KeypoolCountExternalKeys()
Definition: wallet.cpp:3349
bool DelAddressBook(const CTxDestination &address)
Definition: wallet.cpp:3276
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
unsigned int nTxConfirmTarget
Definition: wallet.cpp:44
An instance of this class represents one database.
Definition: db.h:93
int64_t nTime
Definition: wallet.h:123
unsigned int HighestTargetTracked(FeeEstimateHorizon horizon) const
Calculation of highest target that estimates are tracked for.
Definition: fees.cpp:771
bool WriteTokenTx(const CTokenTx &wTokenTx)
Definition: walletdb.cpp:917
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, std::string &strSentAccount, const isminefilter &filter) const
Definition: wallet.cpp:1550
#define LogPrintf(...)
Definition: util.h:153
static CFeeRate m_discard_rate
Definition: wallet.h:993
bool CheckFinalTx(const CTransaction &tx, int flags)
Check if transaction will be final in the next block to be created.
Definition: validation.cpp:271
bool EraseToken(uint256 hash)
Definition: walletdb.cpp:912
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:217
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1137
DBErrors LoadWallet(bool &fFirstRunRet)
Definition: wallet.cpp:3175
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:535
void UnlockCoin(const COutPoint &output)
Definition: wallet.cpp:3761
bool signalRbf
Signal BIP-125 replace by fee.
Definition: coincontrol.h:31
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
Definition: walletdb.cpp:871
bool WritePool(int64_t nPool, const CKeyPool &keypool)
Definition: walletdb.cpp:143
static bool VerifyEnvironment(const std::string &walletFile, const fs::path &dataDir, std::string &errorStr)
Definition: walletdb.cpp:856
uint64_t nEntryNo
Definition: wallet.h:599
const std::string & GetAccountName(const CScript &scriptPubKey) const
Definition: wallet.cpp:3296
CPubKey GenerateNewKey(CWalletDB &walletdb, bool internal=false)
keystore implementation Generate a new key
Definition: wallet.cpp:148
void TransactionAddedToMempool(const CTransactionRef &tx) override
Notifies listeners of a transaction having been added to mempool.
Definition: wallet.cpp:1269
bool InMempool() const
Definition: wallet.cpp:1914
CTransactionRef tx
Definition: wallet.h:211
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:103
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
Definition: wallet.cpp:3323
std::string strContractAddress
Definition: wallet.h:1300
isminetype
IsMine() return codes.
Definition: ismine.h:17
An input of a transaction.
Definition: transaction.h:61
bool fWalletRbf
Definition: wallet.cpp:47
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/fabcoin/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:318
bool IsNull() const
Definition: uint256.h:38
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:147
#define LOCK(cs)
Definition: sync.h:175
We want to be able to estimate feerates that are needed on tx&#39;s to be included in a certain number of...
Definition: fees.h:162
bool WriteName(const std::string &strAddress, const std::string &strName)
Definition: walletdb.cpp:27
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
Definition: key.cpp:134
DBErrors LoadWallet(CWallet *pwallet)
Definition: walletdb.cpp:563
ExecStats::duration max
Definition: ExecStats.cpp:36
CKeyPool()
Definition: wallet.cpp:4458
void SetBestChain(const CBlockLocator &loc) override
Notifies listeners of the new active block chain on-disk.
Definition: wallet.cpp:446
void operator()(const CScriptID &scriptId)
Definition: wallet.cpp:130
CTxDestination destChange
Definition: coincontrol.h:19
const uint32_t BIP32_HARDENED_KEY_LIMIT
Definition: wallet.cpp:53
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet, txnouttype *typeRet)
Definition: standard.cpp:268
Fast randomness source.
Definition: random.h:44
int CoinbaseLock
Block height before which the coinbase subsidy will be locked for the same period.
Definition: params.h:62
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
Definition: wallet.cpp:1130
bool EraseContractData(const std::string &address, const std::string &key)
Erase contract data tuple from wallet database.
Definition: walletdb.cpp:931
void Select(const COutPoint &output)
Definition: coincontrol.h:63
uint256 uint256S(const char *str)
Definition: uint256.h:153
An encapsulated public key.
Definition: pubkey.h:39
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
Definition: coincontrol.h:21
bool Unlock(const CKeyingMaterial &vMasterKeyIn)
Definition: crypter.cpp:170
CAmount GetBalance() const
Definition: wallet.cpp:2019
uint32_t n
Definition: transaction.h:22
bool operator()(const CInputCoin &t1, const CInputCoin &t2) const
Definition: wallet.cpp:95
static bool VerifyDatabaseFile(const std::string &walletFile, const fs::path &dataDir, std::string &warningStr, std::string &errorStr)
Definition: walletdb.cpp:861
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
Definition: key.cpp:126
const std::vector< CTxOut > vout
Definition: transaction.h:293
Chars allowed in filenames.
const ChainTxData & TxData() const
Definition: chainparams.h:83
bool SelectCoins(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=nullptr) const
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coinControl are...
Definition: wallet.cpp:2493
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
Definition: script.h:690
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:866
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
Definition: wallet.cpp:520
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
Definition: wallet.cpp:3921
void UpdateTimeFirstKey(int64_t nCreateTime)
Update wallet first key creation time.
Definition: wallet.cpp:306
CScript script
Definition: wallet.cpp:58
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
Definition: walletdb.cpp:788
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman *connman) override
Tells listeners to broadcast their data.
Definition: wallet.cpp:1985
bool GetReservedKey(CPubKey &pubkey, bool internal=false)
Definition: wallet.cpp:3686
#define t1
std::string ToString() const
Definition: base58.cpp:193
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
Definition: wallet.cpp:3868
bool ParseMoney(const std::string &str, CAmount &nRet)
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:1319
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: wallet.cpp:3203
Definition: net.h:120
An output of a transaction.
Definition: transaction.h:131
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
static bool Recover(const std::string &filename, void *callbackDataIn, bool(*recoverKVcallback)(void *callbackData, CDataStream ssKey, CDataStream ssValue), std::string &out_backup_filename)
Definition: walletdb.cpp:821
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const CBlockIndex *pIndex, int posInBlock, bool fUpdate)
Add a transaction to the wallet, or update it.
Definition: wallet.cpp:1071
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:370
bool LoadToWallet(const CWalletTx &wtxIn)
Definition: wallet.cpp:1037
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:477
Parameters that influence chain consensus.
Definition: params.h:39
std::string AmountHighWarn(const std::string &optname)
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
int64_t nCreateTime
Definition: walletdb.h:102
std::vector< CTxOut > vout
Definition: transaction.h:393
bool ErasePool(int64_t nPool)
Definition: walletdb.cpp:148
bool EraseWatchOnly(const CScript &script)
Definition: walletdb.cpp:108
unsigned int fTimeReceivedIsTxTime
Definition: wallet.h:320
static CWallet * CreateWalletFromFile(const std::string walletFile)
Definition: wallet.cpp:4005
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:183
virtual bool RemoveWatchOnly(const CScript &dest) override
Definition: keystore.cpp:93
void LockCoin(const COutPoint &output)
Definition: wallet.cpp:3755
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:953
CCriticalSection cs
Definition: txmempool.h:523
Access to the wallet database.
Definition: walletdb.h:143
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee, bool rawTx)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
std::string strLabel
Definition: wallet.h:1365
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:287
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: walletdb.cpp:771
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
bool fCheckForUpdates
Definition: wallet.cpp:49
#define t2
std::map< CTxDestination, std::vector< COutput > > ListCoins() const
Return list of available coins and locked coins grouped by non-change output address.
Definition: wallet.cpp:2278
bool SetHDMasterKey(const CPubKey &key)
Definition: wallet.cpp:1476
bool exists(uint256 hash) const
Definition: txmempool.h:671
bool ReadBestBlock(CBlockLocator &locator)
Definition: walletdb.cpp:122
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
Definition: chain.cpp:64
std::string GetRejectReason() const
Definition: validation.h:89
bool WriteDefaultKey(const CPubKey &vchPubKey)
Definition: walletdb.cpp:133
int64_t RescanFromTime(int64_t startTime, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1614
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const
Find non-change parent output.
Definition: wallet.cpp:2324
CPubKey vchPubKey
Definition: wallet.h:1247
void KeepKey()
Definition: wallet.cpp:3704
std::string ToString() const
Definition: feerate.cpp:40
#define LogPrint(category,...)
Definition: util.h:164
CAmount GetWatchOnlyBalance() const
Definition: wallet.cpp:2064
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
Definition: walletdb.cpp:877
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:507
Signature sign(Secret const &_k, h256 const &_hash)
Returns siganture of message hash.
Definition: Common.cpp:233
CAmount GetFee(size_t nBytes) const
Return the fee in liu for the given size in bytes.
Definition: feerate.cpp:23
txnouttype
Definition: standard.h:51
Capture information about block/transaction validation.
Definition: validation.h:27
std::vector< uint256 > ResendWalletTransactionsBefore(int64_t nTime, CConnman *connman)
Definition: wallet.cpp:1960
bool WriteBestBlock(const CBlockLocator &locator)
Definition: walletdb.cpp:116
256-bit opaque blob.
Definition: uint256.h:132
CPubKey vchPubKey
Definition: wallet.h:124
static bool Verify()
Responsible for reading and validating the -wallet arguments and verifying the wallet database...
Definition: wallet.cpp:525
const unsigned int WALLET_CRYPTO_SALT_SIZE
Definition: crypter.h:13
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs) ...
Definition: wallet.cpp:490
ArgsManager gArgs
Definition: util.cpp:94
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
Definition: wallet.cpp:3744
static std::atomic< bool > fFlushScheduled
Definition: wallet.h:675
static CAmount GetMinimumFee(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: wallet.cpp:3114
std::vector< CTransactionRef > vtx
Definition: block.h:159
CAmount GetImmatureWatchOnlyBalance() const
Definition: wallet.cpp:2095
const CWalletTx * GetWalletTx(const uint256 &hash) const
Definition: wallet.cpp:139
bool InitError(const std::string &str)
Show error message.
uint8_t nDecimals
Definition: wallet.h:1303
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:465
bool randbool()
Generate a random boolean.
Definition: random.h:123
int64_t nCreateTime
Definition: wallet.h:1362
int GetRequestCount() const
Definition: wallet.cpp:1511
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
Definition: wallet.cpp:3233
static CFeeRate fallbackFee
If fee estimation does not have enough data to provide estimates, use this fee instead.
Definition: wallet.h:992
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:400
PlatformStyle::TableColorType type
Definition: rpcconsole.cpp:61
A key allocated from the key pool.
Definition: wallet.h:1209
bool LoadKeyMetadata(const CTxDestination &pubKey, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
Definition: wallet.cpp:289
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >)
Definition: wallet.cpp:582
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:177
const CChainParams & Params()
Return the currently selected parameters.
bool ReadPool(int64_t nPool, CKeyPool &keypool)
Definition: walletdb.cpp:138
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
bool LoadTokenTx(const CTokenTx &tokenTx)
Definition: wallet.cpp:4364
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
Definition: crypter.cpp:75
bool RemoveTokenEntry(const uint256 &tokenHash, bool fFlushOnClose=true)
Definition: wallet.cpp:4607
CAmount GetAccountCreditDebit(const std::string &strAccount)
Definition: walletdb.cpp:174
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3374
bool fWalletUnlockStakingOnly
Definition: wallet.cpp:328
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:271
int64_t GetTimeMillis()
Definition: utiltime.cpp:39
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
Definition: wallet.h:331
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:1274
void ListAccountCreditDebit(const std::string &strAccount, std::list< CAccountingEntry > &entries)
Definition: wallet.cpp:3084
A virtual base class for key stores.
Definition: keystore.h:18
bool SetDefaultKey(const CPubKey &vchPubKey)
Definition: wallet.cpp:3311
bool RelayWalletTransaction(CConnman *connman)
Definition: wallet.cpp:1720
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
Definition: validation.cpp:233
int64_t GetAdjustedTime()
Definition: timedata.cpp:35
void runCommand(const std::string &strCommand)
Definition: util.cpp:881
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
bool WriteContractData(const std::string &address, const std::string &key, const std::string &value)
Write contract data key,value tuple to database.
Definition: walletdb.cpp:926
Internal transfers.
Definition: wallet.h:589
std::string ToString() const
Definition: wallet.cpp:102
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:530
bool GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew=false)
Definition: wallet.cpp:877
static CFeeRate minTxFee
Fees smaller than this (in liu) are considered zero fee (for transaction creation) Override with -min...
Definition: wallet.h:991
bool isAbandoned() const
Definition: wallet.h:275
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:672
bool IsValid() const
Definition: pubkey.h:162
void operator()(const CKeyID &keyId)
Definition: wallet.cpp:125
Fee rate in liu per kilobyte: CAmount / kB.
Definition: feerate.h:20
bool SetHDChain(const CHDChain &chain, bool memonly)
Definition: wallet.cpp:1490
bool LoadCScript(const CScript &redeemScript)
Definition: wallet.cpp:330
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Transaction fee set by the user.
void SetMaster(const unsigned char *seed, unsigned int nSeedLen)
Definition: key.cpp:244
std::vector< unsigned char > vchSalt
Definition: crypter.h:36
Definition: wallet.h:196
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:815
static const int VERSION_HD_CHAIN_SPLIT
Definition: walletdb.h:70
bool LoadToken(const CTokenInfo &token)
Definition: wallet.cpp:4356
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:28
bool GetKeyFromPool(CPubKey &key, bool internal=false)
Definition: wallet.cpp:3490
std::vector< CKeyID > & vKeys
Definition: wallet.cpp:110
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:52
A mutable version of CTransaction.
Definition: transaction.h:390
const uint256 & GetHash() const
Definition: transaction.h:325
std::set< uint256 > GetConflicts() const
Definition: wallet.cpp:1742
Indicates that we know how to create a scriptSig that would solve this if we were given the appropria...
Definition: ismine.h:23
std::vector< std::string > GetDestValues(const std::string &prefix) const
Get all destination values matching a prefix.
Definition: wallet.cpp:3950
FeeEstimateMode m_fee_mode
Fee estimation mode to control arguments to estimateSmartFee.
Definition: coincontrol.h:33
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:623
void ReturnKey()
Definition: wallet.cpp:3712
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1302
uint256 nValue
Definition: wallet.h:1358
std::string strSenderAddress
Definition: wallet.h:1356
std::map< int, ScriptsElement > scriptsMap
Cache of the recent mpos scripts for the block reward recipients The max size of the map is 2 * nCach...
Definition: wallet.cpp:66
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
bool IsLockedCoin(uint256 hash, unsigned int n) const
Definition: wallet.cpp:3773
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:19
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
unsigned int nTimeReceived
time received by this node
Definition: wallet.h:321
void InitWarning(const std::string &str)
Show warning message.
An encapsulated private key.
Definition: key.h:35
bool EraseName(const std::string &strAddress)
Definition: walletdb.cpp:32
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:25
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
uint256 GetHash() const
Definition: wallet.cpp:4549
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
Use default settings based on other criteria.
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:3912
Information about a peer.
Definition: net.h:599
unsigned int nDeriveIterations
Definition: crypter.h:40
full block available in blk*.dat
Definition: chain.h:161
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
Definition: walletdb.cpp:95
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
Definition: walletdb.cpp:39
bool IsSpent(const uint256 &hash, unsigned int n) const
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:623
int64_t GetBlockTime() const
Definition: chain.h:329
std::pair< CWalletTx *, CAccountingEntry * > TxPair
Definition: wallet.h:818
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:87
bool IsSelected(const COutPoint &output) const
Definition: coincontrol.h:58
bool BackupWallet(const std::string &strDest)
Definition: wallet.cpp:4351
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:146
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
bool AddAccountingEntry(const CAccountingEntry &)
Definition: wallet.cpp:3089
bool fNotUseChangeAddress
Definition: wallet.cpp:48
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
COutPoint prevout
Definition: transaction.h:64
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: walletdb.cpp:733
void mine(Client &c, int numBlocks)
Definition: TestHelper.cpp:39
std::string strOtherAccount
Definition: wallet.h:595
bool bZeroBalanceAddressToken
Definition: wallet.cpp:46
void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey &pubkey)
Definition: wallet.cpp:3475
bool AcceptToMemoryPool(const CAmount &nAbsurdFee, CValidationState &state)
Pass this transaction to the mempool.
Definition: wallet.cpp:4538
int nVersion
Definition: walletdb.h:72
uint8_t const * data
Definition: sha3.h:19
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: util.cpp:559
BlockMap mapBlockIndex
Definition: validation.cpp:79
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
Definition: walletdb.cpp:100
bool ReadAccount(const std::string &strAccount, CAccount &account)
Definition: walletdb.cpp:158
bool fInternal
Definition: wallet.h:125
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:209
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
Definition: wallet.cpp:375
static const int VERSION_HD_BASE
Definition: walletdb.h:69
CAmount nCreditDebit
Definition: wallet.h:593
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
Try to calculate all in-mempool ancestors of entry.
Definition: txmempool.cpp:158
int64_t nTime
Definition: wallet.h:594
bool AddTokenTxEntry(const CTokenTx &tokenTx, bool fFlushOnClose=true)
Definition: wallet.cpp:4421
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:71
CTxOut txout
Definition: wallet.h:512
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
Definition: ui_interface.h:81
bool RemoveWatchOnly(const CScript &dest) override
Definition: wallet.cpp:362
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
uint256 GetBlockHash() const
Definition: chain.h:324
bool HasSelected() const
Definition: coincontrol.h:53
uint64_t GetRand(uint64_t nMax)
Definition: random.cpp:352
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
Definition: wallet.cpp:113
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
Definition: walletdb.cpp:59
bool Unlock(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:380
virtual bool AddWatchOnly(const CScript &dest) override
Support for Watch-only addresses.
Definition: keystore.cpp:83
CAmount GetChange() const
Definition: wallet.cpp:1905
bool IsCoinBase() const
Definition: wallet.h:279
A key pool entry.
Definition: wallet.h:120
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:42
const CKeyStore & keystore
Definition: wallet.cpp:109
std::vector< std::pair< std::string, std::string > > vOrderForm
Definition: wallet.h:319
uint256 hash
Definition: transaction.h:21
bool CommitTransaction(CWalletTx &wtxNew, CReserveKey &reservekey, CConnman *connman, CValidationState &state)
Call after CreateTransaction unless you want to abort.
Definition: wallet.cpp:3045
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:3934
CFeeRate dustRelayFee
Definition: policy.cpp:251
std::string strAccount
Definition: wallet.h:592