don't attempt mempool entry for wallet transactions on startup if already in mempool
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobcb81ec37f53501c7d6f019382e8a0a8ebcd10ce3
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)
1718 CWalletTx& wtx = *(item.second);
1720 LOCK(mempool.cs);
1721 CValidationState state;
1722 wtx.AcceptToMemoryPool(maxTxFee, state);
1726 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1728 assert(pwallet->GetBroadcastTransactions());
1729 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1731 CValidationState state;
1732 /* GetDepthInMainChain already catches known conflicts. */
1733 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1734 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1735 if (connman) {
1736 CInv inv(MSG_TX, GetHash());
1737 connman->ForEachNode([&inv](CNode* pnode)
1739 pnode->PushInventory(inv);
1741 return true;
1745 return false;
1748 std::set<uint256> CWalletTx::GetConflicts() const
1750 std::set<uint256> result;
1751 if (pwallet != nullptr)
1753 uint256 myHash = GetHash();
1754 result = pwallet->GetConflicts(myHash);
1755 result.erase(myHash);
1757 return result;
1760 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1762 if (tx->vin.empty())
1763 return 0;
1765 CAmount debit = 0;
1766 if(filter & ISMINE_SPENDABLE)
1768 if (fDebitCached)
1769 debit += nDebitCached;
1770 else
1772 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1773 fDebitCached = true;
1774 debit += nDebitCached;
1777 if(filter & ISMINE_WATCH_ONLY)
1779 if(fWatchDebitCached)
1780 debit += nWatchDebitCached;
1781 else
1783 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1784 fWatchDebitCached = true;
1785 debit += nWatchDebitCached;
1788 return debit;
1791 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1793 // Must wait until coinbase is safely deep enough in the chain before valuing it
1794 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1795 return 0;
1797 CAmount credit = 0;
1798 if (filter & ISMINE_SPENDABLE)
1800 // GetBalance can assume transactions in mapWallet won't change
1801 if (fCreditCached)
1802 credit += nCreditCached;
1803 else
1805 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1806 fCreditCached = true;
1807 credit += nCreditCached;
1810 if (filter & ISMINE_WATCH_ONLY)
1812 if (fWatchCreditCached)
1813 credit += nWatchCreditCached;
1814 else
1816 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1817 fWatchCreditCached = true;
1818 credit += nWatchCreditCached;
1821 return credit;
1824 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1826 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1828 if (fUseCache && fImmatureCreditCached)
1829 return nImmatureCreditCached;
1830 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1831 fImmatureCreditCached = true;
1832 return nImmatureCreditCached;
1835 return 0;
1838 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1840 if (pwallet == nullptr)
1841 return 0;
1843 // Must wait until coinbase is safely deep enough in the chain before valuing it
1844 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1845 return 0;
1847 if (fUseCache && fAvailableCreditCached)
1848 return nAvailableCreditCached;
1850 CAmount nCredit = 0;
1851 uint256 hashTx = GetHash();
1852 for (unsigned int i = 0; i < tx->vout.size(); i++)
1854 if (!pwallet->IsSpent(hashTx, i))
1856 const CTxOut &txout = tx->vout[i];
1857 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1858 if (!MoneyRange(nCredit))
1859 throw std::runtime_error(std::string(__func__) + " : value out of range");
1863 nAvailableCreditCached = nCredit;
1864 fAvailableCreditCached = true;
1865 return nCredit;
1868 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1870 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1872 if (fUseCache && fImmatureWatchCreditCached)
1873 return nImmatureWatchCreditCached;
1874 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1875 fImmatureWatchCreditCached = true;
1876 return nImmatureWatchCreditCached;
1879 return 0;
1882 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1884 if (pwallet == nullptr)
1885 return 0;
1887 // Must wait until coinbase is safely deep enough in the chain before valuing it
1888 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1889 return 0;
1891 if (fUseCache && fAvailableWatchCreditCached)
1892 return nAvailableWatchCreditCached;
1894 CAmount nCredit = 0;
1895 for (unsigned int i = 0; i < tx->vout.size(); i++)
1897 if (!pwallet->IsSpent(GetHash(), i))
1899 const CTxOut &txout = tx->vout[i];
1900 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1901 if (!MoneyRange(nCredit))
1902 throw std::runtime_error(std::string(__func__) + ": value out of range");
1906 nAvailableWatchCreditCached = nCredit;
1907 fAvailableWatchCreditCached = true;
1908 return nCredit;
1911 CAmount CWalletTx::GetChange() const
1913 if (fChangeCached)
1914 return nChangeCached;
1915 nChangeCached = pwallet->GetChange(*tx);
1916 fChangeCached = true;
1917 return nChangeCached;
1920 bool CWalletTx::InMempool() const
1922 return fInMempool;
1925 bool CWalletTx::IsTrusted() const
1927 // Quick answer in most cases
1928 if (!CheckFinalTx(*tx))
1929 return false;
1930 int nDepth = GetDepthInMainChain();
1931 if (nDepth >= 1)
1932 return true;
1933 if (nDepth < 0)
1934 return false;
1935 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1936 return false;
1938 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1939 if (!InMempool())
1940 return false;
1942 // Trusted if all inputs are from us and are in the mempool:
1943 for (const CTxIn& txin : tx->vin)
1945 // Transactions not sent by us: not trusted
1946 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1947 if (parent == nullptr)
1948 return false;
1949 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1950 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1951 return false;
1953 return true;
1956 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1958 CMutableTransaction tx1 = *this->tx;
1959 CMutableTransaction tx2 = *_tx.tx;
1960 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1961 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1962 return CTransaction(tx1) == CTransaction(tx2);
1965 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1967 std::vector<uint256> result;
1969 LOCK(cs_wallet);
1971 // Sort them in chronological order
1972 std::multimap<unsigned int, CWalletTx*> mapSorted;
1973 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1975 CWalletTx& wtx = item.second;
1976 // Don't rebroadcast if newer than nTime:
1977 if (wtx.nTimeReceived > nTime)
1978 continue;
1979 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1981 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1983 CWalletTx& wtx = *item.second;
1984 if (wtx.RelayWalletTransaction(connman))
1985 result.push_back(wtx.GetHash());
1987 return result;
1990 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1992 // Do this infrequently and randomly to avoid giving away
1993 // that these are our transactions.
1994 if (GetTime() < nNextResend || !fBroadcastTransactions)
1995 return;
1996 bool fFirst = (nNextResend == 0);
1997 nNextResend = GetTime() + GetRand(30 * 60);
1998 if (fFirst)
1999 return;
2001 // Only do it if there's been a new block since last time
2002 if (nBestBlockTime < nLastResend)
2003 return;
2004 nLastResend = GetTime();
2006 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2007 // block was found:
2008 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2009 if (!relayed.empty())
2010 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2013 /** @} */ // end of mapWallet
2018 /** @defgroup Actions
2020 * @{
2024 CAmount CWallet::GetBalance() const
2026 CAmount nTotal = 0;
2028 LOCK2(cs_main, cs_wallet);
2029 for (const auto& entry : mapWallet)
2031 const CWalletTx* pcoin = &entry.second;
2032 if (pcoin->IsTrusted())
2033 nTotal += pcoin->GetAvailableCredit();
2037 return nTotal;
2040 CAmount CWallet::GetUnconfirmedBalance() const
2042 CAmount nTotal = 0;
2044 LOCK2(cs_main, cs_wallet);
2045 for (const auto& entry : mapWallet)
2047 const CWalletTx* pcoin = &entry.second;
2048 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2049 nTotal += pcoin->GetAvailableCredit();
2052 return nTotal;
2055 CAmount CWallet::GetImmatureBalance() const
2057 CAmount nTotal = 0;
2059 LOCK2(cs_main, cs_wallet);
2060 for (const auto& entry : mapWallet)
2062 const CWalletTx* pcoin = &entry.second;
2063 nTotal += pcoin->GetImmatureCredit();
2066 return nTotal;
2069 CAmount CWallet::GetWatchOnlyBalance() const
2071 CAmount nTotal = 0;
2073 LOCK2(cs_main, cs_wallet);
2074 for (const auto& entry : mapWallet)
2076 const CWalletTx* pcoin = &entry.second;
2077 if (pcoin->IsTrusted())
2078 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2082 return nTotal;
2085 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2087 CAmount nTotal = 0;
2089 LOCK2(cs_main, cs_wallet);
2090 for (const auto& entry : mapWallet)
2092 const CWalletTx* pcoin = &entry.second;
2093 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2094 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2097 return nTotal;
2100 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2102 CAmount nTotal = 0;
2104 LOCK2(cs_main, cs_wallet);
2105 for (const auto& entry : mapWallet)
2107 const CWalletTx* pcoin = &entry.second;
2108 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2111 return nTotal;
2114 // Calculate total balance in a different way from GetBalance. The biggest
2115 // difference is that GetBalance sums up all unspent TxOuts paying to the
2116 // wallet, while this sums up both spent and unspent TxOuts paying to the
2117 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2118 // also has fewer restrictions on which unconfirmed transactions are considered
2119 // trusted.
2120 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2122 LOCK2(cs_main, cs_wallet);
2124 CAmount balance = 0;
2125 for (const auto& entry : mapWallet) {
2126 const CWalletTx& wtx = entry.second;
2127 const int depth = wtx.GetDepthInMainChain();
2128 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2129 continue;
2132 // Loop through tx outputs and add incoming payments. For outgoing txs,
2133 // treat change outputs specially, as part of the amount debited.
2134 CAmount debit = wtx.GetDebit(filter);
2135 const bool outgoing = debit > 0;
2136 for (const CTxOut& out : wtx.tx->vout) {
2137 if (outgoing && IsChange(out)) {
2138 debit -= out.nValue;
2139 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2140 balance += out.nValue;
2144 // For outgoing txs, subtract amount debited.
2145 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2146 balance -= debit;
2150 if (account) {
2151 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2154 return balance;
2157 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2159 LOCK2(cs_main, cs_wallet);
2161 CAmount balance = 0;
2162 std::vector<COutput> vCoins;
2163 AvailableCoins(vCoins, true, coinControl);
2164 for (const COutput& out : vCoins) {
2165 if (out.fSpendable) {
2166 balance += out.tx->tx->vout[out.i].nValue;
2169 return balance;
2172 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
2174 vCoins.clear();
2177 LOCK2(cs_main, cs_wallet);
2179 CAmount nTotal = 0;
2181 for (const auto& entry : mapWallet)
2183 const uint256& wtxid = entry.first;
2184 const CWalletTx* pcoin = &entry.second;
2186 if (!CheckFinalTx(*pcoin->tx))
2187 continue;
2189 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2190 continue;
2192 int nDepth = pcoin->GetDepthInMainChain();
2193 if (nDepth < 0)
2194 continue;
2196 // We should not consider coins which aren't at least in our mempool
2197 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2198 if (nDepth == 0 && !pcoin->InMempool())
2199 continue;
2201 bool safeTx = pcoin->IsTrusted();
2203 // We should not consider coins from transactions that are replacing
2204 // other transactions.
2206 // Example: There is a transaction A which is replaced by bumpfee
2207 // transaction B. In this case, we want to prevent creation of
2208 // a transaction B' which spends an output of B.
2210 // Reason: If transaction A were initially confirmed, transactions B
2211 // and B' would no longer be valid, so the user would have to create
2212 // a new transaction C to replace B'. However, in the case of a
2213 // one-block reorg, transactions B' and C might BOTH be accepted,
2214 // when the user only wanted one of them. Specifically, there could
2215 // be a 1-block reorg away from the chain where transactions A and C
2216 // were accepted to another chain where B, B', and C were all
2217 // accepted.
2218 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2219 safeTx = false;
2222 // Similarly, we should not consider coins from transactions that
2223 // have been replaced. In the example above, we would want to prevent
2224 // creation of a transaction A' spending an output of A, because if
2225 // transaction B were initially confirmed, conflicting with A and
2226 // A', we wouldn't want to the user to create a transaction D
2227 // intending to replace A', but potentially resulting in a scenario
2228 // where A, A', and D could all be accepted (instead of just B and
2229 // D, or just A and A' like the user would want).
2230 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2231 safeTx = false;
2234 if (fOnlySafe && !safeTx) {
2235 continue;
2238 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2239 continue;
2241 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2242 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2243 continue;
2245 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2246 continue;
2248 if (IsLockedCoin(entry.first, i))
2249 continue;
2251 if (IsSpent(wtxid, i))
2252 continue;
2254 isminetype mine = IsMine(pcoin->tx->vout[i]);
2256 if (mine == ISMINE_NO) {
2257 continue;
2260 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2261 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2263 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2265 // Checks the sum amount of all UTXO's.
2266 if (nMinimumSumAmount != MAX_MONEY) {
2267 nTotal += pcoin->tx->vout[i].nValue;
2269 if (nTotal >= nMinimumSumAmount) {
2270 return;
2274 // Checks the maximum number of UTXO's.
2275 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2276 return;
2283 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2285 // TODO: Add AssertLockHeld(cs_wallet) here.
2287 // Because the return value from this function contains pointers to
2288 // CWalletTx objects, callers to this function really should acquire the
2289 // cs_wallet lock before calling it. However, the current caller doesn't
2290 // acquire this lock yet. There was an attempt to add the missing lock in
2291 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2292 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2293 // avoid adding some extra complexity to the Qt code.
2295 std::map<CTxDestination, std::vector<COutput>> result;
2297 std::vector<COutput> availableCoins;
2298 AvailableCoins(availableCoins);
2300 LOCK2(cs_main, cs_wallet);
2301 for (auto& coin : availableCoins) {
2302 CTxDestination address;
2303 if (coin.fSpendable &&
2304 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2305 result[address].emplace_back(std::move(coin));
2309 std::vector<COutPoint> lockedCoins;
2310 ListLockedCoins(lockedCoins);
2311 for (const auto& output : lockedCoins) {
2312 auto it = mapWallet.find(output.hash);
2313 if (it != mapWallet.end()) {
2314 int depth = it->second.GetDepthInMainChain();
2315 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2316 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2317 CTxDestination address;
2318 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2319 result[address].emplace_back(
2320 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2326 return result;
2329 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2331 const CTransaction* ptx = &tx;
2332 int n = output;
2333 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2334 const COutPoint& prevout = ptx->vin[0].prevout;
2335 auto it = mapWallet.find(prevout.hash);
2336 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2337 !IsMine(it->second.tx->vout[prevout.n])) {
2338 break;
2340 ptx = it->second.tx.get();
2341 n = prevout.n;
2343 return ptx->vout[n];
2346 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2347 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2349 std::vector<char> vfIncluded;
2351 vfBest.assign(vValue.size(), true);
2352 nBest = nTotalLower;
2354 FastRandomContext insecure_rand;
2356 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2358 vfIncluded.assign(vValue.size(), false);
2359 CAmount nTotal = 0;
2360 bool fReachedTarget = false;
2361 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2363 for (unsigned int i = 0; i < vValue.size(); i++)
2365 //The solver here uses a randomized algorithm,
2366 //the randomness serves no real security purpose but is just
2367 //needed to prevent degenerate behavior and it is important
2368 //that the rng is fast. We do not use a constant random sequence,
2369 //because there may be some privacy improvement by making
2370 //the selection random.
2371 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2373 nTotal += vValue[i].txout.nValue;
2374 vfIncluded[i] = true;
2375 if (nTotal >= nTargetValue)
2377 fReachedTarget = true;
2378 if (nTotal < nBest)
2380 nBest = nTotal;
2381 vfBest = vfIncluded;
2383 nTotal -= vValue[i].txout.nValue;
2384 vfIncluded[i] = false;
2392 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2393 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2395 setCoinsRet.clear();
2396 nValueRet = 0;
2398 // List of values less than target
2399 boost::optional<CInputCoin> coinLowestLarger;
2400 std::vector<CInputCoin> vValue;
2401 CAmount nTotalLower = 0;
2403 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2405 for (const COutput &output : vCoins)
2407 if (!output.fSpendable)
2408 continue;
2410 const CWalletTx *pcoin = output.tx;
2412 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2413 continue;
2415 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2416 continue;
2418 int i = output.i;
2420 CInputCoin coin = CInputCoin(pcoin, i);
2422 if (coin.txout.nValue == nTargetValue)
2424 setCoinsRet.insert(coin);
2425 nValueRet += coin.txout.nValue;
2426 return true;
2428 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2430 vValue.push_back(coin);
2431 nTotalLower += coin.txout.nValue;
2433 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2435 coinLowestLarger = coin;
2439 if (nTotalLower == nTargetValue)
2441 for (const auto& input : vValue)
2443 setCoinsRet.insert(input);
2444 nValueRet += input.txout.nValue;
2446 return true;
2449 if (nTotalLower < nTargetValue)
2451 if (!coinLowestLarger)
2452 return false;
2453 setCoinsRet.insert(coinLowestLarger.get());
2454 nValueRet += coinLowestLarger->txout.nValue;
2455 return true;
2458 // Solve subset sum by stochastic approximation
2459 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2460 std::reverse(vValue.begin(), vValue.end());
2461 std::vector<char> vfBest;
2462 CAmount nBest;
2464 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2465 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2466 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2468 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2469 // or the next bigger coin is closer), return the bigger coin
2470 if (coinLowestLarger &&
2471 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2473 setCoinsRet.insert(coinLowestLarger.get());
2474 nValueRet += coinLowestLarger->txout.nValue;
2476 else {
2477 for (unsigned int i = 0; i < vValue.size(); i++)
2478 if (vfBest[i])
2480 setCoinsRet.insert(vValue[i]);
2481 nValueRet += vValue[i].txout.nValue;
2484 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2485 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2486 for (unsigned int i = 0; i < vValue.size(); i++) {
2487 if (vfBest[i]) {
2488 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2491 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2495 return true;
2498 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2500 std::vector<COutput> vCoins(vAvailableCoins);
2502 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2503 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2505 for (const COutput& out : vCoins)
2507 if (!out.fSpendable)
2508 continue;
2509 nValueRet += out.tx->tx->vout[out.i].nValue;
2510 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2512 return (nValueRet >= nTargetValue);
2515 // calculate value from preset inputs and store them
2516 std::set<CInputCoin> setPresetCoins;
2517 CAmount nValueFromPresetInputs = 0;
2519 std::vector<COutPoint> vPresetInputs;
2520 if (coinControl)
2521 coinControl->ListSelected(vPresetInputs);
2522 for (const COutPoint& outpoint : vPresetInputs)
2524 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2525 if (it != mapWallet.end())
2527 const CWalletTx* pcoin = &it->second;
2528 // Clearly invalid input, fail
2529 if (pcoin->tx->vout.size() <= outpoint.n)
2530 return false;
2531 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2532 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2533 } else
2534 return false; // TODO: Allow non-wallet inputs
2537 // remove preset inputs from vCoins
2538 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2540 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2541 it = vCoins.erase(it);
2542 else
2543 ++it;
2546 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2547 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2549 bool res = nTargetValue <= nValueFromPresetInputs ||
2550 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2551 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2552 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2553 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2554 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2555 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2556 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2558 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2559 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2561 // add preset inputs to the total value selected
2562 nValueRet += nValueFromPresetInputs;
2564 return res;
2567 bool CWallet::SignTransaction(CMutableTransaction &tx)
2569 AssertLockHeld(cs_wallet); // mapWallet
2571 // sign the new tx
2572 CTransaction txNewConst(tx);
2573 int nIn = 0;
2574 for (const auto& input : tx.vin) {
2575 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2576 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2577 return false;
2579 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2580 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2581 SignatureData sigdata;
2582 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2583 return false;
2585 UpdateTransaction(tx, nIn, sigdata);
2586 nIn++;
2588 return true;
2591 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2593 std::vector<CRecipient> vecSend;
2595 // Turn the txout set into a CRecipient vector
2596 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2598 const CTxOut& txOut = tx.vout[idx];
2599 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2600 vecSend.push_back(recipient);
2603 coinControl.fAllowOtherInputs = true;
2605 for (const CTxIn& txin : tx.vin)
2606 coinControl.Select(txin.prevout);
2608 CReserveKey reservekey(this);
2609 CWalletTx wtx;
2610 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2611 return false;
2614 if (nChangePosInOut != -1) {
2615 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2616 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2617 // so just remove the key from the keypool here.
2618 reservekey.KeepKey();
2621 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2622 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2623 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2625 // Add new txins (keeping original txin scriptSig/order)
2626 for (const CTxIn& txin : wtx.tx->vin)
2628 if (!coinControl.IsSelected(txin.prevout))
2630 tx.vin.push_back(txin);
2632 if (lockUnspents)
2634 LOCK2(cs_main, cs_wallet);
2635 LockCoin(txin.prevout);
2641 return true;
2644 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2645 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2647 CAmount nValue = 0;
2648 int nChangePosRequest = nChangePosInOut;
2649 unsigned int nSubtractFeeFromAmount = 0;
2650 for (const auto& recipient : vecSend)
2652 if (nValue < 0 || recipient.nAmount < 0)
2654 strFailReason = _("Transaction amounts must not be negative");
2655 return false;
2657 nValue += recipient.nAmount;
2659 if (recipient.fSubtractFeeFromAmount)
2660 nSubtractFeeFromAmount++;
2662 if (vecSend.empty())
2664 strFailReason = _("Transaction must have at least one recipient");
2665 return false;
2668 wtxNew.fTimeReceivedIsTxTime = true;
2669 wtxNew.BindWallet(this);
2670 CMutableTransaction txNew;
2672 // Discourage fee sniping.
2674 // For a large miner the value of the transactions in the best block and
2675 // the mempool can exceed the cost of deliberately attempting to mine two
2676 // blocks to orphan the current best block. By setting nLockTime such that
2677 // only the next block can include the transaction, we discourage this
2678 // practice as the height restricted and limited blocksize gives miners
2679 // considering fee sniping fewer options for pulling off this attack.
2681 // A simple way to think about this is from the wallet's point of view we
2682 // always want the blockchain to move forward. By setting nLockTime this
2683 // way we're basically making the statement that we only want this
2684 // transaction to appear in the next block; we don't want to potentially
2685 // encourage reorgs by allowing transactions to appear at lower heights
2686 // than the next block in forks of the best chain.
2688 // Of course, the subsidy is high enough, and transaction volume low
2689 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2690 // now we ensure code won't be written that makes assumptions about
2691 // nLockTime that preclude a fix later.
2692 txNew.nLockTime = chainActive.Height();
2694 // Secondly occasionally randomly pick a nLockTime even further back, so
2695 // that transactions that are delayed after signing for whatever reason,
2696 // e.g. high-latency mix networks and some CoinJoin implementations, have
2697 // better privacy.
2698 if (GetRandInt(10) == 0)
2699 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2701 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2702 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2703 FeeCalculation feeCalc;
2704 CAmount nFeeNeeded;
2705 unsigned int nBytes;
2707 std::set<CInputCoin> setCoins;
2708 LOCK2(cs_main, cs_wallet);
2710 std::vector<COutput> vAvailableCoins;
2711 AvailableCoins(vAvailableCoins, true, &coin_control);
2713 // Create change script that will be used if we need change
2714 // TODO: pass in scriptChange instead of reservekey so
2715 // change transaction isn't always pay-to-bitcoin-address
2716 CScript scriptChange;
2718 // coin control: send change to custom address
2719 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2720 scriptChange = GetScriptForDestination(coin_control.destChange);
2721 } else { // no coin control: send change to newly generated address
2722 // Note: We use a new key here to keep it from being obvious which side is the change.
2723 // The drawback is that by not reusing a previous key, the change may be lost if a
2724 // backup is restored, if the backup doesn't have the new private key for the change.
2725 // If we reused the old key, it would be possible to add code to look for and
2726 // rediscover unknown transactions that were written with keys of ours to recover
2727 // post-backup change.
2729 // Reserve a new key pair from key pool
2730 CPubKey vchPubKey;
2731 bool ret;
2732 ret = reservekey.GetReservedKey(vchPubKey, true);
2733 if (!ret)
2735 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2736 return false;
2739 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2741 CTxOut change_prototype_txout(0, scriptChange);
2742 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2744 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2745 nFeeRet = 0;
2746 bool pick_new_inputs = true;
2747 CAmount nValueIn = 0;
2748 // Start with no fee and loop until there is enough fee
2749 while (true)
2751 nChangePosInOut = nChangePosRequest;
2752 txNew.vin.clear();
2753 txNew.vout.clear();
2754 wtxNew.fFromMe = true;
2755 bool fFirst = true;
2757 CAmount nValueToSelect = nValue;
2758 if (nSubtractFeeFromAmount == 0)
2759 nValueToSelect += nFeeRet;
2760 // vouts to the payees
2761 for (const auto& recipient : vecSend)
2763 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2765 if (recipient.fSubtractFeeFromAmount)
2767 assert(nSubtractFeeFromAmount != 0);
2768 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2770 if (fFirst) // first receiver pays the remainder not divisible by output count
2772 fFirst = false;
2773 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2777 if (IsDust(txout, ::dustRelayFee))
2779 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2781 if (txout.nValue < 0)
2782 strFailReason = _("The transaction amount is too small to pay the fee");
2783 else
2784 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2786 else
2787 strFailReason = _("Transaction amount too small");
2788 return false;
2790 txNew.vout.push_back(txout);
2793 // Choose coins to use
2794 if (pick_new_inputs) {
2795 nValueIn = 0;
2796 setCoins.clear();
2797 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2799 strFailReason = _("Insufficient funds");
2800 return false;
2804 const CAmount nChange = nValueIn - nValueToSelect;
2806 if (nChange > 0)
2808 // Fill a vout to ourself
2809 CTxOut newTxOut(nChange, scriptChange);
2811 // Never create dust outputs; if we would, just
2812 // add the dust to the fee.
2813 if (IsDust(newTxOut, discard_rate))
2815 nChangePosInOut = -1;
2816 nFeeRet += nChange;
2818 else
2820 if (nChangePosInOut == -1)
2822 // Insert change txn at random position:
2823 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2825 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2827 strFailReason = _("Change index out of range");
2828 return false;
2831 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2832 txNew.vout.insert(position, newTxOut);
2834 } else {
2835 nChangePosInOut = -1;
2838 // Fill vin
2840 // Note how the sequence number is set to non-maxint so that
2841 // the nLockTime set above actually works.
2843 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2844 // we use the highest possible value in that range (maxint-2)
2845 // to avoid conflicting with other possible uses of nSequence,
2846 // and in the spirit of "smallest possible change from prior
2847 // behavior."
2848 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2849 for (const auto& coin : setCoins)
2850 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2851 nSequence));
2853 // Fill in dummy signatures for fee calculation.
2854 if (!DummySignTx(txNew, setCoins)) {
2855 strFailReason = _("Signing transaction failed");
2856 return false;
2859 nBytes = GetVirtualTransactionSize(txNew);
2861 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2862 for (auto& vin : txNew.vin) {
2863 vin.scriptSig = CScript();
2864 vin.scriptWitness.SetNull();
2867 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2869 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2870 // because we must be at the maximum allowed fee.
2871 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2873 strFailReason = _("Transaction too large for fee policy");
2874 return false;
2877 if (nFeeRet >= nFeeNeeded) {
2878 // Reduce fee to only the needed amount if possible. This
2879 // prevents potential overpayment in fees if the coins
2880 // selected to meet nFeeNeeded result in a transaction that
2881 // requires less fee than the prior iteration.
2883 // If we have no change and a big enough excess fee, then
2884 // try to construct transaction again only without picking
2885 // new inputs. We now know we only need the smaller fee
2886 // (because of reduced tx size) and so we should add a
2887 // change output. Only try this once.
2888 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2889 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2890 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2891 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2892 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2893 pick_new_inputs = false;
2894 nFeeRet = fee_needed_with_change;
2895 continue;
2899 // If we have change output already, just increase it
2900 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2901 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2902 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2903 change_position->nValue += extraFeePaid;
2904 nFeeRet -= extraFeePaid;
2906 break; // Done, enough fee included.
2908 else if (!pick_new_inputs) {
2909 // This shouldn't happen, we should have had enough excess
2910 // fee to pay for the new output and still meet nFeeNeeded
2911 // Or we should have just subtracted fee from recipients and
2912 // nFeeNeeded should not have changed
2913 strFailReason = _("Transaction fee and change calculation failed");
2914 return false;
2917 // Try to reduce change to include necessary fee
2918 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2919 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2920 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2921 // Only reduce change if remaining amount is still a large enough output.
2922 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2923 change_position->nValue -= additionalFeeNeeded;
2924 nFeeRet += additionalFeeNeeded;
2925 break; // Done, able to increase fee from change
2929 // If subtracting fee from recipients, we now know what fee we
2930 // need to subtract, we have no reason to reselect inputs
2931 if (nSubtractFeeFromAmount > 0) {
2932 pick_new_inputs = false;
2935 // Include more fee and try again.
2936 nFeeRet = nFeeNeeded;
2937 continue;
2941 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2943 if (sign)
2945 CTransaction txNewConst(txNew);
2946 int nIn = 0;
2947 for (const auto& coin : setCoins)
2949 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2950 SignatureData sigdata;
2952 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2954 strFailReason = _("Signing transaction failed");
2955 return false;
2956 } else {
2957 UpdateTransaction(txNew, nIn, sigdata);
2960 nIn++;
2964 // Embed the constructed transaction data in wtxNew.
2965 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2967 // Limit size
2968 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2970 strFailReason = _("Transaction too large");
2971 return false;
2975 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2976 // Lastly, ensure this tx will pass the mempool's chain limits
2977 LockPoints lp;
2978 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2979 CTxMemPool::setEntries setAncestors;
2980 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2981 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2982 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2983 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2984 std::string errString;
2985 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2986 strFailReason = _("Transaction has too long of a mempool chain");
2987 return false;
2991 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",
2992 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2993 feeCalc.est.pass.start, feeCalc.est.pass.end,
2994 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2995 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2996 feeCalc.est.fail.start, feeCalc.est.fail.end,
2997 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2998 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2999 return true;
3003 * Call after CreateTransaction unless you want to abort
3005 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3008 LOCK2(cs_main, cs_wallet);
3009 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3011 // Take key pair from key pool so it won't be used again
3012 reservekey.KeepKey();
3014 // Add tx to wallet, because if it has change it's also ours,
3015 // otherwise just for transaction history.
3016 AddToWallet(wtxNew);
3018 // Notify that old coins are spent
3019 for (const CTxIn& txin : wtxNew.tx->vin)
3021 CWalletTx &coin = mapWallet[txin.prevout.hash];
3022 coin.BindWallet(this);
3023 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3027 // Track how many getdata requests our transaction gets
3028 mapRequestCount[wtxNew.GetHash()] = 0;
3030 // Get the inserted-CWalletTx from mapWallet so that the
3031 // fInMempool flag is cached properly
3032 CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
3034 if (fBroadcastTransactions)
3036 // Broadcast
3037 if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
3038 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3039 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3040 } else {
3041 wtx.RelayWalletTransaction(connman);
3045 return true;
3048 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3049 CWalletDB walletdb(*dbw);
3050 return walletdb.ListAccountCreditDebit(strAccount, entries);
3053 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3055 CWalletDB walletdb(*dbw);
3057 return AddAccountingEntry(acentry, &walletdb);
3060 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3062 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3063 return false;
3066 laccentries.push_back(acentry);
3067 CAccountingEntry & entry = laccentries.back();
3068 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3070 return true;
3073 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3075 LOCK2(cs_main, cs_wallet);
3077 fFirstRunRet = false;
3078 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3079 if (nLoadWalletRet == DB_NEED_REWRITE)
3081 if (dbw->Rewrite("\x04pool"))
3083 setInternalKeyPool.clear();
3084 setExternalKeyPool.clear();
3085 m_pool_key_to_index.clear();
3086 // Note: can't top-up keypool here, because wallet is locked.
3087 // User will be prompted to unlock wallet the next operation
3088 // that requires a new key.
3092 // This wallet is in its first run if all of these are empty
3093 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3095 if (nLoadWalletRet != DB_LOAD_OK)
3096 return nLoadWalletRet;
3098 uiInterface.LoadWallet(this);
3100 return DB_LOAD_OK;
3103 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3105 AssertLockHeld(cs_wallet); // mapWallet
3106 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3107 for (uint256 hash : vHashOut)
3108 mapWallet.erase(hash);
3110 if (nZapSelectTxRet == DB_NEED_REWRITE)
3112 if (dbw->Rewrite("\x04pool"))
3114 setInternalKeyPool.clear();
3115 setExternalKeyPool.clear();
3116 m_pool_key_to_index.clear();
3117 // Note: can't top-up keypool here, because wallet is locked.
3118 // User will be prompted to unlock wallet the next operation
3119 // that requires a new key.
3123 if (nZapSelectTxRet != DB_LOAD_OK)
3124 return nZapSelectTxRet;
3126 MarkDirty();
3128 return DB_LOAD_OK;
3132 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3134 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3135 if (nZapWalletTxRet == DB_NEED_REWRITE)
3137 if (dbw->Rewrite("\x04pool"))
3139 LOCK(cs_wallet);
3140 setInternalKeyPool.clear();
3141 setExternalKeyPool.clear();
3142 m_pool_key_to_index.clear();
3143 // Note: can't top-up keypool here, because wallet is locked.
3144 // User will be prompted to unlock wallet the next operation
3145 // that requires a new key.
3149 if (nZapWalletTxRet != DB_LOAD_OK)
3150 return nZapWalletTxRet;
3152 return DB_LOAD_OK;
3156 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3158 bool fUpdated = false;
3160 LOCK(cs_wallet); // mapAddressBook
3161 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3162 fUpdated = mi != mapAddressBook.end();
3163 mapAddressBook[address].name = strName;
3164 if (!strPurpose.empty()) /* update purpose only if requested */
3165 mapAddressBook[address].purpose = strPurpose;
3167 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3168 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3169 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3170 return false;
3171 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3174 bool CWallet::DelAddressBook(const CTxDestination& address)
3177 LOCK(cs_wallet); // mapAddressBook
3179 // Delete destdata tuples associated with address
3180 std::string strAddress = EncodeDestination(address);
3181 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3183 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3185 mapAddressBook.erase(address);
3188 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3190 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3191 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3194 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3196 CTxDestination address;
3197 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3198 auto mi = mapAddressBook.find(address);
3199 if (mi != mapAddressBook.end()) {
3200 return mi->second.name;
3203 // A scriptPubKey that doesn't have an entry in the address book is
3204 // associated with the default account ("").
3205 const static std::string DEFAULT_ACCOUNT_NAME;
3206 return DEFAULT_ACCOUNT_NAME;
3210 * Mark old keypool keys as used,
3211 * and generate all new keys
3213 bool CWallet::NewKeyPool()
3216 LOCK(cs_wallet);
3217 CWalletDB walletdb(*dbw);
3219 for (int64_t nIndex : setInternalKeyPool) {
3220 walletdb.ErasePool(nIndex);
3222 setInternalKeyPool.clear();
3224 for (int64_t nIndex : setExternalKeyPool) {
3225 walletdb.ErasePool(nIndex);
3227 setExternalKeyPool.clear();
3229 m_pool_key_to_index.clear();
3231 if (!TopUpKeyPool()) {
3232 return false;
3234 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3236 return true;
3239 size_t CWallet::KeypoolCountExternalKeys()
3241 AssertLockHeld(cs_wallet); // setExternalKeyPool
3242 return setExternalKeyPool.size();
3245 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3247 AssertLockHeld(cs_wallet);
3248 if (keypool.fInternal) {
3249 setInternalKeyPool.insert(nIndex);
3250 } else {
3251 setExternalKeyPool.insert(nIndex);
3253 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3254 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3256 // If no metadata exists yet, create a default with the pool key's
3257 // creation time. Note that this may be overwritten by actually
3258 // stored metadata for that key later, which is fine.
3259 CKeyID keyid = keypool.vchPubKey.GetID();
3260 if (mapKeyMetadata.count(keyid) == 0)
3261 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3264 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3267 LOCK(cs_wallet);
3269 if (IsLocked())
3270 return false;
3272 // Top up key pool
3273 unsigned int nTargetSize;
3274 if (kpSize > 0)
3275 nTargetSize = kpSize;
3276 else
3277 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3279 // count amount of available keys (internal, external)
3280 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3281 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3282 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3284 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3286 // don't create extra internal keys
3287 missingInternal = 0;
3289 bool internal = false;
3290 CWalletDB walletdb(*dbw);
3291 for (int64_t i = missingInternal + missingExternal; i--;)
3293 if (i < missingInternal) {
3294 internal = true;
3297 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3298 int64_t index = ++m_max_keypool_index;
3300 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3301 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3302 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3305 if (internal) {
3306 setInternalKeyPool.insert(index);
3307 } else {
3308 setExternalKeyPool.insert(index);
3310 m_pool_key_to_index[pubkey.GetID()] = index;
3312 if (missingInternal + missingExternal > 0) {
3313 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3316 return true;
3319 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3321 nIndex = -1;
3322 keypool.vchPubKey = CPubKey();
3324 LOCK(cs_wallet);
3326 if (!IsLocked())
3327 TopUpKeyPool();
3329 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3330 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3332 // Get the oldest key
3333 if(setKeyPool.empty())
3334 return;
3336 CWalletDB walletdb(*dbw);
3338 auto it = setKeyPool.begin();
3339 nIndex = *it;
3340 setKeyPool.erase(it);
3341 if (!walletdb.ReadPool(nIndex, keypool)) {
3342 throw std::runtime_error(std::string(__func__) + ": read failed");
3344 if (!HaveKey(keypool.vchPubKey.GetID())) {
3345 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3347 if (keypool.fInternal != fReturningInternal) {
3348 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3351 assert(keypool.vchPubKey.IsValid());
3352 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3353 LogPrintf("keypool reserve %d\n", nIndex);
3357 void CWallet::KeepKey(int64_t nIndex)
3359 // Remove from key pool
3360 CWalletDB walletdb(*dbw);
3361 walletdb.ErasePool(nIndex);
3362 LogPrintf("keypool keep %d\n", nIndex);
3365 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3367 // Return to key pool
3369 LOCK(cs_wallet);
3370 if (fInternal) {
3371 setInternalKeyPool.insert(nIndex);
3372 } else {
3373 setExternalKeyPool.insert(nIndex);
3375 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3377 LogPrintf("keypool return %d\n", nIndex);
3380 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3382 CKeyPool keypool;
3384 LOCK(cs_wallet);
3385 int64_t nIndex = 0;
3386 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3387 if (nIndex == -1)
3389 if (IsLocked()) return false;
3390 CWalletDB walletdb(*dbw);
3391 result = GenerateNewKey(walletdb, internal);
3392 return true;
3394 KeepKey(nIndex);
3395 result = keypool.vchPubKey;
3397 return true;
3400 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3401 if (setKeyPool.empty()) {
3402 return GetTime();
3405 CKeyPool keypool;
3406 int64_t nIndex = *(setKeyPool.begin());
3407 if (!walletdb.ReadPool(nIndex, keypool)) {
3408 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3410 assert(keypool.vchPubKey.IsValid());
3411 return keypool.nTime;
3414 int64_t CWallet::GetOldestKeyPoolTime()
3416 LOCK(cs_wallet);
3418 CWalletDB walletdb(*dbw);
3420 // load oldest key from keypool, get time and return
3421 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3422 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3423 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3426 return oldestKey;
3429 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3431 std::map<CTxDestination, CAmount> balances;
3434 LOCK(cs_wallet);
3435 for (const auto& walletEntry : mapWallet)
3437 const CWalletTx *pcoin = &walletEntry.second;
3439 if (!pcoin->IsTrusted())
3440 continue;
3442 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3443 continue;
3445 int nDepth = pcoin->GetDepthInMainChain();
3446 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3447 continue;
3449 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3451 CTxDestination addr;
3452 if (!IsMine(pcoin->tx->vout[i]))
3453 continue;
3454 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3455 continue;
3457 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3459 if (!balances.count(addr))
3460 balances[addr] = 0;
3461 balances[addr] += n;
3466 return balances;
3469 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3471 AssertLockHeld(cs_wallet); // mapWallet
3472 std::set< std::set<CTxDestination> > groupings;
3473 std::set<CTxDestination> grouping;
3475 for (const auto& walletEntry : mapWallet)
3477 const CWalletTx *pcoin = &walletEntry.second;
3479 if (pcoin->tx->vin.size() > 0)
3481 bool any_mine = false;
3482 // group all input addresses with each other
3483 for (CTxIn txin : pcoin->tx->vin)
3485 CTxDestination address;
3486 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3487 continue;
3488 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3489 continue;
3490 grouping.insert(address);
3491 any_mine = true;
3494 // group change with input addresses
3495 if (any_mine)
3497 for (CTxOut txout : pcoin->tx->vout)
3498 if (IsChange(txout))
3500 CTxDestination txoutAddr;
3501 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3502 continue;
3503 grouping.insert(txoutAddr);
3506 if (grouping.size() > 0)
3508 groupings.insert(grouping);
3509 grouping.clear();
3513 // group lone addrs by themselves
3514 for (const auto& txout : pcoin->tx->vout)
3515 if (IsMine(txout))
3517 CTxDestination address;
3518 if(!ExtractDestination(txout.scriptPubKey, address))
3519 continue;
3520 grouping.insert(address);
3521 groupings.insert(grouping);
3522 grouping.clear();
3526 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3527 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3528 for (std::set<CTxDestination> _grouping : groupings)
3530 // make a set of all the groups hit by this new group
3531 std::set< std::set<CTxDestination>* > hits;
3532 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3533 for (CTxDestination address : _grouping)
3534 if ((it = setmap.find(address)) != setmap.end())
3535 hits.insert((*it).second);
3537 // merge all hit groups into a new single group and delete old groups
3538 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3539 for (std::set<CTxDestination>* hit : hits)
3541 merged->insert(hit->begin(), hit->end());
3542 uniqueGroupings.erase(hit);
3543 delete hit;
3545 uniqueGroupings.insert(merged);
3547 // update setmap
3548 for (CTxDestination element : *merged)
3549 setmap[element] = merged;
3552 std::set< std::set<CTxDestination> > ret;
3553 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3555 ret.insert(*uniqueGrouping);
3556 delete uniqueGrouping;
3559 return ret;
3562 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3564 LOCK(cs_wallet);
3565 std::set<CTxDestination> result;
3566 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3568 const CTxDestination& address = item.first;
3569 const std::string& strName = item.second.name;
3570 if (strName == strAccount)
3571 result.insert(address);
3573 return result;
3576 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3578 if (nIndex == -1)
3580 CKeyPool keypool;
3581 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3582 if (nIndex != -1)
3583 vchPubKey = keypool.vchPubKey;
3584 else {
3585 return false;
3587 fInternal = keypool.fInternal;
3589 assert(vchPubKey.IsValid());
3590 pubkey = vchPubKey;
3591 return true;
3594 void CReserveKey::KeepKey()
3596 if (nIndex != -1)
3597 pwallet->KeepKey(nIndex);
3598 nIndex = -1;
3599 vchPubKey = CPubKey();
3602 void CReserveKey::ReturnKey()
3604 if (nIndex != -1) {
3605 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3607 nIndex = -1;
3608 vchPubKey = CPubKey();
3611 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3613 AssertLockHeld(cs_wallet);
3614 bool internal = setInternalKeyPool.count(keypool_id);
3615 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3616 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3617 auto it = setKeyPool->begin();
3619 CWalletDB walletdb(*dbw);
3620 while (it != std::end(*setKeyPool)) {
3621 const int64_t& index = *(it);
3622 if (index > keypool_id) break; // set*KeyPool is ordered
3624 CKeyPool keypool;
3625 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3626 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3628 walletdb.ErasePool(index);
3629 LogPrintf("keypool index %d removed\n", index);
3630 it = setKeyPool->erase(it);
3634 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3636 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3637 CPubKey pubkey;
3638 if (!rKey->GetReservedKey(pubkey))
3639 return;
3641 script = rKey;
3642 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3645 void CWallet::LockCoin(const COutPoint& output)
3647 AssertLockHeld(cs_wallet); // setLockedCoins
3648 setLockedCoins.insert(output);
3651 void CWallet::UnlockCoin(const COutPoint& output)
3653 AssertLockHeld(cs_wallet); // setLockedCoins
3654 setLockedCoins.erase(output);
3657 void CWallet::UnlockAllCoins()
3659 AssertLockHeld(cs_wallet); // setLockedCoins
3660 setLockedCoins.clear();
3663 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3665 AssertLockHeld(cs_wallet); // setLockedCoins
3666 COutPoint outpt(hash, n);
3668 return (setLockedCoins.count(outpt) > 0);
3671 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3673 AssertLockHeld(cs_wallet); // setLockedCoins
3674 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3675 it != setLockedCoins.end(); it++) {
3676 COutPoint outpt = (*it);
3677 vOutpts.push_back(outpt);
3681 /** @} */ // end of Actions
3683 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3684 AssertLockHeld(cs_wallet); // mapKeyMetadata
3685 mapKeyBirth.clear();
3687 // get birth times for keys with metadata
3688 for (const auto& entry : mapKeyMetadata) {
3689 if (entry.second.nCreateTime) {
3690 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3694 // map in which we'll infer heights of other keys
3695 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3696 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3697 for (const CKeyID &keyid : GetKeys()) {
3698 if (mapKeyBirth.count(keyid) == 0)
3699 mapKeyFirstBlock[keyid] = pindexMax;
3702 // if there are no such keys, we're done
3703 if (mapKeyFirstBlock.empty())
3704 return;
3706 // find first block that affects those keys, if there are any left
3707 std::vector<CKeyID> vAffected;
3708 for (const auto& entry : mapWallet) {
3709 // iterate over all wallet transactions...
3710 const CWalletTx &wtx = entry.second;
3711 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3712 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3713 // ... which are already in a block
3714 int nHeight = blit->second->nHeight;
3715 for (const CTxOut &txout : wtx.tx->vout) {
3716 // iterate over all their outputs
3717 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3718 for (const CKeyID &keyid : vAffected) {
3719 // ... and all their affected keys
3720 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3721 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3722 rit->second = blit->second;
3724 vAffected.clear();
3729 // Extract block timestamps for those keys
3730 for (const auto& entry : mapKeyFirstBlock)
3731 mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3735 * Compute smart timestamp for a transaction being added to the wallet.
3737 * Logic:
3738 * - If sending a transaction, assign its timestamp to the current time.
3739 * - If receiving a transaction outside a block, assign its timestamp to the
3740 * current time.
3741 * - If receiving a block with a future timestamp, assign all its (not already
3742 * known) transactions' timestamps to the current time.
3743 * - If receiving a block with a past timestamp, before the most recent known
3744 * transaction (that we care about), assign all its (not already known)
3745 * transactions' timestamps to the same timestamp as that most-recent-known
3746 * transaction.
3747 * - If receiving a block with a past timestamp, but after the most recent known
3748 * transaction, assign all its (not already known) transactions' timestamps to
3749 * the block time.
3751 * For more information see CWalletTx::nTimeSmart,
3752 * https://bitcointalk.org/?topic=54527, or
3753 * https://github.com/bitcoin/bitcoin/pull/1393.
3755 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3757 unsigned int nTimeSmart = wtx.nTimeReceived;
3758 if (!wtx.hashUnset()) {
3759 if (mapBlockIndex.count(wtx.hashBlock)) {
3760 int64_t latestNow = wtx.nTimeReceived;
3761 int64_t latestEntry = 0;
3763 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3764 int64_t latestTolerated = latestNow + 300;
3765 const TxItems& txOrdered = wtxOrdered;
3766 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3767 CWalletTx* const pwtx = it->second.first;
3768 if (pwtx == &wtx) {
3769 continue;
3771 CAccountingEntry* const pacentry = it->second.second;
3772 int64_t nSmartTime;
3773 if (pwtx) {
3774 nSmartTime = pwtx->nTimeSmart;
3775 if (!nSmartTime) {
3776 nSmartTime = pwtx->nTimeReceived;
3778 } else {
3779 nSmartTime = pacentry->nTime;
3781 if (nSmartTime <= latestTolerated) {
3782 latestEntry = nSmartTime;
3783 if (nSmartTime > latestNow) {
3784 latestNow = nSmartTime;
3786 break;
3790 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3791 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3792 } else {
3793 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3796 return nTimeSmart;
3799 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3801 if (boost::get<CNoDestination>(&dest))
3802 return false;
3804 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3805 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3808 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3810 if (!mapAddressBook[dest].destdata.erase(key))
3811 return false;
3812 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3815 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3817 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3818 return true;
3821 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3823 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3824 if(i != mapAddressBook.end())
3826 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3827 if(j != i->second.destdata.end())
3829 if(value)
3830 *value = j->second;
3831 return true;
3834 return false;
3837 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3839 LOCK(cs_wallet);
3840 std::vector<std::string> values;
3841 for (const auto& address : mapAddressBook) {
3842 for (const auto& data : address.second.destdata) {
3843 if (!data.first.compare(0, prefix.size(), prefix)) {
3844 values.emplace_back(data.second);
3848 return values;
3851 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3853 // needed to restore wallet transaction meta data after -zapwallettxes
3854 std::vector<CWalletTx> vWtx;
3856 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3857 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3859 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3860 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3861 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3862 if (nZapWalletRet != DB_LOAD_OK) {
3863 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3864 return nullptr;
3868 uiInterface.InitMessage(_("Loading wallet..."));
3870 int64_t nStart = GetTimeMillis();
3871 bool fFirstRun = true;
3872 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3873 CWallet *walletInstance = new CWallet(std::move(dbw));
3874 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3875 if (nLoadWalletRet != DB_LOAD_OK)
3877 if (nLoadWalletRet == DB_CORRUPT) {
3878 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3879 return nullptr;
3881 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3883 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3884 " or address book entries might be missing or incorrect."),
3885 walletFile));
3887 else if (nLoadWalletRet == DB_TOO_NEW) {
3888 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3889 return nullptr;
3891 else if (nLoadWalletRet == DB_NEED_REWRITE)
3893 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3894 return nullptr;
3896 else {
3897 InitError(strprintf(_("Error loading %s"), walletFile));
3898 return nullptr;
3902 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3904 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3905 if (nMaxVersion == 0) // the -upgradewallet without argument case
3907 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3908 nMaxVersion = CLIENT_VERSION;
3909 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3911 else
3912 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3913 if (nMaxVersion < walletInstance->GetVersion())
3915 InitError(_("Cannot downgrade wallet"));
3916 return nullptr;
3918 walletInstance->SetMaxVersion(nMaxVersion);
3921 if (fFirstRun)
3923 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3924 if (!gArgs.GetBoolArg("-usehd", true)) {
3925 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3926 return nullptr;
3928 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3930 // generate a new master key
3931 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3932 if (!walletInstance->SetHDMasterKey(masterPubKey))
3933 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3935 // Top up the keypool
3936 if (!walletInstance->TopUpKeyPool()) {
3937 InitError(_("Unable to generate initial keys") += "\n");
3938 return nullptr;
3941 walletInstance->SetBestChain(chainActive.GetLocator());
3943 else if (gArgs.IsArgSet("-usehd")) {
3944 bool useHD = gArgs.GetBoolArg("-usehd", true);
3945 if (walletInstance->IsHDEnabled() && !useHD) {
3946 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3947 return nullptr;
3949 if (!walletInstance->IsHDEnabled() && useHD) {
3950 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3951 return nullptr;
3955 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3957 // Try to top up keypool. No-op if the wallet is locked.
3958 walletInstance->TopUpKeyPool();
3960 CBlockIndex *pindexRescan = chainActive.Genesis();
3961 if (!gArgs.GetBoolArg("-rescan", false))
3963 CWalletDB walletdb(*walletInstance->dbw);
3964 CBlockLocator locator;
3965 if (walletdb.ReadBestBlock(locator))
3966 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3969 walletInstance->m_last_block_processed = chainActive.Tip();
3970 RegisterValidationInterface(walletInstance);
3972 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3974 //We can't rescan beyond non-pruned blocks, stop and throw an error
3975 //this might happen if a user uses an old wallet within a pruned node
3976 // or if he ran -disablewallet for a longer time, then decided to re-enable
3977 if (fPruneMode)
3979 CBlockIndex *block = chainActive.Tip();
3980 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3981 block = block->pprev;
3983 if (pindexRescan != block) {
3984 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3985 return nullptr;
3989 uiInterface.InitMessage(_("Rescanning..."));
3990 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3992 // No need to read and scan block if block was created before
3993 // our wallet birthday (as adjusted for block time variability)
3994 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3995 pindexRescan = chainActive.Next(pindexRescan);
3998 nStart = GetTimeMillis();
3999 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
4000 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4001 walletInstance->SetBestChain(chainActive.GetLocator());
4002 walletInstance->dbw->IncrementUpdateCounter();
4004 // Restore wallet transaction metadata after -zapwallettxes=1
4005 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4007 CWalletDB walletdb(*walletInstance->dbw);
4009 for (const CWalletTx& wtxOld : vWtx)
4011 uint256 hash = wtxOld.GetHash();
4012 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4013 if (mi != walletInstance->mapWallet.end())
4015 const CWalletTx* copyFrom = &wtxOld;
4016 CWalletTx* copyTo = &mi->second;
4017 copyTo->mapValue = copyFrom->mapValue;
4018 copyTo->vOrderForm = copyFrom->vOrderForm;
4019 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4020 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4021 copyTo->fFromMe = copyFrom->fFromMe;
4022 copyTo->strFromAccount = copyFrom->strFromAccount;
4023 copyTo->nOrderPos = copyFrom->nOrderPos;
4024 walletdb.WriteTx(*copyTo);
4029 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4032 LOCK(walletInstance->cs_wallet);
4033 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4034 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4035 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4038 return walletInstance;
4041 std::atomic<bool> CWallet::fFlushScheduled(false);
4043 void CWallet::postInitProcess(CScheduler& scheduler)
4045 // Add wallet transactions that aren't already in a block to mempool
4046 // Do this here as mempool requires genesis block to be loaded
4047 ReacceptWalletTransactions();
4049 // Run a thread to flush wallet periodically
4050 if (!CWallet::fFlushScheduled.exchange(true)) {
4051 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4055 bool CWallet::BackupWallet(const std::string& strDest)
4057 return dbw->Backup(strDest);
4060 CKeyPool::CKeyPool()
4062 nTime = GetTime();
4063 fInternal = false;
4066 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4068 nTime = GetTime();
4069 vchPubKey = vchPubKeyIn;
4070 fInternal = internalIn;
4073 CWalletKey::CWalletKey(int64_t nExpires)
4075 nTimeCreated = (nExpires ? GetTime() : 0);
4076 nTimeExpires = nExpires;
4079 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4081 // Update the tx's hashBlock
4082 hashBlock = pindex->GetBlockHash();
4084 // set the position of the transaction in the block
4085 nIndex = posInBlock;
4088 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4090 if (hashUnset())
4091 return 0;
4093 AssertLockHeld(cs_main);
4095 // Find the block it claims to be in
4096 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4097 if (mi == mapBlockIndex.end())
4098 return 0;
4099 CBlockIndex* pindex = (*mi).second;
4100 if (!pindex || !chainActive.Contains(pindex))
4101 return 0;
4103 pindexRet = pindex;
4104 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4107 int CMerkleTx::GetBlocksToMaturity() const
4109 if (!IsCoinBase())
4110 return 0;
4111 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4115 bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4117 // Quick check to avoid re-setting fInMempool to false
4118 if (mempool.exists(tx->GetHash())) {
4119 return false;
4122 // We must set fInMempool here - while it will be re-set to true by the
4123 // entered-mempool callback, if we did not there would be a race where a
4124 // user could call sendmoney in a loop and hit spurious out of funds errors
4125 // because we think that the transaction they just generated's change is
4126 // unavailable as we're not yet aware its in mempool.
4127 bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4128 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
4129 fInMempool = ret;
4130 return ret;