Merge #12079: Improve prioritisetransaction test coverage
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobe8b21b3d6f8e4c3c23f3edf9ad8b147ea6258030
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
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).
1295 SyncWithValidationInterfaceQueue();
1299 isminetype CWallet::IsMine(const CTxIn &txin) const
1302 LOCK(cs_wallet);
1303 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1304 if (mi != mapWallet.end())
1306 const CWalletTx& prev = (*mi).second;
1307 if (txin.prevout.n < prev.tx->vout.size())
1308 return IsMine(prev.tx->vout[txin.prevout.n]);
1311 return ISMINE_NO;
1314 // Note that this function doesn't distinguish between a 0-valued input,
1315 // and a not-"is mine" (according to the filter) input.
1316 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1319 LOCK(cs_wallet);
1320 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1321 if (mi != mapWallet.end())
1323 const CWalletTx& prev = (*mi).second;
1324 if (txin.prevout.n < prev.tx->vout.size())
1325 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1326 return prev.tx->vout[txin.prevout.n].nValue;
1329 return 0;
1332 isminetype CWallet::IsMine(const CTxOut& txout) const
1334 return ::IsMine(*this, txout.scriptPubKey);
1337 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1339 if (!MoneyRange(txout.nValue))
1340 throw std::runtime_error(std::string(__func__) + ": value out of range");
1341 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1344 bool CWallet::IsChange(const CTxOut& txout) const
1346 // TODO: fix handling of 'change' outputs. The assumption is that any
1347 // payment to a script that is ours, but is not in the address book
1348 // is change. That assumption is likely to break when we implement multisignature
1349 // wallets that return change back into a multi-signature-protected address;
1350 // a better way of identifying which outputs are 'the send' and which are
1351 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1352 // which output, if any, was change).
1353 if (::IsMine(*this, txout.scriptPubKey))
1355 CTxDestination address;
1356 if (!ExtractDestination(txout.scriptPubKey, address))
1357 return true;
1359 LOCK(cs_wallet);
1360 if (!mapAddressBook.count(address))
1361 return true;
1363 return false;
1366 CAmount CWallet::GetChange(const CTxOut& txout) const
1368 if (!MoneyRange(txout.nValue))
1369 throw std::runtime_error(std::string(__func__) + ": value out of range");
1370 return (IsChange(txout) ? txout.nValue : 0);
1373 bool CWallet::IsMine(const CTransaction& tx) const
1375 for (const CTxOut& txout : tx.vout)
1376 if (IsMine(txout))
1377 return true;
1378 return false;
1381 bool CWallet::IsFromMe(const CTransaction& tx) const
1383 return (GetDebit(tx, ISMINE_ALL) > 0);
1386 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1388 CAmount nDebit = 0;
1389 for (const CTxIn& txin : tx.vin)
1391 nDebit += GetDebit(txin, filter);
1392 if (!MoneyRange(nDebit))
1393 throw std::runtime_error(std::string(__func__) + ": value out of range");
1395 return nDebit;
1398 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1400 LOCK(cs_wallet);
1402 for (const CTxIn& txin : tx.vin)
1404 auto mi = mapWallet.find(txin.prevout.hash);
1405 if (mi == mapWallet.end())
1406 return false; // any unknown inputs can't be from us
1408 const CWalletTx& prev = (*mi).second;
1410 if (txin.prevout.n >= prev.tx->vout.size())
1411 return false; // invalid input!
1413 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1414 return false;
1416 return true;
1419 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1421 CAmount nCredit = 0;
1422 for (const CTxOut& txout : tx.vout)
1424 nCredit += GetCredit(txout, filter);
1425 if (!MoneyRange(nCredit))
1426 throw std::runtime_error(std::string(__func__) + ": value out of range");
1428 return nCredit;
1431 CAmount CWallet::GetChange(const CTransaction& tx) const
1433 CAmount nChange = 0;
1434 for (const CTxOut& txout : tx.vout)
1436 nChange += GetChange(txout);
1437 if (!MoneyRange(nChange))
1438 throw std::runtime_error(std::string(__func__) + ": value out of range");
1440 return nChange;
1443 CPubKey CWallet::GenerateNewHDMasterKey()
1445 CKey key;
1446 key.MakeNewKey(true);
1448 int64_t nCreationTime = GetTime();
1449 CKeyMetadata metadata(nCreationTime);
1451 // calculate the pubkey
1452 CPubKey pubkey = key.GetPubKey();
1453 assert(key.VerifyPubKey(pubkey));
1455 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1456 metadata.hdKeypath = "m";
1457 metadata.hdMasterKeyID = pubkey.GetID();
1460 LOCK(cs_wallet);
1462 // mem store the metadata
1463 mapKeyMetadata[pubkey.GetID()] = metadata;
1465 // write the key&metadata to the database
1466 if (!AddKeyPubKey(key, pubkey))
1467 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1470 return pubkey;
1473 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1475 LOCK(cs_wallet);
1476 // store the keyid (hash160) together with
1477 // the child index counter in the database
1478 // as a hdchain object
1479 CHDChain newHdChain;
1480 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1481 newHdChain.masterKeyID = pubkey.GetID();
1482 SetHDChain(newHdChain, false);
1484 return true;
1487 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1489 LOCK(cs_wallet);
1490 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1491 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1493 hdChain = chain;
1494 return true;
1497 bool CWallet::IsHDEnabled() const
1499 return !hdChain.masterKeyID.IsNull();
1502 int64_t CWalletTx::GetTxTime() const
1504 int64_t n = nTimeSmart;
1505 return n ? n : nTimeReceived;
1508 int CWalletTx::GetRequestCount() const
1510 // Returns -1 if it wasn't being tracked
1511 int nRequests = -1;
1513 LOCK(pwallet->cs_wallet);
1514 if (IsCoinBase())
1516 // Generated block
1517 if (!hashUnset())
1519 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1520 if (mi != pwallet->mapRequestCount.end())
1521 nRequests = (*mi).second;
1524 else
1526 // Did anyone request this transaction?
1527 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1528 if (mi != pwallet->mapRequestCount.end())
1530 nRequests = (*mi).second;
1532 // How about the block it's in?
1533 if (nRequests == 0 && !hashUnset())
1535 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1536 if (_mi != pwallet->mapRequestCount.end())
1537 nRequests = (*_mi).second;
1538 else
1539 nRequests = 1; // If it's in someone else's block it must have got out
1544 return nRequests;
1547 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1548 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1550 nFee = 0;
1551 listReceived.clear();
1552 listSent.clear();
1553 strSentAccount = strFromAccount;
1555 // Compute fee:
1556 CAmount nDebit = GetDebit(filter);
1557 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1559 CAmount nValueOut = tx->GetValueOut();
1560 nFee = nDebit - nValueOut;
1563 // Sent/received.
1564 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1566 const CTxOut& txout = tx->vout[i];
1567 isminetype fIsMine = pwallet->IsMine(txout);
1568 // Only need to handle txouts if AT LEAST one of these is true:
1569 // 1) they debit from us (sent)
1570 // 2) the output is to us (received)
1571 if (nDebit > 0)
1573 // Don't report 'change' txouts
1574 if (pwallet->IsChange(txout))
1575 continue;
1577 else if (!(fIsMine & filter))
1578 continue;
1580 // In either case, we need to get the destination address
1581 CTxDestination address;
1583 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1585 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1586 this->GetHash().ToString());
1587 address = CNoDestination();
1590 COutputEntry output = {address, txout.nValue, (int)i};
1592 // If we are debited by the transaction, add the output as a "sent" entry
1593 if (nDebit > 0)
1594 listSent.push_back(output);
1596 // If we are receiving the output, add it as a "received" entry
1597 if (fIsMine & filter)
1598 listReceived.push_back(output);
1604 * Scan active chain for relevant transactions after importing keys. This should
1605 * be called whenever new keys are added to the wallet, with the oldest key
1606 * creation time.
1608 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1609 * returned will be higher than startTime if relevant blocks could not be read.
1611 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1613 AssertLockHeld(cs_main);
1614 AssertLockHeld(cs_wallet);
1616 // Find starting block. May be null if nCreateTime is greater than the
1617 // highest blockchain timestamp, in which case there is nothing that needs
1618 // to be scanned.
1619 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1620 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1622 if (startBlock) {
1623 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1624 if (failedBlock) {
1625 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1628 return startTime;
1632 * Scan the block chain (starting in pindexStart) for transactions
1633 * from or to us. If fUpdate is true, found transactions that already
1634 * exist in the wallet will be updated.
1636 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1637 * possible (due to pruning or corruption), returns pointer to the most recent
1638 * block that could not be scanned.
1640 * If pindexStop is not a nullptr, the scan will stop at the block-index
1641 * defined by pindexStop
1643 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1645 int64_t nNow = GetTime();
1646 const CChainParams& chainParams = Params();
1648 if (pindexStop) {
1649 assert(pindexStop->nHeight >= pindexStart->nHeight);
1652 CBlockIndex* pindex = pindexStart;
1653 CBlockIndex* ret = nullptr;
1655 LOCK2(cs_main, cs_wallet);
1656 fAbortRescan = false;
1657 fScanningWallet = true;
1659 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1660 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1661 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1662 while (pindex && !fAbortRescan)
1664 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1665 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1666 if (GetTime() >= nNow + 60) {
1667 nNow = GetTime();
1668 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1671 CBlock block;
1672 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1673 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1674 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1676 } else {
1677 ret = pindex;
1679 if (pindex == pindexStop) {
1680 break;
1682 pindex = chainActive.Next(pindex);
1684 if (pindex && fAbortRescan) {
1685 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1687 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1689 fScanningWallet = false;
1691 return ret;
1694 void CWallet::ReacceptWalletTransactions()
1696 // If transactions aren't being broadcasted, don't let them into local mempool either
1697 if (!fBroadcastTransactions)
1698 return;
1699 LOCK2(cs_main, cs_wallet);
1700 std::map<int64_t, CWalletTx*> mapSorted;
1702 // Sort pending wallet transactions based on their initial wallet insertion order
1703 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1705 const uint256& wtxid = item.first;
1706 CWalletTx& wtx = item.second;
1707 assert(wtx.GetHash() == wtxid);
1709 int nDepth = wtx.GetDepthInMainChain();
1711 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1712 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1716 // Try to add wallet transactions to memory pool
1717 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1718 CWalletTx& wtx = *(item.second);
1719 CValidationState state;
1720 wtx.AcceptToMemoryPool(maxTxFee, state);
1724 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1726 assert(pwallet->GetBroadcastTransactions());
1727 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1729 CValidationState state;
1730 /* GetDepthInMainChain already catches known conflicts. */
1731 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1732 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1733 if (connman) {
1734 CInv inv(MSG_TX, GetHash());
1735 connman->ForEachNode([&inv](CNode* pnode)
1737 pnode->PushInventory(inv);
1739 return true;
1743 return false;
1746 std::set<uint256> CWalletTx::GetConflicts() const
1748 std::set<uint256> result;
1749 if (pwallet != nullptr)
1751 uint256 myHash = GetHash();
1752 result = pwallet->GetConflicts(myHash);
1753 result.erase(myHash);
1755 return result;
1758 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1760 if (tx->vin.empty())
1761 return 0;
1763 CAmount debit = 0;
1764 if(filter & ISMINE_SPENDABLE)
1766 if (fDebitCached)
1767 debit += nDebitCached;
1768 else
1770 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1771 fDebitCached = true;
1772 debit += nDebitCached;
1775 if(filter & ISMINE_WATCH_ONLY)
1777 if(fWatchDebitCached)
1778 debit += nWatchDebitCached;
1779 else
1781 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1782 fWatchDebitCached = true;
1783 debit += nWatchDebitCached;
1786 return debit;
1789 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1791 // Must wait until coinbase is safely deep enough in the chain before valuing it
1792 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1793 return 0;
1795 CAmount credit = 0;
1796 if (filter & ISMINE_SPENDABLE)
1798 // GetBalance can assume transactions in mapWallet won't change
1799 if (fCreditCached)
1800 credit += nCreditCached;
1801 else
1803 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1804 fCreditCached = true;
1805 credit += nCreditCached;
1808 if (filter & ISMINE_WATCH_ONLY)
1810 if (fWatchCreditCached)
1811 credit += nWatchCreditCached;
1812 else
1814 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1815 fWatchCreditCached = true;
1816 credit += nWatchCreditCached;
1819 return credit;
1822 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1824 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1826 if (fUseCache && fImmatureCreditCached)
1827 return nImmatureCreditCached;
1828 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1829 fImmatureCreditCached = true;
1830 return nImmatureCreditCached;
1833 return 0;
1836 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1838 if (pwallet == nullptr)
1839 return 0;
1841 // Must wait until coinbase is safely deep enough in the chain before valuing it
1842 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1843 return 0;
1845 if (fUseCache && fAvailableCreditCached)
1846 return nAvailableCreditCached;
1848 CAmount nCredit = 0;
1849 uint256 hashTx = GetHash();
1850 for (unsigned int i = 0; i < tx->vout.size(); i++)
1852 if (!pwallet->IsSpent(hashTx, i))
1854 const CTxOut &txout = tx->vout[i];
1855 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1856 if (!MoneyRange(nCredit))
1857 throw std::runtime_error(std::string(__func__) + " : value out of range");
1861 nAvailableCreditCached = nCredit;
1862 fAvailableCreditCached = true;
1863 return nCredit;
1866 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool fUseCache) const
1868 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1870 if (fUseCache && fImmatureWatchCreditCached)
1871 return nImmatureWatchCreditCached;
1872 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1873 fImmatureWatchCreditCached = true;
1874 return nImmatureWatchCreditCached;
1877 return 0;
1880 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool fUseCache) const
1882 if (pwallet == nullptr)
1883 return 0;
1885 // Must wait until coinbase is safely deep enough in the chain before valuing it
1886 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1887 return 0;
1889 if (fUseCache && fAvailableWatchCreditCached)
1890 return nAvailableWatchCreditCached;
1892 CAmount nCredit = 0;
1893 for (unsigned int i = 0; i < tx->vout.size(); i++)
1895 if (!pwallet->IsSpent(GetHash(), i))
1897 const CTxOut &txout = tx->vout[i];
1898 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1899 if (!MoneyRange(nCredit))
1900 throw std::runtime_error(std::string(__func__) + ": value out of range");
1904 nAvailableWatchCreditCached = nCredit;
1905 fAvailableWatchCreditCached = true;
1906 return nCredit;
1909 CAmount CWalletTx::GetChange() const
1911 if (fChangeCached)
1912 return nChangeCached;
1913 nChangeCached = pwallet->GetChange(*tx);
1914 fChangeCached = true;
1915 return nChangeCached;
1918 bool CWalletTx::InMempool() const
1920 return fInMempool;
1923 bool CWalletTx::IsTrusted() const
1925 // Quick answer in most cases
1926 if (!CheckFinalTx(*tx))
1927 return false;
1928 int nDepth = GetDepthInMainChain();
1929 if (nDepth >= 1)
1930 return true;
1931 if (nDepth < 0)
1932 return false;
1933 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1934 return false;
1936 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1937 if (!InMempool())
1938 return false;
1940 // Trusted if all inputs are from us and are in the mempool:
1941 for (const CTxIn& txin : tx->vin)
1943 // Transactions not sent by us: not trusted
1944 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1945 if (parent == nullptr)
1946 return false;
1947 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1948 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1949 return false;
1951 return true;
1954 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1956 CMutableTransaction tx1 = *this->tx;
1957 CMutableTransaction tx2 = *_tx.tx;
1958 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1959 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1960 return CTransaction(tx1) == CTransaction(tx2);
1963 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1965 std::vector<uint256> result;
1967 LOCK(cs_wallet);
1969 // Sort them in chronological order
1970 std::multimap<unsigned int, CWalletTx*> mapSorted;
1971 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1973 CWalletTx& wtx = item.second;
1974 // Don't rebroadcast if newer than nTime:
1975 if (wtx.nTimeReceived > nTime)
1976 continue;
1977 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1979 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1981 CWalletTx& wtx = *item.second;
1982 if (wtx.RelayWalletTransaction(connman))
1983 result.push_back(wtx.GetHash());
1985 return result;
1988 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1990 // Do this infrequently and randomly to avoid giving away
1991 // that these are our transactions.
1992 if (GetTime() < nNextResend || !fBroadcastTransactions)
1993 return;
1994 bool fFirst = (nNextResend == 0);
1995 nNextResend = GetTime() + GetRand(30 * 60);
1996 if (fFirst)
1997 return;
1999 // Only do it if there's been a new block since last time
2000 if (nBestBlockTime < nLastResend)
2001 return;
2002 nLastResend = GetTime();
2004 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2005 // block was found:
2006 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2007 if (!relayed.empty())
2008 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2011 /** @} */ // end of mapWallet
2016 /** @defgroup Actions
2018 * @{
2022 CAmount CWallet::GetBalance() const
2024 CAmount nTotal = 0;
2026 LOCK2(cs_main, cs_wallet);
2027 for (const auto& entry : mapWallet)
2029 const CWalletTx* pcoin = &entry.second;
2030 if (pcoin->IsTrusted())
2031 nTotal += pcoin->GetAvailableCredit();
2035 return nTotal;
2038 CAmount CWallet::GetUnconfirmedBalance() const
2040 CAmount nTotal = 0;
2042 LOCK2(cs_main, cs_wallet);
2043 for (const auto& entry : mapWallet)
2045 const CWalletTx* pcoin = &entry.second;
2046 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2047 nTotal += pcoin->GetAvailableCredit();
2050 return nTotal;
2053 CAmount CWallet::GetImmatureBalance() const
2055 CAmount nTotal = 0;
2057 LOCK2(cs_main, cs_wallet);
2058 for (const auto& entry : mapWallet)
2060 const CWalletTx* pcoin = &entry.second;
2061 nTotal += pcoin->GetImmatureCredit();
2064 return nTotal;
2067 CAmount CWallet::GetWatchOnlyBalance() const
2069 CAmount nTotal = 0;
2071 LOCK2(cs_main, cs_wallet);
2072 for (const auto& entry : mapWallet)
2074 const CWalletTx* pcoin = &entry.second;
2075 if (pcoin->IsTrusted())
2076 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2080 return nTotal;
2083 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2085 CAmount nTotal = 0;
2087 LOCK2(cs_main, cs_wallet);
2088 for (const auto& entry : mapWallet)
2090 const CWalletTx* pcoin = &entry.second;
2091 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2092 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2095 return nTotal;
2098 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2100 CAmount nTotal = 0;
2102 LOCK2(cs_main, cs_wallet);
2103 for (const auto& entry : mapWallet)
2105 const CWalletTx* pcoin = &entry.second;
2106 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2109 return nTotal;
2112 // Calculate total balance in a different way from GetBalance. The biggest
2113 // difference is that GetBalance sums up all unspent TxOuts paying to the
2114 // wallet, while this sums up both spent and unspent TxOuts paying to the
2115 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2116 // also has fewer restrictions on which unconfirmed transactions are considered
2117 // trusted.
2118 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2120 LOCK2(cs_main, cs_wallet);
2122 CAmount balance = 0;
2123 for (const auto& entry : mapWallet) {
2124 const CWalletTx& wtx = entry.second;
2125 const int depth = wtx.GetDepthInMainChain();
2126 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2127 continue;
2130 // Loop through tx outputs and add incoming payments. For outgoing txs,
2131 // treat change outputs specially, as part of the amount debited.
2132 CAmount debit = wtx.GetDebit(filter);
2133 const bool outgoing = debit > 0;
2134 for (const CTxOut& out : wtx.tx->vout) {
2135 if (outgoing && IsChange(out)) {
2136 debit -= out.nValue;
2137 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2138 balance += out.nValue;
2142 // For outgoing txs, subtract amount debited.
2143 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2144 balance -= debit;
2148 if (account) {
2149 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2152 return balance;
2155 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2157 LOCK2(cs_main, cs_wallet);
2159 CAmount balance = 0;
2160 std::vector<COutput> vCoins;
2161 AvailableCoins(vCoins, true, coinControl);
2162 for (const COutput& out : vCoins) {
2163 if (out.fSpendable) {
2164 balance += out.tx->tx->vout[out.i].nValue;
2167 return balance;
2170 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
2172 vCoins.clear();
2175 LOCK2(cs_main, cs_wallet);
2177 CAmount nTotal = 0;
2179 for (const auto& entry : mapWallet)
2181 const uint256& wtxid = entry.first;
2182 const CWalletTx* pcoin = &entry.second;
2184 if (!CheckFinalTx(*pcoin->tx))
2185 continue;
2187 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2188 continue;
2190 int nDepth = pcoin->GetDepthInMainChain();
2191 if (nDepth < 0)
2192 continue;
2194 // We should not consider coins which aren't at least in our mempool
2195 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2196 if (nDepth == 0 && !pcoin->InMempool())
2197 continue;
2199 bool safeTx = pcoin->IsTrusted();
2201 // We should not consider coins from transactions that are replacing
2202 // other transactions.
2204 // Example: There is a transaction A which is replaced by bumpfee
2205 // transaction B. In this case, we want to prevent creation of
2206 // a transaction B' which spends an output of B.
2208 // Reason: If transaction A were initially confirmed, transactions B
2209 // and B' would no longer be valid, so the user would have to create
2210 // a new transaction C to replace B'. However, in the case of a
2211 // one-block reorg, transactions B' and C might BOTH be accepted,
2212 // when the user only wanted one of them. Specifically, there could
2213 // be a 1-block reorg away from the chain where transactions A and C
2214 // were accepted to another chain where B, B', and C were all
2215 // accepted.
2216 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2217 safeTx = false;
2220 // Similarly, we should not consider coins from transactions that
2221 // have been replaced. In the example above, we would want to prevent
2222 // creation of a transaction A' spending an output of A, because if
2223 // transaction B were initially confirmed, conflicting with A and
2224 // A', we wouldn't want to the user to create a transaction D
2225 // intending to replace A', but potentially resulting in a scenario
2226 // where A, A', and D could all be accepted (instead of just B and
2227 // D, or just A and A' like the user would want).
2228 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2229 safeTx = false;
2232 if (fOnlySafe && !safeTx) {
2233 continue;
2236 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2237 continue;
2239 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2240 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2241 continue;
2243 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2244 continue;
2246 if (IsLockedCoin(entry.first, i))
2247 continue;
2249 if (IsSpent(wtxid, i))
2250 continue;
2252 isminetype mine = IsMine(pcoin->tx->vout[i]);
2254 if (mine == ISMINE_NO) {
2255 continue;
2258 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2259 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2261 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2263 // Checks the sum amount of all UTXO's.
2264 if (nMinimumSumAmount != MAX_MONEY) {
2265 nTotal += pcoin->tx->vout[i].nValue;
2267 if (nTotal >= nMinimumSumAmount) {
2268 return;
2272 // Checks the maximum number of UTXO's.
2273 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2274 return;
2281 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2283 // TODO: Add AssertLockHeld(cs_wallet) here.
2285 // Because the return value from this function contains pointers to
2286 // CWalletTx objects, callers to this function really should acquire the
2287 // cs_wallet lock before calling it. However, the current caller doesn't
2288 // acquire this lock yet. There was an attempt to add the missing lock in
2289 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2290 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2291 // avoid adding some extra complexity to the Qt code.
2293 std::map<CTxDestination, std::vector<COutput>> result;
2295 std::vector<COutput> availableCoins;
2296 AvailableCoins(availableCoins);
2298 LOCK2(cs_main, cs_wallet);
2299 for (auto& coin : availableCoins) {
2300 CTxDestination address;
2301 if (coin.fSpendable &&
2302 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2303 result[address].emplace_back(std::move(coin));
2307 std::vector<COutPoint> lockedCoins;
2308 ListLockedCoins(lockedCoins);
2309 for (const auto& output : lockedCoins) {
2310 auto it = mapWallet.find(output.hash);
2311 if (it != mapWallet.end()) {
2312 int depth = it->second.GetDepthInMainChain();
2313 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2314 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2315 CTxDestination address;
2316 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2317 result[address].emplace_back(
2318 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2324 return result;
2327 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2329 const CTransaction* ptx = &tx;
2330 int n = output;
2331 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2332 const COutPoint& prevout = ptx->vin[0].prevout;
2333 auto it = mapWallet.find(prevout.hash);
2334 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2335 !IsMine(it->second.tx->vout[prevout.n])) {
2336 break;
2338 ptx = it->second.tx.get();
2339 n = prevout.n;
2341 return ptx->vout[n];
2344 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2345 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2347 std::vector<char> vfIncluded;
2349 vfBest.assign(vValue.size(), true);
2350 nBest = nTotalLower;
2352 FastRandomContext insecure_rand;
2354 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2356 vfIncluded.assign(vValue.size(), false);
2357 CAmount nTotal = 0;
2358 bool fReachedTarget = false;
2359 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2361 for (unsigned int i = 0; i < vValue.size(); i++)
2363 //The solver here uses a randomized algorithm,
2364 //the randomness serves no real security purpose but is just
2365 //needed to prevent degenerate behavior and it is important
2366 //that the rng is fast. We do not use a constant random sequence,
2367 //because there may be some privacy improvement by making
2368 //the selection random.
2369 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2371 nTotal += vValue[i].txout.nValue;
2372 vfIncluded[i] = true;
2373 if (nTotal >= nTargetValue)
2375 fReachedTarget = true;
2376 if (nTotal < nBest)
2378 nBest = nTotal;
2379 vfBest = vfIncluded;
2381 nTotal -= vValue[i].txout.nValue;
2382 vfIncluded[i] = false;
2390 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2391 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2393 setCoinsRet.clear();
2394 nValueRet = 0;
2396 // List of values less than target
2397 boost::optional<CInputCoin> coinLowestLarger;
2398 std::vector<CInputCoin> vValue;
2399 CAmount nTotalLower = 0;
2401 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2403 for (const COutput &output : vCoins)
2405 if (!output.fSpendable)
2406 continue;
2408 const CWalletTx *pcoin = output.tx;
2410 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2411 continue;
2413 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2414 continue;
2416 int i = output.i;
2418 CInputCoin coin = CInputCoin(pcoin, i);
2420 if (coin.txout.nValue == nTargetValue)
2422 setCoinsRet.insert(coin);
2423 nValueRet += coin.txout.nValue;
2424 return true;
2426 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2428 vValue.push_back(coin);
2429 nTotalLower += coin.txout.nValue;
2431 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2433 coinLowestLarger = coin;
2437 if (nTotalLower == nTargetValue)
2439 for (const auto& input : vValue)
2441 setCoinsRet.insert(input);
2442 nValueRet += input.txout.nValue;
2444 return true;
2447 if (nTotalLower < nTargetValue)
2449 if (!coinLowestLarger)
2450 return false;
2451 setCoinsRet.insert(coinLowestLarger.get());
2452 nValueRet += coinLowestLarger->txout.nValue;
2453 return true;
2456 // Solve subset sum by stochastic approximation
2457 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2458 std::reverse(vValue.begin(), vValue.end());
2459 std::vector<char> vfBest;
2460 CAmount nBest;
2462 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2463 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2464 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2466 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2467 // or the next bigger coin is closer), return the bigger coin
2468 if (coinLowestLarger &&
2469 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2471 setCoinsRet.insert(coinLowestLarger.get());
2472 nValueRet += coinLowestLarger->txout.nValue;
2474 else {
2475 for (unsigned int i = 0; i < vValue.size(); i++)
2476 if (vfBest[i])
2478 setCoinsRet.insert(vValue[i]);
2479 nValueRet += vValue[i].txout.nValue;
2482 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2483 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2484 for (unsigned int i = 0; i < vValue.size(); i++) {
2485 if (vfBest[i]) {
2486 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2489 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2493 return true;
2496 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2498 std::vector<COutput> vCoins(vAvailableCoins);
2500 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2501 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2503 for (const COutput& out : vCoins)
2505 if (!out.fSpendable)
2506 continue;
2507 nValueRet += out.tx->tx->vout[out.i].nValue;
2508 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2510 return (nValueRet >= nTargetValue);
2513 // calculate value from preset inputs and store them
2514 std::set<CInputCoin> setPresetCoins;
2515 CAmount nValueFromPresetInputs = 0;
2517 std::vector<COutPoint> vPresetInputs;
2518 if (coinControl)
2519 coinControl->ListSelected(vPresetInputs);
2520 for (const COutPoint& outpoint : vPresetInputs)
2522 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2523 if (it != mapWallet.end())
2525 const CWalletTx* pcoin = &it->second;
2526 // Clearly invalid input, fail
2527 if (pcoin->tx->vout.size() <= outpoint.n)
2528 return false;
2529 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2530 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2531 } else
2532 return false; // TODO: Allow non-wallet inputs
2535 // remove preset inputs from vCoins
2536 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2538 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2539 it = vCoins.erase(it);
2540 else
2541 ++it;
2544 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2545 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2547 bool res = nTargetValue <= nValueFromPresetInputs ||
2548 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2549 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2550 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2551 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2552 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2553 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2554 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2556 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2557 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2559 // add preset inputs to the total value selected
2560 nValueRet += nValueFromPresetInputs;
2562 return res;
2565 bool CWallet::SignTransaction(CMutableTransaction &tx)
2567 AssertLockHeld(cs_wallet); // mapWallet
2569 // sign the new tx
2570 CTransaction txNewConst(tx);
2571 int nIn = 0;
2572 for (const auto& input : tx.vin) {
2573 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2574 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2575 return false;
2577 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2578 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2579 SignatureData sigdata;
2580 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2581 return false;
2583 UpdateTransaction(tx, nIn, sigdata);
2584 nIn++;
2586 return true;
2589 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2591 std::vector<CRecipient> vecSend;
2593 // Turn the txout set into a CRecipient vector.
2594 for (size_t idx = 0; idx < tx.vout.size(); idx++) {
2595 const CTxOut& txOut = tx.vout[idx];
2596 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2597 vecSend.push_back(recipient);
2600 coinControl.fAllowOtherInputs = true;
2602 for (const CTxIn& txin : tx.vin) {
2603 coinControl.Select(txin.prevout);
2606 // Acquire the locks to prevent races to the new locked unspents between the
2607 // CreateTransaction call and LockCoin calls (when lockUnspents is true).
2608 LOCK2(cs_main, cs_wallet);
2610 CReserveKey reservekey(this);
2611 CWalletTx wtx;
2612 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2613 return false;
2616 if (nChangePosInOut != -1) {
2617 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2618 // We don't have the normal Create/Commit cycle, and don't want to risk
2619 // reusing change, so just remove the key from the keypool here.
2620 reservekey.KeepKey();
2623 // Copy output sizes from new transaction; they may have had the fee
2624 // subtracted from them.
2625 for (unsigned int idx = 0; idx < tx.vout.size(); idx++) {
2626 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2629 // Add new txins while keeping original txin scriptSig/order.
2630 for (const CTxIn& txin : wtx.tx->vin) {
2631 if (!coinControl.IsSelected(txin.prevout)) {
2632 tx.vin.push_back(txin);
2634 if (lockUnspents) {
2635 LockCoin(txin.prevout);
2640 return true;
2643 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2644 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2646 CAmount nValue = 0;
2647 int nChangePosRequest = nChangePosInOut;
2648 unsigned int nSubtractFeeFromAmount = 0;
2649 for (const auto& recipient : vecSend)
2651 if (nValue < 0 || recipient.nAmount < 0)
2653 strFailReason = _("Transaction amounts must not be negative");
2654 return false;
2656 nValue += recipient.nAmount;
2658 if (recipient.fSubtractFeeFromAmount)
2659 nSubtractFeeFromAmount++;
2661 if (vecSend.empty())
2663 strFailReason = _("Transaction must have at least one recipient");
2664 return false;
2667 wtxNew.fTimeReceivedIsTxTime = true;
2668 wtxNew.BindWallet(this);
2669 CMutableTransaction txNew;
2671 // Discourage fee sniping.
2673 // For a large miner the value of the transactions in the best block and
2674 // the mempool can exceed the cost of deliberately attempting to mine two
2675 // blocks to orphan the current best block. By setting nLockTime such that
2676 // only the next block can include the transaction, we discourage this
2677 // practice as the height restricted and limited blocksize gives miners
2678 // considering fee sniping fewer options for pulling off this attack.
2680 // A simple way to think about this is from the wallet's point of view we
2681 // always want the blockchain to move forward. By setting nLockTime this
2682 // way we're basically making the statement that we only want this
2683 // transaction to appear in the next block; we don't want to potentially
2684 // encourage reorgs by allowing transactions to appear at lower heights
2685 // than the next block in forks of the best chain.
2687 // Of course, the subsidy is high enough, and transaction volume low
2688 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2689 // now we ensure code won't be written that makes assumptions about
2690 // nLockTime that preclude a fix later.
2691 txNew.nLockTime = chainActive.Height();
2693 // Secondly occasionally randomly pick a nLockTime even further back, so
2694 // that transactions that are delayed after signing for whatever reason,
2695 // e.g. high-latency mix networks and some CoinJoin implementations, have
2696 // better privacy.
2697 if (GetRandInt(10) == 0)
2698 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2700 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2701 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2702 FeeCalculation feeCalc;
2703 CAmount nFeeNeeded;
2704 unsigned int nBytes;
2706 std::set<CInputCoin> setCoins;
2707 LOCK2(cs_main, cs_wallet);
2709 std::vector<COutput> vAvailableCoins;
2710 AvailableCoins(vAvailableCoins, true, &coin_control);
2712 // Create change script that will be used if we need change
2713 // TODO: pass in scriptChange instead of reservekey so
2714 // change transaction isn't always pay-to-bitcoin-address
2715 CScript scriptChange;
2717 // coin control: send change to custom address
2718 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2719 scriptChange = GetScriptForDestination(coin_control.destChange);
2720 } else { // no coin control: send change to newly generated address
2721 // Note: We use a new key here to keep it from being obvious which side is the change.
2722 // The drawback is that by not reusing a previous key, the change may be lost if a
2723 // backup is restored, if the backup doesn't have the new private key for the change.
2724 // If we reused the old key, it would be possible to add code to look for and
2725 // rediscover unknown transactions that were written with keys of ours to recover
2726 // post-backup change.
2728 // Reserve a new key pair from key pool
2729 CPubKey vchPubKey;
2730 bool ret;
2731 ret = reservekey.GetReservedKey(vchPubKey, true);
2732 if (!ret)
2734 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2735 return false;
2738 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2740 CTxOut change_prototype_txout(0, scriptChange);
2741 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2743 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2744 nFeeRet = 0;
2745 bool pick_new_inputs = true;
2746 CAmount nValueIn = 0;
2747 // Start with no fee and loop until there is enough fee
2748 while (true)
2750 nChangePosInOut = nChangePosRequest;
2751 txNew.vin.clear();
2752 txNew.vout.clear();
2753 wtxNew.fFromMe = true;
2754 bool fFirst = true;
2756 CAmount nValueToSelect = nValue;
2757 if (nSubtractFeeFromAmount == 0)
2758 nValueToSelect += nFeeRet;
2759 // vouts to the payees
2760 for (const auto& recipient : vecSend)
2762 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2764 if (recipient.fSubtractFeeFromAmount)
2766 assert(nSubtractFeeFromAmount != 0);
2767 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2769 if (fFirst) // first receiver pays the remainder not divisible by output count
2771 fFirst = false;
2772 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2776 if (IsDust(txout, ::dustRelayFee))
2778 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2780 if (txout.nValue < 0)
2781 strFailReason = _("The transaction amount is too small to pay the fee");
2782 else
2783 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2785 else
2786 strFailReason = _("Transaction amount too small");
2787 return false;
2789 txNew.vout.push_back(txout);
2792 // Choose coins to use
2793 if (pick_new_inputs) {
2794 nValueIn = 0;
2795 setCoins.clear();
2796 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2798 strFailReason = _("Insufficient funds");
2799 return false;
2803 const CAmount nChange = nValueIn - nValueToSelect;
2805 if (nChange > 0)
2807 // Fill a vout to ourself
2808 CTxOut newTxOut(nChange, scriptChange);
2810 // Never create dust outputs; if we would, just
2811 // add the dust to the fee.
2812 if (IsDust(newTxOut, discard_rate))
2814 nChangePosInOut = -1;
2815 nFeeRet += nChange;
2817 else
2819 if (nChangePosInOut == -1)
2821 // Insert change txn at random position:
2822 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2824 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2826 strFailReason = _("Change index out of range");
2827 return false;
2830 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2831 txNew.vout.insert(position, newTxOut);
2833 } else {
2834 nChangePosInOut = -1;
2837 // Fill vin
2839 // Note how the sequence number is set to non-maxint so that
2840 // the nLockTime set above actually works.
2842 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2843 // we use the highest possible value in that range (maxint-2)
2844 // to avoid conflicting with other possible uses of nSequence,
2845 // and in the spirit of "smallest possible change from prior
2846 // behavior."
2847 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2848 for (const auto& coin : setCoins)
2849 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2850 nSequence));
2852 // Fill in dummy signatures for fee calculation.
2853 if (!DummySignTx(txNew, setCoins)) {
2854 strFailReason = _("Signing transaction failed");
2855 return false;
2858 nBytes = GetVirtualTransactionSize(txNew);
2860 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2861 for (auto& vin : txNew.vin) {
2862 vin.scriptSig = CScript();
2863 vin.scriptWitness.SetNull();
2866 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2868 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2869 // because we must be at the maximum allowed fee.
2870 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2872 strFailReason = _("Transaction too large for fee policy");
2873 return false;
2876 if (nFeeRet >= nFeeNeeded) {
2877 // Reduce fee to only the needed amount if possible. This
2878 // prevents potential overpayment in fees if the coins
2879 // selected to meet nFeeNeeded result in a transaction that
2880 // requires less fee than the prior iteration.
2882 // If we have no change and a big enough excess fee, then
2883 // try to construct transaction again only without picking
2884 // new inputs. We now know we only need the smaller fee
2885 // (because of reduced tx size) and so we should add a
2886 // change output. Only try this once.
2887 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2888 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2889 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2890 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2891 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2892 pick_new_inputs = false;
2893 nFeeRet = fee_needed_with_change;
2894 continue;
2898 // If we have change output already, just increase it
2899 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2900 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2901 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2902 change_position->nValue += extraFeePaid;
2903 nFeeRet -= extraFeePaid;
2905 break; // Done, enough fee included.
2907 else if (!pick_new_inputs) {
2908 // This shouldn't happen, we should have had enough excess
2909 // fee to pay for the new output and still meet nFeeNeeded
2910 // Or we should have just subtracted fee from recipients and
2911 // nFeeNeeded should not have changed
2912 strFailReason = _("Transaction fee and change calculation failed");
2913 return false;
2916 // Try to reduce change to include necessary fee
2917 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2918 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2919 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2920 // Only reduce change if remaining amount is still a large enough output.
2921 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2922 change_position->nValue -= additionalFeeNeeded;
2923 nFeeRet += additionalFeeNeeded;
2924 break; // Done, able to increase fee from change
2928 // If subtracting fee from recipients, we now know what fee we
2929 // need to subtract, we have no reason to reselect inputs
2930 if (nSubtractFeeFromAmount > 0) {
2931 pick_new_inputs = false;
2934 // Include more fee and try again.
2935 nFeeRet = nFeeNeeded;
2936 continue;
2940 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2942 if (sign)
2944 CTransaction txNewConst(txNew);
2945 int nIn = 0;
2946 for (const auto& coin : setCoins)
2948 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2949 SignatureData sigdata;
2951 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2953 strFailReason = _("Signing transaction failed");
2954 return false;
2955 } else {
2956 UpdateTransaction(txNew, nIn, sigdata);
2959 nIn++;
2963 // Embed the constructed transaction data in wtxNew.
2964 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2966 // Limit size
2967 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2969 strFailReason = _("Transaction too large");
2970 return false;
2974 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2975 // Lastly, ensure this tx will pass the mempool's chain limits
2976 LockPoints lp;
2977 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2978 CTxMemPool::setEntries setAncestors;
2979 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2980 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2981 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2982 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2983 std::string errString;
2984 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2985 strFailReason = _("Transaction has too long of a mempool chain");
2986 return false;
2990 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",
2991 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2992 feeCalc.est.pass.start, feeCalc.est.pass.end,
2993 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2994 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2995 feeCalc.est.fail.start, feeCalc.est.fail.end,
2996 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2997 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2998 return true;
3002 * Call after CreateTransaction unless you want to abort
3004 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3007 LOCK2(cs_main, cs_wallet);
3008 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3010 // Take key pair from key pool so it won't be used again
3011 reservekey.KeepKey();
3013 // Add tx to wallet, because if it has change it's also ours,
3014 // otherwise just for transaction history.
3015 AddToWallet(wtxNew);
3017 // Notify that old coins are spent
3018 for (const CTxIn& txin : wtxNew.tx->vin)
3020 CWalletTx &coin = mapWallet[txin.prevout.hash];
3021 coin.BindWallet(this);
3022 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3026 // Track how many getdata requests our transaction gets
3027 mapRequestCount[wtxNew.GetHash()] = 0;
3029 // Get the inserted-CWalletTx from mapWallet so that the
3030 // fInMempool flag is cached properly
3031 CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
3033 if (fBroadcastTransactions)
3035 // Broadcast
3036 if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
3037 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3038 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3039 } else {
3040 wtx.RelayWalletTransaction(connman);
3044 return true;
3047 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3048 CWalletDB walletdb(*dbw);
3049 return walletdb.ListAccountCreditDebit(strAccount, entries);
3052 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3054 CWalletDB walletdb(*dbw);
3056 return AddAccountingEntry(acentry, &walletdb);
3059 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3061 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3062 return false;
3065 laccentries.push_back(acentry);
3066 CAccountingEntry & entry = laccentries.back();
3067 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3069 return true;
3072 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3074 LOCK2(cs_main, cs_wallet);
3076 fFirstRunRet = false;
3077 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3078 if (nLoadWalletRet == DB_NEED_REWRITE)
3080 if (dbw->Rewrite("\x04pool"))
3082 setInternalKeyPool.clear();
3083 setExternalKeyPool.clear();
3084 m_pool_key_to_index.clear();
3085 // Note: can't top-up keypool here, because wallet is locked.
3086 // User will be prompted to unlock wallet the next operation
3087 // that requires a new key.
3091 // This wallet is in its first run if all of these are empty
3092 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3094 if (nLoadWalletRet != DB_LOAD_OK)
3095 return nLoadWalletRet;
3097 uiInterface.LoadWallet(this);
3099 return DB_LOAD_OK;
3102 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3104 AssertLockHeld(cs_wallet); // mapWallet
3105 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3106 for (uint256 hash : vHashOut)
3107 mapWallet.erase(hash);
3109 if (nZapSelectTxRet == DB_NEED_REWRITE)
3111 if (dbw->Rewrite("\x04pool"))
3113 setInternalKeyPool.clear();
3114 setExternalKeyPool.clear();
3115 m_pool_key_to_index.clear();
3116 // Note: can't top-up keypool here, because wallet is locked.
3117 // User will be prompted to unlock wallet the next operation
3118 // that requires a new key.
3122 if (nZapSelectTxRet != DB_LOAD_OK)
3123 return nZapSelectTxRet;
3125 MarkDirty();
3127 return DB_LOAD_OK;
3131 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3133 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3134 if (nZapWalletTxRet == DB_NEED_REWRITE)
3136 if (dbw->Rewrite("\x04pool"))
3138 LOCK(cs_wallet);
3139 setInternalKeyPool.clear();
3140 setExternalKeyPool.clear();
3141 m_pool_key_to_index.clear();
3142 // Note: can't top-up keypool here, because wallet is locked.
3143 // User will be prompted to unlock wallet the next operation
3144 // that requires a new key.
3148 if (nZapWalletTxRet != DB_LOAD_OK)
3149 return nZapWalletTxRet;
3151 return DB_LOAD_OK;
3155 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3157 bool fUpdated = false;
3159 LOCK(cs_wallet); // mapAddressBook
3160 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3161 fUpdated = mi != mapAddressBook.end();
3162 mapAddressBook[address].name = strName;
3163 if (!strPurpose.empty()) /* update purpose only if requested */
3164 mapAddressBook[address].purpose = strPurpose;
3166 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3167 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3168 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3169 return false;
3170 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3173 bool CWallet::DelAddressBook(const CTxDestination& address)
3176 LOCK(cs_wallet); // mapAddressBook
3178 // Delete destdata tuples associated with address
3179 std::string strAddress = EncodeDestination(address);
3180 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3182 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3184 mapAddressBook.erase(address);
3187 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3189 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3190 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3193 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3195 CTxDestination address;
3196 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3197 auto mi = mapAddressBook.find(address);
3198 if (mi != mapAddressBook.end()) {
3199 return mi->second.name;
3202 // A scriptPubKey that doesn't have an entry in the address book is
3203 // associated with the default account ("").
3204 const static std::string DEFAULT_ACCOUNT_NAME;
3205 return DEFAULT_ACCOUNT_NAME;
3209 * Mark old keypool keys as used,
3210 * and generate all new keys
3212 bool CWallet::NewKeyPool()
3215 LOCK(cs_wallet);
3216 CWalletDB walletdb(*dbw);
3218 for (int64_t nIndex : setInternalKeyPool) {
3219 walletdb.ErasePool(nIndex);
3221 setInternalKeyPool.clear();
3223 for (int64_t nIndex : setExternalKeyPool) {
3224 walletdb.ErasePool(nIndex);
3226 setExternalKeyPool.clear();
3228 m_pool_key_to_index.clear();
3230 if (!TopUpKeyPool()) {
3231 return false;
3233 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3235 return true;
3238 size_t CWallet::KeypoolCountExternalKeys()
3240 AssertLockHeld(cs_wallet); // setExternalKeyPool
3241 return setExternalKeyPool.size();
3244 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3246 AssertLockHeld(cs_wallet);
3247 if (keypool.fInternal) {
3248 setInternalKeyPool.insert(nIndex);
3249 } else {
3250 setExternalKeyPool.insert(nIndex);
3252 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3253 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3255 // If no metadata exists yet, create a default with the pool key's
3256 // creation time. Note that this may be overwritten by actually
3257 // stored metadata for that key later, which is fine.
3258 CKeyID keyid = keypool.vchPubKey.GetID();
3259 if (mapKeyMetadata.count(keyid) == 0)
3260 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3263 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3266 LOCK(cs_wallet);
3268 if (IsLocked())
3269 return false;
3271 // Top up key pool
3272 unsigned int nTargetSize;
3273 if (kpSize > 0)
3274 nTargetSize = kpSize;
3275 else
3276 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3278 // count amount of available keys (internal, external)
3279 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3280 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3281 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3283 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3285 // don't create extra internal keys
3286 missingInternal = 0;
3288 bool internal = false;
3289 CWalletDB walletdb(*dbw);
3290 for (int64_t i = missingInternal + missingExternal; i--;)
3292 if (i < missingInternal) {
3293 internal = true;
3296 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3297 int64_t index = ++m_max_keypool_index;
3299 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3300 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3301 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3304 if (internal) {
3305 setInternalKeyPool.insert(index);
3306 } else {
3307 setExternalKeyPool.insert(index);
3309 m_pool_key_to_index[pubkey.GetID()] = index;
3311 if (missingInternal + missingExternal > 0) {
3312 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3315 return true;
3318 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3320 nIndex = -1;
3321 keypool.vchPubKey = CPubKey();
3323 LOCK(cs_wallet);
3325 if (!IsLocked())
3326 TopUpKeyPool();
3328 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3329 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3331 // Get the oldest key
3332 if(setKeyPool.empty())
3333 return;
3335 CWalletDB walletdb(*dbw);
3337 auto it = setKeyPool.begin();
3338 nIndex = *it;
3339 setKeyPool.erase(it);
3340 if (!walletdb.ReadPool(nIndex, keypool)) {
3341 throw std::runtime_error(std::string(__func__) + ": read failed");
3343 if (!HaveKey(keypool.vchPubKey.GetID())) {
3344 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3346 if (keypool.fInternal != fReturningInternal) {
3347 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3350 assert(keypool.vchPubKey.IsValid());
3351 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3352 LogPrintf("keypool reserve %d\n", nIndex);
3356 void CWallet::KeepKey(int64_t nIndex)
3358 // Remove from key pool
3359 CWalletDB walletdb(*dbw);
3360 walletdb.ErasePool(nIndex);
3361 LogPrintf("keypool keep %d\n", nIndex);
3364 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3366 // Return to key pool
3368 LOCK(cs_wallet);
3369 if (fInternal) {
3370 setInternalKeyPool.insert(nIndex);
3371 } else {
3372 setExternalKeyPool.insert(nIndex);
3374 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3376 LogPrintf("keypool return %d\n", nIndex);
3379 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3381 CKeyPool keypool;
3383 LOCK(cs_wallet);
3384 int64_t nIndex = 0;
3385 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3386 if (nIndex == -1)
3388 if (IsLocked()) return false;
3389 CWalletDB walletdb(*dbw);
3390 result = GenerateNewKey(walletdb, internal);
3391 return true;
3393 KeepKey(nIndex);
3394 result = keypool.vchPubKey;
3396 return true;
3399 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3400 if (setKeyPool.empty()) {
3401 return GetTime();
3404 CKeyPool keypool;
3405 int64_t nIndex = *(setKeyPool.begin());
3406 if (!walletdb.ReadPool(nIndex, keypool)) {
3407 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3409 assert(keypool.vchPubKey.IsValid());
3410 return keypool.nTime;
3413 int64_t CWallet::GetOldestKeyPoolTime()
3415 LOCK(cs_wallet);
3417 CWalletDB walletdb(*dbw);
3419 // load oldest key from keypool, get time and return
3420 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3421 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3422 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3425 return oldestKey;
3428 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3430 std::map<CTxDestination, CAmount> balances;
3433 LOCK(cs_wallet);
3434 for (const auto& walletEntry : mapWallet)
3436 const CWalletTx *pcoin = &walletEntry.second;
3438 if (!pcoin->IsTrusted())
3439 continue;
3441 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3442 continue;
3444 int nDepth = pcoin->GetDepthInMainChain();
3445 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3446 continue;
3448 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3450 CTxDestination addr;
3451 if (!IsMine(pcoin->tx->vout[i]))
3452 continue;
3453 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3454 continue;
3456 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3458 if (!balances.count(addr))
3459 balances[addr] = 0;
3460 balances[addr] += n;
3465 return balances;
3468 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3470 AssertLockHeld(cs_wallet); // mapWallet
3471 std::set< std::set<CTxDestination> > groupings;
3472 std::set<CTxDestination> grouping;
3474 for (const auto& walletEntry : mapWallet)
3476 const CWalletTx *pcoin = &walletEntry.second;
3478 if (pcoin->tx->vin.size() > 0)
3480 bool any_mine = false;
3481 // group all input addresses with each other
3482 for (CTxIn txin : pcoin->tx->vin)
3484 CTxDestination address;
3485 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3486 continue;
3487 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3488 continue;
3489 grouping.insert(address);
3490 any_mine = true;
3493 // group change with input addresses
3494 if (any_mine)
3496 for (CTxOut txout : pcoin->tx->vout)
3497 if (IsChange(txout))
3499 CTxDestination txoutAddr;
3500 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3501 continue;
3502 grouping.insert(txoutAddr);
3505 if (grouping.size() > 0)
3507 groupings.insert(grouping);
3508 grouping.clear();
3512 // group lone addrs by themselves
3513 for (const auto& txout : pcoin->tx->vout)
3514 if (IsMine(txout))
3516 CTxDestination address;
3517 if(!ExtractDestination(txout.scriptPubKey, address))
3518 continue;
3519 grouping.insert(address);
3520 groupings.insert(grouping);
3521 grouping.clear();
3525 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3526 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3527 for (std::set<CTxDestination> _grouping : groupings)
3529 // make a set of all the groups hit by this new group
3530 std::set< std::set<CTxDestination>* > hits;
3531 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3532 for (CTxDestination address : _grouping)
3533 if ((it = setmap.find(address)) != setmap.end())
3534 hits.insert((*it).second);
3536 // merge all hit groups into a new single group and delete old groups
3537 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3538 for (std::set<CTxDestination>* hit : hits)
3540 merged->insert(hit->begin(), hit->end());
3541 uniqueGroupings.erase(hit);
3542 delete hit;
3544 uniqueGroupings.insert(merged);
3546 // update setmap
3547 for (CTxDestination element : *merged)
3548 setmap[element] = merged;
3551 std::set< std::set<CTxDestination> > ret;
3552 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3554 ret.insert(*uniqueGrouping);
3555 delete uniqueGrouping;
3558 return ret;
3561 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3563 LOCK(cs_wallet);
3564 std::set<CTxDestination> result;
3565 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3567 const CTxDestination& address = item.first;
3568 const std::string& strName = item.second.name;
3569 if (strName == strAccount)
3570 result.insert(address);
3572 return result;
3575 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3577 if (nIndex == -1)
3579 CKeyPool keypool;
3580 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3581 if (nIndex != -1)
3582 vchPubKey = keypool.vchPubKey;
3583 else {
3584 return false;
3586 fInternal = keypool.fInternal;
3588 assert(vchPubKey.IsValid());
3589 pubkey = vchPubKey;
3590 return true;
3593 void CReserveKey::KeepKey()
3595 if (nIndex != -1)
3596 pwallet->KeepKey(nIndex);
3597 nIndex = -1;
3598 vchPubKey = CPubKey();
3601 void CReserveKey::ReturnKey()
3603 if (nIndex != -1) {
3604 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3606 nIndex = -1;
3607 vchPubKey = CPubKey();
3610 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3612 AssertLockHeld(cs_wallet);
3613 bool internal = setInternalKeyPool.count(keypool_id);
3614 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3615 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3616 auto it = setKeyPool->begin();
3618 CWalletDB walletdb(*dbw);
3619 while (it != std::end(*setKeyPool)) {
3620 const int64_t& index = *(it);
3621 if (index > keypool_id) break; // set*KeyPool is ordered
3623 CKeyPool keypool;
3624 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3625 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3627 walletdb.ErasePool(index);
3628 LogPrintf("keypool index %d removed\n", index);
3629 it = setKeyPool->erase(it);
3633 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3635 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3636 CPubKey pubkey;
3637 if (!rKey->GetReservedKey(pubkey))
3638 return;
3640 script = rKey;
3641 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3644 void CWallet::LockCoin(const COutPoint& output)
3646 AssertLockHeld(cs_wallet); // setLockedCoins
3647 setLockedCoins.insert(output);
3650 void CWallet::UnlockCoin(const COutPoint& output)
3652 AssertLockHeld(cs_wallet); // setLockedCoins
3653 setLockedCoins.erase(output);
3656 void CWallet::UnlockAllCoins()
3658 AssertLockHeld(cs_wallet); // setLockedCoins
3659 setLockedCoins.clear();
3662 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3664 AssertLockHeld(cs_wallet); // setLockedCoins
3665 COutPoint outpt(hash, n);
3667 return (setLockedCoins.count(outpt) > 0);
3670 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3672 AssertLockHeld(cs_wallet); // setLockedCoins
3673 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3674 it != setLockedCoins.end(); it++) {
3675 COutPoint outpt = (*it);
3676 vOutpts.push_back(outpt);
3680 /** @} */ // end of Actions
3682 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3683 AssertLockHeld(cs_wallet); // mapKeyMetadata
3684 mapKeyBirth.clear();
3686 // get birth times for keys with metadata
3687 for (const auto& entry : mapKeyMetadata) {
3688 if (entry.second.nCreateTime) {
3689 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3693 // map in which we'll infer heights of other keys
3694 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3695 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3696 for (const CKeyID &keyid : GetKeys()) {
3697 if (mapKeyBirth.count(keyid) == 0)
3698 mapKeyFirstBlock[keyid] = pindexMax;
3701 // if there are no such keys, we're done
3702 if (mapKeyFirstBlock.empty())
3703 return;
3705 // find first block that affects those keys, if there are any left
3706 std::vector<CKeyID> vAffected;
3707 for (const auto& entry : mapWallet) {
3708 // iterate over all wallet transactions...
3709 const CWalletTx &wtx = entry.second;
3710 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3711 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3712 // ... which are already in a block
3713 int nHeight = blit->second->nHeight;
3714 for (const CTxOut &txout : wtx.tx->vout) {
3715 // iterate over all their outputs
3716 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3717 for (const CKeyID &keyid : vAffected) {
3718 // ... and all their affected keys
3719 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3720 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3721 rit->second = blit->second;
3723 vAffected.clear();
3728 // Extract block timestamps for those keys
3729 for (const auto& entry : mapKeyFirstBlock)
3730 mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3734 * Compute smart timestamp for a transaction being added to the wallet.
3736 * Logic:
3737 * - If sending a transaction, assign its timestamp to the current time.
3738 * - If receiving a transaction outside a block, assign its timestamp to the
3739 * current time.
3740 * - If receiving a block with a future timestamp, assign all its (not already
3741 * known) transactions' timestamps to the current time.
3742 * - If receiving a block with a past timestamp, before the most recent known
3743 * transaction (that we care about), assign all its (not already known)
3744 * transactions' timestamps to the same timestamp as that most-recent-known
3745 * transaction.
3746 * - If receiving a block with a past timestamp, but after the most recent known
3747 * transaction, assign all its (not already known) transactions' timestamps to
3748 * the block time.
3750 * For more information see CWalletTx::nTimeSmart,
3751 * https://bitcointalk.org/?topic=54527, or
3752 * https://github.com/bitcoin/bitcoin/pull/1393.
3754 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3756 unsigned int nTimeSmart = wtx.nTimeReceived;
3757 if (!wtx.hashUnset()) {
3758 if (mapBlockIndex.count(wtx.hashBlock)) {
3759 int64_t latestNow = wtx.nTimeReceived;
3760 int64_t latestEntry = 0;
3762 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3763 int64_t latestTolerated = latestNow + 300;
3764 const TxItems& txOrdered = wtxOrdered;
3765 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3766 CWalletTx* const pwtx = it->second.first;
3767 if (pwtx == &wtx) {
3768 continue;
3770 CAccountingEntry* const pacentry = it->second.second;
3771 int64_t nSmartTime;
3772 if (pwtx) {
3773 nSmartTime = pwtx->nTimeSmart;
3774 if (!nSmartTime) {
3775 nSmartTime = pwtx->nTimeReceived;
3777 } else {
3778 nSmartTime = pacentry->nTime;
3780 if (nSmartTime <= latestTolerated) {
3781 latestEntry = nSmartTime;
3782 if (nSmartTime > latestNow) {
3783 latestNow = nSmartTime;
3785 break;
3789 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3790 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3791 } else {
3792 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3795 return nTimeSmart;
3798 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3800 if (boost::get<CNoDestination>(&dest))
3801 return false;
3803 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3804 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3807 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3809 if (!mapAddressBook[dest].destdata.erase(key))
3810 return false;
3811 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3814 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3816 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3817 return true;
3820 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3822 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3823 if(i != mapAddressBook.end())
3825 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3826 if(j != i->second.destdata.end())
3828 if(value)
3829 *value = j->second;
3830 return true;
3833 return false;
3836 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3838 LOCK(cs_wallet);
3839 std::vector<std::string> values;
3840 for (const auto& address : mapAddressBook) {
3841 for (const auto& data : address.second.destdata) {
3842 if (!data.first.compare(0, prefix.size(), prefix)) {
3843 values.emplace_back(data.second);
3847 return values;
3850 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3852 // needed to restore wallet transaction meta data after -zapwallettxes
3853 std::vector<CWalletTx> vWtx;
3855 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3856 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3858 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3859 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3860 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3861 if (nZapWalletRet != DB_LOAD_OK) {
3862 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3863 return nullptr;
3867 uiInterface.InitMessage(_("Loading wallet..."));
3869 int64_t nStart = GetTimeMillis();
3870 bool fFirstRun = true;
3871 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3872 CWallet *walletInstance = new CWallet(std::move(dbw));
3873 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3874 if (nLoadWalletRet != DB_LOAD_OK)
3876 if (nLoadWalletRet == DB_CORRUPT) {
3877 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3878 return nullptr;
3880 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3882 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3883 " or address book entries might be missing or incorrect."),
3884 walletFile));
3886 else if (nLoadWalletRet == DB_TOO_NEW) {
3887 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3888 return nullptr;
3890 else if (nLoadWalletRet == DB_NEED_REWRITE)
3892 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3893 return nullptr;
3895 else {
3896 InitError(strprintf(_("Error loading %s"), walletFile));
3897 return nullptr;
3901 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3903 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3904 if (nMaxVersion == 0) // the -upgradewallet without argument case
3906 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3907 nMaxVersion = CLIENT_VERSION;
3908 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3910 else
3911 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3912 if (nMaxVersion < walletInstance->GetVersion())
3914 InitError(_("Cannot downgrade wallet"));
3915 return nullptr;
3917 walletInstance->SetMaxVersion(nMaxVersion);
3920 if (fFirstRun)
3922 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3923 if (!gArgs.GetBoolArg("-usehd", true)) {
3924 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3925 return nullptr;
3927 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3929 // generate a new master key
3930 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3931 if (!walletInstance->SetHDMasterKey(masterPubKey))
3932 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3934 // Top up the keypool
3935 if (!walletInstance->TopUpKeyPool()) {
3936 InitError(_("Unable to generate initial keys") += "\n");
3937 return nullptr;
3940 walletInstance->SetBestChain(chainActive.GetLocator());
3942 else if (gArgs.IsArgSet("-usehd")) {
3943 bool useHD = gArgs.GetBoolArg("-usehd", true);
3944 if (walletInstance->IsHDEnabled() && !useHD) {
3945 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3946 return nullptr;
3948 if (!walletInstance->IsHDEnabled() && useHD) {
3949 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3950 return nullptr;
3954 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3956 // Try to top up keypool. No-op if the wallet is locked.
3957 walletInstance->TopUpKeyPool();
3959 CBlockIndex *pindexRescan = chainActive.Genesis();
3960 if (!gArgs.GetBoolArg("-rescan", false))
3962 CWalletDB walletdb(*walletInstance->dbw);
3963 CBlockLocator locator;
3964 if (walletdb.ReadBestBlock(locator))
3965 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3968 walletInstance->m_last_block_processed = chainActive.Tip();
3969 RegisterValidationInterface(walletInstance);
3971 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3973 //We can't rescan beyond non-pruned blocks, stop and throw an error
3974 //this might happen if a user uses an old wallet within a pruned node
3975 // or if he ran -disablewallet for a longer time, then decided to re-enable
3976 if (fPruneMode)
3978 CBlockIndex *block = chainActive.Tip();
3979 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3980 block = block->pprev;
3982 if (pindexRescan != block) {
3983 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3984 return nullptr;
3988 uiInterface.InitMessage(_("Rescanning..."));
3989 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3991 // No need to read and scan block if block was created before
3992 // our wallet birthday (as adjusted for block time variability)
3993 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3994 pindexRescan = chainActive.Next(pindexRescan);
3997 nStart = GetTimeMillis();
3998 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
3999 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4000 walletInstance->SetBestChain(chainActive.GetLocator());
4001 walletInstance->dbw->IncrementUpdateCounter();
4003 // Restore wallet transaction metadata after -zapwallettxes=1
4004 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4006 CWalletDB walletdb(*walletInstance->dbw);
4008 for (const CWalletTx& wtxOld : vWtx)
4010 uint256 hash = wtxOld.GetHash();
4011 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4012 if (mi != walletInstance->mapWallet.end())
4014 const CWalletTx* copyFrom = &wtxOld;
4015 CWalletTx* copyTo = &mi->second;
4016 copyTo->mapValue = copyFrom->mapValue;
4017 copyTo->vOrderForm = copyFrom->vOrderForm;
4018 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4019 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4020 copyTo->fFromMe = copyFrom->fFromMe;
4021 copyTo->strFromAccount = copyFrom->strFromAccount;
4022 copyTo->nOrderPos = copyFrom->nOrderPos;
4023 walletdb.WriteTx(*copyTo);
4028 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4031 LOCK(walletInstance->cs_wallet);
4032 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4033 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4034 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4037 return walletInstance;
4040 std::atomic<bool> CWallet::fFlushScheduled(false);
4042 void CWallet::postInitProcess(CScheduler& scheduler)
4044 // Add wallet transactions that aren't already in a block to mempool
4045 // Do this here as mempool requires genesis block to be loaded
4046 ReacceptWalletTransactions();
4048 // Run a thread to flush wallet periodically
4049 if (!CWallet::fFlushScheduled.exchange(true)) {
4050 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4054 bool CWallet::BackupWallet(const std::string& strDest)
4056 return dbw->Backup(strDest);
4059 CKeyPool::CKeyPool()
4061 nTime = GetTime();
4062 fInternal = false;
4065 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4067 nTime = GetTime();
4068 vchPubKey = vchPubKeyIn;
4069 fInternal = internalIn;
4072 CWalletKey::CWalletKey(int64_t nExpires)
4074 nTimeCreated = (nExpires ? GetTime() : 0);
4075 nTimeExpires = nExpires;
4078 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4080 // Update the tx's hashBlock
4081 hashBlock = pindex->GetBlockHash();
4083 // set the position of the transaction in the block
4084 nIndex = posInBlock;
4087 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4089 if (hashUnset())
4090 return 0;
4092 AssertLockHeld(cs_main);
4094 // Find the block it claims to be in
4095 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4096 if (mi == mapBlockIndex.end())
4097 return 0;
4098 CBlockIndex* pindex = (*mi).second;
4099 if (!pindex || !chainActive.Contains(pindex))
4100 return 0;
4102 pindexRet = pindex;
4103 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4106 int CMerkleTx::GetBlocksToMaturity() const
4108 if (!IsCoinBase())
4109 return 0;
4110 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4114 bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4116 // Quick check to avoid re-setting fInMempool to false
4117 if (mempool.exists(tx->GetHash())) {
4118 return false;
4121 // We must set fInMempool here - while it will be re-set to true by the
4122 // entered-mempool callback, if we did not there would be a race where a
4123 // user could call sendmoney in a loop and hit spurious out of funds errors
4124 // because we think that the transaction they just generated's change is
4125 // unavailable as we're not yet aware its in mempool.
4126 bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4127 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
4128 fInMempool = ret;
4129 return ret;