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