wallet: Remove unnecessary mempool lock in ReacceptWalletTransactions
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobd4e7de2e33fea35d5cc90d583902778b75bcd00b
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 <script/sign.h>
27 #include <scheduler.h>
28 #include <timedata.h>
29 #include <txmempool.h>
30 #include <util.h>
31 #include <ui_interface.h>
32 #include <utilmoneystr.h>
33 #include <wallet/fees.h>
35 #include <assert.h>
36 #include <future>
38 #include <boost/algorithm/string/replace.hpp>
39 #include <boost/thread.hpp>
41 std::vector<CWalletRef> vpwallets;
42 /** Transaction fee set by the user */
43 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
44 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
45 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
46 bool fWalletRbf = DEFAULT_WALLET_RBF;
48 const char * DEFAULT_WALLET_DAT = "wallet.dat";
49 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
51 /**
52 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
53 * Override with -mintxfee
55 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
56 /**
57 * If fee estimation does not have enough data to provide estimates, use this fee instead.
58 * Has no effect if not using fee estimation
59 * Override with -fallbackfee
61 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
63 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
65 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
67 /** @defgroup mapWallet
69 * @{
72 struct CompareValueOnly
74 bool operator()(const CInputCoin& t1,
75 const CInputCoin& t2) const
77 return t1.txout.nValue < t2.txout.nValue;
81 std::string COutput::ToString() const
83 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
86 class CAffectedKeysVisitor : public boost::static_visitor<void> {
87 private:
88 const CKeyStore &keystore;
89 std::vector<CKeyID> &vKeys;
91 public:
92 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
94 void Process(const CScript &script) {
95 txnouttype type;
96 std::vector<CTxDestination> vDest;
97 int nRequired;
98 if (ExtractDestinations(script, type, vDest, nRequired)) {
99 for (const CTxDestination &dest : vDest)
100 boost::apply_visitor(*this, dest);
104 void operator()(const CKeyID &keyId) {
105 if (keystore.HaveKey(keyId))
106 vKeys.push_back(keyId);
109 void operator()(const CScriptID &scriptId) {
110 CScript script;
111 if (keystore.GetCScript(scriptId, script))
112 Process(script);
115 void operator()(const WitnessV0ScriptHash& scriptID)
117 CScriptID id;
118 CRIPEMD160().Write(scriptID.begin(), 32).Finalize(id.begin());
119 CScript script;
120 if (keystore.GetCScript(id, script)) {
121 Process(script);
125 void operator()(const WitnessV0KeyHash& keyid)
127 CKeyID id(keyid);
128 if (keystore.HaveKey(id)) {
129 vKeys.push_back(id);
133 template<typename X>
134 void operator()(const X &none) {}
137 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
139 LOCK(cs_wallet);
140 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
141 if (it == mapWallet.end())
142 return nullptr;
143 return &(it->second);
146 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
148 AssertLockHeld(cs_wallet); // mapKeyMetadata
149 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
151 CKey secret;
153 // Create new metadata
154 int64_t nCreationTime = GetTime();
155 CKeyMetadata metadata(nCreationTime);
157 // use HD key derivation if HD was enabled during wallet creation
158 if (IsHDEnabled()) {
159 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
160 } else {
161 secret.MakeNewKey(fCompressed);
164 // Compressed public keys were introduced in version 0.6.0
165 if (fCompressed) {
166 SetMinVersion(FEATURE_COMPRPUBKEY);
169 CPubKey pubkey = secret.GetPubKey();
170 assert(secret.VerifyPubKey(pubkey));
172 mapKeyMetadata[pubkey.GetID()] = metadata;
173 UpdateTimeFirstKey(nCreationTime);
175 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
176 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
178 return pubkey;
181 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
183 // for now we use a fixed keypath scheme of m/0'/0'/k
184 CKey key; //master key seed (256bit)
185 CExtKey masterKey; //hd master key
186 CExtKey accountKey; //key at m/0'
187 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
188 CExtKey childKey; //key at m/0'/0'/<n>'
190 // try to get the master key
191 if (!GetKey(hdChain.masterKeyID, key))
192 throw std::runtime_error(std::string(__func__) + ": Master key not found");
194 masterKey.SetMaster(key.begin(), key.size());
196 // derive m/0'
197 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
198 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
200 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
201 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
202 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
204 // derive child key at next index, skip keys already known to the wallet
205 do {
206 // always derive hardened keys
207 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
208 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
209 if (internal) {
210 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
211 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
212 hdChain.nInternalChainCounter++;
214 else {
215 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
216 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
217 hdChain.nExternalChainCounter++;
219 } while (HaveKey(childKey.key.GetPubKey().GetID()));
220 secret = childKey.key;
221 metadata.hdMasterKeyID = hdChain.masterKeyID;
222 // update the chain model in the database
223 if (!walletdb.WriteHDChain(hdChain))
224 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
227 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
229 AssertLockHeld(cs_wallet); // mapKeyMetadata
231 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
232 // which is overridden below. To avoid flushes, the database handle is
233 // tunneled through to it.
234 bool needsDB = !pwalletdbEncryption;
235 if (needsDB) {
236 pwalletdbEncryption = &walletdb;
238 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
239 if (needsDB) pwalletdbEncryption = nullptr;
240 return false;
242 if (needsDB) pwalletdbEncryption = nullptr;
244 // check if we need to remove from watch-only
245 CScript script;
246 script = GetScriptForDestination(pubkey.GetID());
247 if (HaveWatchOnly(script)) {
248 RemoveWatchOnly(script);
250 script = GetScriptForRawPubKey(pubkey);
251 if (HaveWatchOnly(script)) {
252 RemoveWatchOnly(script);
255 if (!IsCrypted()) {
256 return walletdb.WriteKey(pubkey,
257 secret.GetPrivKey(),
258 mapKeyMetadata[pubkey.GetID()]);
260 return true;
263 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
265 CWalletDB walletdb(*dbw);
266 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
269 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
270 const std::vector<unsigned char> &vchCryptedSecret)
272 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
273 return false;
275 LOCK(cs_wallet);
276 if (pwalletdbEncryption)
277 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
278 vchCryptedSecret,
279 mapKeyMetadata[vchPubKey.GetID()]);
280 else
281 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
282 vchCryptedSecret,
283 mapKeyMetadata[vchPubKey.GetID()]);
287 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
289 AssertLockHeld(cs_wallet); // mapKeyMetadata
290 UpdateTimeFirstKey(meta.nCreateTime);
291 mapKeyMetadata[keyID] = meta;
292 return true;
295 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
297 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
301 * Update wallet first key creation time. This should be called whenever keys
302 * are added to the wallet, with the oldest key creation time.
304 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
306 AssertLockHeld(cs_wallet);
307 if (nCreateTime <= 1) {
308 // Cannot determine birthday information, so set the wallet birthday to
309 // the beginning of time.
310 nTimeFirstKey = 1;
311 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
312 nTimeFirstKey = nCreateTime;
316 bool CWallet::AddCScript(const CScript& redeemScript)
318 if (!CCryptoKeyStore::AddCScript(redeemScript))
319 return false;
320 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
323 bool CWallet::LoadCScript(const CScript& redeemScript)
325 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
326 * that never can be redeemed. However, old wallets may still contain
327 * these. Do not add them to the wallet and warn. */
328 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
330 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
331 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",
332 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
333 return true;
336 return CCryptoKeyStore::AddCScript(redeemScript);
339 bool CWallet::AddWatchOnly(const CScript& dest)
341 if (!CCryptoKeyStore::AddWatchOnly(dest))
342 return false;
343 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
344 UpdateTimeFirstKey(meta.nCreateTime);
345 NotifyWatchonlyChanged(true);
346 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
349 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
351 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
352 return AddWatchOnly(dest);
355 bool CWallet::RemoveWatchOnly(const CScript &dest)
357 AssertLockHeld(cs_wallet);
358 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
359 return false;
360 if (!HaveWatchOnly())
361 NotifyWatchonlyChanged(false);
362 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
363 return false;
365 return true;
368 bool CWallet::LoadWatchOnly(const CScript &dest)
370 return CCryptoKeyStore::AddWatchOnly(dest);
373 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
375 CCrypter crypter;
376 CKeyingMaterial _vMasterKey;
379 LOCK(cs_wallet);
380 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
382 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
383 return false;
384 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
385 continue; // try another master key
386 if (CCryptoKeyStore::Unlock(_vMasterKey))
387 return true;
390 return false;
393 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
395 bool fWasLocked = IsLocked();
398 LOCK(cs_wallet);
399 Lock();
401 CCrypter crypter;
402 CKeyingMaterial _vMasterKey;
403 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
405 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
406 return false;
407 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
408 return false;
409 if (CCryptoKeyStore::Unlock(_vMasterKey))
411 int64_t nStartTime = GetTimeMillis();
412 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
413 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
415 nStartTime = GetTimeMillis();
416 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
417 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
419 if (pMasterKey.second.nDeriveIterations < 25000)
420 pMasterKey.second.nDeriveIterations = 25000;
422 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
424 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
425 return false;
426 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
427 return false;
428 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
429 if (fWasLocked)
430 Lock();
431 return true;
436 return false;
439 void CWallet::SetBestChain(const CBlockLocator& loc)
441 CWalletDB walletdb(*dbw);
442 walletdb.WriteBestBlock(loc);
445 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
447 LOCK(cs_wallet); // nWalletVersion
448 if (nWalletVersion >= nVersion)
449 return true;
451 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
452 if (fExplicit && nVersion > nWalletMaxVersion)
453 nVersion = FEATURE_LATEST;
455 nWalletVersion = nVersion;
457 if (nVersion > nWalletMaxVersion)
458 nWalletMaxVersion = nVersion;
461 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
462 if (nWalletVersion > 40000)
463 pwalletdb->WriteMinVersion(nWalletVersion);
464 if (!pwalletdbIn)
465 delete pwalletdb;
468 return true;
471 bool CWallet::SetMaxVersion(int nVersion)
473 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
474 // cannot downgrade below current version
475 if (nWalletVersion > nVersion)
476 return false;
478 nWalletMaxVersion = nVersion;
480 return true;
483 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
485 std::set<uint256> result;
486 AssertLockHeld(cs_wallet);
488 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
489 if (it == mapWallet.end())
490 return result;
491 const CWalletTx& wtx = it->second;
493 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
495 for (const CTxIn& txin : wtx.tx->vin)
497 if (mapTxSpends.count(txin.prevout) <= 1)
498 continue; // No conflict if zero or one spends
499 range = mapTxSpends.equal_range(txin.prevout);
500 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
501 result.insert(_it->second);
503 return result;
506 bool CWallet::HasWalletSpend(const uint256& txid) const
508 AssertLockHeld(cs_wallet);
509 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
510 return (iter != mapTxSpends.end() && iter->first.hash == txid);
513 void CWallet::Flush(bool shutdown)
515 dbw->Flush(shutdown);
518 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
520 // We want all the wallet transactions in range to have the same metadata as
521 // the oldest (smallest nOrderPos).
522 // So: find smallest nOrderPos:
524 int nMinOrderPos = std::numeric_limits<int>::max();
525 const CWalletTx* copyFrom = nullptr;
526 for (TxSpends::iterator it = range.first; it != range.second; ++it)
528 const uint256& hash = it->second;
529 int n = mapWallet[hash].nOrderPos;
530 if (n < nMinOrderPos)
532 nMinOrderPos = n;
533 copyFrom = &mapWallet[hash];
537 assert(copyFrom);
539 // Now copy data from copyFrom to rest:
540 for (TxSpends::iterator it = range.first; it != range.second; ++it)
542 const uint256& hash = it->second;
543 CWalletTx* copyTo = &mapWallet[hash];
544 if (copyFrom == copyTo) continue;
545 assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
546 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
547 copyTo->mapValue = copyFrom->mapValue;
548 copyTo->vOrderForm = copyFrom->vOrderForm;
549 // fTimeReceivedIsTxTime not copied on purpose
550 // nTimeReceived not copied on purpose
551 copyTo->nTimeSmart = copyFrom->nTimeSmart;
552 copyTo->fFromMe = copyFrom->fFromMe;
553 copyTo->strFromAccount = copyFrom->strFromAccount;
554 // nOrderPos not copied on purpose
555 // cached members not copied on purpose
560 * Outpoint is spent if any non-conflicted transaction
561 * spends it:
563 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
565 const COutPoint outpoint(hash, n);
566 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
567 range = mapTxSpends.equal_range(outpoint);
569 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
571 const uint256& wtxid = it->second;
572 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
573 if (mit != mapWallet.end()) {
574 int depth = mit->second.GetDepthInMainChain();
575 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
576 return true; // Spent
579 return false;
582 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
584 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
586 std::pair<TxSpends::iterator, TxSpends::iterator> range;
587 range = mapTxSpends.equal_range(outpoint);
588 SyncMetaData(range);
592 void CWallet::AddToSpends(const uint256& wtxid)
594 auto it = mapWallet.find(wtxid);
595 assert(it != mapWallet.end());
596 CWalletTx& thisTx = it->second;
597 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
598 return;
600 for (const CTxIn& txin : thisTx.tx->vin)
601 AddToSpends(txin.prevout, wtxid);
604 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
606 if (IsCrypted())
607 return false;
609 CKeyingMaterial _vMasterKey;
611 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
612 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
614 CMasterKey kMasterKey;
616 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
617 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
619 CCrypter crypter;
620 int64_t nStartTime = GetTimeMillis();
621 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
622 kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
624 nStartTime = GetTimeMillis();
625 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
626 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
628 if (kMasterKey.nDeriveIterations < 25000)
629 kMasterKey.nDeriveIterations = 25000;
631 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
633 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
634 return false;
635 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
636 return false;
639 LOCK(cs_wallet);
640 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
641 assert(!pwalletdbEncryption);
642 pwalletdbEncryption = new CWalletDB(*dbw);
643 if (!pwalletdbEncryption->TxnBegin()) {
644 delete pwalletdbEncryption;
645 pwalletdbEncryption = nullptr;
646 return false;
648 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
650 if (!EncryptKeys(_vMasterKey))
652 pwalletdbEncryption->TxnAbort();
653 delete pwalletdbEncryption;
654 // We now probably have half of our keys encrypted in memory, and half not...
655 // die and let the user reload the unencrypted wallet.
656 assert(false);
659 // Encryption was introduced in version 0.4.0
660 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
662 if (!pwalletdbEncryption->TxnCommit()) {
663 delete pwalletdbEncryption;
664 // We now have keys encrypted in memory, but not on disk...
665 // die to avoid confusion and let the user reload the unencrypted wallet.
666 assert(false);
669 delete pwalletdbEncryption;
670 pwalletdbEncryption = nullptr;
672 Lock();
673 Unlock(strWalletPassphrase);
675 // if we are using HD, replace the HD master key (seed) with a new one
676 if (IsHDEnabled()) {
677 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
678 return false;
682 NewKeyPool();
683 Lock();
685 // Need to completely rewrite the wallet file; if we don't, bdb might keep
686 // bits of the unencrypted private key in slack space in the database file.
687 dbw->Rewrite();
690 NotifyStatusChanged(this);
692 return true;
695 DBErrors CWallet::ReorderTransactions()
697 LOCK(cs_wallet);
698 CWalletDB walletdb(*dbw);
700 // Old wallets didn't have any defined order for transactions
701 // Probably a bad idea to change the output of this
703 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
704 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
705 typedef std::multimap<int64_t, TxPair > TxItems;
706 TxItems txByTime;
708 for (auto& entry : mapWallet)
710 CWalletTx* wtx = &entry.second;
711 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
713 std::list<CAccountingEntry> acentries;
714 walletdb.ListAccountCreditDebit("", acentries);
715 for (CAccountingEntry& entry : acentries)
717 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
720 nOrderPosNext = 0;
721 std::vector<int64_t> nOrderPosOffsets;
722 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
724 CWalletTx *const pwtx = (*it).second.first;
725 CAccountingEntry *const pacentry = (*it).second.second;
726 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
728 if (nOrderPos == -1)
730 nOrderPos = nOrderPosNext++;
731 nOrderPosOffsets.push_back(nOrderPos);
733 if (pwtx)
735 if (!walletdb.WriteTx(*pwtx))
736 return DB_LOAD_FAIL;
738 else
739 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
740 return DB_LOAD_FAIL;
742 else
744 int64_t nOrderPosOff = 0;
745 for (const int64_t& nOffsetStart : nOrderPosOffsets)
747 if (nOrderPos >= nOffsetStart)
748 ++nOrderPosOff;
750 nOrderPos += nOrderPosOff;
751 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
753 if (!nOrderPosOff)
754 continue;
756 // Since we're changing the order, write it back
757 if (pwtx)
759 if (!walletdb.WriteTx(*pwtx))
760 return DB_LOAD_FAIL;
762 else
763 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
764 return DB_LOAD_FAIL;
767 walletdb.WriteOrderPosNext(nOrderPosNext);
769 return DB_LOAD_OK;
772 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
774 AssertLockHeld(cs_wallet); // nOrderPosNext
775 int64_t nRet = nOrderPosNext++;
776 if (pwalletdb) {
777 pwalletdb->WriteOrderPosNext(nOrderPosNext);
778 } else {
779 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
781 return nRet;
784 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
786 CWalletDB walletdb(*dbw);
787 if (!walletdb.TxnBegin())
788 return false;
790 int64_t nNow = GetAdjustedTime();
792 // Debit
793 CAccountingEntry debit;
794 debit.nOrderPos = IncOrderPosNext(&walletdb);
795 debit.strAccount = strFrom;
796 debit.nCreditDebit = -nAmount;
797 debit.nTime = nNow;
798 debit.strOtherAccount = strTo;
799 debit.strComment = strComment;
800 AddAccountingEntry(debit, &walletdb);
802 // Credit
803 CAccountingEntry credit;
804 credit.nOrderPos = IncOrderPosNext(&walletdb);
805 credit.strAccount = strTo;
806 credit.nCreditDebit = nAmount;
807 credit.nTime = nNow;
808 credit.strOtherAccount = strFrom;
809 credit.strComment = strComment;
810 AddAccountingEntry(credit, &walletdb);
812 if (!walletdb.TxnCommit())
813 return false;
815 return true;
818 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
820 CWalletDB walletdb(*dbw);
822 CAccount account;
823 walletdb.ReadAccount(strAccount, account);
825 if (!bForceNew) {
826 if (!account.vchPubKey.IsValid())
827 bForceNew = true;
828 else {
829 // Check if the current key has been used
830 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
831 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
832 it != mapWallet.end() && account.vchPubKey.IsValid();
833 ++it)
834 for (const CTxOut& txout : (*it).second.tx->vout)
835 if (txout.scriptPubKey == scriptPubKey) {
836 bForceNew = true;
837 break;
842 // Generate a new key
843 if (bForceNew) {
844 if (!GetKeyFromPool(account.vchPubKey, false))
845 return false;
847 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
848 walletdb.WriteAccount(strAccount, account);
851 pubKey = account.vchPubKey;
853 return true;
856 void CWallet::MarkDirty()
859 LOCK(cs_wallet);
860 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
861 item.second.MarkDirty();
865 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
867 LOCK(cs_wallet);
869 auto mi = mapWallet.find(originalHash);
871 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
872 assert(mi != mapWallet.end());
874 CWalletTx& wtx = (*mi).second;
876 // Ensure for now that we're not overwriting data
877 assert(wtx.mapValue.count("replaced_by_txid") == 0);
879 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
881 CWalletDB walletdb(*dbw, "r+");
883 bool success = true;
884 if (!walletdb.WriteTx(wtx)) {
885 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
886 success = false;
889 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
891 return success;
894 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
896 LOCK(cs_wallet);
898 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
900 uint256 hash = wtxIn.GetHash();
902 // Inserts only if not already there, returns tx inserted or tx found
903 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
904 CWalletTx& wtx = (*ret.first).second;
905 wtx.BindWallet(this);
906 bool fInsertedNew = ret.second;
907 if (fInsertedNew)
909 wtx.nTimeReceived = GetAdjustedTime();
910 wtx.nOrderPos = IncOrderPosNext(&walletdb);
911 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
912 wtx.nTimeSmart = ComputeTimeSmart(wtx);
913 AddToSpends(hash);
916 bool fUpdated = false;
917 if (!fInsertedNew)
919 // Merge
920 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
922 wtx.hashBlock = wtxIn.hashBlock;
923 fUpdated = true;
925 // If no longer abandoned, update
926 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
928 wtx.hashBlock = wtxIn.hashBlock;
929 fUpdated = true;
931 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
933 wtx.nIndex = wtxIn.nIndex;
934 fUpdated = true;
936 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
938 wtx.fFromMe = wtxIn.fFromMe;
939 fUpdated = true;
941 // If we have a witness-stripped version of this transaction, and we
942 // see a new version with a witness, then we must be upgrading a pre-segwit
943 // wallet. Store the new version of the transaction with the witness,
944 // as the stripped-version must be invalid.
945 // TODO: Store all versions of the transaction, instead of just one.
946 if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
947 wtx.SetTx(wtxIn.tx);
948 fUpdated = true;
952 //// debug print
953 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
955 // Write to disk
956 if (fInsertedNew || fUpdated)
957 if (!walletdb.WriteTx(wtx))
958 return false;
960 // Break debit/credit balance caches:
961 wtx.MarkDirty();
963 // Notify UI of new or updated transaction
964 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
966 // notify an external script when a wallet transaction comes in or is updated
967 std::string strCmd = gArgs.GetArg("-walletnotify", "");
969 if (!strCmd.empty())
971 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
972 boost::thread t(runCommand, strCmd); // thread runs free
975 return true;
978 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
980 uint256 hash = wtxIn.GetHash();
982 mapWallet[hash] = wtxIn;
983 CWalletTx& wtx = mapWallet[hash];
984 wtx.BindWallet(this);
985 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
986 AddToSpends(hash);
987 for (const CTxIn& txin : wtx.tx->vin) {
988 auto it = mapWallet.find(txin.prevout.hash);
989 if (it != mapWallet.end()) {
990 CWalletTx& prevtx = it->second;
991 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
992 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
997 return true;
1001 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1002 * be set when the transaction was known to be included in a block. When
1003 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1004 * notifications happen and cached balances are marked dirty.
1006 * If fUpdate is true, existing transactions will be updated.
1007 * TODO: One exception to this is that the abandoned state is cleared under the
1008 * assumption that any further notification of a transaction that was considered
1009 * abandoned is an indication that it is not safe to be considered abandoned.
1010 * Abandoned state should probably be more carefully tracked via different
1011 * posInBlock signals or by checking mempool presence when necessary.
1013 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1015 const CTransaction& tx = *ptx;
1017 AssertLockHeld(cs_wallet);
1019 if (pIndex != nullptr) {
1020 for (const CTxIn& txin : tx.vin) {
1021 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1022 while (range.first != range.second) {
1023 if (range.first->second != tx.GetHash()) {
1024 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);
1025 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1027 range.first++;
1032 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1033 if (fExisted && !fUpdate) return false;
1034 if (fExisted || IsMine(tx) || IsFromMe(tx))
1036 /* Check if any keys in the wallet keypool that were supposed to be unused
1037 * have appeared in a new transaction. If so, remove those keys from the keypool.
1038 * This can happen when restoring an old wallet backup that does not contain
1039 * the mostly recently created transactions from newer versions of the wallet.
1042 // loop though all outputs
1043 for (const CTxOut& txout: tx.vout) {
1044 // extract addresses and check if they match with an unused keypool key
1045 std::vector<CKeyID> vAffected;
1046 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1047 for (const CKeyID &keyid : vAffected) {
1048 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1049 if (mi != m_pool_key_to_index.end()) {
1050 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1051 MarkReserveKeysAsUsed(mi->second);
1053 if (!TopUpKeyPool()) {
1054 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1060 CWalletTx wtx(this, ptx);
1062 // Get merkle branch if transaction was found in a block
1063 if (pIndex != nullptr)
1064 wtx.SetMerkleBranch(pIndex, posInBlock);
1066 return AddToWallet(wtx, false);
1069 return false;
1072 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1074 LOCK2(cs_main, cs_wallet);
1075 const CWalletTx* wtx = GetWalletTx(hashTx);
1076 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1079 bool CWallet::AbandonTransaction(const uint256& hashTx)
1081 LOCK2(cs_main, cs_wallet);
1083 CWalletDB walletdb(*dbw, "r+");
1085 std::set<uint256> todo;
1086 std::set<uint256> done;
1088 // Can't mark abandoned if confirmed or in mempool
1089 auto it = mapWallet.find(hashTx);
1090 assert(it != mapWallet.end());
1091 CWalletTx& origtx = it->second;
1092 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1093 return false;
1096 todo.insert(hashTx);
1098 while (!todo.empty()) {
1099 uint256 now = *todo.begin();
1100 todo.erase(now);
1101 done.insert(now);
1102 auto it = mapWallet.find(now);
1103 assert(it != mapWallet.end());
1104 CWalletTx& wtx = it->second;
1105 int currentconfirm = wtx.GetDepthInMainChain();
1106 // If the orig tx was not in block, none of its spends can be
1107 assert(currentconfirm <= 0);
1108 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1109 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1110 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1111 assert(!wtx.InMempool());
1112 wtx.nIndex = -1;
1113 wtx.setAbandoned();
1114 wtx.MarkDirty();
1115 walletdb.WriteTx(wtx);
1116 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1117 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1118 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1119 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1120 if (!done.count(iter->second)) {
1121 todo.insert(iter->second);
1123 iter++;
1125 // If a transaction changes 'conflicted' state, that changes the balance
1126 // available of the outputs it spends. So force those to be recomputed
1127 for (const CTxIn& txin : wtx.tx->vin)
1129 auto it = mapWallet.find(txin.prevout.hash);
1130 if (it != mapWallet.end()) {
1131 it->second.MarkDirty();
1137 return true;
1140 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1142 LOCK2(cs_main, cs_wallet);
1144 int conflictconfirms = 0;
1145 if (mapBlockIndex.count(hashBlock)) {
1146 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1147 if (chainActive.Contains(pindex)) {
1148 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1151 // If number of conflict confirms cannot be determined, this means
1152 // that the block is still unknown or not yet part of the main chain,
1153 // for example when loading the wallet during a reindex. Do nothing in that
1154 // case.
1155 if (conflictconfirms >= 0)
1156 return;
1158 // Do not flush the wallet here for performance reasons
1159 CWalletDB walletdb(*dbw, "r+", false);
1161 std::set<uint256> todo;
1162 std::set<uint256> done;
1164 todo.insert(hashTx);
1166 while (!todo.empty()) {
1167 uint256 now = *todo.begin();
1168 todo.erase(now);
1169 done.insert(now);
1170 auto it = mapWallet.find(now);
1171 assert(it != mapWallet.end());
1172 CWalletTx& wtx = it->second;
1173 int currentconfirm = wtx.GetDepthInMainChain();
1174 if (conflictconfirms < currentconfirm) {
1175 // Block is 'more conflicted' than current confirm; update.
1176 // Mark transaction as conflicted with this block.
1177 wtx.nIndex = -1;
1178 wtx.hashBlock = hashBlock;
1179 wtx.MarkDirty();
1180 walletdb.WriteTx(wtx);
1181 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1182 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1183 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1184 if (!done.count(iter->second)) {
1185 todo.insert(iter->second);
1187 iter++;
1189 // If a transaction changes 'conflicted' state, that changes the balance
1190 // available of the outputs it spends. So force those to be recomputed
1191 for (const CTxIn& txin : wtx.tx->vin) {
1192 auto it = mapWallet.find(txin.prevout.hash);
1193 if (it != mapWallet.end()) {
1194 it->second.MarkDirty();
1201 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1202 const CTransaction& tx = *ptx;
1204 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1205 return; // Not one of ours
1207 // If a transaction changes 'conflicted' state, that changes the balance
1208 // available of the outputs it spends. So force those to be
1209 // recomputed, also:
1210 for (const CTxIn& txin : tx.vin) {
1211 auto it = mapWallet.find(txin.prevout.hash);
1212 if (it != mapWallet.end()) {
1213 it->second.MarkDirty();
1218 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1219 LOCK2(cs_main, cs_wallet);
1220 SyncTransaction(ptx);
1222 auto it = mapWallet.find(ptx->GetHash());
1223 if (it != mapWallet.end()) {
1224 it->second.fInMempool = true;
1228 void CWallet::TransactionRemovedFromMempool(const CTransactionRef &ptx) {
1229 LOCK(cs_wallet);
1230 auto it = mapWallet.find(ptx->GetHash());
1231 if (it != mapWallet.end()) {
1232 it->second.fInMempool = false;
1236 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1237 LOCK2(cs_main, cs_wallet);
1238 // TODO: Temporarily ensure that mempool removals are notified before
1239 // connected transactions. This shouldn't matter, but the abandoned
1240 // state of transactions in our wallet is currently cleared when we
1241 // receive another notification and there is a race condition where
1242 // notification of a connected conflict might cause an outside process
1243 // to abandon a transaction and then have it inadvertently cleared by
1244 // the notification that the conflicted transaction was evicted.
1246 for (const CTransactionRef& ptx : vtxConflicted) {
1247 SyncTransaction(ptx);
1248 TransactionRemovedFromMempool(ptx);
1250 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1251 SyncTransaction(pblock->vtx[i], pindex, i);
1252 TransactionRemovedFromMempool(pblock->vtx[i]);
1255 m_last_block_processed = pindex;
1258 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1259 LOCK2(cs_main, cs_wallet);
1261 for (const CTransactionRef& ptx : pblock->vtx) {
1262 SyncTransaction(ptx);
1268 void CWallet::BlockUntilSyncedToCurrentChain() {
1269 AssertLockNotHeld(cs_main);
1270 AssertLockNotHeld(cs_wallet);
1273 // Skip the queue-draining stuff if we know we're caught up with
1274 // chainActive.Tip()...
1275 // We could also take cs_wallet here, and call m_last_block_processed
1276 // protected by cs_wallet instead of cs_main, but as long as we need
1277 // cs_main here anyway, its easier to just call it cs_main-protected.
1278 LOCK(cs_main);
1279 const CBlockIndex* initialChainTip = chainActive.Tip();
1281 if (m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) {
1282 return;
1286 // ...otherwise put a callback in the validation interface queue and wait
1287 // for the queue to drain enough to execute it (indicating we are caught up
1288 // at least with the time we entered this function).
1290 std::promise<void> promise;
1291 CallFunctionInValidationInterfaceQueue([&promise] {
1292 promise.set_value();
1294 promise.get_future().wait();
1298 isminetype CWallet::IsMine(const CTxIn &txin) const
1301 LOCK(cs_wallet);
1302 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1303 if (mi != mapWallet.end())
1305 const CWalletTx& prev = (*mi).second;
1306 if (txin.prevout.n < prev.tx->vout.size())
1307 return IsMine(prev.tx->vout[txin.prevout.n]);
1310 return ISMINE_NO;
1313 // Note that this function doesn't distinguish between a 0-valued input,
1314 // and a not-"is mine" (according to the filter) input.
1315 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1318 LOCK(cs_wallet);
1319 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1320 if (mi != mapWallet.end())
1322 const CWalletTx& prev = (*mi).second;
1323 if (txin.prevout.n < prev.tx->vout.size())
1324 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1325 return prev.tx->vout[txin.prevout.n].nValue;
1328 return 0;
1331 isminetype CWallet::IsMine(const CTxOut& txout) const
1333 return ::IsMine(*this, txout.scriptPubKey);
1336 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1338 if (!MoneyRange(txout.nValue))
1339 throw std::runtime_error(std::string(__func__) + ": value out of range");
1340 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1343 bool CWallet::IsChange(const CTxOut& txout) const
1345 // TODO: fix handling of 'change' outputs. The assumption is that any
1346 // payment to a script that is ours, but is not in the address book
1347 // is change. That assumption is likely to break when we implement multisignature
1348 // wallets that return change back into a multi-signature-protected address;
1349 // a better way of identifying which outputs are 'the send' and which are
1350 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1351 // which output, if any, was change).
1352 if (::IsMine(*this, txout.scriptPubKey))
1354 CTxDestination address;
1355 if (!ExtractDestination(txout.scriptPubKey, address))
1356 return true;
1358 LOCK(cs_wallet);
1359 if (!mapAddressBook.count(address))
1360 return true;
1362 return false;
1365 CAmount CWallet::GetChange(const CTxOut& txout) const
1367 if (!MoneyRange(txout.nValue))
1368 throw std::runtime_error(std::string(__func__) + ": value out of range");
1369 return (IsChange(txout) ? txout.nValue : 0);
1372 bool CWallet::IsMine(const CTransaction& tx) const
1374 for (const CTxOut& txout : tx.vout)
1375 if (IsMine(txout))
1376 return true;
1377 return false;
1380 bool CWallet::IsFromMe(const CTransaction& tx) const
1382 return (GetDebit(tx, ISMINE_ALL) > 0);
1385 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1387 CAmount nDebit = 0;
1388 for (const CTxIn& txin : tx.vin)
1390 nDebit += GetDebit(txin, filter);
1391 if (!MoneyRange(nDebit))
1392 throw std::runtime_error(std::string(__func__) + ": value out of range");
1394 return nDebit;
1397 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1399 LOCK(cs_wallet);
1401 for (const CTxIn& txin : tx.vin)
1403 auto mi = mapWallet.find(txin.prevout.hash);
1404 if (mi == mapWallet.end())
1405 return false; // any unknown inputs can't be from us
1407 const CWalletTx& prev = (*mi).second;
1409 if (txin.prevout.n >= prev.tx->vout.size())
1410 return false; // invalid input!
1412 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1413 return false;
1415 return true;
1418 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1420 CAmount nCredit = 0;
1421 for (const CTxOut& txout : tx.vout)
1423 nCredit += GetCredit(txout, filter);
1424 if (!MoneyRange(nCredit))
1425 throw std::runtime_error(std::string(__func__) + ": value out of range");
1427 return nCredit;
1430 CAmount CWallet::GetChange(const CTransaction& tx) const
1432 CAmount nChange = 0;
1433 for (const CTxOut& txout : tx.vout)
1435 nChange += GetChange(txout);
1436 if (!MoneyRange(nChange))
1437 throw std::runtime_error(std::string(__func__) + ": value out of range");
1439 return nChange;
1442 CPubKey CWallet::GenerateNewHDMasterKey()
1444 CKey key;
1445 key.MakeNewKey(true);
1447 int64_t nCreationTime = GetTime();
1448 CKeyMetadata metadata(nCreationTime);
1450 // calculate the pubkey
1451 CPubKey pubkey = key.GetPubKey();
1452 assert(key.VerifyPubKey(pubkey));
1454 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1455 metadata.hdKeypath = "m";
1456 metadata.hdMasterKeyID = pubkey.GetID();
1459 LOCK(cs_wallet);
1461 // mem store the metadata
1462 mapKeyMetadata[pubkey.GetID()] = metadata;
1464 // write the key&metadata to the database
1465 if (!AddKeyPubKey(key, pubkey))
1466 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1469 return pubkey;
1472 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1474 LOCK(cs_wallet);
1475 // store the keyid (hash160) together with
1476 // the child index counter in the database
1477 // as a hdchain object
1478 CHDChain newHdChain;
1479 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1480 newHdChain.masterKeyID = pubkey.GetID();
1481 SetHDChain(newHdChain, false);
1483 return true;
1486 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1488 LOCK(cs_wallet);
1489 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1490 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1492 hdChain = chain;
1493 return true;
1496 bool CWallet::IsHDEnabled() const
1498 return !hdChain.masterKeyID.IsNull();
1501 int64_t CWalletTx::GetTxTime() const
1503 int64_t n = nTimeSmart;
1504 return n ? n : nTimeReceived;
1507 int CWalletTx::GetRequestCount() const
1509 // Returns -1 if it wasn't being tracked
1510 int nRequests = -1;
1512 LOCK(pwallet->cs_wallet);
1513 if (IsCoinBase())
1515 // Generated block
1516 if (!hashUnset())
1518 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1519 if (mi != pwallet->mapRequestCount.end())
1520 nRequests = (*mi).second;
1523 else
1525 // Did anyone request this transaction?
1526 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1527 if (mi != pwallet->mapRequestCount.end())
1529 nRequests = (*mi).second;
1531 // How about the block it's in?
1532 if (nRequests == 0 && !hashUnset())
1534 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1535 if (_mi != pwallet->mapRequestCount.end())
1536 nRequests = (*_mi).second;
1537 else
1538 nRequests = 1; // If it's in someone else's block it must have got out
1543 return nRequests;
1546 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1547 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1549 nFee = 0;
1550 listReceived.clear();
1551 listSent.clear();
1552 strSentAccount = strFromAccount;
1554 // Compute fee:
1555 CAmount nDebit = GetDebit(filter);
1556 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1558 CAmount nValueOut = tx->GetValueOut();
1559 nFee = nDebit - nValueOut;
1562 // Sent/received.
1563 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1565 const CTxOut& txout = tx->vout[i];
1566 isminetype fIsMine = pwallet->IsMine(txout);
1567 // Only need to handle txouts if AT LEAST one of these is true:
1568 // 1) they debit from us (sent)
1569 // 2) the output is to us (received)
1570 if (nDebit > 0)
1572 // Don't report 'change' txouts
1573 if (pwallet->IsChange(txout))
1574 continue;
1576 else if (!(fIsMine & filter))
1577 continue;
1579 // In either case, we need to get the destination address
1580 CTxDestination address;
1582 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1584 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1585 this->GetHash().ToString());
1586 address = CNoDestination();
1589 COutputEntry output = {address, txout.nValue, (int)i};
1591 // If we are debited by the transaction, add the output as a "sent" entry
1592 if (nDebit > 0)
1593 listSent.push_back(output);
1595 // If we are receiving the output, add it as a "received" entry
1596 if (fIsMine & filter)
1597 listReceived.push_back(output);
1603 * Scan active chain for relevant transactions after importing keys. This should
1604 * be called whenever new keys are added to the wallet, with the oldest key
1605 * creation time.
1607 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1608 * returned will be higher than startTime if relevant blocks could not be read.
1610 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1612 AssertLockHeld(cs_main);
1613 AssertLockHeld(cs_wallet);
1615 // Find starting block. May be null if nCreateTime is greater than the
1616 // highest blockchain timestamp, in which case there is nothing that needs
1617 // to be scanned.
1618 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1619 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1621 if (startBlock) {
1622 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1623 if (failedBlock) {
1624 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1627 return startTime;
1631 * Scan the block chain (starting in pindexStart) for transactions
1632 * from or to us. If fUpdate is true, found transactions that already
1633 * exist in the wallet will be updated.
1635 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1636 * possible (due to pruning or corruption), returns pointer to the most recent
1637 * block that could not be scanned.
1639 * If pindexStop is not a nullptr, the scan will stop at the block-index
1640 * defined by pindexStop
1642 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1644 int64_t nNow = GetTime();
1645 const CChainParams& chainParams = Params();
1647 if (pindexStop) {
1648 assert(pindexStop->nHeight >= pindexStart->nHeight);
1651 CBlockIndex* pindex = pindexStart;
1652 CBlockIndex* ret = nullptr;
1654 LOCK2(cs_main, cs_wallet);
1655 fAbortRescan = false;
1656 fScanningWallet = true;
1658 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1659 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1660 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1661 while (pindex && !fAbortRescan)
1663 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1664 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1665 if (GetTime() >= nNow + 60) {
1666 nNow = GetTime();
1667 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1670 CBlock block;
1671 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1672 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1673 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1675 } else {
1676 ret = pindex;
1678 if (pindex == pindexStop) {
1679 break;
1681 pindex = chainActive.Next(pindex);
1683 if (pindex && fAbortRescan) {
1684 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1686 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1688 fScanningWallet = false;
1690 return ret;
1693 void CWallet::ReacceptWalletTransactions()
1695 // If transactions aren't being broadcasted, don't let them into local mempool either
1696 if (!fBroadcastTransactions)
1697 return;
1698 LOCK2(cs_main, cs_wallet);
1699 std::map<int64_t, CWalletTx*> mapSorted;
1701 // Sort pending wallet transactions based on their initial wallet insertion order
1702 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1704 const uint256& wtxid = item.first;
1705 CWalletTx& wtx = item.second;
1706 assert(wtx.GetHash() == wtxid);
1708 int nDepth = wtx.GetDepthInMainChain();
1710 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1711 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1715 // Try to add wallet transactions to memory pool
1716 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1717 CWalletTx& wtx = *(item.second);
1718 CValidationState state;
1719 wtx.AcceptToMemoryPool(maxTxFee, state);
1723 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1725 assert(pwallet->GetBroadcastTransactions());
1726 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1728 CValidationState state;
1729 /* GetDepthInMainChain already catches known conflicts. */
1730 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1731 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1732 if (connman) {
1733 CInv inv(MSG_TX, GetHash());
1734 connman->ForEachNode([&inv](CNode* pnode)
1736 pnode->PushInventory(inv);
1738 return true;
1742 return false;
1745 std::set<uint256> CWalletTx::GetConflicts() const
1747 std::set<uint256> result;
1748 if (pwallet != nullptr)
1750 uint256 myHash = GetHash();
1751 result = pwallet->GetConflicts(myHash);
1752 result.erase(myHash);
1754 return result;
1757 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1759 if (tx->vin.empty())
1760 return 0;
1762 CAmount debit = 0;
1763 if(filter & ISMINE_SPENDABLE)
1765 if (fDebitCached)
1766 debit += nDebitCached;
1767 else
1769 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1770 fDebitCached = true;
1771 debit += nDebitCached;
1774 if(filter & ISMINE_WATCH_ONLY)
1776 if(fWatchDebitCached)
1777 debit += nWatchDebitCached;
1778 else
1780 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1781 fWatchDebitCached = true;
1782 debit += nWatchDebitCached;
1785 return debit;
1788 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1790 // Must wait until coinbase is safely deep enough in the chain before valuing it
1791 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1792 return 0;
1794 CAmount credit = 0;
1795 if (filter & ISMINE_SPENDABLE)
1797 // GetBalance can assume transactions in mapWallet won't change
1798 if (fCreditCached)
1799 credit += nCreditCached;
1800 else
1802 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1803 fCreditCached = true;
1804 credit += nCreditCached;
1807 if (filter & ISMINE_WATCH_ONLY)
1809 if (fWatchCreditCached)
1810 credit += nWatchCreditCached;
1811 else
1813 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1814 fWatchCreditCached = true;
1815 credit += nWatchCreditCached;
1818 return credit;
1821 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1823 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1825 if (fUseCache && fImmatureCreditCached)
1826 return nImmatureCreditCached;
1827 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1828 fImmatureCreditCached = true;
1829 return nImmatureCreditCached;
1832 return 0;
1835 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1837 if (pwallet == nullptr)
1838 return 0;
1840 // Must wait until coinbase is safely deep enough in the chain before valuing it
1841 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1842 return 0;
1844 if (fUseCache && fAvailableCreditCached)
1845 return nAvailableCreditCached;
1847 CAmount nCredit = 0;
1848 uint256 hashTx = GetHash();
1849 for (unsigned int i = 0; i < tx->vout.size(); i++)
1851 if (!pwallet->IsSpent(hashTx, i))
1853 const CTxOut &txout = tx->vout[i];
1854 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1855 if (!MoneyRange(nCredit))
1856 throw std::runtime_error(std::string(__func__) + " : value out of range");
1860 nAvailableCreditCached = nCredit;
1861 fAvailableCreditCached = true;
1862 return nCredit;
1865 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1867 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1869 if (fUseCache && fImmatureWatchCreditCached)
1870 return nImmatureWatchCreditCached;
1871 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1872 fImmatureWatchCreditCached = true;
1873 return nImmatureWatchCreditCached;
1876 return 0;
1879 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1881 if (pwallet == nullptr)
1882 return 0;
1884 // Must wait until coinbase is safely deep enough in the chain before valuing it
1885 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1886 return 0;
1888 if (fUseCache && fAvailableWatchCreditCached)
1889 return nAvailableWatchCreditCached;
1891 CAmount nCredit = 0;
1892 for (unsigned int i = 0; i < tx->vout.size(); i++)
1894 if (!pwallet->IsSpent(GetHash(), i))
1896 const CTxOut &txout = tx->vout[i];
1897 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1898 if (!MoneyRange(nCredit))
1899 throw std::runtime_error(std::string(__func__) + ": value out of range");
1903 nAvailableWatchCreditCached = nCredit;
1904 fAvailableWatchCreditCached = true;
1905 return nCredit;
1908 CAmount CWalletTx::GetChange() const
1910 if (fChangeCached)
1911 return nChangeCached;
1912 nChangeCached = pwallet->GetChange(*tx);
1913 fChangeCached = true;
1914 return nChangeCached;
1917 bool CWalletTx::InMempool() const
1919 return fInMempool;
1922 bool CWalletTx::IsTrusted() const
1924 // Quick answer in most cases
1925 if (!CheckFinalTx(*tx))
1926 return false;
1927 int nDepth = GetDepthInMainChain();
1928 if (nDepth >= 1)
1929 return true;
1930 if (nDepth < 0)
1931 return false;
1932 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1933 return false;
1935 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1936 if (!InMempool())
1937 return false;
1939 // Trusted if all inputs are from us and are in the mempool:
1940 for (const CTxIn& txin : tx->vin)
1942 // Transactions not sent by us: not trusted
1943 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1944 if (parent == nullptr)
1945 return false;
1946 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1947 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1948 return false;
1950 return true;
1953 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1955 CMutableTransaction tx1 = *this->tx;
1956 CMutableTransaction tx2 = *_tx.tx;
1957 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1958 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1959 return CTransaction(tx1) == CTransaction(tx2);
1962 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1964 std::vector<uint256> result;
1966 LOCK(cs_wallet);
1968 // Sort them in chronological order
1969 std::multimap<unsigned int, CWalletTx*> mapSorted;
1970 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1972 CWalletTx& wtx = item.second;
1973 // Don't rebroadcast if newer than nTime:
1974 if (wtx.nTimeReceived > nTime)
1975 continue;
1976 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1978 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1980 CWalletTx& wtx = *item.second;
1981 if (wtx.RelayWalletTransaction(connman))
1982 result.push_back(wtx.GetHash());
1984 return result;
1987 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1989 // Do this infrequently and randomly to avoid giving away
1990 // that these are our transactions.
1991 if (GetTime() < nNextResend || !fBroadcastTransactions)
1992 return;
1993 bool fFirst = (nNextResend == 0);
1994 nNextResend = GetTime() + GetRand(30 * 60);
1995 if (fFirst)
1996 return;
1998 // Only do it if there's been a new block since last time
1999 if (nBestBlockTime < nLastResend)
2000 return;
2001 nLastResend = GetTime();
2003 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2004 // block was found:
2005 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2006 if (!relayed.empty())
2007 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2010 /** @} */ // end of mapWallet
2015 /** @defgroup Actions
2017 * @{
2021 CAmount CWallet::GetBalance() const
2023 CAmount nTotal = 0;
2025 LOCK2(cs_main, cs_wallet);
2026 for (const auto& entry : mapWallet)
2028 const CWalletTx* pcoin = &entry.second;
2029 if (pcoin->IsTrusted())
2030 nTotal += pcoin->GetAvailableCredit();
2034 return nTotal;
2037 CAmount CWallet::GetUnconfirmedBalance() const
2039 CAmount nTotal = 0;
2041 LOCK2(cs_main, cs_wallet);
2042 for (const auto& entry : mapWallet)
2044 const CWalletTx* pcoin = &entry.second;
2045 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2046 nTotal += pcoin->GetAvailableCredit();
2049 return nTotal;
2052 CAmount CWallet::GetImmatureBalance() const
2054 CAmount nTotal = 0;
2056 LOCK2(cs_main, cs_wallet);
2057 for (const auto& entry : mapWallet)
2059 const CWalletTx* pcoin = &entry.second;
2060 nTotal += pcoin->GetImmatureCredit();
2063 return nTotal;
2066 CAmount CWallet::GetWatchOnlyBalance() const
2068 CAmount nTotal = 0;
2070 LOCK2(cs_main, cs_wallet);
2071 for (const auto& entry : mapWallet)
2073 const CWalletTx* pcoin = &entry.second;
2074 if (pcoin->IsTrusted())
2075 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2079 return nTotal;
2082 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2084 CAmount nTotal = 0;
2086 LOCK2(cs_main, cs_wallet);
2087 for (const auto& entry : mapWallet)
2089 const CWalletTx* pcoin = &entry.second;
2090 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2091 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2094 return nTotal;
2097 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2099 CAmount nTotal = 0;
2101 LOCK2(cs_main, cs_wallet);
2102 for (const auto& entry : mapWallet)
2104 const CWalletTx* pcoin = &entry.second;
2105 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2108 return nTotal;
2111 // Calculate total balance in a different way from GetBalance. The biggest
2112 // difference is that GetBalance sums up all unspent TxOuts paying to the
2113 // wallet, while this sums up both spent and unspent TxOuts paying to the
2114 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2115 // also has fewer restrictions on which unconfirmed transactions are considered
2116 // trusted.
2117 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2119 LOCK2(cs_main, cs_wallet);
2121 CAmount balance = 0;
2122 for (const auto& entry : mapWallet) {
2123 const CWalletTx& wtx = entry.second;
2124 const int depth = wtx.GetDepthInMainChain();
2125 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2126 continue;
2129 // Loop through tx outputs and add incoming payments. For outgoing txs,
2130 // treat change outputs specially, as part of the amount debited.
2131 CAmount debit = wtx.GetDebit(filter);
2132 const bool outgoing = debit > 0;
2133 for (const CTxOut& out : wtx.tx->vout) {
2134 if (outgoing && IsChange(out)) {
2135 debit -= out.nValue;
2136 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2137 balance += out.nValue;
2141 // For outgoing txs, subtract amount debited.
2142 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2143 balance -= debit;
2147 if (account) {
2148 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2151 return balance;
2154 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2156 LOCK2(cs_main, cs_wallet);
2158 CAmount balance = 0;
2159 std::vector<COutput> vCoins;
2160 AvailableCoins(vCoins, true, coinControl);
2161 for (const COutput& out : vCoins) {
2162 if (out.fSpendable) {
2163 balance += out.tx->tx->vout[out.i].nValue;
2166 return balance;
2169 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
2171 vCoins.clear();
2174 LOCK2(cs_main, cs_wallet);
2176 CAmount nTotal = 0;
2178 for (const auto& entry : mapWallet)
2180 const uint256& wtxid = entry.first;
2181 const CWalletTx* pcoin = &entry.second;
2183 if (!CheckFinalTx(*pcoin->tx))
2184 continue;
2186 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2187 continue;
2189 int nDepth = pcoin->GetDepthInMainChain();
2190 if (nDepth < 0)
2191 continue;
2193 // We should not consider coins which aren't at least in our mempool
2194 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2195 if (nDepth == 0 && !pcoin->InMempool())
2196 continue;
2198 bool safeTx = pcoin->IsTrusted();
2200 // We should not consider coins from transactions that are replacing
2201 // other transactions.
2203 // Example: There is a transaction A which is replaced by bumpfee
2204 // transaction B. In this case, we want to prevent creation of
2205 // a transaction B' which spends an output of B.
2207 // Reason: If transaction A were initially confirmed, transactions B
2208 // and B' would no longer be valid, so the user would have to create
2209 // a new transaction C to replace B'. However, in the case of a
2210 // one-block reorg, transactions B' and C might BOTH be accepted,
2211 // when the user only wanted one of them. Specifically, there could
2212 // be a 1-block reorg away from the chain where transactions A and C
2213 // were accepted to another chain where B, B', and C were all
2214 // accepted.
2215 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2216 safeTx = false;
2219 // Similarly, we should not consider coins from transactions that
2220 // have been replaced. In the example above, we would want to prevent
2221 // creation of a transaction A' spending an output of A, because if
2222 // transaction B were initially confirmed, conflicting with A and
2223 // A', we wouldn't want to the user to create a transaction D
2224 // intending to replace A', but potentially resulting in a scenario
2225 // where A, A', and D could all be accepted (instead of just B and
2226 // D, or just A and A' like the user would want).
2227 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2228 safeTx = false;
2231 if (fOnlySafe && !safeTx) {
2232 continue;
2235 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2236 continue;
2238 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2239 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2240 continue;
2242 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2243 continue;
2245 if (IsLockedCoin(entry.first, i))
2246 continue;
2248 if (IsSpent(wtxid, i))
2249 continue;
2251 isminetype mine = IsMine(pcoin->tx->vout[i]);
2253 if (mine == ISMINE_NO) {
2254 continue;
2257 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2258 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2260 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2262 // Checks the sum amount of all UTXO's.
2263 if (nMinimumSumAmount != MAX_MONEY) {
2264 nTotal += pcoin->tx->vout[i].nValue;
2266 if (nTotal >= nMinimumSumAmount) {
2267 return;
2271 // Checks the maximum number of UTXO's.
2272 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2273 return;
2280 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2282 // TODO: Add AssertLockHeld(cs_wallet) here.
2284 // Because the return value from this function contains pointers to
2285 // CWalletTx objects, callers to this function really should acquire the
2286 // cs_wallet lock before calling it. However, the current caller doesn't
2287 // acquire this lock yet. There was an attempt to add the missing lock in
2288 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2289 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2290 // avoid adding some extra complexity to the Qt code.
2292 std::map<CTxDestination, std::vector<COutput>> result;
2294 std::vector<COutput> availableCoins;
2295 AvailableCoins(availableCoins);
2297 LOCK2(cs_main, cs_wallet);
2298 for (auto& coin : availableCoins) {
2299 CTxDestination address;
2300 if (coin.fSpendable &&
2301 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2302 result[address].emplace_back(std::move(coin));
2306 std::vector<COutPoint> lockedCoins;
2307 ListLockedCoins(lockedCoins);
2308 for (const auto& output : lockedCoins) {
2309 auto it = mapWallet.find(output.hash);
2310 if (it != mapWallet.end()) {
2311 int depth = it->second.GetDepthInMainChain();
2312 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2313 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2314 CTxDestination address;
2315 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2316 result[address].emplace_back(
2317 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2323 return result;
2326 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2328 const CTransaction* ptx = &tx;
2329 int n = output;
2330 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2331 const COutPoint& prevout = ptx->vin[0].prevout;
2332 auto it = mapWallet.find(prevout.hash);
2333 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2334 !IsMine(it->second.tx->vout[prevout.n])) {
2335 break;
2337 ptx = it->second.tx.get();
2338 n = prevout.n;
2340 return ptx->vout[n];
2343 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2344 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2346 std::vector<char> vfIncluded;
2348 vfBest.assign(vValue.size(), true);
2349 nBest = nTotalLower;
2351 FastRandomContext insecure_rand;
2353 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2355 vfIncluded.assign(vValue.size(), false);
2356 CAmount nTotal = 0;
2357 bool fReachedTarget = false;
2358 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2360 for (unsigned int i = 0; i < vValue.size(); i++)
2362 //The solver here uses a randomized algorithm,
2363 //the randomness serves no real security purpose but is just
2364 //needed to prevent degenerate behavior and it is important
2365 //that the rng is fast. We do not use a constant random sequence,
2366 //because there may be some privacy improvement by making
2367 //the selection random.
2368 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2370 nTotal += vValue[i].txout.nValue;
2371 vfIncluded[i] = true;
2372 if (nTotal >= nTargetValue)
2374 fReachedTarget = true;
2375 if (nTotal < nBest)
2377 nBest = nTotal;
2378 vfBest = vfIncluded;
2380 nTotal -= vValue[i].txout.nValue;
2381 vfIncluded[i] = false;
2389 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2390 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2392 setCoinsRet.clear();
2393 nValueRet = 0;
2395 // List of values less than target
2396 boost::optional<CInputCoin> coinLowestLarger;
2397 std::vector<CInputCoin> vValue;
2398 CAmount nTotalLower = 0;
2400 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2402 for (const COutput &output : vCoins)
2404 if (!output.fSpendable)
2405 continue;
2407 const CWalletTx *pcoin = output.tx;
2409 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2410 continue;
2412 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2413 continue;
2415 int i = output.i;
2417 CInputCoin coin = CInputCoin(pcoin, i);
2419 if (coin.txout.nValue == nTargetValue)
2421 setCoinsRet.insert(coin);
2422 nValueRet += coin.txout.nValue;
2423 return true;
2425 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2427 vValue.push_back(coin);
2428 nTotalLower += coin.txout.nValue;
2430 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2432 coinLowestLarger = coin;
2436 if (nTotalLower == nTargetValue)
2438 for (const auto& input : vValue)
2440 setCoinsRet.insert(input);
2441 nValueRet += input.txout.nValue;
2443 return true;
2446 if (nTotalLower < nTargetValue)
2448 if (!coinLowestLarger)
2449 return false;
2450 setCoinsRet.insert(coinLowestLarger.get());
2451 nValueRet += coinLowestLarger->txout.nValue;
2452 return true;
2455 // Solve subset sum by stochastic approximation
2456 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2457 std::reverse(vValue.begin(), vValue.end());
2458 std::vector<char> vfBest;
2459 CAmount nBest;
2461 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2462 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2463 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2465 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2466 // or the next bigger coin is closer), return the bigger coin
2467 if (coinLowestLarger &&
2468 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2470 setCoinsRet.insert(coinLowestLarger.get());
2471 nValueRet += coinLowestLarger->txout.nValue;
2473 else {
2474 for (unsigned int i = 0; i < vValue.size(); i++)
2475 if (vfBest[i])
2477 setCoinsRet.insert(vValue[i]);
2478 nValueRet += vValue[i].txout.nValue;
2481 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2482 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2483 for (unsigned int i = 0; i < vValue.size(); i++) {
2484 if (vfBest[i]) {
2485 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2488 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2492 return true;
2495 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2497 std::vector<COutput> vCoins(vAvailableCoins);
2499 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2500 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2502 for (const COutput& out : vCoins)
2504 if (!out.fSpendable)
2505 continue;
2506 nValueRet += out.tx->tx->vout[out.i].nValue;
2507 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2509 return (nValueRet >= nTargetValue);
2512 // calculate value from preset inputs and store them
2513 std::set<CInputCoin> setPresetCoins;
2514 CAmount nValueFromPresetInputs = 0;
2516 std::vector<COutPoint> vPresetInputs;
2517 if (coinControl)
2518 coinControl->ListSelected(vPresetInputs);
2519 for (const COutPoint& outpoint : vPresetInputs)
2521 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2522 if (it != mapWallet.end())
2524 const CWalletTx* pcoin = &it->second;
2525 // Clearly invalid input, fail
2526 if (pcoin->tx->vout.size() <= outpoint.n)
2527 return false;
2528 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2529 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2530 } else
2531 return false; // TODO: Allow non-wallet inputs
2534 // remove preset inputs from vCoins
2535 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2537 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2538 it = vCoins.erase(it);
2539 else
2540 ++it;
2543 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2544 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2546 bool res = nTargetValue <= nValueFromPresetInputs ||
2547 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2548 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2549 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2550 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2551 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2552 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2553 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2555 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2556 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2558 // add preset inputs to the total value selected
2559 nValueRet += nValueFromPresetInputs;
2561 return res;
2564 bool CWallet::SignTransaction(CMutableTransaction &tx)
2566 AssertLockHeld(cs_wallet); // mapWallet
2568 // sign the new tx
2569 CTransaction txNewConst(tx);
2570 int nIn = 0;
2571 for (const auto& input : tx.vin) {
2572 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2573 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2574 return false;
2576 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2577 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2578 SignatureData sigdata;
2579 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2580 return false;
2582 UpdateTransaction(tx, nIn, sigdata);
2583 nIn++;
2585 return true;
2588 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2590 std::vector<CRecipient> vecSend;
2592 // Turn the txout set into a CRecipient vector
2593 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2595 const CTxOut& txOut = tx.vout[idx];
2596 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2597 vecSend.push_back(recipient);
2600 coinControl.fAllowOtherInputs = true;
2602 for (const CTxIn& txin : tx.vin)
2603 coinControl.Select(txin.prevout);
2605 CReserveKey reservekey(this);
2606 CWalletTx wtx;
2607 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2608 return false;
2611 if (nChangePosInOut != -1) {
2612 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2613 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2614 // so just remove the key from the keypool here.
2615 reservekey.KeepKey();
2618 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2619 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2620 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2622 // Add new txins (keeping original txin scriptSig/order)
2623 for (const CTxIn& txin : wtx.tx->vin)
2625 if (!coinControl.IsSelected(txin.prevout))
2627 tx.vin.push_back(txin);
2629 if (lockUnspents)
2631 LOCK2(cs_main, cs_wallet);
2632 LockCoin(txin.prevout);
2638 return true;
2641 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2642 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2644 CAmount nValue = 0;
2645 int nChangePosRequest = nChangePosInOut;
2646 unsigned int nSubtractFeeFromAmount = 0;
2647 for (const auto& recipient : vecSend)
2649 if (nValue < 0 || recipient.nAmount < 0)
2651 strFailReason = _("Transaction amounts must not be negative");
2652 return false;
2654 nValue += recipient.nAmount;
2656 if (recipient.fSubtractFeeFromAmount)
2657 nSubtractFeeFromAmount++;
2659 if (vecSend.empty())
2661 strFailReason = _("Transaction must have at least one recipient");
2662 return false;
2665 wtxNew.fTimeReceivedIsTxTime = true;
2666 wtxNew.BindWallet(this);
2667 CMutableTransaction txNew;
2669 // Discourage fee sniping.
2671 // For a large miner the value of the transactions in the best block and
2672 // the mempool can exceed the cost of deliberately attempting to mine two
2673 // blocks to orphan the current best block. By setting nLockTime such that
2674 // only the next block can include the transaction, we discourage this
2675 // practice as the height restricted and limited blocksize gives miners
2676 // considering fee sniping fewer options for pulling off this attack.
2678 // A simple way to think about this is from the wallet's point of view we
2679 // always want the blockchain to move forward. By setting nLockTime this
2680 // way we're basically making the statement that we only want this
2681 // transaction to appear in the next block; we don't want to potentially
2682 // encourage reorgs by allowing transactions to appear at lower heights
2683 // than the next block in forks of the best chain.
2685 // Of course, the subsidy is high enough, and transaction volume low
2686 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2687 // now we ensure code won't be written that makes assumptions about
2688 // nLockTime that preclude a fix later.
2689 txNew.nLockTime = chainActive.Height();
2691 // Secondly occasionally randomly pick a nLockTime even further back, so
2692 // that transactions that are delayed after signing for whatever reason,
2693 // e.g. high-latency mix networks and some CoinJoin implementations, have
2694 // better privacy.
2695 if (GetRandInt(10) == 0)
2696 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2698 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2699 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2700 FeeCalculation feeCalc;
2701 CAmount nFeeNeeded;
2702 unsigned int nBytes;
2704 std::set<CInputCoin> setCoins;
2705 LOCK2(cs_main, cs_wallet);
2707 std::vector<COutput> vAvailableCoins;
2708 AvailableCoins(vAvailableCoins, true, &coin_control);
2710 // Create change script that will be used if we need change
2711 // TODO: pass in scriptChange instead of reservekey so
2712 // change transaction isn't always pay-to-bitcoin-address
2713 CScript scriptChange;
2715 // coin control: send change to custom address
2716 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2717 scriptChange = GetScriptForDestination(coin_control.destChange);
2718 } else { // no coin control: send change to newly generated address
2719 // Note: We use a new key here to keep it from being obvious which side is the change.
2720 // The drawback is that by not reusing a previous key, the change may be lost if a
2721 // backup is restored, if the backup doesn't have the new private key for the change.
2722 // If we reused the old key, it would be possible to add code to look for and
2723 // rediscover unknown transactions that were written with keys of ours to recover
2724 // post-backup change.
2726 // Reserve a new key pair from key pool
2727 CPubKey vchPubKey;
2728 bool ret;
2729 ret = reservekey.GetReservedKey(vchPubKey, true);
2730 if (!ret)
2732 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2733 return false;
2736 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2738 CTxOut change_prototype_txout(0, scriptChange);
2739 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2741 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2742 nFeeRet = 0;
2743 bool pick_new_inputs = true;
2744 CAmount nValueIn = 0;
2745 // Start with no fee and loop until there is enough fee
2746 while (true)
2748 nChangePosInOut = nChangePosRequest;
2749 txNew.vin.clear();
2750 txNew.vout.clear();
2751 wtxNew.fFromMe = true;
2752 bool fFirst = true;
2754 CAmount nValueToSelect = nValue;
2755 if (nSubtractFeeFromAmount == 0)
2756 nValueToSelect += nFeeRet;
2757 // vouts to the payees
2758 for (const auto& recipient : vecSend)
2760 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2762 if (recipient.fSubtractFeeFromAmount)
2764 assert(nSubtractFeeFromAmount != 0);
2765 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2767 if (fFirst) // first receiver pays the remainder not divisible by output count
2769 fFirst = false;
2770 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2774 if (IsDust(txout, ::dustRelayFee))
2776 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2778 if (txout.nValue < 0)
2779 strFailReason = _("The transaction amount is too small to pay the fee");
2780 else
2781 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2783 else
2784 strFailReason = _("Transaction amount too small");
2785 return false;
2787 txNew.vout.push_back(txout);
2790 // Choose coins to use
2791 if (pick_new_inputs) {
2792 nValueIn = 0;
2793 setCoins.clear();
2794 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2796 strFailReason = _("Insufficient funds");
2797 return false;
2801 const CAmount nChange = nValueIn - nValueToSelect;
2803 if (nChange > 0)
2805 // Fill a vout to ourself
2806 CTxOut newTxOut(nChange, scriptChange);
2808 // Never create dust outputs; if we would, just
2809 // add the dust to the fee.
2810 if (IsDust(newTxOut, discard_rate))
2812 nChangePosInOut = -1;
2813 nFeeRet += nChange;
2815 else
2817 if (nChangePosInOut == -1)
2819 // Insert change txn at random position:
2820 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2822 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2824 strFailReason = _("Change index out of range");
2825 return false;
2828 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2829 txNew.vout.insert(position, newTxOut);
2831 } else {
2832 nChangePosInOut = -1;
2835 // Fill vin
2837 // Note how the sequence number is set to non-maxint so that
2838 // the nLockTime set above actually works.
2840 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2841 // we use the highest possible value in that range (maxint-2)
2842 // to avoid conflicting with other possible uses of nSequence,
2843 // and in the spirit of "smallest possible change from prior
2844 // behavior."
2845 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2846 for (const auto& coin : setCoins)
2847 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2848 nSequence));
2850 // Fill in dummy signatures for fee calculation.
2851 if (!DummySignTx(txNew, setCoins)) {
2852 strFailReason = _("Signing transaction failed");
2853 return false;
2856 nBytes = GetVirtualTransactionSize(txNew);
2858 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2859 for (auto& vin : txNew.vin) {
2860 vin.scriptSig = CScript();
2861 vin.scriptWitness.SetNull();
2864 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2866 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2867 // because we must be at the maximum allowed fee.
2868 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2870 strFailReason = _("Transaction too large for fee policy");
2871 return false;
2874 if (nFeeRet >= nFeeNeeded) {
2875 // Reduce fee to only the needed amount if possible. This
2876 // prevents potential overpayment in fees if the coins
2877 // selected to meet nFeeNeeded result in a transaction that
2878 // requires less fee than the prior iteration.
2880 // If we have no change and a big enough excess fee, then
2881 // try to construct transaction again only without picking
2882 // new inputs. We now know we only need the smaller fee
2883 // (because of reduced tx size) and so we should add a
2884 // change output. Only try this once.
2885 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2886 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2887 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2888 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2889 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2890 pick_new_inputs = false;
2891 nFeeRet = fee_needed_with_change;
2892 continue;
2896 // If we have change output already, just increase it
2897 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2898 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2899 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2900 change_position->nValue += extraFeePaid;
2901 nFeeRet -= extraFeePaid;
2903 break; // Done, enough fee included.
2905 else if (!pick_new_inputs) {
2906 // This shouldn't happen, we should have had enough excess
2907 // fee to pay for the new output and still meet nFeeNeeded
2908 // Or we should have just subtracted fee from recipients and
2909 // nFeeNeeded should not have changed
2910 strFailReason = _("Transaction fee and change calculation failed");
2911 return false;
2914 // Try to reduce change to include necessary fee
2915 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2916 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2917 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2918 // Only reduce change if remaining amount is still a large enough output.
2919 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2920 change_position->nValue -= additionalFeeNeeded;
2921 nFeeRet += additionalFeeNeeded;
2922 break; // Done, able to increase fee from change
2926 // If subtracting fee from recipients, we now know what fee we
2927 // need to subtract, we have no reason to reselect inputs
2928 if (nSubtractFeeFromAmount > 0) {
2929 pick_new_inputs = false;
2932 // Include more fee and try again.
2933 nFeeRet = nFeeNeeded;
2934 continue;
2938 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2940 if (sign)
2942 CTransaction txNewConst(txNew);
2943 int nIn = 0;
2944 for (const auto& coin : setCoins)
2946 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2947 SignatureData sigdata;
2949 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2951 strFailReason = _("Signing transaction failed");
2952 return false;
2953 } else {
2954 UpdateTransaction(txNew, nIn, sigdata);
2957 nIn++;
2961 // Embed the constructed transaction data in wtxNew.
2962 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2964 // Limit size
2965 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2967 strFailReason = _("Transaction too large");
2968 return false;
2972 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2973 // Lastly, ensure this tx will pass the mempool's chain limits
2974 LockPoints lp;
2975 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2976 CTxMemPool::setEntries setAncestors;
2977 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2978 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2979 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2980 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2981 std::string errString;
2982 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2983 strFailReason = _("Transaction has too long of a mempool chain");
2984 return false;
2988 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",
2989 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2990 feeCalc.est.pass.start, feeCalc.est.pass.end,
2991 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2992 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2993 feeCalc.est.fail.start, feeCalc.est.fail.end,
2994 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2995 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2996 return true;
3000 * Call after CreateTransaction unless you want to abort
3002 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3005 LOCK2(cs_main, cs_wallet);
3006 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3008 // Take key pair from key pool so it won't be used again
3009 reservekey.KeepKey();
3011 // Add tx to wallet, because if it has change it's also ours,
3012 // otherwise just for transaction history.
3013 AddToWallet(wtxNew);
3015 // Notify that old coins are spent
3016 for (const CTxIn& txin : wtxNew.tx->vin)
3018 CWalletTx &coin = mapWallet[txin.prevout.hash];
3019 coin.BindWallet(this);
3020 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3024 // Track how many getdata requests our transaction gets
3025 mapRequestCount[wtxNew.GetHash()] = 0;
3027 // Get the inserted-CWalletTx from mapWallet so that the
3028 // fInMempool flag is cached properly
3029 CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
3031 if (fBroadcastTransactions)
3033 // Broadcast
3034 if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
3035 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3036 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3037 } else {
3038 wtx.RelayWalletTransaction(connman);
3042 return true;
3045 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3046 CWalletDB walletdb(*dbw);
3047 return walletdb.ListAccountCreditDebit(strAccount, entries);
3050 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3052 CWalletDB walletdb(*dbw);
3054 return AddAccountingEntry(acentry, &walletdb);
3057 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3059 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3060 return false;
3063 laccentries.push_back(acentry);
3064 CAccountingEntry & entry = laccentries.back();
3065 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3067 return true;
3070 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3072 LOCK2(cs_main, cs_wallet);
3074 fFirstRunRet = false;
3075 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3076 if (nLoadWalletRet == DB_NEED_REWRITE)
3078 if (dbw->Rewrite("\x04pool"))
3080 setInternalKeyPool.clear();
3081 setExternalKeyPool.clear();
3082 m_pool_key_to_index.clear();
3083 // Note: can't top-up keypool here, because wallet is locked.
3084 // User will be prompted to unlock wallet the next operation
3085 // that requires a new key.
3089 // This wallet is in its first run if all of these are empty
3090 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3092 if (nLoadWalletRet != DB_LOAD_OK)
3093 return nLoadWalletRet;
3095 uiInterface.LoadWallet(this);
3097 return DB_LOAD_OK;
3100 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3102 AssertLockHeld(cs_wallet); // mapWallet
3103 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3104 for (uint256 hash : vHashOut)
3105 mapWallet.erase(hash);
3107 if (nZapSelectTxRet == DB_NEED_REWRITE)
3109 if (dbw->Rewrite("\x04pool"))
3111 setInternalKeyPool.clear();
3112 setExternalKeyPool.clear();
3113 m_pool_key_to_index.clear();
3114 // Note: can't top-up keypool here, because wallet is locked.
3115 // User will be prompted to unlock wallet the next operation
3116 // that requires a new key.
3120 if (nZapSelectTxRet != DB_LOAD_OK)
3121 return nZapSelectTxRet;
3123 MarkDirty();
3125 return DB_LOAD_OK;
3129 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3131 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3132 if (nZapWalletTxRet == DB_NEED_REWRITE)
3134 if (dbw->Rewrite("\x04pool"))
3136 LOCK(cs_wallet);
3137 setInternalKeyPool.clear();
3138 setExternalKeyPool.clear();
3139 m_pool_key_to_index.clear();
3140 // Note: can't top-up keypool here, because wallet is locked.
3141 // User will be prompted to unlock wallet the next operation
3142 // that requires a new key.
3146 if (nZapWalletTxRet != DB_LOAD_OK)
3147 return nZapWalletTxRet;
3149 return DB_LOAD_OK;
3153 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3155 bool fUpdated = false;
3157 LOCK(cs_wallet); // mapAddressBook
3158 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3159 fUpdated = mi != mapAddressBook.end();
3160 mapAddressBook[address].name = strName;
3161 if (!strPurpose.empty()) /* update purpose only if requested */
3162 mapAddressBook[address].purpose = strPurpose;
3164 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3165 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3166 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3167 return false;
3168 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3171 bool CWallet::DelAddressBook(const CTxDestination& address)
3174 LOCK(cs_wallet); // mapAddressBook
3176 // Delete destdata tuples associated with address
3177 std::string strAddress = EncodeDestination(address);
3178 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3180 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3182 mapAddressBook.erase(address);
3185 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3187 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3188 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3191 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3193 CTxDestination address;
3194 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3195 auto mi = mapAddressBook.find(address);
3196 if (mi != mapAddressBook.end()) {
3197 return mi->second.name;
3200 // A scriptPubKey that doesn't have an entry in the address book is
3201 // associated with the default account ("").
3202 const static std::string DEFAULT_ACCOUNT_NAME;
3203 return DEFAULT_ACCOUNT_NAME;
3207 * Mark old keypool keys as used,
3208 * and generate all new keys
3210 bool CWallet::NewKeyPool()
3213 LOCK(cs_wallet);
3214 CWalletDB walletdb(*dbw);
3216 for (int64_t nIndex : setInternalKeyPool) {
3217 walletdb.ErasePool(nIndex);
3219 setInternalKeyPool.clear();
3221 for (int64_t nIndex : setExternalKeyPool) {
3222 walletdb.ErasePool(nIndex);
3224 setExternalKeyPool.clear();
3226 m_pool_key_to_index.clear();
3228 if (!TopUpKeyPool()) {
3229 return false;
3231 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3233 return true;
3236 size_t CWallet::KeypoolCountExternalKeys()
3238 AssertLockHeld(cs_wallet); // setExternalKeyPool
3239 return setExternalKeyPool.size();
3242 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3244 AssertLockHeld(cs_wallet);
3245 if (keypool.fInternal) {
3246 setInternalKeyPool.insert(nIndex);
3247 } else {
3248 setExternalKeyPool.insert(nIndex);
3250 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3251 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3253 // If no metadata exists yet, create a default with the pool key's
3254 // creation time. Note that this may be overwritten by actually
3255 // stored metadata for that key later, which is fine.
3256 CKeyID keyid = keypool.vchPubKey.GetID();
3257 if (mapKeyMetadata.count(keyid) == 0)
3258 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3261 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3264 LOCK(cs_wallet);
3266 if (IsLocked())
3267 return false;
3269 // Top up key pool
3270 unsigned int nTargetSize;
3271 if (kpSize > 0)
3272 nTargetSize = kpSize;
3273 else
3274 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3276 // count amount of available keys (internal, external)
3277 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3278 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3279 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3281 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3283 // don't create extra internal keys
3284 missingInternal = 0;
3286 bool internal = false;
3287 CWalletDB walletdb(*dbw);
3288 for (int64_t i = missingInternal + missingExternal; i--;)
3290 if (i < missingInternal) {
3291 internal = true;
3294 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3295 int64_t index = ++m_max_keypool_index;
3297 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3298 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3299 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3302 if (internal) {
3303 setInternalKeyPool.insert(index);
3304 } else {
3305 setExternalKeyPool.insert(index);
3307 m_pool_key_to_index[pubkey.GetID()] = index;
3309 if (missingInternal + missingExternal > 0) {
3310 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3313 return true;
3316 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3318 nIndex = -1;
3319 keypool.vchPubKey = CPubKey();
3321 LOCK(cs_wallet);
3323 if (!IsLocked())
3324 TopUpKeyPool();
3326 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3327 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3329 // Get the oldest key
3330 if(setKeyPool.empty())
3331 return;
3333 CWalletDB walletdb(*dbw);
3335 auto it = setKeyPool.begin();
3336 nIndex = *it;
3337 setKeyPool.erase(it);
3338 if (!walletdb.ReadPool(nIndex, keypool)) {
3339 throw std::runtime_error(std::string(__func__) + ": read failed");
3341 if (!HaveKey(keypool.vchPubKey.GetID())) {
3342 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3344 if (keypool.fInternal != fReturningInternal) {
3345 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3348 assert(keypool.vchPubKey.IsValid());
3349 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3350 LogPrintf("keypool reserve %d\n", nIndex);
3354 void CWallet::KeepKey(int64_t nIndex)
3356 // Remove from key pool
3357 CWalletDB walletdb(*dbw);
3358 walletdb.ErasePool(nIndex);
3359 LogPrintf("keypool keep %d\n", nIndex);
3362 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3364 // Return to key pool
3366 LOCK(cs_wallet);
3367 if (fInternal) {
3368 setInternalKeyPool.insert(nIndex);
3369 } else {
3370 setExternalKeyPool.insert(nIndex);
3372 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3374 LogPrintf("keypool return %d\n", nIndex);
3377 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3379 CKeyPool keypool;
3381 LOCK(cs_wallet);
3382 int64_t nIndex = 0;
3383 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3384 if (nIndex == -1)
3386 if (IsLocked()) return false;
3387 CWalletDB walletdb(*dbw);
3388 result = GenerateNewKey(walletdb, internal);
3389 return true;
3391 KeepKey(nIndex);
3392 result = keypool.vchPubKey;
3394 return true;
3397 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3398 if (setKeyPool.empty()) {
3399 return GetTime();
3402 CKeyPool keypool;
3403 int64_t nIndex = *(setKeyPool.begin());
3404 if (!walletdb.ReadPool(nIndex, keypool)) {
3405 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3407 assert(keypool.vchPubKey.IsValid());
3408 return keypool.nTime;
3411 int64_t CWallet::GetOldestKeyPoolTime()
3413 LOCK(cs_wallet);
3415 CWalletDB walletdb(*dbw);
3417 // load oldest key from keypool, get time and return
3418 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3419 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3420 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3423 return oldestKey;
3426 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3428 std::map<CTxDestination, CAmount> balances;
3431 LOCK(cs_wallet);
3432 for (const auto& walletEntry : mapWallet)
3434 const CWalletTx *pcoin = &walletEntry.second;
3436 if (!pcoin->IsTrusted())
3437 continue;
3439 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3440 continue;
3442 int nDepth = pcoin->GetDepthInMainChain();
3443 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3444 continue;
3446 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3448 CTxDestination addr;
3449 if (!IsMine(pcoin->tx->vout[i]))
3450 continue;
3451 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3452 continue;
3454 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3456 if (!balances.count(addr))
3457 balances[addr] = 0;
3458 balances[addr] += n;
3463 return balances;
3466 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3468 AssertLockHeld(cs_wallet); // mapWallet
3469 std::set< std::set<CTxDestination> > groupings;
3470 std::set<CTxDestination> grouping;
3472 for (const auto& walletEntry : mapWallet)
3474 const CWalletTx *pcoin = &walletEntry.second;
3476 if (pcoin->tx->vin.size() > 0)
3478 bool any_mine = false;
3479 // group all input addresses with each other
3480 for (CTxIn txin : pcoin->tx->vin)
3482 CTxDestination address;
3483 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3484 continue;
3485 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3486 continue;
3487 grouping.insert(address);
3488 any_mine = true;
3491 // group change with input addresses
3492 if (any_mine)
3494 for (CTxOut txout : pcoin->tx->vout)
3495 if (IsChange(txout))
3497 CTxDestination txoutAddr;
3498 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3499 continue;
3500 grouping.insert(txoutAddr);
3503 if (grouping.size() > 0)
3505 groupings.insert(grouping);
3506 grouping.clear();
3510 // group lone addrs by themselves
3511 for (const auto& txout : pcoin->tx->vout)
3512 if (IsMine(txout))
3514 CTxDestination address;
3515 if(!ExtractDestination(txout.scriptPubKey, address))
3516 continue;
3517 grouping.insert(address);
3518 groupings.insert(grouping);
3519 grouping.clear();
3523 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3524 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3525 for (std::set<CTxDestination> _grouping : groupings)
3527 // make a set of all the groups hit by this new group
3528 std::set< std::set<CTxDestination>* > hits;
3529 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3530 for (CTxDestination address : _grouping)
3531 if ((it = setmap.find(address)) != setmap.end())
3532 hits.insert((*it).second);
3534 // merge all hit groups into a new single group and delete old groups
3535 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3536 for (std::set<CTxDestination>* hit : hits)
3538 merged->insert(hit->begin(), hit->end());
3539 uniqueGroupings.erase(hit);
3540 delete hit;
3542 uniqueGroupings.insert(merged);
3544 // update setmap
3545 for (CTxDestination element : *merged)
3546 setmap[element] = merged;
3549 std::set< std::set<CTxDestination> > ret;
3550 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3552 ret.insert(*uniqueGrouping);
3553 delete uniqueGrouping;
3556 return ret;
3559 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3561 LOCK(cs_wallet);
3562 std::set<CTxDestination> result;
3563 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3565 const CTxDestination& address = item.first;
3566 const std::string& strName = item.second.name;
3567 if (strName == strAccount)
3568 result.insert(address);
3570 return result;
3573 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3575 if (nIndex == -1)
3577 CKeyPool keypool;
3578 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3579 if (nIndex != -1)
3580 vchPubKey = keypool.vchPubKey;
3581 else {
3582 return false;
3584 fInternal = keypool.fInternal;
3586 assert(vchPubKey.IsValid());
3587 pubkey = vchPubKey;
3588 return true;
3591 void CReserveKey::KeepKey()
3593 if (nIndex != -1)
3594 pwallet->KeepKey(nIndex);
3595 nIndex = -1;
3596 vchPubKey = CPubKey();
3599 void CReserveKey::ReturnKey()
3601 if (nIndex != -1) {
3602 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3604 nIndex = -1;
3605 vchPubKey = CPubKey();
3608 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3610 AssertLockHeld(cs_wallet);
3611 bool internal = setInternalKeyPool.count(keypool_id);
3612 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3613 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3614 auto it = setKeyPool->begin();
3616 CWalletDB walletdb(*dbw);
3617 while (it != std::end(*setKeyPool)) {
3618 const int64_t& index = *(it);
3619 if (index > keypool_id) break; // set*KeyPool is ordered
3621 CKeyPool keypool;
3622 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3623 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3625 walletdb.ErasePool(index);
3626 LogPrintf("keypool index %d removed\n", index);
3627 it = setKeyPool->erase(it);
3631 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3633 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3634 CPubKey pubkey;
3635 if (!rKey->GetReservedKey(pubkey))
3636 return;
3638 script = rKey;
3639 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3642 void CWallet::LockCoin(const COutPoint& output)
3644 AssertLockHeld(cs_wallet); // setLockedCoins
3645 setLockedCoins.insert(output);
3648 void CWallet::UnlockCoin(const COutPoint& output)
3650 AssertLockHeld(cs_wallet); // setLockedCoins
3651 setLockedCoins.erase(output);
3654 void CWallet::UnlockAllCoins()
3656 AssertLockHeld(cs_wallet); // setLockedCoins
3657 setLockedCoins.clear();
3660 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3662 AssertLockHeld(cs_wallet); // setLockedCoins
3663 COutPoint outpt(hash, n);
3665 return (setLockedCoins.count(outpt) > 0);
3668 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3670 AssertLockHeld(cs_wallet); // setLockedCoins
3671 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3672 it != setLockedCoins.end(); it++) {
3673 COutPoint outpt = (*it);
3674 vOutpts.push_back(outpt);
3678 /** @} */ // end of Actions
3680 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3681 AssertLockHeld(cs_wallet); // mapKeyMetadata
3682 mapKeyBirth.clear();
3684 // get birth times for keys with metadata
3685 for (const auto& entry : mapKeyMetadata) {
3686 if (entry.second.nCreateTime) {
3687 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3691 // map in which we'll infer heights of other keys
3692 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3693 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3694 for (const CKeyID &keyid : GetKeys()) {
3695 if (mapKeyBirth.count(keyid) == 0)
3696 mapKeyFirstBlock[keyid] = pindexMax;
3699 // if there are no such keys, we're done
3700 if (mapKeyFirstBlock.empty())
3701 return;
3703 // find first block that affects those keys, if there are any left
3704 std::vector<CKeyID> vAffected;
3705 for (const auto& entry : mapWallet) {
3706 // iterate over all wallet transactions...
3707 const CWalletTx &wtx = entry.second;
3708 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3709 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3710 // ... which are already in a block
3711 int nHeight = blit->second->nHeight;
3712 for (const CTxOut &txout : wtx.tx->vout) {
3713 // iterate over all their outputs
3714 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3715 for (const CKeyID &keyid : vAffected) {
3716 // ... and all their affected keys
3717 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3718 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3719 rit->second = blit->second;
3721 vAffected.clear();
3726 // Extract block timestamps for those keys
3727 for (const auto& entry : mapKeyFirstBlock)
3728 mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3732 * Compute smart timestamp for a transaction being added to the wallet.
3734 * Logic:
3735 * - If sending a transaction, assign its timestamp to the current time.
3736 * - If receiving a transaction outside a block, assign its timestamp to the
3737 * current time.
3738 * - If receiving a block with a future timestamp, assign all its (not already
3739 * known) transactions' timestamps to the current time.
3740 * - If receiving a block with a past timestamp, before the most recent known
3741 * transaction (that we care about), assign all its (not already known)
3742 * transactions' timestamps to the same timestamp as that most-recent-known
3743 * transaction.
3744 * - If receiving a block with a past timestamp, but after the most recent known
3745 * transaction, assign all its (not already known) transactions' timestamps to
3746 * the block time.
3748 * For more information see CWalletTx::nTimeSmart,
3749 * https://bitcointalk.org/?topic=54527, or
3750 * https://github.com/bitcoin/bitcoin/pull/1393.
3752 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3754 unsigned int nTimeSmart = wtx.nTimeReceived;
3755 if (!wtx.hashUnset()) {
3756 if (mapBlockIndex.count(wtx.hashBlock)) {
3757 int64_t latestNow = wtx.nTimeReceived;
3758 int64_t latestEntry = 0;
3760 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3761 int64_t latestTolerated = latestNow + 300;
3762 const TxItems& txOrdered = wtxOrdered;
3763 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3764 CWalletTx* const pwtx = it->second.first;
3765 if (pwtx == &wtx) {
3766 continue;
3768 CAccountingEntry* const pacentry = it->second.second;
3769 int64_t nSmartTime;
3770 if (pwtx) {
3771 nSmartTime = pwtx->nTimeSmart;
3772 if (!nSmartTime) {
3773 nSmartTime = pwtx->nTimeReceived;
3775 } else {
3776 nSmartTime = pacentry->nTime;
3778 if (nSmartTime <= latestTolerated) {
3779 latestEntry = nSmartTime;
3780 if (nSmartTime > latestNow) {
3781 latestNow = nSmartTime;
3783 break;
3787 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3788 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3789 } else {
3790 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3793 return nTimeSmart;
3796 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3798 if (boost::get<CNoDestination>(&dest))
3799 return false;
3801 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3802 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3805 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3807 if (!mapAddressBook[dest].destdata.erase(key))
3808 return false;
3809 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3812 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3814 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3815 return true;
3818 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3820 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3821 if(i != mapAddressBook.end())
3823 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3824 if(j != i->second.destdata.end())
3826 if(value)
3827 *value = j->second;
3828 return true;
3831 return false;
3834 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3836 LOCK(cs_wallet);
3837 std::vector<std::string> values;
3838 for (const auto& address : mapAddressBook) {
3839 for (const auto& data : address.second.destdata) {
3840 if (!data.first.compare(0, prefix.size(), prefix)) {
3841 values.emplace_back(data.second);
3845 return values;
3848 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3850 // needed to restore wallet transaction meta data after -zapwallettxes
3851 std::vector<CWalletTx> vWtx;
3853 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3854 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3856 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3857 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3858 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3859 if (nZapWalletRet != DB_LOAD_OK) {
3860 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3861 return nullptr;
3865 uiInterface.InitMessage(_("Loading wallet..."));
3867 int64_t nStart = GetTimeMillis();
3868 bool fFirstRun = true;
3869 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3870 CWallet *walletInstance = new CWallet(std::move(dbw));
3871 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3872 if (nLoadWalletRet != DB_LOAD_OK)
3874 if (nLoadWalletRet == DB_CORRUPT) {
3875 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3876 return nullptr;
3878 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3880 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3881 " or address book entries might be missing or incorrect."),
3882 walletFile));
3884 else if (nLoadWalletRet == DB_TOO_NEW) {
3885 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3886 return nullptr;
3888 else if (nLoadWalletRet == DB_NEED_REWRITE)
3890 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3891 return nullptr;
3893 else {
3894 InitError(strprintf(_("Error loading %s"), walletFile));
3895 return nullptr;
3899 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3901 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3902 if (nMaxVersion == 0) // the -upgradewallet without argument case
3904 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3905 nMaxVersion = CLIENT_VERSION;
3906 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3908 else
3909 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3910 if (nMaxVersion < walletInstance->GetVersion())
3912 InitError(_("Cannot downgrade wallet"));
3913 return nullptr;
3915 walletInstance->SetMaxVersion(nMaxVersion);
3918 if (fFirstRun)
3920 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3921 if (!gArgs.GetBoolArg("-usehd", true)) {
3922 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3923 return nullptr;
3925 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3927 // generate a new master key
3928 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3929 if (!walletInstance->SetHDMasterKey(masterPubKey))
3930 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3932 // Top up the keypool
3933 if (!walletInstance->TopUpKeyPool()) {
3934 InitError(_("Unable to generate initial keys") += "\n");
3935 return nullptr;
3938 walletInstance->SetBestChain(chainActive.GetLocator());
3940 else if (gArgs.IsArgSet("-usehd")) {
3941 bool useHD = gArgs.GetBoolArg("-usehd", true);
3942 if (walletInstance->IsHDEnabled() && !useHD) {
3943 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3944 return nullptr;
3946 if (!walletInstance->IsHDEnabled() && useHD) {
3947 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3948 return nullptr;
3952 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3954 // Try to top up keypool. No-op if the wallet is locked.
3955 walletInstance->TopUpKeyPool();
3957 CBlockIndex *pindexRescan = chainActive.Genesis();
3958 if (!gArgs.GetBoolArg("-rescan", false))
3960 CWalletDB walletdb(*walletInstance->dbw);
3961 CBlockLocator locator;
3962 if (walletdb.ReadBestBlock(locator))
3963 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3966 walletInstance->m_last_block_processed = chainActive.Tip();
3967 RegisterValidationInterface(walletInstance);
3969 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3971 //We can't rescan beyond non-pruned blocks, stop and throw an error
3972 //this might happen if a user uses an old wallet within a pruned node
3973 // or if he ran -disablewallet for a longer time, then decided to re-enable
3974 if (fPruneMode)
3976 CBlockIndex *block = chainActive.Tip();
3977 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3978 block = block->pprev;
3980 if (pindexRescan != block) {
3981 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3982 return nullptr;
3986 uiInterface.InitMessage(_("Rescanning..."));
3987 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3989 // No need to read and scan block if block was created before
3990 // our wallet birthday (as adjusted for block time variability)
3991 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3992 pindexRescan = chainActive.Next(pindexRescan);
3995 nStart = GetTimeMillis();
3996 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
3997 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3998 walletInstance->SetBestChain(chainActive.GetLocator());
3999 walletInstance->dbw->IncrementUpdateCounter();
4001 // Restore wallet transaction metadata after -zapwallettxes=1
4002 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4004 CWalletDB walletdb(*walletInstance->dbw);
4006 for (const CWalletTx& wtxOld : vWtx)
4008 uint256 hash = wtxOld.GetHash();
4009 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4010 if (mi != walletInstance->mapWallet.end())
4012 const CWalletTx* copyFrom = &wtxOld;
4013 CWalletTx* copyTo = &mi->second;
4014 copyTo->mapValue = copyFrom->mapValue;
4015 copyTo->vOrderForm = copyFrom->vOrderForm;
4016 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4017 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4018 copyTo->fFromMe = copyFrom->fFromMe;
4019 copyTo->strFromAccount = copyFrom->strFromAccount;
4020 copyTo->nOrderPos = copyFrom->nOrderPos;
4021 walletdb.WriteTx(*copyTo);
4026 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4029 LOCK(walletInstance->cs_wallet);
4030 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4031 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4032 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4035 return walletInstance;
4038 std::atomic<bool> CWallet::fFlushScheduled(false);
4040 void CWallet::postInitProcess(CScheduler& scheduler)
4042 // Add wallet transactions that aren't already in a block to mempool
4043 // Do this here as mempool requires genesis block to be loaded
4044 ReacceptWalletTransactions();
4046 // Run a thread to flush wallet periodically
4047 if (!CWallet::fFlushScheduled.exchange(true)) {
4048 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4052 bool CWallet::BackupWallet(const std::string& strDest)
4054 return dbw->Backup(strDest);
4057 CKeyPool::CKeyPool()
4059 nTime = GetTime();
4060 fInternal = false;
4063 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4065 nTime = GetTime();
4066 vchPubKey = vchPubKeyIn;
4067 fInternal = internalIn;
4070 CWalletKey::CWalletKey(int64_t nExpires)
4072 nTimeCreated = (nExpires ? GetTime() : 0);
4073 nTimeExpires = nExpires;
4076 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4078 // Update the tx's hashBlock
4079 hashBlock = pindex->GetBlockHash();
4081 // set the position of the transaction in the block
4082 nIndex = posInBlock;
4085 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4087 if (hashUnset())
4088 return 0;
4090 AssertLockHeld(cs_main);
4092 // Find the block it claims to be in
4093 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4094 if (mi == mapBlockIndex.end())
4095 return 0;
4096 CBlockIndex* pindex = (*mi).second;
4097 if (!pindex || !chainActive.Contains(pindex))
4098 return 0;
4100 pindexRet = pindex;
4101 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4104 int CMerkleTx::GetBlocksToMaturity() const
4106 if (!IsCoinBase())
4107 return 0;
4108 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4112 bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4114 // Quick check to avoid re-setting fInMempool to false
4115 if (mempool.exists(tx->GetHash())) {
4116 return false;
4119 // We must set fInMempool here - while it will be re-set to true by the
4120 // entered-mempool callback, if we did not there would be a race where a
4121 // user could call sendmoney in a loop and hit spurious out of funds errors
4122 // because we think that the transaction they just generated's change is
4123 // unavailable as we're not yet aware its in mempool.
4124 bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4125 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
4126 fInMempool = ret;
4127 return ret;