Merge #11870: wallet: Remove unnecessary mempool lock in ReacceptWalletTransactions
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobb9b4d8ddff703c4d5569ad2c46640b21f5dd24a7
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #include <wallet/wallet.h>
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 <wallet/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 <scheduler.h>
27 #include <timedata.h>
28 #include <txmempool.h>
29 #include <util.h>
30 #include <utilmoneystr.h>
31 #include <wallet/fees.h>
33 #include <assert.h>
34 #include <future>
36 #include <boost/algorithm/string/replace.hpp>
37 #include <boost/thread.hpp>
39 std::vector<CWalletRef> vpwallets;
40 /** Transaction fee set by the user */
41 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
42 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
43 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
44 bool fWalletRbf = DEFAULT_WALLET_RBF;
46 const char * DEFAULT_WALLET_DAT = "wallet.dat";
47 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
49 /**
50 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
51 * Override with -mintxfee
53 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
54 /**
55 * If fee estimation does not have enough data to provide estimates, use this fee instead.
56 * Has no effect if not using fee estimation
57 * Override with -fallbackfee
59 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
61 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
63 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
65 /** @defgroup mapWallet
67 * @{
70 struct CompareValueOnly
72 bool operator()(const CInputCoin& t1,
73 const CInputCoin& t2) const
75 return t1.txout.nValue < t2.txout.nValue;
79 std::string COutput::ToString() const
81 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
84 class CAffectedKeysVisitor : public boost::static_visitor<void> {
85 private:
86 const CKeyStore &keystore;
87 std::vector<CKeyID> &vKeys;
89 public:
90 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
92 void Process(const CScript &script) {
93 txnouttype type;
94 std::vector<CTxDestination> vDest;
95 int nRequired;
96 if (ExtractDestinations(script, type, vDest, nRequired)) {
97 for (const CTxDestination &dest : vDest)
98 boost::apply_visitor(*this, dest);
102 void operator()(const CKeyID &keyId) {
103 if (keystore.HaveKey(keyId))
104 vKeys.push_back(keyId);
107 void operator()(const CScriptID &scriptId) {
108 CScript script;
109 if (keystore.GetCScript(scriptId, script))
110 Process(script);
113 void operator()(const WitnessV0ScriptHash& scriptID)
115 CScriptID id;
116 CRIPEMD160().Write(scriptID.begin(), 32).Finalize(id.begin());
117 CScript script;
118 if (keystore.GetCScript(id, script)) {
119 Process(script);
123 void operator()(const WitnessV0KeyHash& keyid)
125 CKeyID id(keyid);
126 if (keystore.HaveKey(id)) {
127 vKeys.push_back(id);
131 template<typename X>
132 void operator()(const X &none) {}
135 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
137 LOCK(cs_wallet);
138 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
139 if (it == mapWallet.end())
140 return nullptr;
141 return &(it->second);
144 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
146 AssertLockHeld(cs_wallet); // mapKeyMetadata
147 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
149 CKey secret;
151 // Create new metadata
152 int64_t nCreationTime = GetTime();
153 CKeyMetadata metadata(nCreationTime);
155 // use HD key derivation if HD was enabled during wallet creation
156 if (IsHDEnabled()) {
157 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
158 } else {
159 secret.MakeNewKey(fCompressed);
162 // Compressed public keys were introduced in version 0.6.0
163 if (fCompressed) {
164 SetMinVersion(FEATURE_COMPRPUBKEY);
167 CPubKey pubkey = secret.GetPubKey();
168 assert(secret.VerifyPubKey(pubkey));
170 mapKeyMetadata[pubkey.GetID()] = metadata;
171 UpdateTimeFirstKey(nCreationTime);
173 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
174 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
176 return pubkey;
179 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
181 // for now we use a fixed keypath scheme of m/0'/0'/k
182 CKey key; //master key seed (256bit)
183 CExtKey masterKey; //hd master key
184 CExtKey accountKey; //key at m/0'
185 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
186 CExtKey childKey; //key at m/0'/0'/<n>'
188 // try to get the master key
189 if (!GetKey(hdChain.masterKeyID, key))
190 throw std::runtime_error(std::string(__func__) + ": Master key not found");
192 masterKey.SetMaster(key.begin(), key.size());
194 // derive m/0'
195 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
196 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
198 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
199 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
200 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
202 // derive child key at next index, skip keys already known to the wallet
203 do {
204 // always derive hardened keys
205 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
206 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
207 if (internal) {
208 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
209 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
210 hdChain.nInternalChainCounter++;
212 else {
213 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
214 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
215 hdChain.nExternalChainCounter++;
217 } while (HaveKey(childKey.key.GetPubKey().GetID()));
218 secret = childKey.key;
219 metadata.hdMasterKeyID = hdChain.masterKeyID;
220 // update the chain model in the database
221 if (!walletdb.WriteHDChain(hdChain))
222 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
225 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
227 AssertLockHeld(cs_wallet); // mapKeyMetadata
229 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
230 // which is overridden below. To avoid flushes, the database handle is
231 // tunneled through to it.
232 bool needsDB = !pwalletdbEncryption;
233 if (needsDB) {
234 pwalletdbEncryption = &walletdb;
236 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
237 if (needsDB) pwalletdbEncryption = nullptr;
238 return false;
240 if (needsDB) pwalletdbEncryption = nullptr;
242 // check if we need to remove from watch-only
243 CScript script;
244 script = GetScriptForDestination(pubkey.GetID());
245 if (HaveWatchOnly(script)) {
246 RemoveWatchOnly(script);
248 script = GetScriptForRawPubKey(pubkey);
249 if (HaveWatchOnly(script)) {
250 RemoveWatchOnly(script);
253 if (!IsCrypted()) {
254 return walletdb.WriteKey(pubkey,
255 secret.GetPrivKey(),
256 mapKeyMetadata[pubkey.GetID()]);
258 return true;
261 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
263 CWalletDB walletdb(*dbw);
264 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
267 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
268 const std::vector<unsigned char> &vchCryptedSecret)
270 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
271 return false;
273 LOCK(cs_wallet);
274 if (pwalletdbEncryption)
275 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
276 vchCryptedSecret,
277 mapKeyMetadata[vchPubKey.GetID()]);
278 else
279 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
280 vchCryptedSecret,
281 mapKeyMetadata[vchPubKey.GetID()]);
285 bool CWallet::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &meta)
287 AssertLockHeld(cs_wallet); // mapKeyMetadata
288 UpdateTimeFirstKey(meta.nCreateTime);
289 mapKeyMetadata[keyID] = meta;
290 return true;
293 bool CWallet::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &meta)
295 AssertLockHeld(cs_wallet); // m_script_metadata
296 UpdateTimeFirstKey(meta.nCreateTime);
297 m_script_metadata[script_id] = meta;
298 return true;
301 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
303 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
307 * Update wallet first key creation time. This should be called whenever keys
308 * are added to the wallet, with the oldest key creation time.
310 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
312 AssertLockHeld(cs_wallet);
313 if (nCreateTime <= 1) {
314 // Cannot determine birthday information, so set the wallet birthday to
315 // the beginning of time.
316 nTimeFirstKey = 1;
317 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
318 nTimeFirstKey = nCreateTime;
322 bool CWallet::AddCScript(const CScript& redeemScript)
324 if (!CCryptoKeyStore::AddCScript(redeemScript))
325 return false;
326 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
329 bool CWallet::LoadCScript(const CScript& redeemScript)
331 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
332 * that never can be redeemed. However, old wallets may still contain
333 * these. Do not add them to the wallet and warn. */
334 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
336 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
337 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",
338 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
339 return true;
342 return CCryptoKeyStore::AddCScript(redeemScript);
345 bool CWallet::AddWatchOnly(const CScript& dest)
347 if (!CCryptoKeyStore::AddWatchOnly(dest))
348 return false;
349 const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
350 UpdateTimeFirstKey(meta.nCreateTime);
351 NotifyWatchonlyChanged(true);
352 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
355 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
357 m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
358 return AddWatchOnly(dest);
361 bool CWallet::RemoveWatchOnly(const CScript &dest)
363 AssertLockHeld(cs_wallet);
364 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
365 return false;
366 if (!HaveWatchOnly())
367 NotifyWatchonlyChanged(false);
368 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
369 return false;
371 return true;
374 bool CWallet::LoadWatchOnly(const CScript &dest)
376 return CCryptoKeyStore::AddWatchOnly(dest);
379 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
381 CCrypter crypter;
382 CKeyingMaterial _vMasterKey;
385 LOCK(cs_wallet);
386 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
388 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
389 return false;
390 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
391 continue; // try another master key
392 if (CCryptoKeyStore::Unlock(_vMasterKey))
393 return true;
396 return false;
399 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
401 bool fWasLocked = IsLocked();
404 LOCK(cs_wallet);
405 Lock();
407 CCrypter crypter;
408 CKeyingMaterial _vMasterKey;
409 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
411 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
412 return false;
413 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
414 return false;
415 if (CCryptoKeyStore::Unlock(_vMasterKey))
417 int64_t nStartTime = GetTimeMillis();
418 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
419 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
421 nStartTime = GetTimeMillis();
422 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
423 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
425 if (pMasterKey.second.nDeriveIterations < 25000)
426 pMasterKey.second.nDeriveIterations = 25000;
428 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
430 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
431 return false;
432 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
433 return false;
434 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
435 if (fWasLocked)
436 Lock();
437 return true;
442 return false;
445 void CWallet::SetBestChain(const CBlockLocator& loc)
447 CWalletDB walletdb(*dbw);
448 walletdb.WriteBestBlock(loc);
451 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
453 LOCK(cs_wallet); // nWalletVersion
454 if (nWalletVersion >= nVersion)
455 return true;
457 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
458 if (fExplicit && nVersion > nWalletMaxVersion)
459 nVersion = FEATURE_LATEST;
461 nWalletVersion = nVersion;
463 if (nVersion > nWalletMaxVersion)
464 nWalletMaxVersion = nVersion;
467 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
468 if (nWalletVersion > 40000)
469 pwalletdb->WriteMinVersion(nWalletVersion);
470 if (!pwalletdbIn)
471 delete pwalletdb;
474 return true;
477 bool CWallet::SetMaxVersion(int nVersion)
479 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
480 // cannot downgrade below current version
481 if (nWalletVersion > nVersion)
482 return false;
484 nWalletMaxVersion = nVersion;
486 return true;
489 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
491 std::set<uint256> result;
492 AssertLockHeld(cs_wallet);
494 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
495 if (it == mapWallet.end())
496 return result;
497 const CWalletTx& wtx = it->second;
499 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
501 for (const CTxIn& txin : wtx.tx->vin)
503 if (mapTxSpends.count(txin.prevout) <= 1)
504 continue; // No conflict if zero or one spends
505 range = mapTxSpends.equal_range(txin.prevout);
506 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
507 result.insert(_it->second);
509 return result;
512 bool CWallet::HasWalletSpend(const uint256& txid) const
514 AssertLockHeld(cs_wallet);
515 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
516 return (iter != mapTxSpends.end() && iter->first.hash == txid);
519 void CWallet::Flush(bool shutdown)
521 dbw->Flush(shutdown);
524 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
526 // We want all the wallet transactions in range to have the same metadata as
527 // the oldest (smallest nOrderPos).
528 // So: find smallest nOrderPos:
530 int nMinOrderPos = std::numeric_limits<int>::max();
531 const CWalletTx* copyFrom = nullptr;
532 for (TxSpends::iterator it = range.first; it != range.second; ++it)
534 const uint256& hash = it->second;
535 int n = mapWallet[hash].nOrderPos;
536 if (n < nMinOrderPos)
538 nMinOrderPos = n;
539 copyFrom = &mapWallet[hash];
543 assert(copyFrom);
545 // Now copy data from copyFrom to rest:
546 for (TxSpends::iterator it = range.first; it != range.second; ++it)
548 const uint256& hash = it->second;
549 CWalletTx* copyTo = &mapWallet[hash];
550 if (copyFrom == copyTo) continue;
551 assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
552 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
553 copyTo->mapValue = copyFrom->mapValue;
554 copyTo->vOrderForm = copyFrom->vOrderForm;
555 // fTimeReceivedIsTxTime not copied on purpose
556 // nTimeReceived not copied on purpose
557 copyTo->nTimeSmart = copyFrom->nTimeSmart;
558 copyTo->fFromMe = copyFrom->fFromMe;
559 copyTo->strFromAccount = copyFrom->strFromAccount;
560 // nOrderPos not copied on purpose
561 // cached members not copied on purpose
566 * Outpoint is spent if any non-conflicted transaction
567 * spends it:
569 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
571 const COutPoint outpoint(hash, n);
572 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
573 range = mapTxSpends.equal_range(outpoint);
575 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
577 const uint256& wtxid = it->second;
578 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
579 if (mit != mapWallet.end()) {
580 int depth = mit->second.GetDepthInMainChain();
581 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
582 return true; // Spent
585 return false;
588 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
590 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
592 std::pair<TxSpends::iterator, TxSpends::iterator> range;
593 range = mapTxSpends.equal_range(outpoint);
594 SyncMetaData(range);
598 void CWallet::AddToSpends(const uint256& wtxid)
600 auto it = mapWallet.find(wtxid);
601 assert(it != mapWallet.end());
602 CWalletTx& thisTx = it->second;
603 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
604 return;
606 for (const CTxIn& txin : thisTx.tx->vin)
607 AddToSpends(txin.prevout, wtxid);
610 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
612 if (IsCrypted())
613 return false;
615 CKeyingMaterial _vMasterKey;
617 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
618 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
620 CMasterKey kMasterKey;
622 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
623 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
625 CCrypter crypter;
626 int64_t nStartTime = GetTimeMillis();
627 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
628 kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
630 nStartTime = GetTimeMillis();
631 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
632 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
634 if (kMasterKey.nDeriveIterations < 25000)
635 kMasterKey.nDeriveIterations = 25000;
637 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
639 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
640 return false;
641 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
642 return false;
645 LOCK(cs_wallet);
646 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
647 assert(!pwalletdbEncryption);
648 pwalletdbEncryption = new CWalletDB(*dbw);
649 if (!pwalletdbEncryption->TxnBegin()) {
650 delete pwalletdbEncryption;
651 pwalletdbEncryption = nullptr;
652 return false;
654 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
656 if (!EncryptKeys(_vMasterKey))
658 pwalletdbEncryption->TxnAbort();
659 delete pwalletdbEncryption;
660 // We now probably have half of our keys encrypted in memory, and half not...
661 // die and let the user reload the unencrypted wallet.
662 assert(false);
665 // Encryption was introduced in version 0.4.0
666 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
668 if (!pwalletdbEncryption->TxnCommit()) {
669 delete pwalletdbEncryption;
670 // We now have keys encrypted in memory, but not on disk...
671 // die to avoid confusion and let the user reload the unencrypted wallet.
672 assert(false);
675 delete pwalletdbEncryption;
676 pwalletdbEncryption = nullptr;
678 Lock();
679 Unlock(strWalletPassphrase);
681 // if we are using HD, replace the HD master key (seed) with a new one
682 if (IsHDEnabled()) {
683 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
684 return false;
688 NewKeyPool();
689 Lock();
691 // Need to completely rewrite the wallet file; if we don't, bdb might keep
692 // bits of the unencrypted private key in slack space in the database file.
693 dbw->Rewrite();
696 NotifyStatusChanged(this);
698 return true;
701 DBErrors CWallet::ReorderTransactions()
703 LOCK(cs_wallet);
704 CWalletDB walletdb(*dbw);
706 // Old wallets didn't have any defined order for transactions
707 // Probably a bad idea to change the output of this
709 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
710 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
711 typedef std::multimap<int64_t, TxPair > TxItems;
712 TxItems txByTime;
714 for (auto& entry : mapWallet)
716 CWalletTx* wtx = &entry.second;
717 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
719 std::list<CAccountingEntry> acentries;
720 walletdb.ListAccountCreditDebit("", acentries);
721 for (CAccountingEntry& entry : acentries)
723 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
726 nOrderPosNext = 0;
727 std::vector<int64_t> nOrderPosOffsets;
728 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
730 CWalletTx *const pwtx = (*it).second.first;
731 CAccountingEntry *const pacentry = (*it).second.second;
732 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
734 if (nOrderPos == -1)
736 nOrderPos = nOrderPosNext++;
737 nOrderPosOffsets.push_back(nOrderPos);
739 if (pwtx)
741 if (!walletdb.WriteTx(*pwtx))
742 return DB_LOAD_FAIL;
744 else
745 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
746 return DB_LOAD_FAIL;
748 else
750 int64_t nOrderPosOff = 0;
751 for (const int64_t& nOffsetStart : nOrderPosOffsets)
753 if (nOrderPos >= nOffsetStart)
754 ++nOrderPosOff;
756 nOrderPos += nOrderPosOff;
757 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
759 if (!nOrderPosOff)
760 continue;
762 // Since we're changing the order, write it back
763 if (pwtx)
765 if (!walletdb.WriteTx(*pwtx))
766 return DB_LOAD_FAIL;
768 else
769 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
770 return DB_LOAD_FAIL;
773 walletdb.WriteOrderPosNext(nOrderPosNext);
775 return DB_LOAD_OK;
778 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
780 AssertLockHeld(cs_wallet); // nOrderPosNext
781 int64_t nRet = nOrderPosNext++;
782 if (pwalletdb) {
783 pwalletdb->WriteOrderPosNext(nOrderPosNext);
784 } else {
785 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
787 return nRet;
790 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
792 CWalletDB walletdb(*dbw);
793 if (!walletdb.TxnBegin())
794 return false;
796 int64_t nNow = GetAdjustedTime();
798 // Debit
799 CAccountingEntry debit;
800 debit.nOrderPos = IncOrderPosNext(&walletdb);
801 debit.strAccount = strFrom;
802 debit.nCreditDebit = -nAmount;
803 debit.nTime = nNow;
804 debit.strOtherAccount = strTo;
805 debit.strComment = strComment;
806 AddAccountingEntry(debit, &walletdb);
808 // Credit
809 CAccountingEntry credit;
810 credit.nOrderPos = IncOrderPosNext(&walletdb);
811 credit.strAccount = strTo;
812 credit.nCreditDebit = nAmount;
813 credit.nTime = nNow;
814 credit.strOtherAccount = strFrom;
815 credit.strComment = strComment;
816 AddAccountingEntry(credit, &walletdb);
818 if (!walletdb.TxnCommit())
819 return false;
821 return true;
824 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
826 CWalletDB walletdb(*dbw);
828 CAccount account;
829 walletdb.ReadAccount(strAccount, account);
831 if (!bForceNew) {
832 if (!account.vchPubKey.IsValid())
833 bForceNew = true;
834 else {
835 // Check if the current key has been used
836 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
837 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
838 it != mapWallet.end() && account.vchPubKey.IsValid();
839 ++it)
840 for (const CTxOut& txout : (*it).second.tx->vout)
841 if (txout.scriptPubKey == scriptPubKey) {
842 bForceNew = true;
843 break;
848 // Generate a new key
849 if (bForceNew) {
850 if (!GetKeyFromPool(account.vchPubKey, false))
851 return false;
853 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
854 walletdb.WriteAccount(strAccount, account);
857 pubKey = account.vchPubKey;
859 return true;
862 void CWallet::MarkDirty()
865 LOCK(cs_wallet);
866 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
867 item.second.MarkDirty();
871 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
873 LOCK(cs_wallet);
875 auto mi = mapWallet.find(originalHash);
877 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
878 assert(mi != mapWallet.end());
880 CWalletTx& wtx = (*mi).second;
882 // Ensure for now that we're not overwriting data
883 assert(wtx.mapValue.count("replaced_by_txid") == 0);
885 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
887 CWalletDB walletdb(*dbw, "r+");
889 bool success = true;
890 if (!walletdb.WriteTx(wtx)) {
891 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
892 success = false;
895 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
897 return success;
900 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
902 LOCK(cs_wallet);
904 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
906 uint256 hash = wtxIn.GetHash();
908 // Inserts only if not already there, returns tx inserted or tx found
909 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
910 CWalletTx& wtx = (*ret.first).second;
911 wtx.BindWallet(this);
912 bool fInsertedNew = ret.second;
913 if (fInsertedNew)
915 wtx.nTimeReceived = GetAdjustedTime();
916 wtx.nOrderPos = IncOrderPosNext(&walletdb);
917 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
918 wtx.nTimeSmart = ComputeTimeSmart(wtx);
919 AddToSpends(hash);
922 bool fUpdated = false;
923 if (!fInsertedNew)
925 // Merge
926 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
928 wtx.hashBlock = wtxIn.hashBlock;
929 fUpdated = true;
931 // If no longer abandoned, update
932 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
934 wtx.hashBlock = wtxIn.hashBlock;
935 fUpdated = true;
937 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
939 wtx.nIndex = wtxIn.nIndex;
940 fUpdated = true;
942 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
944 wtx.fFromMe = wtxIn.fFromMe;
945 fUpdated = true;
947 // If we have a witness-stripped version of this transaction, and we
948 // see a new version with a witness, then we must be upgrading a pre-segwit
949 // wallet. Store the new version of the transaction with the witness,
950 // as the stripped-version must be invalid.
951 // TODO: Store all versions of the transaction, instead of just one.
952 if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
953 wtx.SetTx(wtxIn.tx);
954 fUpdated = true;
958 //// debug print
959 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
961 // Write to disk
962 if (fInsertedNew || fUpdated)
963 if (!walletdb.WriteTx(wtx))
964 return false;
966 // Break debit/credit balance caches:
967 wtx.MarkDirty();
969 // Notify UI of new or updated transaction
970 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
972 // notify an external script when a wallet transaction comes in or is updated
973 std::string strCmd = gArgs.GetArg("-walletnotify", "");
975 if (!strCmd.empty())
977 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
978 boost::thread t(runCommand, strCmd); // thread runs free
981 return true;
984 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
986 uint256 hash = wtxIn.GetHash();
988 mapWallet[hash] = wtxIn;
989 CWalletTx& wtx = mapWallet[hash];
990 wtx.BindWallet(this);
991 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
992 AddToSpends(hash);
993 for (const CTxIn& txin : wtx.tx->vin) {
994 auto it = mapWallet.find(txin.prevout.hash);
995 if (it != mapWallet.end()) {
996 CWalletTx& prevtx = it->second;
997 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
998 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1003 return true;
1007 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1008 * be set when the transaction was known to be included in a block. When
1009 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1010 * notifications happen and cached balances are marked dirty.
1012 * If fUpdate is true, existing transactions will be updated.
1013 * TODO: One exception to this is that the abandoned state is cleared under the
1014 * assumption that any further notification of a transaction that was considered
1015 * abandoned is an indication that it is not safe to be considered abandoned.
1016 * Abandoned state should probably be more carefully tracked via different
1017 * posInBlock signals or by checking mempool presence when necessary.
1019 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1021 const CTransaction& tx = *ptx;
1023 AssertLockHeld(cs_wallet);
1025 if (pIndex != nullptr) {
1026 for (const CTxIn& txin : tx.vin) {
1027 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1028 while (range.first != range.second) {
1029 if (range.first->second != tx.GetHash()) {
1030 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);
1031 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1033 range.first++;
1038 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1039 if (fExisted && !fUpdate) return false;
1040 if (fExisted || IsMine(tx) || IsFromMe(tx))
1042 /* Check if any keys in the wallet keypool that were supposed to be unused
1043 * have appeared in a new transaction. If so, remove those keys from the keypool.
1044 * This can happen when restoring an old wallet backup that does not contain
1045 * the mostly recently created transactions from newer versions of the wallet.
1048 // loop though all outputs
1049 for (const CTxOut& txout: tx.vout) {
1050 // extract addresses and check if they match with an unused keypool key
1051 std::vector<CKeyID> vAffected;
1052 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1053 for (const CKeyID &keyid : vAffected) {
1054 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1055 if (mi != m_pool_key_to_index.end()) {
1056 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1057 MarkReserveKeysAsUsed(mi->second);
1059 if (!TopUpKeyPool()) {
1060 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1066 CWalletTx wtx(this, ptx);
1068 // Get merkle branch if transaction was found in a block
1069 if (pIndex != nullptr)
1070 wtx.SetMerkleBranch(pIndex, posInBlock);
1072 return AddToWallet(wtx, false);
1075 return false;
1078 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1080 LOCK2(cs_main, cs_wallet);
1081 const CWalletTx* wtx = GetWalletTx(hashTx);
1082 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1085 bool CWallet::AbandonTransaction(const uint256& hashTx)
1087 LOCK2(cs_main, cs_wallet);
1089 CWalletDB walletdb(*dbw, "r+");
1091 std::set<uint256> todo;
1092 std::set<uint256> done;
1094 // Can't mark abandoned if confirmed or in mempool
1095 auto it = mapWallet.find(hashTx);
1096 assert(it != mapWallet.end());
1097 CWalletTx& origtx = it->second;
1098 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1099 return false;
1102 todo.insert(hashTx);
1104 while (!todo.empty()) {
1105 uint256 now = *todo.begin();
1106 todo.erase(now);
1107 done.insert(now);
1108 auto it = mapWallet.find(now);
1109 assert(it != mapWallet.end());
1110 CWalletTx& wtx = it->second;
1111 int currentconfirm = wtx.GetDepthInMainChain();
1112 // If the orig tx was not in block, none of its spends can be
1113 assert(currentconfirm <= 0);
1114 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1115 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1116 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1117 assert(!wtx.InMempool());
1118 wtx.nIndex = -1;
1119 wtx.setAbandoned();
1120 wtx.MarkDirty();
1121 walletdb.WriteTx(wtx);
1122 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1123 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1124 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1125 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1126 if (!done.count(iter->second)) {
1127 todo.insert(iter->second);
1129 iter++;
1131 // If a transaction changes 'conflicted' state, that changes the balance
1132 // available of the outputs it spends. So force those to be recomputed
1133 for (const CTxIn& txin : wtx.tx->vin)
1135 auto it = mapWallet.find(txin.prevout.hash);
1136 if (it != mapWallet.end()) {
1137 it->second.MarkDirty();
1143 return true;
1146 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1148 LOCK2(cs_main, cs_wallet);
1150 int conflictconfirms = 0;
1151 if (mapBlockIndex.count(hashBlock)) {
1152 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1153 if (chainActive.Contains(pindex)) {
1154 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1157 // If number of conflict confirms cannot be determined, this means
1158 // that the block is still unknown or not yet part of the main chain,
1159 // for example when loading the wallet during a reindex. Do nothing in that
1160 // case.
1161 if (conflictconfirms >= 0)
1162 return;
1164 // Do not flush the wallet here for performance reasons
1165 CWalletDB walletdb(*dbw, "r+", false);
1167 std::set<uint256> todo;
1168 std::set<uint256> done;
1170 todo.insert(hashTx);
1172 while (!todo.empty()) {
1173 uint256 now = *todo.begin();
1174 todo.erase(now);
1175 done.insert(now);
1176 auto it = mapWallet.find(now);
1177 assert(it != mapWallet.end());
1178 CWalletTx& wtx = it->second;
1179 int currentconfirm = wtx.GetDepthInMainChain();
1180 if (conflictconfirms < currentconfirm) {
1181 // Block is 'more conflicted' than current confirm; update.
1182 // Mark transaction as conflicted with this block.
1183 wtx.nIndex = -1;
1184 wtx.hashBlock = hashBlock;
1185 wtx.MarkDirty();
1186 walletdb.WriteTx(wtx);
1187 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1188 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1189 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1190 if (!done.count(iter->second)) {
1191 todo.insert(iter->second);
1193 iter++;
1195 // If a transaction changes 'conflicted' state, that changes the balance
1196 // available of the outputs it spends. So force those to be recomputed
1197 for (const CTxIn& txin : wtx.tx->vin) {
1198 auto it = mapWallet.find(txin.prevout.hash);
1199 if (it != mapWallet.end()) {
1200 it->second.MarkDirty();
1207 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1208 const CTransaction& tx = *ptx;
1210 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1211 return; // Not one of ours
1213 // If a transaction changes 'conflicted' state, that changes the balance
1214 // available of the outputs it spends. So force those to be
1215 // recomputed, also:
1216 for (const CTxIn& txin : tx.vin) {
1217 auto it = mapWallet.find(txin.prevout.hash);
1218 if (it != mapWallet.end()) {
1219 it->second.MarkDirty();
1224 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1225 LOCK2(cs_main, cs_wallet);
1226 SyncTransaction(ptx);
1228 auto it = mapWallet.find(ptx->GetHash());
1229 if (it != mapWallet.end()) {
1230 it->second.fInMempool = true;
1234 void CWallet::TransactionRemovedFromMempool(const CTransactionRef &ptx) {
1235 LOCK(cs_wallet);
1236 auto it = mapWallet.find(ptx->GetHash());
1237 if (it != mapWallet.end()) {
1238 it->second.fInMempool = false;
1242 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1243 LOCK2(cs_main, cs_wallet);
1244 // TODO: Temporarily ensure that mempool removals are notified before
1245 // connected transactions. This shouldn't matter, but the abandoned
1246 // state of transactions in our wallet is currently cleared when we
1247 // receive another notification and there is a race condition where
1248 // notification of a connected conflict might cause an outside process
1249 // to abandon a transaction and then have it inadvertently cleared by
1250 // the notification that the conflicted transaction was evicted.
1252 for (const CTransactionRef& ptx : vtxConflicted) {
1253 SyncTransaction(ptx);
1254 TransactionRemovedFromMempool(ptx);
1256 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1257 SyncTransaction(pblock->vtx[i], pindex, i);
1258 TransactionRemovedFromMempool(pblock->vtx[i]);
1261 m_last_block_processed = pindex;
1264 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1265 LOCK2(cs_main, cs_wallet);
1267 for (const CTransactionRef& ptx : pblock->vtx) {
1268 SyncTransaction(ptx);
1274 void CWallet::BlockUntilSyncedToCurrentChain() {
1275 AssertLockNotHeld(cs_main);
1276 AssertLockNotHeld(cs_wallet);
1279 // Skip the queue-draining stuff if we know we're caught up with
1280 // chainActive.Tip()...
1281 // We could also take cs_wallet here, and call m_last_block_processed
1282 // protected by cs_wallet instead of cs_main, but as long as we need
1283 // cs_main here anyway, its easier to just call it cs_main-protected.
1284 LOCK(cs_main);
1285 const CBlockIndex* initialChainTip = chainActive.Tip();
1287 if (m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) {
1288 return;
1292 // ...otherwise put a callback in the validation interface queue and wait
1293 // for the queue to drain enough to execute it (indicating we are caught up
1294 // at least with the time we entered this function).
1296 std::promise<void> promise;
1297 CallFunctionInValidationInterfaceQueue([&promise] {
1298 promise.set_value();
1300 promise.get_future().wait();
1304 isminetype CWallet::IsMine(const CTxIn &txin) const
1307 LOCK(cs_wallet);
1308 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1309 if (mi != mapWallet.end())
1311 const CWalletTx& prev = (*mi).second;
1312 if (txin.prevout.n < prev.tx->vout.size())
1313 return IsMine(prev.tx->vout[txin.prevout.n]);
1316 return ISMINE_NO;
1319 // Note that this function doesn't distinguish between a 0-valued input,
1320 // and a not-"is mine" (according to the filter) input.
1321 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1324 LOCK(cs_wallet);
1325 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1326 if (mi != mapWallet.end())
1328 const CWalletTx& prev = (*mi).second;
1329 if (txin.prevout.n < prev.tx->vout.size())
1330 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1331 return prev.tx->vout[txin.prevout.n].nValue;
1334 return 0;
1337 isminetype CWallet::IsMine(const CTxOut& txout) const
1339 return ::IsMine(*this, txout.scriptPubKey);
1342 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1344 if (!MoneyRange(txout.nValue))
1345 throw std::runtime_error(std::string(__func__) + ": value out of range");
1346 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1349 bool CWallet::IsChange(const CTxOut& txout) const
1351 // TODO: fix handling of 'change' outputs. The assumption is that any
1352 // payment to a script that is ours, but is not in the address book
1353 // is change. That assumption is likely to break when we implement multisignature
1354 // wallets that return change back into a multi-signature-protected address;
1355 // a better way of identifying which outputs are 'the send' and which are
1356 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1357 // which output, if any, was change).
1358 if (::IsMine(*this, txout.scriptPubKey))
1360 CTxDestination address;
1361 if (!ExtractDestination(txout.scriptPubKey, address))
1362 return true;
1364 LOCK(cs_wallet);
1365 if (!mapAddressBook.count(address))
1366 return true;
1368 return false;
1371 CAmount CWallet::GetChange(const CTxOut& txout) const
1373 if (!MoneyRange(txout.nValue))
1374 throw std::runtime_error(std::string(__func__) + ": value out of range");
1375 return (IsChange(txout) ? txout.nValue : 0);
1378 bool CWallet::IsMine(const CTransaction& tx) const
1380 for (const CTxOut& txout : tx.vout)
1381 if (IsMine(txout))
1382 return true;
1383 return false;
1386 bool CWallet::IsFromMe(const CTransaction& tx) const
1388 return (GetDebit(tx, ISMINE_ALL) > 0);
1391 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1393 CAmount nDebit = 0;
1394 for (const CTxIn& txin : tx.vin)
1396 nDebit += GetDebit(txin, filter);
1397 if (!MoneyRange(nDebit))
1398 throw std::runtime_error(std::string(__func__) + ": value out of range");
1400 return nDebit;
1403 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1405 LOCK(cs_wallet);
1407 for (const CTxIn& txin : tx.vin)
1409 auto mi = mapWallet.find(txin.prevout.hash);
1410 if (mi == mapWallet.end())
1411 return false; // any unknown inputs can't be from us
1413 const CWalletTx& prev = (*mi).second;
1415 if (txin.prevout.n >= prev.tx->vout.size())
1416 return false; // invalid input!
1418 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1419 return false;
1421 return true;
1424 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1426 CAmount nCredit = 0;
1427 for (const CTxOut& txout : tx.vout)
1429 nCredit += GetCredit(txout, filter);
1430 if (!MoneyRange(nCredit))
1431 throw std::runtime_error(std::string(__func__) + ": value out of range");
1433 return nCredit;
1436 CAmount CWallet::GetChange(const CTransaction& tx) const
1438 CAmount nChange = 0;
1439 for (const CTxOut& txout : tx.vout)
1441 nChange += GetChange(txout);
1442 if (!MoneyRange(nChange))
1443 throw std::runtime_error(std::string(__func__) + ": value out of range");
1445 return nChange;
1448 CPubKey CWallet::GenerateNewHDMasterKey()
1450 CKey key;
1451 key.MakeNewKey(true);
1453 int64_t nCreationTime = GetTime();
1454 CKeyMetadata metadata(nCreationTime);
1456 // calculate the pubkey
1457 CPubKey pubkey = key.GetPubKey();
1458 assert(key.VerifyPubKey(pubkey));
1460 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1461 metadata.hdKeypath = "m";
1462 metadata.hdMasterKeyID = pubkey.GetID();
1465 LOCK(cs_wallet);
1467 // mem store the metadata
1468 mapKeyMetadata[pubkey.GetID()] = metadata;
1470 // write the key&metadata to the database
1471 if (!AddKeyPubKey(key, pubkey))
1472 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1475 return pubkey;
1478 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1480 LOCK(cs_wallet);
1481 // store the keyid (hash160) together with
1482 // the child index counter in the database
1483 // as a hdchain object
1484 CHDChain newHdChain;
1485 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1486 newHdChain.masterKeyID = pubkey.GetID();
1487 SetHDChain(newHdChain, false);
1489 return true;
1492 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1494 LOCK(cs_wallet);
1495 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1496 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1498 hdChain = chain;
1499 return true;
1502 bool CWallet::IsHDEnabled() const
1504 return !hdChain.masterKeyID.IsNull();
1507 int64_t CWalletTx::GetTxTime() const
1509 int64_t n = nTimeSmart;
1510 return n ? n : nTimeReceived;
1513 int CWalletTx::GetRequestCount() const
1515 // Returns -1 if it wasn't being tracked
1516 int nRequests = -1;
1518 LOCK(pwallet->cs_wallet);
1519 if (IsCoinBase())
1521 // Generated block
1522 if (!hashUnset())
1524 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1525 if (mi != pwallet->mapRequestCount.end())
1526 nRequests = (*mi).second;
1529 else
1531 // Did anyone request this transaction?
1532 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1533 if (mi != pwallet->mapRequestCount.end())
1535 nRequests = (*mi).second;
1537 // How about the block it's in?
1538 if (nRequests == 0 && !hashUnset())
1540 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1541 if (_mi != pwallet->mapRequestCount.end())
1542 nRequests = (*_mi).second;
1543 else
1544 nRequests = 1; // If it's in someone else's block it must have got out
1549 return nRequests;
1552 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1553 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1555 nFee = 0;
1556 listReceived.clear();
1557 listSent.clear();
1558 strSentAccount = strFromAccount;
1560 // Compute fee:
1561 CAmount nDebit = GetDebit(filter);
1562 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1564 CAmount nValueOut = tx->GetValueOut();
1565 nFee = nDebit - nValueOut;
1568 // Sent/received.
1569 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1571 const CTxOut& txout = tx->vout[i];
1572 isminetype fIsMine = pwallet->IsMine(txout);
1573 // Only need to handle txouts if AT LEAST one of these is true:
1574 // 1) they debit from us (sent)
1575 // 2) the output is to us (received)
1576 if (nDebit > 0)
1578 // Don't report 'change' txouts
1579 if (pwallet->IsChange(txout))
1580 continue;
1582 else if (!(fIsMine & filter))
1583 continue;
1585 // In either case, we need to get the destination address
1586 CTxDestination address;
1588 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1590 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1591 this->GetHash().ToString());
1592 address = CNoDestination();
1595 COutputEntry output = {address, txout.nValue, (int)i};
1597 // If we are debited by the transaction, add the output as a "sent" entry
1598 if (nDebit > 0)
1599 listSent.push_back(output);
1601 // If we are receiving the output, add it as a "received" entry
1602 if (fIsMine & filter)
1603 listReceived.push_back(output);
1609 * Scan active chain for relevant transactions after importing keys. This should
1610 * be called whenever new keys are added to the wallet, with the oldest key
1611 * creation time.
1613 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1614 * returned will be higher than startTime if relevant blocks could not be read.
1616 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1618 AssertLockHeld(cs_main);
1619 AssertLockHeld(cs_wallet);
1621 // Find starting block. May be null if nCreateTime is greater than the
1622 // highest blockchain timestamp, in which case there is nothing that needs
1623 // to be scanned.
1624 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1625 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1627 if (startBlock) {
1628 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1629 if (failedBlock) {
1630 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1633 return startTime;
1637 * Scan the block chain (starting in pindexStart) for transactions
1638 * from or to us. If fUpdate is true, found transactions that already
1639 * exist in the wallet will be updated.
1641 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1642 * possible (due to pruning or corruption), returns pointer to the most recent
1643 * block that could not be scanned.
1645 * If pindexStop is not a nullptr, the scan will stop at the block-index
1646 * defined by pindexStop
1648 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1650 int64_t nNow = GetTime();
1651 const CChainParams& chainParams = Params();
1653 if (pindexStop) {
1654 assert(pindexStop->nHeight >= pindexStart->nHeight);
1657 CBlockIndex* pindex = pindexStart;
1658 CBlockIndex* ret = nullptr;
1660 LOCK2(cs_main, cs_wallet);
1661 fAbortRescan = false;
1662 fScanningWallet = true;
1664 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1665 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1666 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1667 while (pindex && !fAbortRescan)
1669 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1670 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1671 if (GetTime() >= nNow + 60) {
1672 nNow = GetTime();
1673 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1676 CBlock block;
1677 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1678 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1679 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1681 } else {
1682 ret = pindex;
1684 if (pindex == pindexStop) {
1685 break;
1687 pindex = chainActive.Next(pindex);
1689 if (pindex && fAbortRescan) {
1690 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1692 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1694 fScanningWallet = false;
1696 return ret;
1699 void CWallet::ReacceptWalletTransactions()
1701 // If transactions aren't being broadcasted, don't let them into local mempool either
1702 if (!fBroadcastTransactions)
1703 return;
1704 LOCK2(cs_main, cs_wallet);
1705 std::map<int64_t, CWalletTx*> mapSorted;
1707 // Sort pending wallet transactions based on their initial wallet insertion order
1708 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1710 const uint256& wtxid = item.first;
1711 CWalletTx& wtx = item.second;
1712 assert(wtx.GetHash() == wtxid);
1714 int nDepth = wtx.GetDepthInMainChain();
1716 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1717 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1721 // Try to add wallet transactions to memory pool
1722 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1723 CWalletTx& wtx = *(item.second);
1724 CValidationState state;
1725 wtx.AcceptToMemoryPool(maxTxFee, state);
1729 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1731 assert(pwallet->GetBroadcastTransactions());
1732 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1734 CValidationState state;
1735 /* GetDepthInMainChain already catches known conflicts. */
1736 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1737 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1738 if (connman) {
1739 CInv inv(MSG_TX, GetHash());
1740 connman->ForEachNode([&inv](CNode* pnode)
1742 pnode->PushInventory(inv);
1744 return true;
1748 return false;
1751 std::set<uint256> CWalletTx::GetConflicts() const
1753 std::set<uint256> result;
1754 if (pwallet != nullptr)
1756 uint256 myHash = GetHash();
1757 result = pwallet->GetConflicts(myHash);
1758 result.erase(myHash);
1760 return result;
1763 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1765 if (tx->vin.empty())
1766 return 0;
1768 CAmount debit = 0;
1769 if(filter & ISMINE_SPENDABLE)
1771 if (fDebitCached)
1772 debit += nDebitCached;
1773 else
1775 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1776 fDebitCached = true;
1777 debit += nDebitCached;
1780 if(filter & ISMINE_WATCH_ONLY)
1782 if(fWatchDebitCached)
1783 debit += nWatchDebitCached;
1784 else
1786 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1787 fWatchDebitCached = true;
1788 debit += nWatchDebitCached;
1791 return debit;
1794 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1796 // Must wait until coinbase is safely deep enough in the chain before valuing it
1797 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1798 return 0;
1800 CAmount credit = 0;
1801 if (filter & ISMINE_SPENDABLE)
1803 // GetBalance can assume transactions in mapWallet won't change
1804 if (fCreditCached)
1805 credit += nCreditCached;
1806 else
1808 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1809 fCreditCached = true;
1810 credit += nCreditCached;
1813 if (filter & ISMINE_WATCH_ONLY)
1815 if (fWatchCreditCached)
1816 credit += nWatchCreditCached;
1817 else
1819 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1820 fWatchCreditCached = true;
1821 credit += nWatchCreditCached;
1824 return credit;
1827 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1829 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1831 if (fUseCache && fImmatureCreditCached)
1832 return nImmatureCreditCached;
1833 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1834 fImmatureCreditCached = true;
1835 return nImmatureCreditCached;
1838 return 0;
1841 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1843 if (pwallet == nullptr)
1844 return 0;
1846 // Must wait until coinbase is safely deep enough in the chain before valuing it
1847 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1848 return 0;
1850 if (fUseCache && fAvailableCreditCached)
1851 return nAvailableCreditCached;
1853 CAmount nCredit = 0;
1854 uint256 hashTx = GetHash();
1855 for (unsigned int i = 0; i < tx->vout.size(); i++)
1857 if (!pwallet->IsSpent(hashTx, i))
1859 const CTxOut &txout = tx->vout[i];
1860 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1861 if (!MoneyRange(nCredit))
1862 throw std::runtime_error(std::string(__func__) + " : value out of range");
1866 nAvailableCreditCached = nCredit;
1867 fAvailableCreditCached = true;
1868 return nCredit;
1871 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1873 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1875 if (fUseCache && fImmatureWatchCreditCached)
1876 return nImmatureWatchCreditCached;
1877 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1878 fImmatureWatchCreditCached = true;
1879 return nImmatureWatchCreditCached;
1882 return 0;
1885 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1887 if (pwallet == nullptr)
1888 return 0;
1890 // Must wait until coinbase is safely deep enough in the chain before valuing it
1891 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1892 return 0;
1894 if (fUseCache && fAvailableWatchCreditCached)
1895 return nAvailableWatchCreditCached;
1897 CAmount nCredit = 0;
1898 for (unsigned int i = 0; i < tx->vout.size(); i++)
1900 if (!pwallet->IsSpent(GetHash(), i))
1902 const CTxOut &txout = tx->vout[i];
1903 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1904 if (!MoneyRange(nCredit))
1905 throw std::runtime_error(std::string(__func__) + ": value out of range");
1909 nAvailableWatchCreditCached = nCredit;
1910 fAvailableWatchCreditCached = true;
1911 return nCredit;
1914 CAmount CWalletTx::GetChange() const
1916 if (fChangeCached)
1917 return nChangeCached;
1918 nChangeCached = pwallet->GetChange(*tx);
1919 fChangeCached = true;
1920 return nChangeCached;
1923 bool CWalletTx::InMempool() const
1925 return fInMempool;
1928 bool CWalletTx::IsTrusted() const
1930 // Quick answer in most cases
1931 if (!CheckFinalTx(*tx))
1932 return false;
1933 int nDepth = GetDepthInMainChain();
1934 if (nDepth >= 1)
1935 return true;
1936 if (nDepth < 0)
1937 return false;
1938 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1939 return false;
1941 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1942 if (!InMempool())
1943 return false;
1945 // Trusted if all inputs are from us and are in the mempool:
1946 for (const CTxIn& txin : tx->vin)
1948 // Transactions not sent by us: not trusted
1949 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1950 if (parent == nullptr)
1951 return false;
1952 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1953 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1954 return false;
1956 return true;
1959 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1961 CMutableTransaction tx1 = *this->tx;
1962 CMutableTransaction tx2 = *_tx.tx;
1963 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1964 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1965 return CTransaction(tx1) == CTransaction(tx2);
1968 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1970 std::vector<uint256> result;
1972 LOCK(cs_wallet);
1974 // Sort them in chronological order
1975 std::multimap<unsigned int, CWalletTx*> mapSorted;
1976 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1978 CWalletTx& wtx = item.second;
1979 // Don't rebroadcast if newer than nTime:
1980 if (wtx.nTimeReceived > nTime)
1981 continue;
1982 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1984 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1986 CWalletTx& wtx = *item.second;
1987 if (wtx.RelayWalletTransaction(connman))
1988 result.push_back(wtx.GetHash());
1990 return result;
1993 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1995 // Do this infrequently and randomly to avoid giving away
1996 // that these are our transactions.
1997 if (GetTime() < nNextResend || !fBroadcastTransactions)
1998 return;
1999 bool fFirst = (nNextResend == 0);
2000 nNextResend = GetTime() + GetRand(30 * 60);
2001 if (fFirst)
2002 return;
2004 // Only do it if there's been a new block since last time
2005 if (nBestBlockTime < nLastResend)
2006 return;
2007 nLastResend = GetTime();
2009 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2010 // block was found:
2011 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2012 if (!relayed.empty())
2013 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2016 /** @} */ // end of mapWallet
2021 /** @defgroup Actions
2023 * @{
2027 CAmount CWallet::GetBalance() const
2029 CAmount nTotal = 0;
2031 LOCK2(cs_main, cs_wallet);
2032 for (const auto& entry : mapWallet)
2034 const CWalletTx* pcoin = &entry.second;
2035 if (pcoin->IsTrusted())
2036 nTotal += pcoin->GetAvailableCredit();
2040 return nTotal;
2043 CAmount CWallet::GetUnconfirmedBalance() const
2045 CAmount nTotal = 0;
2047 LOCK2(cs_main, cs_wallet);
2048 for (const auto& entry : mapWallet)
2050 const CWalletTx* pcoin = &entry.second;
2051 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2052 nTotal += pcoin->GetAvailableCredit();
2055 return nTotal;
2058 CAmount CWallet::GetImmatureBalance() const
2060 CAmount nTotal = 0;
2062 LOCK2(cs_main, cs_wallet);
2063 for (const auto& entry : mapWallet)
2065 const CWalletTx* pcoin = &entry.second;
2066 nTotal += pcoin->GetImmatureCredit();
2069 return nTotal;
2072 CAmount CWallet::GetWatchOnlyBalance() const
2074 CAmount nTotal = 0;
2076 LOCK2(cs_main, cs_wallet);
2077 for (const auto& entry : mapWallet)
2079 const CWalletTx* pcoin = &entry.second;
2080 if (pcoin->IsTrusted())
2081 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2085 return nTotal;
2088 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2090 CAmount nTotal = 0;
2092 LOCK2(cs_main, cs_wallet);
2093 for (const auto& entry : mapWallet)
2095 const CWalletTx* pcoin = &entry.second;
2096 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2097 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2100 return nTotal;
2103 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2105 CAmount nTotal = 0;
2107 LOCK2(cs_main, cs_wallet);
2108 for (const auto& entry : mapWallet)
2110 const CWalletTx* pcoin = &entry.second;
2111 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2114 return nTotal;
2117 // Calculate total balance in a different way from GetBalance. The biggest
2118 // difference is that GetBalance sums up all unspent TxOuts paying to the
2119 // wallet, while this sums up both spent and unspent TxOuts paying to the
2120 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2121 // also has fewer restrictions on which unconfirmed transactions are considered
2122 // trusted.
2123 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2125 LOCK2(cs_main, cs_wallet);
2127 CAmount balance = 0;
2128 for (const auto& entry : mapWallet) {
2129 const CWalletTx& wtx = entry.second;
2130 const int depth = wtx.GetDepthInMainChain();
2131 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2132 continue;
2135 // Loop through tx outputs and add incoming payments. For outgoing txs,
2136 // treat change outputs specially, as part of the amount debited.
2137 CAmount debit = wtx.GetDebit(filter);
2138 const bool outgoing = debit > 0;
2139 for (const CTxOut& out : wtx.tx->vout) {
2140 if (outgoing && IsChange(out)) {
2141 debit -= out.nValue;
2142 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2143 balance += out.nValue;
2147 // For outgoing txs, subtract amount debited.
2148 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2149 balance -= debit;
2153 if (account) {
2154 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2157 return balance;
2160 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2162 LOCK2(cs_main, cs_wallet);
2164 CAmount balance = 0;
2165 std::vector<COutput> vCoins;
2166 AvailableCoins(vCoins, true, coinControl);
2167 for (const COutput& out : vCoins) {
2168 if (out.fSpendable) {
2169 balance += out.tx->tx->vout[out.i].nValue;
2172 return balance;
2175 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
2177 vCoins.clear();
2180 LOCK2(cs_main, cs_wallet);
2182 CAmount nTotal = 0;
2184 for (const auto& entry : mapWallet)
2186 const uint256& wtxid = entry.first;
2187 const CWalletTx* pcoin = &entry.second;
2189 if (!CheckFinalTx(*pcoin->tx))
2190 continue;
2192 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2193 continue;
2195 int nDepth = pcoin->GetDepthInMainChain();
2196 if (nDepth < 0)
2197 continue;
2199 // We should not consider coins which aren't at least in our mempool
2200 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2201 if (nDepth == 0 && !pcoin->InMempool())
2202 continue;
2204 bool safeTx = pcoin->IsTrusted();
2206 // We should not consider coins from transactions that are replacing
2207 // other transactions.
2209 // Example: There is a transaction A which is replaced by bumpfee
2210 // transaction B. In this case, we want to prevent creation of
2211 // a transaction B' which spends an output of B.
2213 // Reason: If transaction A were initially confirmed, transactions B
2214 // and B' would no longer be valid, so the user would have to create
2215 // a new transaction C to replace B'. However, in the case of a
2216 // one-block reorg, transactions B' and C might BOTH be accepted,
2217 // when the user only wanted one of them. Specifically, there could
2218 // be a 1-block reorg away from the chain where transactions A and C
2219 // were accepted to another chain where B, B', and C were all
2220 // accepted.
2221 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2222 safeTx = false;
2225 // Similarly, we should not consider coins from transactions that
2226 // have been replaced. In the example above, we would want to prevent
2227 // creation of a transaction A' spending an output of A, because if
2228 // transaction B were initially confirmed, conflicting with A and
2229 // A', we wouldn't want to the user to create a transaction D
2230 // intending to replace A', but potentially resulting in a scenario
2231 // where A, A', and D could all be accepted (instead of just B and
2232 // D, or just A and A' like the user would want).
2233 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2234 safeTx = false;
2237 if (fOnlySafe && !safeTx) {
2238 continue;
2241 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2242 continue;
2244 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2245 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2246 continue;
2248 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2249 continue;
2251 if (IsLockedCoin(entry.first, i))
2252 continue;
2254 if (IsSpent(wtxid, i))
2255 continue;
2257 isminetype mine = IsMine(pcoin->tx->vout[i]);
2259 if (mine == ISMINE_NO) {
2260 continue;
2263 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2264 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2266 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2268 // Checks the sum amount of all UTXO's.
2269 if (nMinimumSumAmount != MAX_MONEY) {
2270 nTotal += pcoin->tx->vout[i].nValue;
2272 if (nTotal >= nMinimumSumAmount) {
2273 return;
2277 // Checks the maximum number of UTXO's.
2278 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2279 return;
2286 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2288 // TODO: Add AssertLockHeld(cs_wallet) here.
2290 // Because the return value from this function contains pointers to
2291 // CWalletTx objects, callers to this function really should acquire the
2292 // cs_wallet lock before calling it. However, the current caller doesn't
2293 // acquire this lock yet. There was an attempt to add the missing lock in
2294 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2295 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2296 // avoid adding some extra complexity to the Qt code.
2298 std::map<CTxDestination, std::vector<COutput>> result;
2300 std::vector<COutput> availableCoins;
2301 AvailableCoins(availableCoins);
2303 LOCK2(cs_main, cs_wallet);
2304 for (auto& coin : availableCoins) {
2305 CTxDestination address;
2306 if (coin.fSpendable &&
2307 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2308 result[address].emplace_back(std::move(coin));
2312 std::vector<COutPoint> lockedCoins;
2313 ListLockedCoins(lockedCoins);
2314 for (const auto& output : lockedCoins) {
2315 auto it = mapWallet.find(output.hash);
2316 if (it != mapWallet.end()) {
2317 int depth = it->second.GetDepthInMainChain();
2318 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2319 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2320 CTxDestination address;
2321 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2322 result[address].emplace_back(
2323 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2329 return result;
2332 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2334 const CTransaction* ptx = &tx;
2335 int n = output;
2336 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2337 const COutPoint& prevout = ptx->vin[0].prevout;
2338 auto it = mapWallet.find(prevout.hash);
2339 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2340 !IsMine(it->second.tx->vout[prevout.n])) {
2341 break;
2343 ptx = it->second.tx.get();
2344 n = prevout.n;
2346 return ptx->vout[n];
2349 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2350 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2352 std::vector<char> vfIncluded;
2354 vfBest.assign(vValue.size(), true);
2355 nBest = nTotalLower;
2357 FastRandomContext insecure_rand;
2359 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2361 vfIncluded.assign(vValue.size(), false);
2362 CAmount nTotal = 0;
2363 bool fReachedTarget = false;
2364 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2366 for (unsigned int i = 0; i < vValue.size(); i++)
2368 //The solver here uses a randomized algorithm,
2369 //the randomness serves no real security purpose but is just
2370 //needed to prevent degenerate behavior and it is important
2371 //that the rng is fast. We do not use a constant random sequence,
2372 //because there may be some privacy improvement by making
2373 //the selection random.
2374 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2376 nTotal += vValue[i].txout.nValue;
2377 vfIncluded[i] = true;
2378 if (nTotal >= nTargetValue)
2380 fReachedTarget = true;
2381 if (nTotal < nBest)
2383 nBest = nTotal;
2384 vfBest = vfIncluded;
2386 nTotal -= vValue[i].txout.nValue;
2387 vfIncluded[i] = false;
2395 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2396 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2398 setCoinsRet.clear();
2399 nValueRet = 0;
2401 // List of values less than target
2402 boost::optional<CInputCoin> coinLowestLarger;
2403 std::vector<CInputCoin> vValue;
2404 CAmount nTotalLower = 0;
2406 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2408 for (const COutput &output : vCoins)
2410 if (!output.fSpendable)
2411 continue;
2413 const CWalletTx *pcoin = output.tx;
2415 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2416 continue;
2418 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2419 continue;
2421 int i = output.i;
2423 CInputCoin coin = CInputCoin(pcoin, i);
2425 if (coin.txout.nValue == nTargetValue)
2427 setCoinsRet.insert(coin);
2428 nValueRet += coin.txout.nValue;
2429 return true;
2431 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2433 vValue.push_back(coin);
2434 nTotalLower += coin.txout.nValue;
2436 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2438 coinLowestLarger = coin;
2442 if (nTotalLower == nTargetValue)
2444 for (const auto& input : vValue)
2446 setCoinsRet.insert(input);
2447 nValueRet += input.txout.nValue;
2449 return true;
2452 if (nTotalLower < nTargetValue)
2454 if (!coinLowestLarger)
2455 return false;
2456 setCoinsRet.insert(coinLowestLarger.get());
2457 nValueRet += coinLowestLarger->txout.nValue;
2458 return true;
2461 // Solve subset sum by stochastic approximation
2462 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2463 std::reverse(vValue.begin(), vValue.end());
2464 std::vector<char> vfBest;
2465 CAmount nBest;
2467 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2468 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2469 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2471 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2472 // or the next bigger coin is closer), return the bigger coin
2473 if (coinLowestLarger &&
2474 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2476 setCoinsRet.insert(coinLowestLarger.get());
2477 nValueRet += coinLowestLarger->txout.nValue;
2479 else {
2480 for (unsigned int i = 0; i < vValue.size(); i++)
2481 if (vfBest[i])
2483 setCoinsRet.insert(vValue[i]);
2484 nValueRet += vValue[i].txout.nValue;
2487 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2488 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2489 for (unsigned int i = 0; i < vValue.size(); i++) {
2490 if (vfBest[i]) {
2491 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2494 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2498 return true;
2501 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2503 std::vector<COutput> vCoins(vAvailableCoins);
2505 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2506 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2508 for (const COutput& out : vCoins)
2510 if (!out.fSpendable)
2511 continue;
2512 nValueRet += out.tx->tx->vout[out.i].nValue;
2513 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2515 return (nValueRet >= nTargetValue);
2518 // calculate value from preset inputs and store them
2519 std::set<CInputCoin> setPresetCoins;
2520 CAmount nValueFromPresetInputs = 0;
2522 std::vector<COutPoint> vPresetInputs;
2523 if (coinControl)
2524 coinControl->ListSelected(vPresetInputs);
2525 for (const COutPoint& outpoint : vPresetInputs)
2527 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2528 if (it != mapWallet.end())
2530 const CWalletTx* pcoin = &it->second;
2531 // Clearly invalid input, fail
2532 if (pcoin->tx->vout.size() <= outpoint.n)
2533 return false;
2534 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2535 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2536 } else
2537 return false; // TODO: Allow non-wallet inputs
2540 // remove preset inputs from vCoins
2541 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2543 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2544 it = vCoins.erase(it);
2545 else
2546 ++it;
2549 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2550 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2552 bool res = nTargetValue <= nValueFromPresetInputs ||
2553 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2554 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2555 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2556 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2557 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2558 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2559 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2561 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2562 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2564 // add preset inputs to the total value selected
2565 nValueRet += nValueFromPresetInputs;
2567 return res;
2570 bool CWallet::SignTransaction(CMutableTransaction &tx)
2572 AssertLockHeld(cs_wallet); // mapWallet
2574 // sign the new tx
2575 CTransaction txNewConst(tx);
2576 int nIn = 0;
2577 for (const auto& input : tx.vin) {
2578 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2579 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2580 return false;
2582 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2583 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2584 SignatureData sigdata;
2585 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2586 return false;
2588 UpdateTransaction(tx, nIn, sigdata);
2589 nIn++;
2591 return true;
2594 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2596 std::vector<CRecipient> vecSend;
2598 // Turn the txout set into a CRecipient vector
2599 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2601 const CTxOut& txOut = tx.vout[idx];
2602 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2603 vecSend.push_back(recipient);
2606 coinControl.fAllowOtherInputs = true;
2608 for (const CTxIn& txin : tx.vin)
2609 coinControl.Select(txin.prevout);
2611 CReserveKey reservekey(this);
2612 CWalletTx wtx;
2613 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2614 return false;
2617 if (nChangePosInOut != -1) {
2618 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2619 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2620 // so just remove the key from the keypool here.
2621 reservekey.KeepKey();
2624 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2625 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2626 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2628 // Add new txins (keeping original txin scriptSig/order)
2629 for (const CTxIn& txin : wtx.tx->vin)
2631 if (!coinControl.IsSelected(txin.prevout))
2633 tx.vin.push_back(txin);
2635 if (lockUnspents)
2637 LOCK2(cs_main, cs_wallet);
2638 LockCoin(txin.prevout);
2644 return true;
2647 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2648 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2650 CAmount nValue = 0;
2651 int nChangePosRequest = nChangePosInOut;
2652 unsigned int nSubtractFeeFromAmount = 0;
2653 for (const auto& recipient : vecSend)
2655 if (nValue < 0 || recipient.nAmount < 0)
2657 strFailReason = _("Transaction amounts must not be negative");
2658 return false;
2660 nValue += recipient.nAmount;
2662 if (recipient.fSubtractFeeFromAmount)
2663 nSubtractFeeFromAmount++;
2665 if (vecSend.empty())
2667 strFailReason = _("Transaction must have at least one recipient");
2668 return false;
2671 wtxNew.fTimeReceivedIsTxTime = true;
2672 wtxNew.BindWallet(this);
2673 CMutableTransaction txNew;
2675 // Discourage fee sniping.
2677 // For a large miner the value of the transactions in the best block and
2678 // the mempool can exceed the cost of deliberately attempting to mine two
2679 // blocks to orphan the current best block. By setting nLockTime such that
2680 // only the next block can include the transaction, we discourage this
2681 // practice as the height restricted and limited blocksize gives miners
2682 // considering fee sniping fewer options for pulling off this attack.
2684 // A simple way to think about this is from the wallet's point of view we
2685 // always want the blockchain to move forward. By setting nLockTime this
2686 // way we're basically making the statement that we only want this
2687 // transaction to appear in the next block; we don't want to potentially
2688 // encourage reorgs by allowing transactions to appear at lower heights
2689 // than the next block in forks of the best chain.
2691 // Of course, the subsidy is high enough, and transaction volume low
2692 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2693 // now we ensure code won't be written that makes assumptions about
2694 // nLockTime that preclude a fix later.
2695 txNew.nLockTime = chainActive.Height();
2697 // Secondly occasionally randomly pick a nLockTime even further back, so
2698 // that transactions that are delayed after signing for whatever reason,
2699 // e.g. high-latency mix networks and some CoinJoin implementations, have
2700 // better privacy.
2701 if (GetRandInt(10) == 0)
2702 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2704 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2705 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2706 FeeCalculation feeCalc;
2707 CAmount nFeeNeeded;
2708 unsigned int nBytes;
2710 std::set<CInputCoin> setCoins;
2711 LOCK2(cs_main, cs_wallet);
2713 std::vector<COutput> vAvailableCoins;
2714 AvailableCoins(vAvailableCoins, true, &coin_control);
2716 // Create change script that will be used if we need change
2717 // TODO: pass in scriptChange instead of reservekey so
2718 // change transaction isn't always pay-to-bitcoin-address
2719 CScript scriptChange;
2721 // coin control: send change to custom address
2722 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2723 scriptChange = GetScriptForDestination(coin_control.destChange);
2724 } else { // no coin control: send change to newly generated address
2725 // Note: We use a new key here to keep it from being obvious which side is the change.
2726 // The drawback is that by not reusing a previous key, the change may be lost if a
2727 // backup is restored, if the backup doesn't have the new private key for the change.
2728 // If we reused the old key, it would be possible to add code to look for and
2729 // rediscover unknown transactions that were written with keys of ours to recover
2730 // post-backup change.
2732 // Reserve a new key pair from key pool
2733 CPubKey vchPubKey;
2734 bool ret;
2735 ret = reservekey.GetReservedKey(vchPubKey, true);
2736 if (!ret)
2738 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2739 return false;
2742 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2744 CTxOut change_prototype_txout(0, scriptChange);
2745 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2747 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2748 nFeeRet = 0;
2749 bool pick_new_inputs = true;
2750 CAmount nValueIn = 0;
2751 // Start with no fee and loop until there is enough fee
2752 while (true)
2754 nChangePosInOut = nChangePosRequest;
2755 txNew.vin.clear();
2756 txNew.vout.clear();
2757 wtxNew.fFromMe = true;
2758 bool fFirst = true;
2760 CAmount nValueToSelect = nValue;
2761 if (nSubtractFeeFromAmount == 0)
2762 nValueToSelect += nFeeRet;
2763 // vouts to the payees
2764 for (const auto& recipient : vecSend)
2766 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2768 if (recipient.fSubtractFeeFromAmount)
2770 assert(nSubtractFeeFromAmount != 0);
2771 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2773 if (fFirst) // first receiver pays the remainder not divisible by output count
2775 fFirst = false;
2776 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2780 if (IsDust(txout, ::dustRelayFee))
2782 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2784 if (txout.nValue < 0)
2785 strFailReason = _("The transaction amount is too small to pay the fee");
2786 else
2787 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2789 else
2790 strFailReason = _("Transaction amount too small");
2791 return false;
2793 txNew.vout.push_back(txout);
2796 // Choose coins to use
2797 if (pick_new_inputs) {
2798 nValueIn = 0;
2799 setCoins.clear();
2800 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2802 strFailReason = _("Insufficient funds");
2803 return false;
2807 const CAmount nChange = nValueIn - nValueToSelect;
2809 if (nChange > 0)
2811 // Fill a vout to ourself
2812 CTxOut newTxOut(nChange, scriptChange);
2814 // Never create dust outputs; if we would, just
2815 // add the dust to the fee.
2816 if (IsDust(newTxOut, discard_rate))
2818 nChangePosInOut = -1;
2819 nFeeRet += nChange;
2821 else
2823 if (nChangePosInOut == -1)
2825 // Insert change txn at random position:
2826 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2828 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2830 strFailReason = _("Change index out of range");
2831 return false;
2834 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2835 txNew.vout.insert(position, newTxOut);
2837 } else {
2838 nChangePosInOut = -1;
2841 // Fill vin
2843 // Note how the sequence number is set to non-maxint so that
2844 // the nLockTime set above actually works.
2846 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2847 // we use the highest possible value in that range (maxint-2)
2848 // to avoid conflicting with other possible uses of nSequence,
2849 // and in the spirit of "smallest possible change from prior
2850 // behavior."
2851 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2852 for (const auto& coin : setCoins)
2853 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2854 nSequence));
2856 // Fill in dummy signatures for fee calculation.
2857 if (!DummySignTx(txNew, setCoins)) {
2858 strFailReason = _("Signing transaction failed");
2859 return false;
2862 nBytes = GetVirtualTransactionSize(txNew);
2864 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2865 for (auto& vin : txNew.vin) {
2866 vin.scriptSig = CScript();
2867 vin.scriptWitness.SetNull();
2870 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2872 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2873 // because we must be at the maximum allowed fee.
2874 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2876 strFailReason = _("Transaction too large for fee policy");
2877 return false;
2880 if (nFeeRet >= nFeeNeeded) {
2881 // Reduce fee to only the needed amount if possible. This
2882 // prevents potential overpayment in fees if the coins
2883 // selected to meet nFeeNeeded result in a transaction that
2884 // requires less fee than the prior iteration.
2886 // If we have no change and a big enough excess fee, then
2887 // try to construct transaction again only without picking
2888 // new inputs. We now know we only need the smaller fee
2889 // (because of reduced tx size) and so we should add a
2890 // change output. Only try this once.
2891 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2892 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2893 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2894 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2895 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2896 pick_new_inputs = false;
2897 nFeeRet = fee_needed_with_change;
2898 continue;
2902 // If we have change output already, just increase it
2903 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2904 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2905 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2906 change_position->nValue += extraFeePaid;
2907 nFeeRet -= extraFeePaid;
2909 break; // Done, enough fee included.
2911 else if (!pick_new_inputs) {
2912 // This shouldn't happen, we should have had enough excess
2913 // fee to pay for the new output and still meet nFeeNeeded
2914 // Or we should have just subtracted fee from recipients and
2915 // nFeeNeeded should not have changed
2916 strFailReason = _("Transaction fee and change calculation failed");
2917 return false;
2920 // Try to reduce change to include necessary fee
2921 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2922 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2923 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2924 // Only reduce change if remaining amount is still a large enough output.
2925 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2926 change_position->nValue -= additionalFeeNeeded;
2927 nFeeRet += additionalFeeNeeded;
2928 break; // Done, able to increase fee from change
2932 // If subtracting fee from recipients, we now know what fee we
2933 // need to subtract, we have no reason to reselect inputs
2934 if (nSubtractFeeFromAmount > 0) {
2935 pick_new_inputs = false;
2938 // Include more fee and try again.
2939 nFeeRet = nFeeNeeded;
2940 continue;
2944 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2946 if (sign)
2948 CTransaction txNewConst(txNew);
2949 int nIn = 0;
2950 for (const auto& coin : setCoins)
2952 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2953 SignatureData sigdata;
2955 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2957 strFailReason = _("Signing transaction failed");
2958 return false;
2959 } else {
2960 UpdateTransaction(txNew, nIn, sigdata);
2963 nIn++;
2967 // Embed the constructed transaction data in wtxNew.
2968 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2970 // Limit size
2971 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2973 strFailReason = _("Transaction too large");
2974 return false;
2978 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2979 // Lastly, ensure this tx will pass the mempool's chain limits
2980 LockPoints lp;
2981 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2982 CTxMemPool::setEntries setAncestors;
2983 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2984 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2985 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2986 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2987 std::string errString;
2988 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2989 strFailReason = _("Transaction has too long of a mempool chain");
2990 return false;
2994 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",
2995 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2996 feeCalc.est.pass.start, feeCalc.est.pass.end,
2997 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2998 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2999 feeCalc.est.fail.start, feeCalc.est.fail.end,
3000 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
3001 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3002 return true;
3006 * Call after CreateTransaction unless you want to abort
3008 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3011 LOCK2(cs_main, cs_wallet);
3012 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3014 // Take key pair from key pool so it won't be used again
3015 reservekey.KeepKey();
3017 // Add tx to wallet, because if it has change it's also ours,
3018 // otherwise just for transaction history.
3019 AddToWallet(wtxNew);
3021 // Notify that old coins are spent
3022 for (const CTxIn& txin : wtxNew.tx->vin)
3024 CWalletTx &coin = mapWallet[txin.prevout.hash];
3025 coin.BindWallet(this);
3026 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3030 // Track how many getdata requests our transaction gets
3031 mapRequestCount[wtxNew.GetHash()] = 0;
3033 // Get the inserted-CWalletTx from mapWallet so that the
3034 // fInMempool flag is cached properly
3035 CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
3037 if (fBroadcastTransactions)
3039 // Broadcast
3040 if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
3041 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3042 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3043 } else {
3044 wtx.RelayWalletTransaction(connman);
3048 return true;
3051 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3052 CWalletDB walletdb(*dbw);
3053 return walletdb.ListAccountCreditDebit(strAccount, entries);
3056 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3058 CWalletDB walletdb(*dbw);
3060 return AddAccountingEntry(acentry, &walletdb);
3063 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3065 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3066 return false;
3069 laccentries.push_back(acentry);
3070 CAccountingEntry & entry = laccentries.back();
3071 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3073 return true;
3076 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3078 LOCK2(cs_main, cs_wallet);
3080 fFirstRunRet = false;
3081 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3082 if (nLoadWalletRet == DB_NEED_REWRITE)
3084 if (dbw->Rewrite("\x04pool"))
3086 setInternalKeyPool.clear();
3087 setExternalKeyPool.clear();
3088 m_pool_key_to_index.clear();
3089 // Note: can't top-up keypool here, because wallet is locked.
3090 // User will be prompted to unlock wallet the next operation
3091 // that requires a new key.
3095 // This wallet is in its first run if all of these are empty
3096 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3098 if (nLoadWalletRet != DB_LOAD_OK)
3099 return nLoadWalletRet;
3101 uiInterface.LoadWallet(this);
3103 return DB_LOAD_OK;
3106 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3108 AssertLockHeld(cs_wallet); // mapWallet
3109 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3110 for (uint256 hash : vHashOut)
3111 mapWallet.erase(hash);
3113 if (nZapSelectTxRet == DB_NEED_REWRITE)
3115 if (dbw->Rewrite("\x04pool"))
3117 setInternalKeyPool.clear();
3118 setExternalKeyPool.clear();
3119 m_pool_key_to_index.clear();
3120 // Note: can't top-up keypool here, because wallet is locked.
3121 // User will be prompted to unlock wallet the next operation
3122 // that requires a new key.
3126 if (nZapSelectTxRet != DB_LOAD_OK)
3127 return nZapSelectTxRet;
3129 MarkDirty();
3131 return DB_LOAD_OK;
3135 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3137 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3138 if (nZapWalletTxRet == DB_NEED_REWRITE)
3140 if (dbw->Rewrite("\x04pool"))
3142 LOCK(cs_wallet);
3143 setInternalKeyPool.clear();
3144 setExternalKeyPool.clear();
3145 m_pool_key_to_index.clear();
3146 // Note: can't top-up keypool here, because wallet is locked.
3147 // User will be prompted to unlock wallet the next operation
3148 // that requires a new key.
3152 if (nZapWalletTxRet != DB_LOAD_OK)
3153 return nZapWalletTxRet;
3155 return DB_LOAD_OK;
3159 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3161 bool fUpdated = false;
3163 LOCK(cs_wallet); // mapAddressBook
3164 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3165 fUpdated = mi != mapAddressBook.end();
3166 mapAddressBook[address].name = strName;
3167 if (!strPurpose.empty()) /* update purpose only if requested */
3168 mapAddressBook[address].purpose = strPurpose;
3170 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3171 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3172 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3173 return false;
3174 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3177 bool CWallet::DelAddressBook(const CTxDestination& address)
3180 LOCK(cs_wallet); // mapAddressBook
3182 // Delete destdata tuples associated with address
3183 std::string strAddress = EncodeDestination(address);
3184 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3186 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3188 mapAddressBook.erase(address);
3191 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3193 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3194 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3197 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3199 CTxDestination address;
3200 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3201 auto mi = mapAddressBook.find(address);
3202 if (mi != mapAddressBook.end()) {
3203 return mi->second.name;
3206 // A scriptPubKey that doesn't have an entry in the address book is
3207 // associated with the default account ("").
3208 const static std::string DEFAULT_ACCOUNT_NAME;
3209 return DEFAULT_ACCOUNT_NAME;
3213 * Mark old keypool keys as used,
3214 * and generate all new keys
3216 bool CWallet::NewKeyPool()
3219 LOCK(cs_wallet);
3220 CWalletDB walletdb(*dbw);
3222 for (int64_t nIndex : setInternalKeyPool) {
3223 walletdb.ErasePool(nIndex);
3225 setInternalKeyPool.clear();
3227 for (int64_t nIndex : setExternalKeyPool) {
3228 walletdb.ErasePool(nIndex);
3230 setExternalKeyPool.clear();
3232 m_pool_key_to_index.clear();
3234 if (!TopUpKeyPool()) {
3235 return false;
3237 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3239 return true;
3242 size_t CWallet::KeypoolCountExternalKeys()
3244 AssertLockHeld(cs_wallet); // setExternalKeyPool
3245 return setExternalKeyPool.size();
3248 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3250 AssertLockHeld(cs_wallet);
3251 if (keypool.fInternal) {
3252 setInternalKeyPool.insert(nIndex);
3253 } else {
3254 setExternalKeyPool.insert(nIndex);
3256 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3257 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3259 // If no metadata exists yet, create a default with the pool key's
3260 // creation time. Note that this may be overwritten by actually
3261 // stored metadata for that key later, which is fine.
3262 CKeyID keyid = keypool.vchPubKey.GetID();
3263 if (mapKeyMetadata.count(keyid) == 0)
3264 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3267 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3270 LOCK(cs_wallet);
3272 if (IsLocked())
3273 return false;
3275 // Top up key pool
3276 unsigned int nTargetSize;
3277 if (kpSize > 0)
3278 nTargetSize = kpSize;
3279 else
3280 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3282 // count amount of available keys (internal, external)
3283 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3284 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3285 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3287 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3289 // don't create extra internal keys
3290 missingInternal = 0;
3292 bool internal = false;
3293 CWalletDB walletdb(*dbw);
3294 for (int64_t i = missingInternal + missingExternal; i--;)
3296 if (i < missingInternal) {
3297 internal = true;
3300 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3301 int64_t index = ++m_max_keypool_index;
3303 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3304 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3305 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3308 if (internal) {
3309 setInternalKeyPool.insert(index);
3310 } else {
3311 setExternalKeyPool.insert(index);
3313 m_pool_key_to_index[pubkey.GetID()] = index;
3315 if (missingInternal + missingExternal > 0) {
3316 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3319 return true;
3322 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3324 nIndex = -1;
3325 keypool.vchPubKey = CPubKey();
3327 LOCK(cs_wallet);
3329 if (!IsLocked())
3330 TopUpKeyPool();
3332 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3333 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3335 // Get the oldest key
3336 if(setKeyPool.empty())
3337 return;
3339 CWalletDB walletdb(*dbw);
3341 auto it = setKeyPool.begin();
3342 nIndex = *it;
3343 setKeyPool.erase(it);
3344 if (!walletdb.ReadPool(nIndex, keypool)) {
3345 throw std::runtime_error(std::string(__func__) + ": read failed");
3347 if (!HaveKey(keypool.vchPubKey.GetID())) {
3348 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3350 if (keypool.fInternal != fReturningInternal) {
3351 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3354 assert(keypool.vchPubKey.IsValid());
3355 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3356 LogPrintf("keypool reserve %d\n", nIndex);
3360 void CWallet::KeepKey(int64_t nIndex)
3362 // Remove from key pool
3363 CWalletDB walletdb(*dbw);
3364 walletdb.ErasePool(nIndex);
3365 LogPrintf("keypool keep %d\n", nIndex);
3368 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3370 // Return to key pool
3372 LOCK(cs_wallet);
3373 if (fInternal) {
3374 setInternalKeyPool.insert(nIndex);
3375 } else {
3376 setExternalKeyPool.insert(nIndex);
3378 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3380 LogPrintf("keypool return %d\n", nIndex);
3383 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3385 CKeyPool keypool;
3387 LOCK(cs_wallet);
3388 int64_t nIndex = 0;
3389 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3390 if (nIndex == -1)
3392 if (IsLocked()) return false;
3393 CWalletDB walletdb(*dbw);
3394 result = GenerateNewKey(walletdb, internal);
3395 return true;
3397 KeepKey(nIndex);
3398 result = keypool.vchPubKey;
3400 return true;
3403 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3404 if (setKeyPool.empty()) {
3405 return GetTime();
3408 CKeyPool keypool;
3409 int64_t nIndex = *(setKeyPool.begin());
3410 if (!walletdb.ReadPool(nIndex, keypool)) {
3411 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3413 assert(keypool.vchPubKey.IsValid());
3414 return keypool.nTime;
3417 int64_t CWallet::GetOldestKeyPoolTime()
3419 LOCK(cs_wallet);
3421 CWalletDB walletdb(*dbw);
3423 // load oldest key from keypool, get time and return
3424 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3425 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3426 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3429 return oldestKey;
3432 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3434 std::map<CTxDestination, CAmount> balances;
3437 LOCK(cs_wallet);
3438 for (const auto& walletEntry : mapWallet)
3440 const CWalletTx *pcoin = &walletEntry.second;
3442 if (!pcoin->IsTrusted())
3443 continue;
3445 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3446 continue;
3448 int nDepth = pcoin->GetDepthInMainChain();
3449 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3450 continue;
3452 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3454 CTxDestination addr;
3455 if (!IsMine(pcoin->tx->vout[i]))
3456 continue;
3457 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3458 continue;
3460 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3462 if (!balances.count(addr))
3463 balances[addr] = 0;
3464 balances[addr] += n;
3469 return balances;
3472 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3474 AssertLockHeld(cs_wallet); // mapWallet
3475 std::set< std::set<CTxDestination> > groupings;
3476 std::set<CTxDestination> grouping;
3478 for (const auto& walletEntry : mapWallet)
3480 const CWalletTx *pcoin = &walletEntry.second;
3482 if (pcoin->tx->vin.size() > 0)
3484 bool any_mine = false;
3485 // group all input addresses with each other
3486 for (CTxIn txin : pcoin->tx->vin)
3488 CTxDestination address;
3489 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3490 continue;
3491 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3492 continue;
3493 grouping.insert(address);
3494 any_mine = true;
3497 // group change with input addresses
3498 if (any_mine)
3500 for (CTxOut txout : pcoin->tx->vout)
3501 if (IsChange(txout))
3503 CTxDestination txoutAddr;
3504 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3505 continue;
3506 grouping.insert(txoutAddr);
3509 if (grouping.size() > 0)
3511 groupings.insert(grouping);
3512 grouping.clear();
3516 // group lone addrs by themselves
3517 for (const auto& txout : pcoin->tx->vout)
3518 if (IsMine(txout))
3520 CTxDestination address;
3521 if(!ExtractDestination(txout.scriptPubKey, address))
3522 continue;
3523 grouping.insert(address);
3524 groupings.insert(grouping);
3525 grouping.clear();
3529 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3530 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3531 for (std::set<CTxDestination> _grouping : groupings)
3533 // make a set of all the groups hit by this new group
3534 std::set< std::set<CTxDestination>* > hits;
3535 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3536 for (CTxDestination address : _grouping)
3537 if ((it = setmap.find(address)) != setmap.end())
3538 hits.insert((*it).second);
3540 // merge all hit groups into a new single group and delete old groups
3541 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3542 for (std::set<CTxDestination>* hit : hits)
3544 merged->insert(hit->begin(), hit->end());
3545 uniqueGroupings.erase(hit);
3546 delete hit;
3548 uniqueGroupings.insert(merged);
3550 // update setmap
3551 for (CTxDestination element : *merged)
3552 setmap[element] = merged;
3555 std::set< std::set<CTxDestination> > ret;
3556 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3558 ret.insert(*uniqueGrouping);
3559 delete uniqueGrouping;
3562 return ret;
3565 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3567 LOCK(cs_wallet);
3568 std::set<CTxDestination> result;
3569 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3571 const CTxDestination& address = item.first;
3572 const std::string& strName = item.second.name;
3573 if (strName == strAccount)
3574 result.insert(address);
3576 return result;
3579 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3581 if (nIndex == -1)
3583 CKeyPool keypool;
3584 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3585 if (nIndex != -1)
3586 vchPubKey = keypool.vchPubKey;
3587 else {
3588 return false;
3590 fInternal = keypool.fInternal;
3592 assert(vchPubKey.IsValid());
3593 pubkey = vchPubKey;
3594 return true;
3597 void CReserveKey::KeepKey()
3599 if (nIndex != -1)
3600 pwallet->KeepKey(nIndex);
3601 nIndex = -1;
3602 vchPubKey = CPubKey();
3605 void CReserveKey::ReturnKey()
3607 if (nIndex != -1) {
3608 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3610 nIndex = -1;
3611 vchPubKey = CPubKey();
3614 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3616 AssertLockHeld(cs_wallet);
3617 bool internal = setInternalKeyPool.count(keypool_id);
3618 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3619 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3620 auto it = setKeyPool->begin();
3622 CWalletDB walletdb(*dbw);
3623 while (it != std::end(*setKeyPool)) {
3624 const int64_t& index = *(it);
3625 if (index > keypool_id) break; // set*KeyPool is ordered
3627 CKeyPool keypool;
3628 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3629 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3631 walletdb.ErasePool(index);
3632 LogPrintf("keypool index %d removed\n", index);
3633 it = setKeyPool->erase(it);
3637 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3639 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3640 CPubKey pubkey;
3641 if (!rKey->GetReservedKey(pubkey))
3642 return;
3644 script = rKey;
3645 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3648 void CWallet::LockCoin(const COutPoint& output)
3650 AssertLockHeld(cs_wallet); // setLockedCoins
3651 setLockedCoins.insert(output);
3654 void CWallet::UnlockCoin(const COutPoint& output)
3656 AssertLockHeld(cs_wallet); // setLockedCoins
3657 setLockedCoins.erase(output);
3660 void CWallet::UnlockAllCoins()
3662 AssertLockHeld(cs_wallet); // setLockedCoins
3663 setLockedCoins.clear();
3666 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3668 AssertLockHeld(cs_wallet); // setLockedCoins
3669 COutPoint outpt(hash, n);
3671 return (setLockedCoins.count(outpt) > 0);
3674 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3676 AssertLockHeld(cs_wallet); // setLockedCoins
3677 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3678 it != setLockedCoins.end(); it++) {
3679 COutPoint outpt = (*it);
3680 vOutpts.push_back(outpt);
3684 /** @} */ // end of Actions
3686 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3687 AssertLockHeld(cs_wallet); // mapKeyMetadata
3688 mapKeyBirth.clear();
3690 // get birth times for keys with metadata
3691 for (const auto& entry : mapKeyMetadata) {
3692 if (entry.second.nCreateTime) {
3693 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3697 // map in which we'll infer heights of other keys
3698 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3699 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3700 for (const CKeyID &keyid : GetKeys()) {
3701 if (mapKeyBirth.count(keyid) == 0)
3702 mapKeyFirstBlock[keyid] = pindexMax;
3705 // if there are no such keys, we're done
3706 if (mapKeyFirstBlock.empty())
3707 return;
3709 // find first block that affects those keys, if there are any left
3710 std::vector<CKeyID> vAffected;
3711 for (const auto& entry : mapWallet) {
3712 // iterate over all wallet transactions...
3713 const CWalletTx &wtx = entry.second;
3714 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3715 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3716 // ... which are already in a block
3717 int nHeight = blit->second->nHeight;
3718 for (const CTxOut &txout : wtx.tx->vout) {
3719 // iterate over all their outputs
3720 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3721 for (const CKeyID &keyid : vAffected) {
3722 // ... and all their affected keys
3723 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3724 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3725 rit->second = blit->second;
3727 vAffected.clear();
3732 // Extract block timestamps for those keys
3733 for (const auto& entry : mapKeyFirstBlock)
3734 mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3738 * Compute smart timestamp for a transaction being added to the wallet.
3740 * Logic:
3741 * - If sending a transaction, assign its timestamp to the current time.
3742 * - If receiving a transaction outside a block, assign its timestamp to the
3743 * current time.
3744 * - If receiving a block with a future timestamp, assign all its (not already
3745 * known) transactions' timestamps to the current time.
3746 * - If receiving a block with a past timestamp, before the most recent known
3747 * transaction (that we care about), assign all its (not already known)
3748 * transactions' timestamps to the same timestamp as that most-recent-known
3749 * transaction.
3750 * - If receiving a block with a past timestamp, but after the most recent known
3751 * transaction, assign all its (not already known) transactions' timestamps to
3752 * the block time.
3754 * For more information see CWalletTx::nTimeSmart,
3755 * https://bitcointalk.org/?topic=54527, or
3756 * https://github.com/bitcoin/bitcoin/pull/1393.
3758 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3760 unsigned int nTimeSmart = wtx.nTimeReceived;
3761 if (!wtx.hashUnset()) {
3762 if (mapBlockIndex.count(wtx.hashBlock)) {
3763 int64_t latestNow = wtx.nTimeReceived;
3764 int64_t latestEntry = 0;
3766 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3767 int64_t latestTolerated = latestNow + 300;
3768 const TxItems& txOrdered = wtxOrdered;
3769 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3770 CWalletTx* const pwtx = it->second.first;
3771 if (pwtx == &wtx) {
3772 continue;
3774 CAccountingEntry* const pacentry = it->second.second;
3775 int64_t nSmartTime;
3776 if (pwtx) {
3777 nSmartTime = pwtx->nTimeSmart;
3778 if (!nSmartTime) {
3779 nSmartTime = pwtx->nTimeReceived;
3781 } else {
3782 nSmartTime = pacentry->nTime;
3784 if (nSmartTime <= latestTolerated) {
3785 latestEntry = nSmartTime;
3786 if (nSmartTime > latestNow) {
3787 latestNow = nSmartTime;
3789 break;
3793 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3794 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3795 } else {
3796 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3799 return nTimeSmart;
3802 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3804 if (boost::get<CNoDestination>(&dest))
3805 return false;
3807 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3808 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3811 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3813 if (!mapAddressBook[dest].destdata.erase(key))
3814 return false;
3815 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3818 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3820 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3821 return true;
3824 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3826 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3827 if(i != mapAddressBook.end())
3829 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3830 if(j != i->second.destdata.end())
3832 if(value)
3833 *value = j->second;
3834 return true;
3837 return false;
3840 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3842 LOCK(cs_wallet);
3843 std::vector<std::string> values;
3844 for (const auto& address : mapAddressBook) {
3845 for (const auto& data : address.second.destdata) {
3846 if (!data.first.compare(0, prefix.size(), prefix)) {
3847 values.emplace_back(data.second);
3851 return values;
3854 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3856 // needed to restore wallet transaction meta data after -zapwallettxes
3857 std::vector<CWalletTx> vWtx;
3859 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3860 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3862 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3863 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3864 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3865 if (nZapWalletRet != DB_LOAD_OK) {
3866 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3867 return nullptr;
3871 uiInterface.InitMessage(_("Loading wallet..."));
3873 int64_t nStart = GetTimeMillis();
3874 bool fFirstRun = true;
3875 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3876 CWallet *walletInstance = new CWallet(std::move(dbw));
3877 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3878 if (nLoadWalletRet != DB_LOAD_OK)
3880 if (nLoadWalletRet == DB_CORRUPT) {
3881 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3882 return nullptr;
3884 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3886 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3887 " or address book entries might be missing or incorrect."),
3888 walletFile));
3890 else if (nLoadWalletRet == DB_TOO_NEW) {
3891 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3892 return nullptr;
3894 else if (nLoadWalletRet == DB_NEED_REWRITE)
3896 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3897 return nullptr;
3899 else {
3900 InitError(strprintf(_("Error loading %s"), walletFile));
3901 return nullptr;
3905 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3907 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3908 if (nMaxVersion == 0) // the -upgradewallet without argument case
3910 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3911 nMaxVersion = CLIENT_VERSION;
3912 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3914 else
3915 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3916 if (nMaxVersion < walletInstance->GetVersion())
3918 InitError(_("Cannot downgrade wallet"));
3919 return nullptr;
3921 walletInstance->SetMaxVersion(nMaxVersion);
3924 if (fFirstRun)
3926 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3927 if (!gArgs.GetBoolArg("-usehd", true)) {
3928 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3929 return nullptr;
3931 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3933 // generate a new master key
3934 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3935 if (!walletInstance->SetHDMasterKey(masterPubKey))
3936 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3938 // Top up the keypool
3939 if (!walletInstance->TopUpKeyPool()) {
3940 InitError(_("Unable to generate initial keys") += "\n");
3941 return nullptr;
3944 walletInstance->SetBestChain(chainActive.GetLocator());
3946 else if (gArgs.IsArgSet("-usehd")) {
3947 bool useHD = gArgs.GetBoolArg("-usehd", true);
3948 if (walletInstance->IsHDEnabled() && !useHD) {
3949 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3950 return nullptr;
3952 if (!walletInstance->IsHDEnabled() && useHD) {
3953 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3954 return nullptr;
3958 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3960 // Try to top up keypool. No-op if the wallet is locked.
3961 walletInstance->TopUpKeyPool();
3963 CBlockIndex *pindexRescan = chainActive.Genesis();
3964 if (!gArgs.GetBoolArg("-rescan", false))
3966 CWalletDB walletdb(*walletInstance->dbw);
3967 CBlockLocator locator;
3968 if (walletdb.ReadBestBlock(locator))
3969 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3972 walletInstance->m_last_block_processed = chainActive.Tip();
3973 RegisterValidationInterface(walletInstance);
3975 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3977 //We can't rescan beyond non-pruned blocks, stop and throw an error
3978 //this might happen if a user uses an old wallet within a pruned node
3979 // or if he ran -disablewallet for a longer time, then decided to re-enable
3980 if (fPruneMode)
3982 CBlockIndex *block = chainActive.Tip();
3983 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3984 block = block->pprev;
3986 if (pindexRescan != block) {
3987 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3988 return nullptr;
3992 uiInterface.InitMessage(_("Rescanning..."));
3993 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3995 // No need to read and scan block if block was created before
3996 // our wallet birthday (as adjusted for block time variability)
3997 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3998 pindexRescan = chainActive.Next(pindexRescan);
4001 nStart = GetTimeMillis();
4002 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
4003 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4004 walletInstance->SetBestChain(chainActive.GetLocator());
4005 walletInstance->dbw->IncrementUpdateCounter();
4007 // Restore wallet transaction metadata after -zapwallettxes=1
4008 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4010 CWalletDB walletdb(*walletInstance->dbw);
4012 for (const CWalletTx& wtxOld : vWtx)
4014 uint256 hash = wtxOld.GetHash();
4015 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4016 if (mi != walletInstance->mapWallet.end())
4018 const CWalletTx* copyFrom = &wtxOld;
4019 CWalletTx* copyTo = &mi->second;
4020 copyTo->mapValue = copyFrom->mapValue;
4021 copyTo->vOrderForm = copyFrom->vOrderForm;
4022 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4023 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4024 copyTo->fFromMe = copyFrom->fFromMe;
4025 copyTo->strFromAccount = copyFrom->strFromAccount;
4026 copyTo->nOrderPos = copyFrom->nOrderPos;
4027 walletdb.WriteTx(*copyTo);
4032 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4035 LOCK(walletInstance->cs_wallet);
4036 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4037 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4038 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4041 return walletInstance;
4044 std::atomic<bool> CWallet::fFlushScheduled(false);
4046 void CWallet::postInitProcess(CScheduler& scheduler)
4048 // Add wallet transactions that aren't already in a block to mempool
4049 // Do this here as mempool requires genesis block to be loaded
4050 ReacceptWalletTransactions();
4052 // Run a thread to flush wallet periodically
4053 if (!CWallet::fFlushScheduled.exchange(true)) {
4054 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4058 bool CWallet::BackupWallet(const std::string& strDest)
4060 return dbw->Backup(strDest);
4063 CKeyPool::CKeyPool()
4065 nTime = GetTime();
4066 fInternal = false;
4069 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4071 nTime = GetTime();
4072 vchPubKey = vchPubKeyIn;
4073 fInternal = internalIn;
4076 CWalletKey::CWalletKey(int64_t nExpires)
4078 nTimeCreated = (nExpires ? GetTime() : 0);
4079 nTimeExpires = nExpires;
4082 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4084 // Update the tx's hashBlock
4085 hashBlock = pindex->GetBlockHash();
4087 // set the position of the transaction in the block
4088 nIndex = posInBlock;
4091 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4093 if (hashUnset())
4094 return 0;
4096 AssertLockHeld(cs_main);
4098 // Find the block it claims to be in
4099 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4100 if (mi == mapBlockIndex.end())
4101 return 0;
4102 CBlockIndex* pindex = (*mi).second;
4103 if (!pindex || !chainActive.Contains(pindex))
4104 return 0;
4106 pindexRet = pindex;
4107 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4110 int CMerkleTx::GetBlocksToMaturity() const
4112 if (!IsCoinBase())
4113 return 0;
4114 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4118 bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4120 // Quick check to avoid re-setting fInMempool to false
4121 if (mempool.exists(tx->GetHash())) {
4122 return false;
4125 // We must set fInMempool here - while it will be re-set to true by the
4126 // entered-mempool callback, if we did not there would be a race where a
4127 // user could call sendmoney in a loop and hit spurious out of funds errors
4128 // because we think that the transaction they just generated's change is
4129 // unavailable as we're not yet aware its in mempool.
4130 bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4131 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
4132 fInMempool = ret;
4133 return ret;