Merge #11854: Split up key and script metadata for better type safety
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob873a8d855e57036912e493cb552ee6aa0ad5b057
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <wallet/wallet.h>
8 #include <base58.h>
9 #include <checkpoints.h>
10 #include <chain.h>
11 #include <wallet/coincontrol.h>
12 #include <consensus/consensus.h>
13 #include <consensus/validation.h>
14 #include <fs.h>
15 #include <wallet/init.h>
16 #include <key.h>
17 #include <keystore.h>
18 #include <validation.h>
19 #include <net.h>
20 #include <policy/fees.h>
21 #include <policy/policy.h>
22 #include <policy/rbf.h>
23 #include <primitives/block.h>
24 #include <primitives/transaction.h>
25 #include <script/script.h>
26 #include <scheduler.h>
27 #include <timedata.h>
28 #include <txmempool.h>
29 #include <util.h>
30 #include <utilmoneystr.h>
31 #include <wallet/fees.h>
33 #include <assert.h>
34 #include <future>
36 #include <boost/algorithm/string/replace.hpp>
37 #include <boost/thread.hpp>
39 std::vector<CWalletRef> vpwallets;
40 /** Transaction fee set by the user */
41 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
42 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
43 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
44 bool fWalletRbf = DEFAULT_WALLET_RBF;
46 const char * DEFAULT_WALLET_DAT = "wallet.dat";
47 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
49 /**
50 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
51 * Override with -mintxfee
53 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
54 /**
55 * If fee estimation does not have enough data to provide estimates, use this fee instead.
56 * Has no effect if not using fee estimation
57 * Override with -fallbackfee
59 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
61 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
63 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
65 /** @defgroup mapWallet
67 * @{
70 struct CompareValueOnly
72 bool operator()(const CInputCoin& t1,
73 const CInputCoin& t2) const
75 return t1.txout.nValue < t2.txout.nValue;
79 std::string COutput::ToString() const
81 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
84 class CAffectedKeysVisitor : public boost::static_visitor<void> {
85 private:
86 const CKeyStore &keystore;
87 std::vector<CKeyID> &vKeys;
89 public:
90 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
92 void Process(const CScript &script) {
93 txnouttype type;
94 std::vector<CTxDestination> vDest;
95 int nRequired;
96 if (ExtractDestinations(script, type, vDest, nRequired)) {
97 for (const CTxDestination &dest : vDest)
98 boost::apply_visitor(*this, dest);
102 void operator()(const CKeyID &keyId) {
103 if (keystore.HaveKey(keyId))
104 vKeys.push_back(keyId);
107 void operator()(const CScriptID &scriptId) {
108 CScript script;
109 if (keystore.GetCScript(scriptId, script))
110 Process(script);
113 void operator()(const WitnessV0ScriptHash& scriptID)
115 CScriptID id;
116 CRIPEMD160().Write(scriptID.begin(), 32).Finalize(id.begin());
117 CScript script;
118 if (keystore.GetCScript(id, script)) {
119 Process(script);
123 void operator()(const WitnessV0KeyHash& keyid)
125 CKeyID id(keyid);
126 if (keystore.HaveKey(id)) {
127 vKeys.push_back(id);
131 template<typename X>
132 void operator()(const X &none) {}
135 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
137 LOCK(cs_wallet);
138 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
139 if (it == mapWallet.end())
140 return nullptr;
141 return &(it->second);
144 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
146 AssertLockHeld(cs_wallet); // mapKeyMetadata
147 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
149 CKey secret;
151 // Create new metadata
152 int64_t nCreationTime = GetTime();
153 CKeyMetadata metadata(nCreationTime);
155 // use HD key derivation if HD was enabled during wallet creation
156 if (IsHDEnabled()) {
157 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
158 } else {
159 secret.MakeNewKey(fCompressed);
162 // Compressed public keys were introduced in version 0.6.0
163 if (fCompressed) {
164 SetMinVersion(FEATURE_COMPRPUBKEY);
167 CPubKey pubkey = secret.GetPubKey();
168 assert(secret.VerifyPubKey(pubkey));
170 mapKeyMetadata[pubkey.GetID()] = metadata;
171 UpdateTimeFirstKey(nCreationTime);
173 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
174 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
176 return pubkey;
179 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
181 // for now we use a fixed keypath scheme of m/0'/0'/k
182 CKey key; //master key seed (256bit)
183 CExtKey masterKey; //hd master key
184 CExtKey accountKey; //key at m/0'
185 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
186 CExtKey childKey; //key at m/0'/0'/<n>'
188 // try to get the master key
189 if (!GetKey(hdChain.masterKeyID, key))
190 throw std::runtime_error(std::string(__func__) + ": Master key not found");
192 masterKey.SetMaster(key.begin(), key.size());
194 // derive m/0'
195 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
196 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
198 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
199 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
200 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
202 // derive child key at next index, skip keys already known to the wallet
203 do {
204 // always derive hardened keys
205 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
206 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
207 if (internal) {
208 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
209 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
210 hdChain.nInternalChainCounter++;
212 else {
213 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
214 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
215 hdChain.nExternalChainCounter++;
217 } while (HaveKey(childKey.key.GetPubKey().GetID()));
218 secret = childKey.key;
219 metadata.hdMasterKeyID = hdChain.masterKeyID;
220 // update the chain model in the database
221 if (!walletdb.WriteHDChain(hdChain))
222 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
225 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
227 AssertLockHeld(cs_wallet); // mapKeyMetadata
229 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
230 // which is overridden below. To avoid flushes, the database handle is
231 // tunneled through to it.
232 bool needsDB = !pwalletdbEncryption;
233 if (needsDB) {
234 pwalletdbEncryption = &walletdb;
236 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
237 if (needsDB) pwalletdbEncryption = nullptr;
238 return false;
240 if (needsDB) pwalletdbEncryption = nullptr;
242 // check if we need to remove from watch-only
243 CScript script;
244 script = GetScriptForDestination(pubkey.GetID());
245 if (HaveWatchOnly(script)) {
246 RemoveWatchOnly(script);
248 script = GetScriptForRawPubKey(pubkey);
249 if (HaveWatchOnly(script)) {
250 RemoveWatchOnly(script);
253 if (!IsCrypted()) {
254 return walletdb.WriteKey(pubkey,
255 secret.GetPrivKey(),
256 mapKeyMetadata[pubkey.GetID()]);
258 return true;
261 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
263 CWalletDB walletdb(*dbw);
264 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
267 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
268 const std::vector<unsigned char> &vchCryptedSecret)
270 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
271 return false;
273 LOCK(cs_wallet);
274 if (pwalletdbEncryption)
275 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
276 vchCryptedSecret,
277 mapKeyMetadata[vchPubKey.GetID()]);
278 else
279 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
280 vchCryptedSecret,
281 mapKeyMetadata[vchPubKey.GetID()]);
285 bool CWallet::LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &meta)
287 AssertLockHeld(cs_wallet); // mapKeyMetadata
288 UpdateTimeFirstKey(meta.nCreateTime);
289 mapKeyMetadata[keyID] = meta;
290 return true;
293 bool CWallet::LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &meta)
295 AssertLockHeld(cs_wallet); // m_script_metadata
296 UpdateTimeFirstKey(meta.nCreateTime);
297 m_script_metadata[script_id] = meta;
298 return true;
301 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
303 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
307 * Update wallet first key creation time. This should be called whenever keys
308 * are added to the wallet, with the oldest key creation time.
310 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
312 AssertLockHeld(cs_wallet);
313 if (nCreateTime <= 1) {
314 // Cannot determine birthday information, so set the wallet birthday to
315 // the beginning of time.
316 nTimeFirstKey = 1;
317 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
318 nTimeFirstKey = nCreateTime;
322 bool CWallet::AddCScript(const CScript& redeemScript)
324 if (!CCryptoKeyStore::AddCScript(redeemScript))
325 return false;
326 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
329 bool CWallet::LoadCScript(const CScript& redeemScript)
331 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
332 * that never can be redeemed. However, old wallets may still contain
333 * these. Do not add them to the wallet and warn. */
334 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
336 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
337 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
338 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
339 return true;
342 return CCryptoKeyStore::AddCScript(redeemScript);
345 bool CWallet::AddWatchOnly(const CScript& dest)
347 if (!CCryptoKeyStore::AddWatchOnly(dest))
348 return false;
349 const CKeyMetadata& meta = m_script_metadata[CScriptID(dest)];
350 UpdateTimeFirstKey(meta.nCreateTime);
351 NotifyWatchonlyChanged(true);
352 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
355 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
357 m_script_metadata[CScriptID(dest)].nCreateTime = nCreateTime;
358 return AddWatchOnly(dest);
361 bool CWallet::RemoveWatchOnly(const CScript &dest)
363 AssertLockHeld(cs_wallet);
364 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
365 return false;
366 if (!HaveWatchOnly())
367 NotifyWatchonlyChanged(false);
368 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
369 return false;
371 return true;
374 bool CWallet::LoadWatchOnly(const CScript &dest)
376 return CCryptoKeyStore::AddWatchOnly(dest);
379 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
381 CCrypter crypter;
382 CKeyingMaterial _vMasterKey;
385 LOCK(cs_wallet);
386 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
388 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
389 return false;
390 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
391 continue; // try another master key
392 if (CCryptoKeyStore::Unlock(_vMasterKey))
393 return true;
396 return false;
399 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
401 bool fWasLocked = IsLocked();
404 LOCK(cs_wallet);
405 Lock();
407 CCrypter crypter;
408 CKeyingMaterial _vMasterKey;
409 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
411 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
412 return false;
413 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
414 return false;
415 if (CCryptoKeyStore::Unlock(_vMasterKey))
417 int64_t nStartTime = GetTimeMillis();
418 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
419 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
421 nStartTime = GetTimeMillis();
422 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
423 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
425 if (pMasterKey.second.nDeriveIterations < 25000)
426 pMasterKey.second.nDeriveIterations = 25000;
428 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
430 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
431 return false;
432 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
433 return false;
434 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
435 if (fWasLocked)
436 Lock();
437 return true;
442 return false;
445 void CWallet::SetBestChain(const CBlockLocator& loc)
447 CWalletDB walletdb(*dbw);
448 walletdb.WriteBestBlock(loc);
451 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
453 LOCK(cs_wallet); // nWalletVersion
454 if (nWalletVersion >= nVersion)
455 return true;
457 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
458 if (fExplicit && nVersion > nWalletMaxVersion)
459 nVersion = FEATURE_LATEST;
461 nWalletVersion = nVersion;
463 if (nVersion > nWalletMaxVersion)
464 nWalletMaxVersion = nVersion;
467 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
468 if (nWalletVersion > 40000)
469 pwalletdb->WriteMinVersion(nWalletVersion);
470 if (!pwalletdbIn)
471 delete pwalletdb;
474 return true;
477 bool CWallet::SetMaxVersion(int nVersion)
479 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
480 // cannot downgrade below current version
481 if (nWalletVersion > nVersion)
482 return false;
484 nWalletMaxVersion = nVersion;
486 return true;
489 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
491 std::set<uint256> result;
492 AssertLockHeld(cs_wallet);
494 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
495 if (it == mapWallet.end())
496 return result;
497 const CWalletTx& wtx = it->second;
499 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
501 for (const CTxIn& txin : wtx.tx->vin)
503 if (mapTxSpends.count(txin.prevout) <= 1)
504 continue; // No conflict if zero or one spends
505 range = mapTxSpends.equal_range(txin.prevout);
506 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
507 result.insert(_it->second);
509 return result;
512 bool CWallet::HasWalletSpend(const uint256& txid) const
514 AssertLockHeld(cs_wallet);
515 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
516 return (iter != mapTxSpends.end() && iter->first.hash == txid);
519 void CWallet::Flush(bool shutdown)
521 dbw->Flush(shutdown);
524 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
526 // We want all the wallet transactions in range to have the same metadata as
527 // the oldest (smallest nOrderPos).
528 // So: find smallest nOrderPos:
530 int nMinOrderPos = std::numeric_limits<int>::max();
531 const CWalletTx* copyFrom = nullptr;
532 for (TxSpends::iterator it = range.first; it != range.second; ++it)
534 const uint256& hash = it->second;
535 int n = mapWallet[hash].nOrderPos;
536 if (n < nMinOrderPos)
538 nMinOrderPos = n;
539 copyFrom = &mapWallet[hash];
543 assert(copyFrom);
545 // Now copy data from copyFrom to rest:
546 for (TxSpends::iterator it = range.first; it != range.second; ++it)
548 const uint256& hash = it->second;
549 CWalletTx* copyTo = &mapWallet[hash];
550 if (copyFrom == copyTo) continue;
551 assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
552 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
553 copyTo->mapValue = copyFrom->mapValue;
554 copyTo->vOrderForm = copyFrom->vOrderForm;
555 // fTimeReceivedIsTxTime not copied on purpose
556 // nTimeReceived not copied on purpose
557 copyTo->nTimeSmart = copyFrom->nTimeSmart;
558 copyTo->fFromMe = copyFrom->fFromMe;
559 copyTo->strFromAccount = copyFrom->strFromAccount;
560 // nOrderPos not copied on purpose
561 // cached members not copied on purpose
566 * Outpoint is spent if any non-conflicted transaction
567 * spends it:
569 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
571 const COutPoint outpoint(hash, n);
572 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
573 range = mapTxSpends.equal_range(outpoint);
575 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
577 const uint256& wtxid = it->second;
578 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
579 if (mit != mapWallet.end()) {
580 int depth = mit->second.GetDepthInMainChain();
581 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
582 return true; // Spent
585 return false;
588 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
590 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
592 std::pair<TxSpends::iterator, TxSpends::iterator> range;
593 range = mapTxSpends.equal_range(outpoint);
594 SyncMetaData(range);
598 void CWallet::AddToSpends(const uint256& wtxid)
600 auto it = mapWallet.find(wtxid);
601 assert(it != mapWallet.end());
602 CWalletTx& thisTx = it->second;
603 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
604 return;
606 for (const CTxIn& txin : thisTx.tx->vin)
607 AddToSpends(txin.prevout, wtxid);
610 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
612 if (IsCrypted())
613 return false;
615 CKeyingMaterial _vMasterKey;
617 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
618 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
620 CMasterKey kMasterKey;
622 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
623 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
625 CCrypter crypter;
626 int64_t nStartTime = GetTimeMillis();
627 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
628 kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
630 nStartTime = GetTimeMillis();
631 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
632 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
634 if (kMasterKey.nDeriveIterations < 25000)
635 kMasterKey.nDeriveIterations = 25000;
637 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
639 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
640 return false;
641 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
642 return false;
645 LOCK(cs_wallet);
646 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
647 assert(!pwalletdbEncryption);
648 pwalletdbEncryption = new CWalletDB(*dbw);
649 if (!pwalletdbEncryption->TxnBegin()) {
650 delete pwalletdbEncryption;
651 pwalletdbEncryption = nullptr;
652 return false;
654 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
656 if (!EncryptKeys(_vMasterKey))
658 pwalletdbEncryption->TxnAbort();
659 delete pwalletdbEncryption;
660 // We now probably have half of our keys encrypted in memory, and half not...
661 // die and let the user reload the unencrypted wallet.
662 assert(false);
665 // Encryption was introduced in version 0.4.0
666 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
668 if (!pwalletdbEncryption->TxnCommit()) {
669 delete pwalletdbEncryption;
670 // We now have keys encrypted in memory, but not on disk...
671 // die to avoid confusion and let the user reload the unencrypted wallet.
672 assert(false);
675 delete pwalletdbEncryption;
676 pwalletdbEncryption = nullptr;
678 Lock();
679 Unlock(strWalletPassphrase);
681 // if we are using HD, replace the HD master key (seed) with a new one
682 if (IsHDEnabled()) {
683 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
684 return false;
688 NewKeyPool();
689 Lock();
691 // Need to completely rewrite the wallet file; if we don't, bdb might keep
692 // bits of the unencrypted private key in slack space in the database file.
693 dbw->Rewrite();
696 NotifyStatusChanged(this);
698 return true;
701 DBErrors CWallet::ReorderTransactions()
703 LOCK(cs_wallet);
704 CWalletDB walletdb(*dbw);
706 // Old wallets didn't have any defined order for transactions
707 // Probably a bad idea to change the output of this
709 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
710 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
711 typedef std::multimap<int64_t, TxPair > TxItems;
712 TxItems txByTime;
714 for (auto& entry : mapWallet)
716 CWalletTx* wtx = &entry.second;
717 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
719 std::list<CAccountingEntry> acentries;
720 walletdb.ListAccountCreditDebit("", acentries);
721 for (CAccountingEntry& entry : acentries)
723 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
726 nOrderPosNext = 0;
727 std::vector<int64_t> nOrderPosOffsets;
728 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
730 CWalletTx *const pwtx = (*it).second.first;
731 CAccountingEntry *const pacentry = (*it).second.second;
732 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
734 if (nOrderPos == -1)
736 nOrderPos = nOrderPosNext++;
737 nOrderPosOffsets.push_back(nOrderPos);
739 if (pwtx)
741 if (!walletdb.WriteTx(*pwtx))
742 return DB_LOAD_FAIL;
744 else
745 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
746 return DB_LOAD_FAIL;
748 else
750 int64_t nOrderPosOff = 0;
751 for (const int64_t& nOffsetStart : nOrderPosOffsets)
753 if (nOrderPos >= nOffsetStart)
754 ++nOrderPosOff;
756 nOrderPos += nOrderPosOff;
757 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
759 if (!nOrderPosOff)
760 continue;
762 // Since we're changing the order, write it back
763 if (pwtx)
765 if (!walletdb.WriteTx(*pwtx))
766 return DB_LOAD_FAIL;
768 else
769 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
770 return DB_LOAD_FAIL;
773 walletdb.WriteOrderPosNext(nOrderPosNext);
775 return DB_LOAD_OK;
778 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
780 AssertLockHeld(cs_wallet); // nOrderPosNext
781 int64_t nRet = nOrderPosNext++;
782 if (pwalletdb) {
783 pwalletdb->WriteOrderPosNext(nOrderPosNext);
784 } else {
785 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
787 return nRet;
790 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
792 CWalletDB walletdb(*dbw);
793 if (!walletdb.TxnBegin())
794 return false;
796 int64_t nNow = GetAdjustedTime();
798 // Debit
799 CAccountingEntry debit;
800 debit.nOrderPos = IncOrderPosNext(&walletdb);
801 debit.strAccount = strFrom;
802 debit.nCreditDebit = -nAmount;
803 debit.nTime = nNow;
804 debit.strOtherAccount = strTo;
805 debit.strComment = strComment;
806 AddAccountingEntry(debit, &walletdb);
808 // Credit
809 CAccountingEntry credit;
810 credit.nOrderPos = IncOrderPosNext(&walletdb);
811 credit.strAccount = strTo;
812 credit.nCreditDebit = nAmount;
813 credit.nTime = nNow;
814 credit.strOtherAccount = strFrom;
815 credit.strComment = strComment;
816 AddAccountingEntry(credit, &walletdb);
818 if (!walletdb.TxnCommit())
819 return false;
821 return true;
824 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
826 CWalletDB walletdb(*dbw);
828 CAccount account;
829 walletdb.ReadAccount(strAccount, account);
831 if (!bForceNew) {
832 if (!account.vchPubKey.IsValid())
833 bForceNew = true;
834 else {
835 // Check if the current key has been used
836 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
837 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
838 it != mapWallet.end() && account.vchPubKey.IsValid();
839 ++it)
840 for (const CTxOut& txout : (*it).second.tx->vout)
841 if (txout.scriptPubKey == scriptPubKey) {
842 bForceNew = true;
843 break;
848 // Generate a new key
849 if (bForceNew) {
850 if (!GetKeyFromPool(account.vchPubKey, false))
851 return false;
853 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
854 walletdb.WriteAccount(strAccount, account);
857 pubKey = account.vchPubKey;
859 return true;
862 void CWallet::MarkDirty()
865 LOCK(cs_wallet);
866 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
867 item.second.MarkDirty();
871 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
873 LOCK(cs_wallet);
875 auto mi = mapWallet.find(originalHash);
877 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
878 assert(mi != mapWallet.end());
880 CWalletTx& wtx = (*mi).second;
882 // Ensure for now that we're not overwriting data
883 assert(wtx.mapValue.count("replaced_by_txid") == 0);
885 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
887 CWalletDB walletdb(*dbw, "r+");
889 bool success = true;
890 if (!walletdb.WriteTx(wtx)) {
891 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
892 success = false;
895 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
897 return success;
900 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
902 LOCK(cs_wallet);
904 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
906 uint256 hash = wtxIn.GetHash();
908 // Inserts only if not already there, returns tx inserted or tx found
909 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
910 CWalletTx& wtx = (*ret.first).second;
911 wtx.BindWallet(this);
912 bool fInsertedNew = ret.second;
913 if (fInsertedNew)
915 wtx.nTimeReceived = GetAdjustedTime();
916 wtx.nOrderPos = IncOrderPosNext(&walletdb);
917 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
918 wtx.nTimeSmart = ComputeTimeSmart(wtx);
919 AddToSpends(hash);
922 bool fUpdated = false;
923 if (!fInsertedNew)
925 // Merge
926 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
928 wtx.hashBlock = wtxIn.hashBlock;
929 fUpdated = true;
931 // If no longer abandoned, update
932 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
934 wtx.hashBlock = wtxIn.hashBlock;
935 fUpdated = true;
937 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
939 wtx.nIndex = wtxIn.nIndex;
940 fUpdated = true;
942 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
944 wtx.fFromMe = wtxIn.fFromMe;
945 fUpdated = true;
947 // If we have a witness-stripped version of this transaction, and we
948 // see a new version with a witness, then we must be upgrading a pre-segwit
949 // wallet. Store the new version of the transaction with the witness,
950 // as the stripped-version must be invalid.
951 // TODO: Store all versions of the transaction, instead of just one.
952 if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
953 wtx.SetTx(wtxIn.tx);
954 fUpdated = true;
958 //// debug print
959 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
961 // Write to disk
962 if (fInsertedNew || fUpdated)
963 if (!walletdb.WriteTx(wtx))
964 return false;
966 // Break debit/credit balance caches:
967 wtx.MarkDirty();
969 // Notify UI of new or updated transaction
970 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
972 // notify an external script when a wallet transaction comes in or is updated
973 std::string strCmd = gArgs.GetArg("-walletnotify", "");
975 if (!strCmd.empty())
977 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
978 boost::thread t(runCommand, strCmd); // thread runs free
981 return true;
984 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
986 uint256 hash = wtxIn.GetHash();
988 mapWallet[hash] = wtxIn;
989 CWalletTx& wtx = mapWallet[hash];
990 wtx.BindWallet(this);
991 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
992 AddToSpends(hash);
993 for (const CTxIn& txin : wtx.tx->vin) {
994 auto it = mapWallet.find(txin.prevout.hash);
995 if (it != mapWallet.end()) {
996 CWalletTx& prevtx = it->second;
997 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
998 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1003 return true;
1007 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1008 * be set when the transaction was known to be included in a block. When
1009 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1010 * notifications happen and cached balances are marked dirty.
1012 * If fUpdate is true, existing transactions will be updated.
1013 * TODO: One exception to this is that the abandoned state is cleared under the
1014 * assumption that any further notification of a transaction that was considered
1015 * abandoned is an indication that it is not safe to be considered abandoned.
1016 * Abandoned state should probably be more carefully tracked via different
1017 * posInBlock signals or by checking mempool presence when necessary.
1019 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1021 const CTransaction& tx = *ptx;
1023 AssertLockHeld(cs_wallet);
1025 if (pIndex != nullptr) {
1026 for (const CTxIn& txin : tx.vin) {
1027 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1028 while (range.first != range.second) {
1029 if (range.first->second != tx.GetHash()) {
1030 LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1031 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1033 range.first++;
1038 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1039 if (fExisted && !fUpdate) return false;
1040 if (fExisted || IsMine(tx) || IsFromMe(tx))
1042 /* Check if any keys in the wallet keypool that were supposed to be unused
1043 * have appeared in a new transaction. If so, remove those keys from the keypool.
1044 * This can happen when restoring an old wallet backup that does not contain
1045 * the mostly recently created transactions from newer versions of the wallet.
1048 // loop though all outputs
1049 for (const CTxOut& txout: tx.vout) {
1050 // extract addresses and check if they match with an unused keypool key
1051 std::vector<CKeyID> vAffected;
1052 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1053 for (const CKeyID &keyid : vAffected) {
1054 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1055 if (mi != m_pool_key_to_index.end()) {
1056 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1057 MarkReserveKeysAsUsed(mi->second);
1059 if (!TopUpKeyPool()) {
1060 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1066 CWalletTx wtx(this, ptx);
1068 // Get merkle branch if transaction was found in a block
1069 if (pIndex != nullptr)
1070 wtx.SetMerkleBranch(pIndex, posInBlock);
1072 return AddToWallet(wtx, false);
1075 return false;
1078 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1080 LOCK2(cs_main, cs_wallet);
1081 const CWalletTx* wtx = GetWalletTx(hashTx);
1082 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1085 bool CWallet::AbandonTransaction(const uint256& hashTx)
1087 LOCK2(cs_main, cs_wallet);
1089 CWalletDB walletdb(*dbw, "r+");
1091 std::set<uint256> todo;
1092 std::set<uint256> done;
1094 // Can't mark abandoned if confirmed or in mempool
1095 auto it = mapWallet.find(hashTx);
1096 assert(it != mapWallet.end());
1097 CWalletTx& origtx = it->second;
1098 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1099 return false;
1102 todo.insert(hashTx);
1104 while (!todo.empty()) {
1105 uint256 now = *todo.begin();
1106 todo.erase(now);
1107 done.insert(now);
1108 auto it = mapWallet.find(now);
1109 assert(it != mapWallet.end());
1110 CWalletTx& wtx = it->second;
1111 int currentconfirm = wtx.GetDepthInMainChain();
1112 // If the orig tx was not in block, none of its spends can be
1113 assert(currentconfirm <= 0);
1114 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1115 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1116 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1117 assert(!wtx.InMempool());
1118 wtx.nIndex = -1;
1119 wtx.setAbandoned();
1120 wtx.MarkDirty();
1121 walletdb.WriteTx(wtx);
1122 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1123 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1124 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1125 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1126 if (!done.count(iter->second)) {
1127 todo.insert(iter->second);
1129 iter++;
1131 // If a transaction changes 'conflicted' state, that changes the balance
1132 // available of the outputs it spends. So force those to be recomputed
1133 for (const CTxIn& txin : wtx.tx->vin)
1135 auto it = mapWallet.find(txin.prevout.hash);
1136 if (it != mapWallet.end()) {
1137 it->second.MarkDirty();
1143 return true;
1146 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1148 LOCK2(cs_main, cs_wallet);
1150 int conflictconfirms = 0;
1151 if (mapBlockIndex.count(hashBlock)) {
1152 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1153 if (chainActive.Contains(pindex)) {
1154 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1157 // If number of conflict confirms cannot be determined, this means
1158 // that the block is still unknown or not yet part of the main chain,
1159 // for example when loading the wallet during a reindex. Do nothing in that
1160 // case.
1161 if (conflictconfirms >= 0)
1162 return;
1164 // Do not flush the wallet here for performance reasons
1165 CWalletDB walletdb(*dbw, "r+", false);
1167 std::set<uint256> todo;
1168 std::set<uint256> done;
1170 todo.insert(hashTx);
1172 while (!todo.empty()) {
1173 uint256 now = *todo.begin();
1174 todo.erase(now);
1175 done.insert(now);
1176 auto it = mapWallet.find(now);
1177 assert(it != mapWallet.end());
1178 CWalletTx& wtx = it->second;
1179 int currentconfirm = wtx.GetDepthInMainChain();
1180 if (conflictconfirms < currentconfirm) {
1181 // Block is 'more conflicted' than current confirm; update.
1182 // Mark transaction as conflicted with this block.
1183 wtx.nIndex = -1;
1184 wtx.hashBlock = hashBlock;
1185 wtx.MarkDirty();
1186 walletdb.WriteTx(wtx);
1187 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1188 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1189 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1190 if (!done.count(iter->second)) {
1191 todo.insert(iter->second);
1193 iter++;
1195 // If a transaction changes 'conflicted' state, that changes the balance
1196 // available of the outputs it spends. So force those to be recomputed
1197 for (const CTxIn& txin : wtx.tx->vin) {
1198 auto it = mapWallet.find(txin.prevout.hash);
1199 if (it != mapWallet.end()) {
1200 it->second.MarkDirty();
1207 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1208 const CTransaction& tx = *ptx;
1210 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1211 return; // Not one of ours
1213 // If a transaction changes 'conflicted' state, that changes the balance
1214 // available of the outputs it spends. So force those to be
1215 // recomputed, also:
1216 for (const CTxIn& txin : tx.vin) {
1217 auto it = mapWallet.find(txin.prevout.hash);
1218 if (it != mapWallet.end()) {
1219 it->second.MarkDirty();
1224 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1225 LOCK2(cs_main, cs_wallet);
1226 SyncTransaction(ptx);
1228 auto it = mapWallet.find(ptx->GetHash());
1229 if (it != mapWallet.end()) {
1230 it->second.fInMempool = true;
1234 void CWallet::TransactionRemovedFromMempool(const CTransactionRef &ptx) {
1235 LOCK(cs_wallet);
1236 auto it = mapWallet.find(ptx->GetHash());
1237 if (it != mapWallet.end()) {
1238 it->second.fInMempool = false;
1242 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1243 LOCK2(cs_main, cs_wallet);
1244 // TODO: Temporarily ensure that mempool removals are notified before
1245 // connected transactions. This shouldn't matter, but the abandoned
1246 // state of transactions in our wallet is currently cleared when we
1247 // receive another notification and there is a race condition where
1248 // notification of a connected conflict might cause an outside process
1249 // to abandon a transaction and then have it inadvertently cleared by
1250 // the notification that the conflicted transaction was evicted.
1252 for (const CTransactionRef& ptx : vtxConflicted) {
1253 SyncTransaction(ptx);
1254 TransactionRemovedFromMempool(ptx);
1256 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1257 SyncTransaction(pblock->vtx[i], pindex, i);
1258 TransactionRemovedFromMempool(pblock->vtx[i]);
1261 m_last_block_processed = pindex;
1264 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1265 LOCK2(cs_main, cs_wallet);
1267 for (const CTransactionRef& ptx : pblock->vtx) {
1268 SyncTransaction(ptx);
1274 void CWallet::BlockUntilSyncedToCurrentChain() {
1275 AssertLockNotHeld(cs_main);
1276 AssertLockNotHeld(cs_wallet);
1279 // Skip the queue-draining stuff if we know we're caught up with
1280 // chainActive.Tip()...
1281 // We could also take cs_wallet here, and call m_last_block_processed
1282 // protected by cs_wallet instead of cs_main, but as long as we need
1283 // cs_main here anyway, its easier to just call it cs_main-protected.
1284 LOCK(cs_main);
1285 const CBlockIndex* initialChainTip = chainActive.Tip();
1287 if (m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) {
1288 return;
1292 // ...otherwise put a callback in the validation interface queue and wait
1293 // for the queue to drain enough to execute it (indicating we are caught up
1294 // at least with the time we entered this function).
1296 std::promise<void> promise;
1297 CallFunctionInValidationInterfaceQueue([&promise] {
1298 promise.set_value();
1300 promise.get_future().wait();
1304 isminetype CWallet::IsMine(const CTxIn &txin) const
1307 LOCK(cs_wallet);
1308 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1309 if (mi != mapWallet.end())
1311 const CWalletTx& prev = (*mi).second;
1312 if (txin.prevout.n < prev.tx->vout.size())
1313 return IsMine(prev.tx->vout[txin.prevout.n]);
1316 return ISMINE_NO;
1319 // Note that this function doesn't distinguish between a 0-valued input,
1320 // and a not-"is mine" (according to the filter) input.
1321 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1324 LOCK(cs_wallet);
1325 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1326 if (mi != mapWallet.end())
1328 const CWalletTx& prev = (*mi).second;
1329 if (txin.prevout.n < prev.tx->vout.size())
1330 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1331 return prev.tx->vout[txin.prevout.n].nValue;
1334 return 0;
1337 isminetype CWallet::IsMine(const CTxOut& txout) const
1339 return ::IsMine(*this, txout.scriptPubKey);
1342 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1344 if (!MoneyRange(txout.nValue))
1345 throw std::runtime_error(std::string(__func__) + ": value out of range");
1346 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1349 bool CWallet::IsChange(const CTxOut& txout) const
1351 // TODO: fix handling of 'change' outputs. The assumption is that any
1352 // payment to a script that is ours, but is not in the address book
1353 // is change. That assumption is likely to break when we implement multisignature
1354 // wallets that return change back into a multi-signature-protected address;
1355 // a better way of identifying which outputs are 'the send' and which are
1356 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1357 // which output, if any, was change).
1358 if (::IsMine(*this, txout.scriptPubKey))
1360 CTxDestination address;
1361 if (!ExtractDestination(txout.scriptPubKey, address))
1362 return true;
1364 LOCK(cs_wallet);
1365 if (!mapAddressBook.count(address))
1366 return true;
1368 return false;
1371 CAmount CWallet::GetChange(const CTxOut& txout) const
1373 if (!MoneyRange(txout.nValue))
1374 throw std::runtime_error(std::string(__func__) + ": value out of range");
1375 return (IsChange(txout) ? txout.nValue : 0);
1378 bool CWallet::IsMine(const CTransaction& tx) const
1380 for (const CTxOut& txout : tx.vout)
1381 if (IsMine(txout))
1382 return true;
1383 return false;
1386 bool CWallet::IsFromMe(const CTransaction& tx) const
1388 return (GetDebit(tx, ISMINE_ALL) > 0);
1391 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1393 CAmount nDebit = 0;
1394 for (const CTxIn& txin : tx.vin)
1396 nDebit += GetDebit(txin, filter);
1397 if (!MoneyRange(nDebit))
1398 throw std::runtime_error(std::string(__func__) + ": value out of range");
1400 return nDebit;
1403 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1405 LOCK(cs_wallet);
1407 for (const CTxIn& txin : tx.vin)
1409 auto mi = mapWallet.find(txin.prevout.hash);
1410 if (mi == mapWallet.end())
1411 return false; // any unknown inputs can't be from us
1413 const CWalletTx& prev = (*mi).second;
1415 if (txin.prevout.n >= prev.tx->vout.size())
1416 return false; // invalid input!
1418 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1419 return false;
1421 return true;
1424 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1426 CAmount nCredit = 0;
1427 for (const CTxOut& txout : tx.vout)
1429 nCredit += GetCredit(txout, filter);
1430 if (!MoneyRange(nCredit))
1431 throw std::runtime_error(std::string(__func__) + ": value out of range");
1433 return nCredit;
1436 CAmount CWallet::GetChange(const CTransaction& tx) const
1438 CAmount nChange = 0;
1439 for (const CTxOut& txout : tx.vout)
1441 nChange += GetChange(txout);
1442 if (!MoneyRange(nChange))
1443 throw std::runtime_error(std::string(__func__) + ": value out of range");
1445 return nChange;
1448 CPubKey CWallet::GenerateNewHDMasterKey()
1450 CKey key;
1451 key.MakeNewKey(true);
1453 int64_t nCreationTime = GetTime();
1454 CKeyMetadata metadata(nCreationTime);
1456 // calculate the pubkey
1457 CPubKey pubkey = key.GetPubKey();
1458 assert(key.VerifyPubKey(pubkey));
1460 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1461 metadata.hdKeypath = "m";
1462 metadata.hdMasterKeyID = pubkey.GetID();
1465 LOCK(cs_wallet);
1467 // mem store the metadata
1468 mapKeyMetadata[pubkey.GetID()] = metadata;
1470 // write the key&metadata to the database
1471 if (!AddKeyPubKey(key, pubkey))
1472 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1475 return pubkey;
1478 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1480 LOCK(cs_wallet);
1481 // store the keyid (hash160) together with
1482 // the child index counter in the database
1483 // as a hdchain object
1484 CHDChain newHdChain;
1485 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1486 newHdChain.masterKeyID = pubkey.GetID();
1487 SetHDChain(newHdChain, false);
1489 return true;
1492 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1494 LOCK(cs_wallet);
1495 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1496 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1498 hdChain = chain;
1499 return true;
1502 bool CWallet::IsHDEnabled() const
1504 return !hdChain.masterKeyID.IsNull();
1507 int64_t CWalletTx::GetTxTime() const
1509 int64_t n = nTimeSmart;
1510 return n ? n : nTimeReceived;
1513 int CWalletTx::GetRequestCount() const
1515 // Returns -1 if it wasn't being tracked
1516 int nRequests = -1;
1518 LOCK(pwallet->cs_wallet);
1519 if (IsCoinBase())
1521 // Generated block
1522 if (!hashUnset())
1524 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1525 if (mi != pwallet->mapRequestCount.end())
1526 nRequests = (*mi).second;
1529 else
1531 // Did anyone request this transaction?
1532 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1533 if (mi != pwallet->mapRequestCount.end())
1535 nRequests = (*mi).second;
1537 // How about the block it's in?
1538 if (nRequests == 0 && !hashUnset())
1540 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1541 if (_mi != pwallet->mapRequestCount.end())
1542 nRequests = (*_mi).second;
1543 else
1544 nRequests = 1; // If it's in someone else's block it must have got out
1549 return nRequests;
1552 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1553 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1555 nFee = 0;
1556 listReceived.clear();
1557 listSent.clear();
1558 strSentAccount = strFromAccount;
1560 // Compute fee:
1561 CAmount nDebit = GetDebit(filter);
1562 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1564 CAmount nValueOut = tx->GetValueOut();
1565 nFee = nDebit - nValueOut;
1568 // Sent/received.
1569 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1571 const CTxOut& txout = tx->vout[i];
1572 isminetype fIsMine = pwallet->IsMine(txout);
1573 // Only need to handle txouts if AT LEAST one of these is true:
1574 // 1) they debit from us (sent)
1575 // 2) the output is to us (received)
1576 if (nDebit > 0)
1578 // Don't report 'change' txouts
1579 if (pwallet->IsChange(txout))
1580 continue;
1582 else if (!(fIsMine & filter))
1583 continue;
1585 // In either case, we need to get the destination address
1586 CTxDestination address;
1588 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1590 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1591 this->GetHash().ToString());
1592 address = CNoDestination();
1595 COutputEntry output = {address, txout.nValue, (int)i};
1597 // If we are debited by the transaction, add the output as a "sent" entry
1598 if (nDebit > 0)
1599 listSent.push_back(output);
1601 // If we are receiving the output, add it as a "received" entry
1602 if (fIsMine & filter)
1603 listReceived.push_back(output);
1609 * Scan active chain for relevant transactions after importing keys. This should
1610 * be called whenever new keys are added to the wallet, with the oldest key
1611 * creation time.
1613 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1614 * returned will be higher than startTime if relevant blocks could not be read.
1616 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1618 AssertLockHeld(cs_main);
1619 AssertLockHeld(cs_wallet);
1621 // Find starting block. May be null if nCreateTime is greater than the
1622 // highest blockchain timestamp, in which case there is nothing that needs
1623 // to be scanned.
1624 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1625 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1627 if (startBlock) {
1628 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1629 if (failedBlock) {
1630 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1633 return startTime;
1637 * Scan the block chain (starting in pindexStart) for transactions
1638 * from or to us. If fUpdate is true, found transactions that already
1639 * exist in the wallet will be updated.
1641 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1642 * possible (due to pruning or corruption), returns pointer to the most recent
1643 * block that could not be scanned.
1645 * If pindexStop is not a nullptr, the scan will stop at the block-index
1646 * defined by pindexStop
1648 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1650 int64_t nNow = GetTime();
1651 const CChainParams& chainParams = Params();
1653 if (pindexStop) {
1654 assert(pindexStop->nHeight >= pindexStart->nHeight);
1657 CBlockIndex* pindex = pindexStart;
1658 CBlockIndex* ret = nullptr;
1660 LOCK2(cs_main, cs_wallet);
1661 fAbortRescan = false;
1662 fScanningWallet = true;
1664 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1665 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1666 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1667 while (pindex && !fAbortRescan)
1669 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1670 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1671 if (GetTime() >= nNow + 60) {
1672 nNow = GetTime();
1673 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1676 CBlock block;
1677 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1678 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1679 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1681 } else {
1682 ret = pindex;
1684 if (pindex == pindexStop) {
1685 break;
1687 pindex = chainActive.Next(pindex);
1689 if (pindex && fAbortRescan) {
1690 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1692 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1694 fScanningWallet = false;
1696 return ret;
1699 void CWallet::ReacceptWalletTransactions()
1701 // If transactions aren't being broadcasted, don't let them into local mempool either
1702 if (!fBroadcastTransactions)
1703 return;
1704 LOCK2(cs_main, cs_wallet);
1705 std::map<int64_t, CWalletTx*> mapSorted;
1707 // Sort pending wallet transactions based on their initial wallet insertion order
1708 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1710 const uint256& wtxid = item.first;
1711 CWalletTx& wtx = item.second;
1712 assert(wtx.GetHash() == wtxid);
1714 int nDepth = wtx.GetDepthInMainChain();
1716 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1717 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1721 // Try to add wallet transactions to memory pool
1722 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1724 CWalletTx& wtx = *(item.second);
1726 LOCK(mempool.cs);
1727 CValidationState state;
1728 wtx.AcceptToMemoryPool(maxTxFee, state);
1732 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1734 assert(pwallet->GetBroadcastTransactions());
1735 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1737 CValidationState state;
1738 /* GetDepthInMainChain already catches known conflicts. */
1739 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1740 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1741 if (connman) {
1742 CInv inv(MSG_TX, GetHash());
1743 connman->ForEachNode([&inv](CNode* pnode)
1745 pnode->PushInventory(inv);
1747 return true;
1751 return false;
1754 std::set<uint256> CWalletTx::GetConflicts() const
1756 std::set<uint256> result;
1757 if (pwallet != nullptr)
1759 uint256 myHash = GetHash();
1760 result = pwallet->GetConflicts(myHash);
1761 result.erase(myHash);
1763 return result;
1766 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1768 if (tx->vin.empty())
1769 return 0;
1771 CAmount debit = 0;
1772 if(filter & ISMINE_SPENDABLE)
1774 if (fDebitCached)
1775 debit += nDebitCached;
1776 else
1778 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1779 fDebitCached = true;
1780 debit += nDebitCached;
1783 if(filter & ISMINE_WATCH_ONLY)
1785 if(fWatchDebitCached)
1786 debit += nWatchDebitCached;
1787 else
1789 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1790 fWatchDebitCached = true;
1791 debit += nWatchDebitCached;
1794 return debit;
1797 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1799 // Must wait until coinbase is safely deep enough in the chain before valuing it
1800 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1801 return 0;
1803 CAmount credit = 0;
1804 if (filter & ISMINE_SPENDABLE)
1806 // GetBalance can assume transactions in mapWallet won't change
1807 if (fCreditCached)
1808 credit += nCreditCached;
1809 else
1811 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1812 fCreditCached = true;
1813 credit += nCreditCached;
1816 if (filter & ISMINE_WATCH_ONLY)
1818 if (fWatchCreditCached)
1819 credit += nWatchCreditCached;
1820 else
1822 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1823 fWatchCreditCached = true;
1824 credit += nWatchCreditCached;
1827 return credit;
1830 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1832 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1834 if (fUseCache && fImmatureCreditCached)
1835 return nImmatureCreditCached;
1836 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1837 fImmatureCreditCached = true;
1838 return nImmatureCreditCached;
1841 return 0;
1844 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1846 if (pwallet == nullptr)
1847 return 0;
1849 // Must wait until coinbase is safely deep enough in the chain before valuing it
1850 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1851 return 0;
1853 if (fUseCache && fAvailableCreditCached)
1854 return nAvailableCreditCached;
1856 CAmount nCredit = 0;
1857 uint256 hashTx = GetHash();
1858 for (unsigned int i = 0; i < tx->vout.size(); i++)
1860 if (!pwallet->IsSpent(hashTx, i))
1862 const CTxOut &txout = tx->vout[i];
1863 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1864 if (!MoneyRange(nCredit))
1865 throw std::runtime_error(std::string(__func__) + " : value out of range");
1869 nAvailableCreditCached = nCredit;
1870 fAvailableCreditCached = true;
1871 return nCredit;
1874 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1876 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1878 if (fUseCache && fImmatureWatchCreditCached)
1879 return nImmatureWatchCreditCached;
1880 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1881 fImmatureWatchCreditCached = true;
1882 return nImmatureWatchCreditCached;
1885 return 0;
1888 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1890 if (pwallet == nullptr)
1891 return 0;
1893 // Must wait until coinbase is safely deep enough in the chain before valuing it
1894 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1895 return 0;
1897 if (fUseCache && fAvailableWatchCreditCached)
1898 return nAvailableWatchCreditCached;
1900 CAmount nCredit = 0;
1901 for (unsigned int i = 0; i < tx->vout.size(); i++)
1903 if (!pwallet->IsSpent(GetHash(), i))
1905 const CTxOut &txout = tx->vout[i];
1906 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1907 if (!MoneyRange(nCredit))
1908 throw std::runtime_error(std::string(__func__) + ": value out of range");
1912 nAvailableWatchCreditCached = nCredit;
1913 fAvailableWatchCreditCached = true;
1914 return nCredit;
1917 CAmount CWalletTx::GetChange() const
1919 if (fChangeCached)
1920 return nChangeCached;
1921 nChangeCached = pwallet->GetChange(*tx);
1922 fChangeCached = true;
1923 return nChangeCached;
1926 bool CWalletTx::InMempool() const
1928 return fInMempool;
1931 bool CWalletTx::IsTrusted() const
1933 // Quick answer in most cases
1934 if (!CheckFinalTx(*tx))
1935 return false;
1936 int nDepth = GetDepthInMainChain();
1937 if (nDepth >= 1)
1938 return true;
1939 if (nDepth < 0)
1940 return false;
1941 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1942 return false;
1944 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1945 if (!InMempool())
1946 return false;
1948 // Trusted if all inputs are from us and are in the mempool:
1949 for (const CTxIn& txin : tx->vin)
1951 // Transactions not sent by us: not trusted
1952 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1953 if (parent == nullptr)
1954 return false;
1955 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1956 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1957 return false;
1959 return true;
1962 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1964 CMutableTransaction tx1 = *this->tx;
1965 CMutableTransaction tx2 = *_tx.tx;
1966 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1967 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1968 return CTransaction(tx1) == CTransaction(tx2);
1971 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1973 std::vector<uint256> result;
1975 LOCK(cs_wallet);
1977 // Sort them in chronological order
1978 std::multimap<unsigned int, CWalletTx*> mapSorted;
1979 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1981 CWalletTx& wtx = item.second;
1982 // Don't rebroadcast if newer than nTime:
1983 if (wtx.nTimeReceived > nTime)
1984 continue;
1985 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1987 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1989 CWalletTx& wtx = *item.second;
1990 if (wtx.RelayWalletTransaction(connman))
1991 result.push_back(wtx.GetHash());
1993 return result;
1996 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1998 // Do this infrequently and randomly to avoid giving away
1999 // that these are our transactions.
2000 if (GetTime() < nNextResend || !fBroadcastTransactions)
2001 return;
2002 bool fFirst = (nNextResend == 0);
2003 nNextResend = GetTime() + GetRand(30 * 60);
2004 if (fFirst)
2005 return;
2007 // Only do it if there's been a new block since last time
2008 if (nBestBlockTime < nLastResend)
2009 return;
2010 nLastResend = GetTime();
2012 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2013 // block was found:
2014 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
2015 if (!relayed.empty())
2016 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2019 /** @} */ // end of mapWallet
2024 /** @defgroup Actions
2026 * @{
2030 CAmount CWallet::GetBalance() const
2032 CAmount nTotal = 0;
2034 LOCK2(cs_main, cs_wallet);
2035 for (const auto& entry : mapWallet)
2037 const CWalletTx* pcoin = &entry.second;
2038 if (pcoin->IsTrusted())
2039 nTotal += pcoin->GetAvailableCredit();
2043 return nTotal;
2046 CAmount CWallet::GetUnconfirmedBalance() const
2048 CAmount nTotal = 0;
2050 LOCK2(cs_main, cs_wallet);
2051 for (const auto& entry : mapWallet)
2053 const CWalletTx* pcoin = &entry.second;
2054 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2055 nTotal += pcoin->GetAvailableCredit();
2058 return nTotal;
2061 CAmount CWallet::GetImmatureBalance() const
2063 CAmount nTotal = 0;
2065 LOCK2(cs_main, cs_wallet);
2066 for (const auto& entry : mapWallet)
2068 const CWalletTx* pcoin = &entry.second;
2069 nTotal += pcoin->GetImmatureCredit();
2072 return nTotal;
2075 CAmount CWallet::GetWatchOnlyBalance() const
2077 CAmount nTotal = 0;
2079 LOCK2(cs_main, cs_wallet);
2080 for (const auto& entry : mapWallet)
2082 const CWalletTx* pcoin = &entry.second;
2083 if (pcoin->IsTrusted())
2084 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2088 return nTotal;
2091 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2093 CAmount nTotal = 0;
2095 LOCK2(cs_main, cs_wallet);
2096 for (const auto& entry : mapWallet)
2098 const CWalletTx* pcoin = &entry.second;
2099 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2100 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2103 return nTotal;
2106 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2108 CAmount nTotal = 0;
2110 LOCK2(cs_main, cs_wallet);
2111 for (const auto& entry : mapWallet)
2113 const CWalletTx* pcoin = &entry.second;
2114 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2117 return nTotal;
2120 // Calculate total balance in a different way from GetBalance. The biggest
2121 // difference is that GetBalance sums up all unspent TxOuts paying to the
2122 // wallet, while this sums up both spent and unspent TxOuts paying to the
2123 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2124 // also has fewer restrictions on which unconfirmed transactions are considered
2125 // trusted.
2126 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2128 LOCK2(cs_main, cs_wallet);
2130 CAmount balance = 0;
2131 for (const auto& entry : mapWallet) {
2132 const CWalletTx& wtx = entry.second;
2133 const int depth = wtx.GetDepthInMainChain();
2134 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2135 continue;
2138 // Loop through tx outputs and add incoming payments. For outgoing txs,
2139 // treat change outputs specially, as part of the amount debited.
2140 CAmount debit = wtx.GetDebit(filter);
2141 const bool outgoing = debit > 0;
2142 for (const CTxOut& out : wtx.tx->vout) {
2143 if (outgoing && IsChange(out)) {
2144 debit -= out.nValue;
2145 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2146 balance += out.nValue;
2150 // For outgoing txs, subtract amount debited.
2151 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2152 balance -= debit;
2156 if (account) {
2157 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2160 return balance;
2163 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2165 LOCK2(cs_main, cs_wallet);
2167 CAmount balance = 0;
2168 std::vector<COutput> vCoins;
2169 AvailableCoins(vCoins, true, coinControl);
2170 for (const COutput& out : vCoins) {
2171 if (out.fSpendable) {
2172 balance += out.tx->tx->vout[out.i].nValue;
2175 return balance;
2178 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
2180 vCoins.clear();
2183 LOCK2(cs_main, cs_wallet);
2185 CAmount nTotal = 0;
2187 for (const auto& entry : mapWallet)
2189 const uint256& wtxid = entry.first;
2190 const CWalletTx* pcoin = &entry.second;
2192 if (!CheckFinalTx(*pcoin->tx))
2193 continue;
2195 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2196 continue;
2198 int nDepth = pcoin->GetDepthInMainChain();
2199 if (nDepth < 0)
2200 continue;
2202 // We should not consider coins which aren't at least in our mempool
2203 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2204 if (nDepth == 0 && !pcoin->InMempool())
2205 continue;
2207 bool safeTx = pcoin->IsTrusted();
2209 // We should not consider coins from transactions that are replacing
2210 // other transactions.
2212 // Example: There is a transaction A which is replaced by bumpfee
2213 // transaction B. In this case, we want to prevent creation of
2214 // a transaction B' which spends an output of B.
2216 // Reason: If transaction A were initially confirmed, transactions B
2217 // and B' would no longer be valid, so the user would have to create
2218 // a new transaction C to replace B'. However, in the case of a
2219 // one-block reorg, transactions B' and C might BOTH be accepted,
2220 // when the user only wanted one of them. Specifically, there could
2221 // be a 1-block reorg away from the chain where transactions A and C
2222 // were accepted to another chain where B, B', and C were all
2223 // accepted.
2224 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2225 safeTx = false;
2228 // Similarly, we should not consider coins from transactions that
2229 // have been replaced. In the example above, we would want to prevent
2230 // creation of a transaction A' spending an output of A, because if
2231 // transaction B were initially confirmed, conflicting with A and
2232 // A', we wouldn't want to the user to create a transaction D
2233 // intending to replace A', but potentially resulting in a scenario
2234 // where A, A', and D could all be accepted (instead of just B and
2235 // D, or just A and A' like the user would want).
2236 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2237 safeTx = false;
2240 if (fOnlySafe && !safeTx) {
2241 continue;
2244 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2245 continue;
2247 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2248 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2249 continue;
2251 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint(entry.first, i)))
2252 continue;
2254 if (IsLockedCoin(entry.first, i))
2255 continue;
2257 if (IsSpent(wtxid, i))
2258 continue;
2260 isminetype mine = IsMine(pcoin->tx->vout[i]);
2262 if (mine == ISMINE_NO) {
2263 continue;
2266 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2267 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2269 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2271 // Checks the sum amount of all UTXO's.
2272 if (nMinimumSumAmount != MAX_MONEY) {
2273 nTotal += pcoin->tx->vout[i].nValue;
2275 if (nTotal >= nMinimumSumAmount) {
2276 return;
2280 // Checks the maximum number of UTXO's.
2281 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2282 return;
2289 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2291 // TODO: Add AssertLockHeld(cs_wallet) here.
2293 // Because the return value from this function contains pointers to
2294 // CWalletTx objects, callers to this function really should acquire the
2295 // cs_wallet lock before calling it. However, the current caller doesn't
2296 // acquire this lock yet. There was an attempt to add the missing lock in
2297 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2298 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2299 // avoid adding some extra complexity to the Qt code.
2301 std::map<CTxDestination, std::vector<COutput>> result;
2303 std::vector<COutput> availableCoins;
2304 AvailableCoins(availableCoins);
2306 LOCK2(cs_main, cs_wallet);
2307 for (auto& coin : availableCoins) {
2308 CTxDestination address;
2309 if (coin.fSpendable &&
2310 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2311 result[address].emplace_back(std::move(coin));
2315 std::vector<COutPoint> lockedCoins;
2316 ListLockedCoins(lockedCoins);
2317 for (const auto& output : lockedCoins) {
2318 auto it = mapWallet.find(output.hash);
2319 if (it != mapWallet.end()) {
2320 int depth = it->second.GetDepthInMainChain();
2321 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2322 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2323 CTxDestination address;
2324 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2325 result[address].emplace_back(
2326 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2332 return result;
2335 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2337 const CTransaction* ptx = &tx;
2338 int n = output;
2339 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2340 const COutPoint& prevout = ptx->vin[0].prevout;
2341 auto it = mapWallet.find(prevout.hash);
2342 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2343 !IsMine(it->second.tx->vout[prevout.n])) {
2344 break;
2346 ptx = it->second.tx.get();
2347 n = prevout.n;
2349 return ptx->vout[n];
2352 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2353 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2355 std::vector<char> vfIncluded;
2357 vfBest.assign(vValue.size(), true);
2358 nBest = nTotalLower;
2360 FastRandomContext insecure_rand;
2362 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2364 vfIncluded.assign(vValue.size(), false);
2365 CAmount nTotal = 0;
2366 bool fReachedTarget = false;
2367 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2369 for (unsigned int i = 0; i < vValue.size(); i++)
2371 //The solver here uses a randomized algorithm,
2372 //the randomness serves no real security purpose but is just
2373 //needed to prevent degenerate behavior and it is important
2374 //that the rng is fast. We do not use a constant random sequence,
2375 //because there may be some privacy improvement by making
2376 //the selection random.
2377 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2379 nTotal += vValue[i].txout.nValue;
2380 vfIncluded[i] = true;
2381 if (nTotal >= nTargetValue)
2383 fReachedTarget = true;
2384 if (nTotal < nBest)
2386 nBest = nTotal;
2387 vfBest = vfIncluded;
2389 nTotal -= vValue[i].txout.nValue;
2390 vfIncluded[i] = false;
2398 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2399 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2401 setCoinsRet.clear();
2402 nValueRet = 0;
2404 // List of values less than target
2405 boost::optional<CInputCoin> coinLowestLarger;
2406 std::vector<CInputCoin> vValue;
2407 CAmount nTotalLower = 0;
2409 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2411 for (const COutput &output : vCoins)
2413 if (!output.fSpendable)
2414 continue;
2416 const CWalletTx *pcoin = output.tx;
2418 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2419 continue;
2421 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2422 continue;
2424 int i = output.i;
2426 CInputCoin coin = CInputCoin(pcoin, i);
2428 if (coin.txout.nValue == nTargetValue)
2430 setCoinsRet.insert(coin);
2431 nValueRet += coin.txout.nValue;
2432 return true;
2434 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2436 vValue.push_back(coin);
2437 nTotalLower += coin.txout.nValue;
2439 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2441 coinLowestLarger = coin;
2445 if (nTotalLower == nTargetValue)
2447 for (const auto& input : vValue)
2449 setCoinsRet.insert(input);
2450 nValueRet += input.txout.nValue;
2452 return true;
2455 if (nTotalLower < nTargetValue)
2457 if (!coinLowestLarger)
2458 return false;
2459 setCoinsRet.insert(coinLowestLarger.get());
2460 nValueRet += coinLowestLarger->txout.nValue;
2461 return true;
2464 // Solve subset sum by stochastic approximation
2465 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2466 std::reverse(vValue.begin(), vValue.end());
2467 std::vector<char> vfBest;
2468 CAmount nBest;
2470 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2471 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2472 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2474 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2475 // or the next bigger coin is closer), return the bigger coin
2476 if (coinLowestLarger &&
2477 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2479 setCoinsRet.insert(coinLowestLarger.get());
2480 nValueRet += coinLowestLarger->txout.nValue;
2482 else {
2483 for (unsigned int i = 0; i < vValue.size(); i++)
2484 if (vfBest[i])
2486 setCoinsRet.insert(vValue[i]);
2487 nValueRet += vValue[i].txout.nValue;
2490 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2491 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2492 for (unsigned int i = 0; i < vValue.size(); i++) {
2493 if (vfBest[i]) {
2494 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2497 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2501 return true;
2504 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2506 std::vector<COutput> vCoins(vAvailableCoins);
2508 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2509 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2511 for (const COutput& out : vCoins)
2513 if (!out.fSpendable)
2514 continue;
2515 nValueRet += out.tx->tx->vout[out.i].nValue;
2516 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2518 return (nValueRet >= nTargetValue);
2521 // calculate value from preset inputs and store them
2522 std::set<CInputCoin> setPresetCoins;
2523 CAmount nValueFromPresetInputs = 0;
2525 std::vector<COutPoint> vPresetInputs;
2526 if (coinControl)
2527 coinControl->ListSelected(vPresetInputs);
2528 for (const COutPoint& outpoint : vPresetInputs)
2530 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2531 if (it != mapWallet.end())
2533 const CWalletTx* pcoin = &it->second;
2534 // Clearly invalid input, fail
2535 if (pcoin->tx->vout.size() <= outpoint.n)
2536 return false;
2537 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2538 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2539 } else
2540 return false; // TODO: Allow non-wallet inputs
2543 // remove preset inputs from vCoins
2544 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2546 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2547 it = vCoins.erase(it);
2548 else
2549 ++it;
2552 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2553 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2555 bool res = nTargetValue <= nValueFromPresetInputs ||
2556 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2557 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2558 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2559 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2560 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2561 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2562 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2564 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2565 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2567 // add preset inputs to the total value selected
2568 nValueRet += nValueFromPresetInputs;
2570 return res;
2573 bool CWallet::SignTransaction(CMutableTransaction &tx)
2575 AssertLockHeld(cs_wallet); // mapWallet
2577 // sign the new tx
2578 CTransaction txNewConst(tx);
2579 int nIn = 0;
2580 for (const auto& input : tx.vin) {
2581 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2582 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2583 return false;
2585 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2586 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2587 SignatureData sigdata;
2588 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2589 return false;
2591 UpdateTransaction(tx, nIn, sigdata);
2592 nIn++;
2594 return true;
2597 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2599 std::vector<CRecipient> vecSend;
2601 // Turn the txout set into a CRecipient vector
2602 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2604 const CTxOut& txOut = tx.vout[idx];
2605 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2606 vecSend.push_back(recipient);
2609 coinControl.fAllowOtherInputs = true;
2611 for (const CTxIn& txin : tx.vin)
2612 coinControl.Select(txin.prevout);
2614 CReserveKey reservekey(this);
2615 CWalletTx wtx;
2616 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2617 return false;
2620 if (nChangePosInOut != -1) {
2621 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2622 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2623 // so just remove the key from the keypool here.
2624 reservekey.KeepKey();
2627 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2628 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2629 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2631 // Add new txins (keeping original txin scriptSig/order)
2632 for (const CTxIn& txin : wtx.tx->vin)
2634 if (!coinControl.IsSelected(txin.prevout))
2636 tx.vin.push_back(txin);
2638 if (lockUnspents)
2640 LOCK2(cs_main, cs_wallet);
2641 LockCoin(txin.prevout);
2647 return true;
2650 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2651 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2653 CAmount nValue = 0;
2654 int nChangePosRequest = nChangePosInOut;
2655 unsigned int nSubtractFeeFromAmount = 0;
2656 for (const auto& recipient : vecSend)
2658 if (nValue < 0 || recipient.nAmount < 0)
2660 strFailReason = _("Transaction amounts must not be negative");
2661 return false;
2663 nValue += recipient.nAmount;
2665 if (recipient.fSubtractFeeFromAmount)
2666 nSubtractFeeFromAmount++;
2668 if (vecSend.empty())
2670 strFailReason = _("Transaction must have at least one recipient");
2671 return false;
2674 wtxNew.fTimeReceivedIsTxTime = true;
2675 wtxNew.BindWallet(this);
2676 CMutableTransaction txNew;
2678 // Discourage fee sniping.
2680 // For a large miner the value of the transactions in the best block and
2681 // the mempool can exceed the cost of deliberately attempting to mine two
2682 // blocks to orphan the current best block. By setting nLockTime such that
2683 // only the next block can include the transaction, we discourage this
2684 // practice as the height restricted and limited blocksize gives miners
2685 // considering fee sniping fewer options for pulling off this attack.
2687 // A simple way to think about this is from the wallet's point of view we
2688 // always want the blockchain to move forward. By setting nLockTime this
2689 // way we're basically making the statement that we only want this
2690 // transaction to appear in the next block; we don't want to potentially
2691 // encourage reorgs by allowing transactions to appear at lower heights
2692 // than the next block in forks of the best chain.
2694 // Of course, the subsidy is high enough, and transaction volume low
2695 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2696 // now we ensure code won't be written that makes assumptions about
2697 // nLockTime that preclude a fix later.
2698 txNew.nLockTime = chainActive.Height();
2700 // Secondly occasionally randomly pick a nLockTime even further back, so
2701 // that transactions that are delayed after signing for whatever reason,
2702 // e.g. high-latency mix networks and some CoinJoin implementations, have
2703 // better privacy.
2704 if (GetRandInt(10) == 0)
2705 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2707 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2708 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2709 FeeCalculation feeCalc;
2710 CAmount nFeeNeeded;
2711 unsigned int nBytes;
2713 std::set<CInputCoin> setCoins;
2714 LOCK2(cs_main, cs_wallet);
2716 std::vector<COutput> vAvailableCoins;
2717 AvailableCoins(vAvailableCoins, true, &coin_control);
2719 // Create change script that will be used if we need change
2720 // TODO: pass in scriptChange instead of reservekey so
2721 // change transaction isn't always pay-to-bitcoin-address
2722 CScript scriptChange;
2724 // coin control: send change to custom address
2725 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2726 scriptChange = GetScriptForDestination(coin_control.destChange);
2727 } else { // no coin control: send change to newly generated address
2728 // Note: We use a new key here to keep it from being obvious which side is the change.
2729 // The drawback is that by not reusing a previous key, the change may be lost if a
2730 // backup is restored, if the backup doesn't have the new private key for the change.
2731 // If we reused the old key, it would be possible to add code to look for and
2732 // rediscover unknown transactions that were written with keys of ours to recover
2733 // post-backup change.
2735 // Reserve a new key pair from key pool
2736 CPubKey vchPubKey;
2737 bool ret;
2738 ret = reservekey.GetReservedKey(vchPubKey, true);
2739 if (!ret)
2741 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2742 return false;
2745 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2747 CTxOut change_prototype_txout(0, scriptChange);
2748 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2750 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2751 nFeeRet = 0;
2752 bool pick_new_inputs = true;
2753 CAmount nValueIn = 0;
2754 // Start with no fee and loop until there is enough fee
2755 while (true)
2757 nChangePosInOut = nChangePosRequest;
2758 txNew.vin.clear();
2759 txNew.vout.clear();
2760 wtxNew.fFromMe = true;
2761 bool fFirst = true;
2763 CAmount nValueToSelect = nValue;
2764 if (nSubtractFeeFromAmount == 0)
2765 nValueToSelect += nFeeRet;
2766 // vouts to the payees
2767 for (const auto& recipient : vecSend)
2769 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2771 if (recipient.fSubtractFeeFromAmount)
2773 assert(nSubtractFeeFromAmount != 0);
2774 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2776 if (fFirst) // first receiver pays the remainder not divisible by output count
2778 fFirst = false;
2779 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2783 if (IsDust(txout, ::dustRelayFee))
2785 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2787 if (txout.nValue < 0)
2788 strFailReason = _("The transaction amount is too small to pay the fee");
2789 else
2790 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2792 else
2793 strFailReason = _("Transaction amount too small");
2794 return false;
2796 txNew.vout.push_back(txout);
2799 // Choose coins to use
2800 if (pick_new_inputs) {
2801 nValueIn = 0;
2802 setCoins.clear();
2803 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2805 strFailReason = _("Insufficient funds");
2806 return false;
2810 const CAmount nChange = nValueIn - nValueToSelect;
2812 if (nChange > 0)
2814 // Fill a vout to ourself
2815 CTxOut newTxOut(nChange, scriptChange);
2817 // Never create dust outputs; if we would, just
2818 // add the dust to the fee.
2819 if (IsDust(newTxOut, discard_rate))
2821 nChangePosInOut = -1;
2822 nFeeRet += nChange;
2824 else
2826 if (nChangePosInOut == -1)
2828 // Insert change txn at random position:
2829 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2831 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2833 strFailReason = _("Change index out of range");
2834 return false;
2837 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2838 txNew.vout.insert(position, newTxOut);
2840 } else {
2841 nChangePosInOut = -1;
2844 // Fill vin
2846 // Note how the sequence number is set to non-maxint so that
2847 // the nLockTime set above actually works.
2849 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2850 // we use the highest possible value in that range (maxint-2)
2851 // to avoid conflicting with other possible uses of nSequence,
2852 // and in the spirit of "smallest possible change from prior
2853 // behavior."
2854 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2855 for (const auto& coin : setCoins)
2856 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2857 nSequence));
2859 // Fill in dummy signatures for fee calculation.
2860 if (!DummySignTx(txNew, setCoins)) {
2861 strFailReason = _("Signing transaction failed");
2862 return false;
2865 nBytes = GetVirtualTransactionSize(txNew);
2867 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2868 for (auto& vin : txNew.vin) {
2869 vin.scriptSig = CScript();
2870 vin.scriptWitness.SetNull();
2873 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2875 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2876 // because we must be at the maximum allowed fee.
2877 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2879 strFailReason = _("Transaction too large for fee policy");
2880 return false;
2883 if (nFeeRet >= nFeeNeeded) {
2884 // Reduce fee to only the needed amount if possible. This
2885 // prevents potential overpayment in fees if the coins
2886 // selected to meet nFeeNeeded result in a transaction that
2887 // requires less fee than the prior iteration.
2889 // If we have no change and a big enough excess fee, then
2890 // try to construct transaction again only without picking
2891 // new inputs. We now know we only need the smaller fee
2892 // (because of reduced tx size) and so we should add a
2893 // change output. Only try this once.
2894 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2895 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2896 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2897 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2898 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2899 pick_new_inputs = false;
2900 nFeeRet = fee_needed_with_change;
2901 continue;
2905 // If we have change output already, just increase it
2906 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2907 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2908 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2909 change_position->nValue += extraFeePaid;
2910 nFeeRet -= extraFeePaid;
2912 break; // Done, enough fee included.
2914 else if (!pick_new_inputs) {
2915 // This shouldn't happen, we should have had enough excess
2916 // fee to pay for the new output and still meet nFeeNeeded
2917 // Or we should have just subtracted fee from recipients and
2918 // nFeeNeeded should not have changed
2919 strFailReason = _("Transaction fee and change calculation failed");
2920 return false;
2923 // Try to reduce change to include necessary fee
2924 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2925 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2926 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2927 // Only reduce change if remaining amount is still a large enough output.
2928 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2929 change_position->nValue -= additionalFeeNeeded;
2930 nFeeRet += additionalFeeNeeded;
2931 break; // Done, able to increase fee from change
2935 // If subtracting fee from recipients, we now know what fee we
2936 // need to subtract, we have no reason to reselect inputs
2937 if (nSubtractFeeFromAmount > 0) {
2938 pick_new_inputs = false;
2941 // Include more fee and try again.
2942 nFeeRet = nFeeNeeded;
2943 continue;
2947 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2949 if (sign)
2951 CTransaction txNewConst(txNew);
2952 int nIn = 0;
2953 for (const auto& coin : setCoins)
2955 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2956 SignatureData sigdata;
2958 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2960 strFailReason = _("Signing transaction failed");
2961 return false;
2962 } else {
2963 UpdateTransaction(txNew, nIn, sigdata);
2966 nIn++;
2970 // Embed the constructed transaction data in wtxNew.
2971 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2973 // Limit size
2974 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2976 strFailReason = _("Transaction too large");
2977 return false;
2981 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2982 // Lastly, ensure this tx will pass the mempool's chain limits
2983 LockPoints lp;
2984 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2985 CTxMemPool::setEntries setAncestors;
2986 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2987 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2988 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2989 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2990 std::string errString;
2991 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2992 strFailReason = _("Transaction has too long of a mempool chain");
2993 return false;
2997 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",
2998 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2999 feeCalc.est.pass.start, feeCalc.est.pass.end,
3000 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
3001 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
3002 feeCalc.est.fail.start, feeCalc.est.fail.end,
3003 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
3004 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
3005 return true;
3009 * Call after CreateTransaction unless you want to abort
3011 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
3014 LOCK2(cs_main, cs_wallet);
3015 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
3017 // Take key pair from key pool so it won't be used again
3018 reservekey.KeepKey();
3020 // Add tx to wallet, because if it has change it's also ours,
3021 // otherwise just for transaction history.
3022 AddToWallet(wtxNew);
3024 // Notify that old coins are spent
3025 for (const CTxIn& txin : wtxNew.tx->vin)
3027 CWalletTx &coin = mapWallet[txin.prevout.hash];
3028 coin.BindWallet(this);
3029 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3033 // Track how many getdata requests our transaction gets
3034 mapRequestCount[wtxNew.GetHash()] = 0;
3036 // Get the inserted-CWalletTx from mapWallet so that the
3037 // fInMempool flag is cached properly
3038 CWalletTx& wtx = mapWallet[wtxNew.GetHash()];
3040 if (fBroadcastTransactions)
3042 // Broadcast
3043 if (!wtx.AcceptToMemoryPool(maxTxFee, state)) {
3044 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3045 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3046 } else {
3047 wtx.RelayWalletTransaction(connman);
3051 return true;
3054 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3055 CWalletDB walletdb(*dbw);
3056 return walletdb.ListAccountCreditDebit(strAccount, entries);
3059 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3061 CWalletDB walletdb(*dbw);
3063 return AddAccountingEntry(acentry, &walletdb);
3066 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3068 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3069 return false;
3072 laccentries.push_back(acentry);
3073 CAccountingEntry & entry = laccentries.back();
3074 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3076 return true;
3079 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3081 LOCK2(cs_main, cs_wallet);
3083 fFirstRunRet = false;
3084 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3085 if (nLoadWalletRet == DB_NEED_REWRITE)
3087 if (dbw->Rewrite("\x04pool"))
3089 setInternalKeyPool.clear();
3090 setExternalKeyPool.clear();
3091 m_pool_key_to_index.clear();
3092 // Note: can't top-up keypool here, because wallet is locked.
3093 // User will be prompted to unlock wallet the next operation
3094 // that requires a new key.
3098 // This wallet is in its first run if all of these are empty
3099 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3101 if (nLoadWalletRet != DB_LOAD_OK)
3102 return nLoadWalletRet;
3104 uiInterface.LoadWallet(this);
3106 return DB_LOAD_OK;
3109 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3111 AssertLockHeld(cs_wallet); // mapWallet
3112 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3113 for (uint256 hash : vHashOut)
3114 mapWallet.erase(hash);
3116 if (nZapSelectTxRet == DB_NEED_REWRITE)
3118 if (dbw->Rewrite("\x04pool"))
3120 setInternalKeyPool.clear();
3121 setExternalKeyPool.clear();
3122 m_pool_key_to_index.clear();
3123 // Note: can't top-up keypool here, because wallet is locked.
3124 // User will be prompted to unlock wallet the next operation
3125 // that requires a new key.
3129 if (nZapSelectTxRet != DB_LOAD_OK)
3130 return nZapSelectTxRet;
3132 MarkDirty();
3134 return DB_LOAD_OK;
3138 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3140 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3141 if (nZapWalletTxRet == DB_NEED_REWRITE)
3143 if (dbw->Rewrite("\x04pool"))
3145 LOCK(cs_wallet);
3146 setInternalKeyPool.clear();
3147 setExternalKeyPool.clear();
3148 m_pool_key_to_index.clear();
3149 // Note: can't top-up keypool here, because wallet is locked.
3150 // User will be prompted to unlock wallet the next operation
3151 // that requires a new key.
3155 if (nZapWalletTxRet != DB_LOAD_OK)
3156 return nZapWalletTxRet;
3158 return DB_LOAD_OK;
3162 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3164 bool fUpdated = false;
3166 LOCK(cs_wallet); // mapAddressBook
3167 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3168 fUpdated = mi != mapAddressBook.end();
3169 mapAddressBook[address].name = strName;
3170 if (!strPurpose.empty()) /* update purpose only if requested */
3171 mapAddressBook[address].purpose = strPurpose;
3173 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3174 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3175 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3176 return false;
3177 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3180 bool CWallet::DelAddressBook(const CTxDestination& address)
3183 LOCK(cs_wallet); // mapAddressBook
3185 // Delete destdata tuples associated with address
3186 std::string strAddress = EncodeDestination(address);
3187 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3189 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3191 mapAddressBook.erase(address);
3194 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3196 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3197 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3200 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3202 CTxDestination address;
3203 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3204 auto mi = mapAddressBook.find(address);
3205 if (mi != mapAddressBook.end()) {
3206 return mi->second.name;
3209 // A scriptPubKey that doesn't have an entry in the address book is
3210 // associated with the default account ("").
3211 const static std::string DEFAULT_ACCOUNT_NAME;
3212 return DEFAULT_ACCOUNT_NAME;
3216 * Mark old keypool keys as used,
3217 * and generate all new keys
3219 bool CWallet::NewKeyPool()
3222 LOCK(cs_wallet);
3223 CWalletDB walletdb(*dbw);
3225 for (int64_t nIndex : setInternalKeyPool) {
3226 walletdb.ErasePool(nIndex);
3228 setInternalKeyPool.clear();
3230 for (int64_t nIndex : setExternalKeyPool) {
3231 walletdb.ErasePool(nIndex);
3233 setExternalKeyPool.clear();
3235 m_pool_key_to_index.clear();
3237 if (!TopUpKeyPool()) {
3238 return false;
3240 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3242 return true;
3245 size_t CWallet::KeypoolCountExternalKeys()
3247 AssertLockHeld(cs_wallet); // setExternalKeyPool
3248 return setExternalKeyPool.size();
3251 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3253 AssertLockHeld(cs_wallet);
3254 if (keypool.fInternal) {
3255 setInternalKeyPool.insert(nIndex);
3256 } else {
3257 setExternalKeyPool.insert(nIndex);
3259 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3260 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3262 // If no metadata exists yet, create a default with the pool key's
3263 // creation time. Note that this may be overwritten by actually
3264 // stored metadata for that key later, which is fine.
3265 CKeyID keyid = keypool.vchPubKey.GetID();
3266 if (mapKeyMetadata.count(keyid) == 0)
3267 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3270 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3273 LOCK(cs_wallet);
3275 if (IsLocked())
3276 return false;
3278 // Top up key pool
3279 unsigned int nTargetSize;
3280 if (kpSize > 0)
3281 nTargetSize = kpSize;
3282 else
3283 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3285 // count amount of available keys (internal, external)
3286 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3287 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3288 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3290 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3292 // don't create extra internal keys
3293 missingInternal = 0;
3295 bool internal = false;
3296 CWalletDB walletdb(*dbw);
3297 for (int64_t i = missingInternal + missingExternal; i--;)
3299 if (i < missingInternal) {
3300 internal = true;
3303 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3304 int64_t index = ++m_max_keypool_index;
3306 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3307 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3308 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3311 if (internal) {
3312 setInternalKeyPool.insert(index);
3313 } else {
3314 setExternalKeyPool.insert(index);
3316 m_pool_key_to_index[pubkey.GetID()] = index;
3318 if (missingInternal + missingExternal > 0) {
3319 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3322 return true;
3325 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3327 nIndex = -1;
3328 keypool.vchPubKey = CPubKey();
3330 LOCK(cs_wallet);
3332 if (!IsLocked())
3333 TopUpKeyPool();
3335 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3336 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3338 // Get the oldest key
3339 if(setKeyPool.empty())
3340 return;
3342 CWalletDB walletdb(*dbw);
3344 auto it = setKeyPool.begin();
3345 nIndex = *it;
3346 setKeyPool.erase(it);
3347 if (!walletdb.ReadPool(nIndex, keypool)) {
3348 throw std::runtime_error(std::string(__func__) + ": read failed");
3350 if (!HaveKey(keypool.vchPubKey.GetID())) {
3351 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3353 if (keypool.fInternal != fReturningInternal) {
3354 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3357 assert(keypool.vchPubKey.IsValid());
3358 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3359 LogPrintf("keypool reserve %d\n", nIndex);
3363 void CWallet::KeepKey(int64_t nIndex)
3365 // Remove from key pool
3366 CWalletDB walletdb(*dbw);
3367 walletdb.ErasePool(nIndex);
3368 LogPrintf("keypool keep %d\n", nIndex);
3371 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3373 // Return to key pool
3375 LOCK(cs_wallet);
3376 if (fInternal) {
3377 setInternalKeyPool.insert(nIndex);
3378 } else {
3379 setExternalKeyPool.insert(nIndex);
3381 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3383 LogPrintf("keypool return %d\n", nIndex);
3386 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3388 CKeyPool keypool;
3390 LOCK(cs_wallet);
3391 int64_t nIndex = 0;
3392 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3393 if (nIndex == -1)
3395 if (IsLocked()) return false;
3396 CWalletDB walletdb(*dbw);
3397 result = GenerateNewKey(walletdb, internal);
3398 return true;
3400 KeepKey(nIndex);
3401 result = keypool.vchPubKey;
3403 return true;
3406 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3407 if (setKeyPool.empty()) {
3408 return GetTime();
3411 CKeyPool keypool;
3412 int64_t nIndex = *(setKeyPool.begin());
3413 if (!walletdb.ReadPool(nIndex, keypool)) {
3414 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3416 assert(keypool.vchPubKey.IsValid());
3417 return keypool.nTime;
3420 int64_t CWallet::GetOldestKeyPoolTime()
3422 LOCK(cs_wallet);
3424 CWalletDB walletdb(*dbw);
3426 // load oldest key from keypool, get time and return
3427 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3428 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3429 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3432 return oldestKey;
3435 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3437 std::map<CTxDestination, CAmount> balances;
3440 LOCK(cs_wallet);
3441 for (const auto& walletEntry : mapWallet)
3443 const CWalletTx *pcoin = &walletEntry.second;
3445 if (!pcoin->IsTrusted())
3446 continue;
3448 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3449 continue;
3451 int nDepth = pcoin->GetDepthInMainChain();
3452 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3453 continue;
3455 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3457 CTxDestination addr;
3458 if (!IsMine(pcoin->tx->vout[i]))
3459 continue;
3460 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3461 continue;
3463 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3465 if (!balances.count(addr))
3466 balances[addr] = 0;
3467 balances[addr] += n;
3472 return balances;
3475 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3477 AssertLockHeld(cs_wallet); // mapWallet
3478 std::set< std::set<CTxDestination> > groupings;
3479 std::set<CTxDestination> grouping;
3481 for (const auto& walletEntry : mapWallet)
3483 const CWalletTx *pcoin = &walletEntry.second;
3485 if (pcoin->tx->vin.size() > 0)
3487 bool any_mine = false;
3488 // group all input addresses with each other
3489 for (CTxIn txin : pcoin->tx->vin)
3491 CTxDestination address;
3492 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3493 continue;
3494 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3495 continue;
3496 grouping.insert(address);
3497 any_mine = true;
3500 // group change with input addresses
3501 if (any_mine)
3503 for (CTxOut txout : pcoin->tx->vout)
3504 if (IsChange(txout))
3506 CTxDestination txoutAddr;
3507 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3508 continue;
3509 grouping.insert(txoutAddr);
3512 if (grouping.size() > 0)
3514 groupings.insert(grouping);
3515 grouping.clear();
3519 // group lone addrs by themselves
3520 for (const auto& txout : pcoin->tx->vout)
3521 if (IsMine(txout))
3523 CTxDestination address;
3524 if(!ExtractDestination(txout.scriptPubKey, address))
3525 continue;
3526 grouping.insert(address);
3527 groupings.insert(grouping);
3528 grouping.clear();
3532 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3533 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3534 for (std::set<CTxDestination> _grouping : groupings)
3536 // make a set of all the groups hit by this new group
3537 std::set< std::set<CTxDestination>* > hits;
3538 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3539 for (CTxDestination address : _grouping)
3540 if ((it = setmap.find(address)) != setmap.end())
3541 hits.insert((*it).second);
3543 // merge all hit groups into a new single group and delete old groups
3544 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3545 for (std::set<CTxDestination>* hit : hits)
3547 merged->insert(hit->begin(), hit->end());
3548 uniqueGroupings.erase(hit);
3549 delete hit;
3551 uniqueGroupings.insert(merged);
3553 // update setmap
3554 for (CTxDestination element : *merged)
3555 setmap[element] = merged;
3558 std::set< std::set<CTxDestination> > ret;
3559 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3561 ret.insert(*uniqueGrouping);
3562 delete uniqueGrouping;
3565 return ret;
3568 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3570 LOCK(cs_wallet);
3571 std::set<CTxDestination> result;
3572 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3574 const CTxDestination& address = item.first;
3575 const std::string& strName = item.second.name;
3576 if (strName == strAccount)
3577 result.insert(address);
3579 return result;
3582 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3584 if (nIndex == -1)
3586 CKeyPool keypool;
3587 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3588 if (nIndex != -1)
3589 vchPubKey = keypool.vchPubKey;
3590 else {
3591 return false;
3593 fInternal = keypool.fInternal;
3595 assert(vchPubKey.IsValid());
3596 pubkey = vchPubKey;
3597 return true;
3600 void CReserveKey::KeepKey()
3602 if (nIndex != -1)
3603 pwallet->KeepKey(nIndex);
3604 nIndex = -1;
3605 vchPubKey = CPubKey();
3608 void CReserveKey::ReturnKey()
3610 if (nIndex != -1) {
3611 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3613 nIndex = -1;
3614 vchPubKey = CPubKey();
3617 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3619 AssertLockHeld(cs_wallet);
3620 bool internal = setInternalKeyPool.count(keypool_id);
3621 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3622 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3623 auto it = setKeyPool->begin();
3625 CWalletDB walletdb(*dbw);
3626 while (it != std::end(*setKeyPool)) {
3627 const int64_t& index = *(it);
3628 if (index > keypool_id) break; // set*KeyPool is ordered
3630 CKeyPool keypool;
3631 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3632 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3634 walletdb.ErasePool(index);
3635 LogPrintf("keypool index %d removed\n", index);
3636 it = setKeyPool->erase(it);
3640 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3642 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3643 CPubKey pubkey;
3644 if (!rKey->GetReservedKey(pubkey))
3645 return;
3647 script = rKey;
3648 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3651 void CWallet::LockCoin(const COutPoint& output)
3653 AssertLockHeld(cs_wallet); // setLockedCoins
3654 setLockedCoins.insert(output);
3657 void CWallet::UnlockCoin(const COutPoint& output)
3659 AssertLockHeld(cs_wallet); // setLockedCoins
3660 setLockedCoins.erase(output);
3663 void CWallet::UnlockAllCoins()
3665 AssertLockHeld(cs_wallet); // setLockedCoins
3666 setLockedCoins.clear();
3669 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3671 AssertLockHeld(cs_wallet); // setLockedCoins
3672 COutPoint outpt(hash, n);
3674 return (setLockedCoins.count(outpt) > 0);
3677 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3679 AssertLockHeld(cs_wallet); // setLockedCoins
3680 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3681 it != setLockedCoins.end(); it++) {
3682 COutPoint outpt = (*it);
3683 vOutpts.push_back(outpt);
3687 /** @} */ // end of Actions
3689 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3690 AssertLockHeld(cs_wallet); // mapKeyMetadata
3691 mapKeyBirth.clear();
3693 // get birth times for keys with metadata
3694 for (const auto& entry : mapKeyMetadata) {
3695 if (entry.second.nCreateTime) {
3696 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3700 // map in which we'll infer heights of other keys
3701 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3702 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3703 for (const CKeyID &keyid : GetKeys()) {
3704 if (mapKeyBirth.count(keyid) == 0)
3705 mapKeyFirstBlock[keyid] = pindexMax;
3708 // if there are no such keys, we're done
3709 if (mapKeyFirstBlock.empty())
3710 return;
3712 // find first block that affects those keys, if there are any left
3713 std::vector<CKeyID> vAffected;
3714 for (const auto& entry : mapWallet) {
3715 // iterate over all wallet transactions...
3716 const CWalletTx &wtx = entry.second;
3717 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3718 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3719 // ... which are already in a block
3720 int nHeight = blit->second->nHeight;
3721 for (const CTxOut &txout : wtx.tx->vout) {
3722 // iterate over all their outputs
3723 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3724 for (const CKeyID &keyid : vAffected) {
3725 // ... and all their affected keys
3726 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3727 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3728 rit->second = blit->second;
3730 vAffected.clear();
3735 // Extract block timestamps for those keys
3736 for (const auto& entry : mapKeyFirstBlock)
3737 mapKeyBirth[entry.first] = entry.second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3741 * Compute smart timestamp for a transaction being added to the wallet.
3743 * Logic:
3744 * - If sending a transaction, assign its timestamp to the current time.
3745 * - If receiving a transaction outside a block, assign its timestamp to the
3746 * current time.
3747 * - If receiving a block with a future timestamp, assign all its (not already
3748 * known) transactions' timestamps to the current time.
3749 * - If receiving a block with a past timestamp, before the most recent known
3750 * transaction (that we care about), assign all its (not already known)
3751 * transactions' timestamps to the same timestamp as that most-recent-known
3752 * transaction.
3753 * - If receiving a block with a past timestamp, but after the most recent known
3754 * transaction, assign all its (not already known) transactions' timestamps to
3755 * the block time.
3757 * For more information see CWalletTx::nTimeSmart,
3758 * https://bitcointalk.org/?topic=54527, or
3759 * https://github.com/bitcoin/bitcoin/pull/1393.
3761 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3763 unsigned int nTimeSmart = wtx.nTimeReceived;
3764 if (!wtx.hashUnset()) {
3765 if (mapBlockIndex.count(wtx.hashBlock)) {
3766 int64_t latestNow = wtx.nTimeReceived;
3767 int64_t latestEntry = 0;
3769 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3770 int64_t latestTolerated = latestNow + 300;
3771 const TxItems& txOrdered = wtxOrdered;
3772 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3773 CWalletTx* const pwtx = it->second.first;
3774 if (pwtx == &wtx) {
3775 continue;
3777 CAccountingEntry* const pacentry = it->second.second;
3778 int64_t nSmartTime;
3779 if (pwtx) {
3780 nSmartTime = pwtx->nTimeSmart;
3781 if (!nSmartTime) {
3782 nSmartTime = pwtx->nTimeReceived;
3784 } else {
3785 nSmartTime = pacentry->nTime;
3787 if (nSmartTime <= latestTolerated) {
3788 latestEntry = nSmartTime;
3789 if (nSmartTime > latestNow) {
3790 latestNow = nSmartTime;
3792 break;
3796 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3797 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3798 } else {
3799 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3802 return nTimeSmart;
3805 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3807 if (boost::get<CNoDestination>(&dest))
3808 return false;
3810 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3811 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3814 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3816 if (!mapAddressBook[dest].destdata.erase(key))
3817 return false;
3818 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3821 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3823 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3824 return true;
3827 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3829 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3830 if(i != mapAddressBook.end())
3832 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3833 if(j != i->second.destdata.end())
3835 if(value)
3836 *value = j->second;
3837 return true;
3840 return false;
3843 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3845 LOCK(cs_wallet);
3846 std::vector<std::string> values;
3847 for (const auto& address : mapAddressBook) {
3848 for (const auto& data : address.second.destdata) {
3849 if (!data.first.compare(0, prefix.size(), prefix)) {
3850 values.emplace_back(data.second);
3854 return values;
3857 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3859 // needed to restore wallet transaction meta data after -zapwallettxes
3860 std::vector<CWalletTx> vWtx;
3862 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3863 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3865 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3866 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3867 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3868 if (nZapWalletRet != DB_LOAD_OK) {
3869 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3870 return nullptr;
3874 uiInterface.InitMessage(_("Loading wallet..."));
3876 int64_t nStart = GetTimeMillis();
3877 bool fFirstRun = true;
3878 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3879 CWallet *walletInstance = new CWallet(std::move(dbw));
3880 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3881 if (nLoadWalletRet != DB_LOAD_OK)
3883 if (nLoadWalletRet == DB_CORRUPT) {
3884 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3885 return nullptr;
3887 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3889 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3890 " or address book entries might be missing or incorrect."),
3891 walletFile));
3893 else if (nLoadWalletRet == DB_TOO_NEW) {
3894 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3895 return nullptr;
3897 else if (nLoadWalletRet == DB_NEED_REWRITE)
3899 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3900 return nullptr;
3902 else {
3903 InitError(strprintf(_("Error loading %s"), walletFile));
3904 return nullptr;
3908 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3910 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3911 if (nMaxVersion == 0) // the -upgradewallet without argument case
3913 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3914 nMaxVersion = CLIENT_VERSION;
3915 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3917 else
3918 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3919 if (nMaxVersion < walletInstance->GetVersion())
3921 InitError(_("Cannot downgrade wallet"));
3922 return nullptr;
3924 walletInstance->SetMaxVersion(nMaxVersion);
3927 if (fFirstRun)
3929 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3930 if (!gArgs.GetBoolArg("-usehd", true)) {
3931 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3932 return nullptr;
3934 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3936 // generate a new master key
3937 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3938 if (!walletInstance->SetHDMasterKey(masterPubKey))
3939 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3941 // Top up the keypool
3942 if (!walletInstance->TopUpKeyPool()) {
3943 InitError(_("Unable to generate initial keys") += "\n");
3944 return nullptr;
3947 walletInstance->SetBestChain(chainActive.GetLocator());
3949 else if (gArgs.IsArgSet("-usehd")) {
3950 bool useHD = gArgs.GetBoolArg("-usehd", true);
3951 if (walletInstance->IsHDEnabled() && !useHD) {
3952 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3953 return nullptr;
3955 if (!walletInstance->IsHDEnabled() && useHD) {
3956 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3957 return nullptr;
3961 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3963 // Try to top up keypool. No-op if the wallet is locked.
3964 walletInstance->TopUpKeyPool();
3966 CBlockIndex *pindexRescan = chainActive.Genesis();
3967 if (!gArgs.GetBoolArg("-rescan", false))
3969 CWalletDB walletdb(*walletInstance->dbw);
3970 CBlockLocator locator;
3971 if (walletdb.ReadBestBlock(locator))
3972 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3975 walletInstance->m_last_block_processed = chainActive.Tip();
3976 RegisterValidationInterface(walletInstance);
3978 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3980 //We can't rescan beyond non-pruned blocks, stop and throw an error
3981 //this might happen if a user uses an old wallet within a pruned node
3982 // or if he ran -disablewallet for a longer time, then decided to re-enable
3983 if (fPruneMode)
3985 CBlockIndex *block = chainActive.Tip();
3986 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3987 block = block->pprev;
3989 if (pindexRescan != block) {
3990 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3991 return nullptr;
3995 uiInterface.InitMessage(_("Rescanning..."));
3996 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3998 // No need to read and scan block if block was created before
3999 // our wallet birthday (as adjusted for block time variability)
4000 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4001 pindexRescan = chainActive.Next(pindexRescan);
4004 nStart = GetTimeMillis();
4005 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
4006 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4007 walletInstance->SetBestChain(chainActive.GetLocator());
4008 walletInstance->dbw->IncrementUpdateCounter();
4010 // Restore wallet transaction metadata after -zapwallettxes=1
4011 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4013 CWalletDB walletdb(*walletInstance->dbw);
4015 for (const CWalletTx& wtxOld : vWtx)
4017 uint256 hash = wtxOld.GetHash();
4018 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4019 if (mi != walletInstance->mapWallet.end())
4021 const CWalletTx* copyFrom = &wtxOld;
4022 CWalletTx* copyTo = &mi->second;
4023 copyTo->mapValue = copyFrom->mapValue;
4024 copyTo->vOrderForm = copyFrom->vOrderForm;
4025 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4026 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4027 copyTo->fFromMe = copyFrom->fFromMe;
4028 copyTo->strFromAccount = copyFrom->strFromAccount;
4029 copyTo->nOrderPos = copyFrom->nOrderPos;
4030 walletdb.WriteTx(*copyTo);
4035 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4038 LOCK(walletInstance->cs_wallet);
4039 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4040 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4041 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4044 return walletInstance;
4047 std::atomic<bool> CWallet::fFlushScheduled(false);
4049 void CWallet::postInitProcess(CScheduler& scheduler)
4051 // Add wallet transactions that aren't already in a block to mempool
4052 // Do this here as mempool requires genesis block to be loaded
4053 ReacceptWalletTransactions();
4055 // Run a thread to flush wallet periodically
4056 if (!CWallet::fFlushScheduled.exchange(true)) {
4057 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4061 bool CWallet::BackupWallet(const std::string& strDest)
4063 return dbw->Backup(strDest);
4066 CKeyPool::CKeyPool()
4068 nTime = GetTime();
4069 fInternal = false;
4072 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4074 nTime = GetTime();
4075 vchPubKey = vchPubKeyIn;
4076 fInternal = internalIn;
4079 CWalletKey::CWalletKey(int64_t nExpires)
4081 nTimeCreated = (nExpires ? GetTime() : 0);
4082 nTimeExpires = nExpires;
4085 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4087 // Update the tx's hashBlock
4088 hashBlock = pindex->GetBlockHash();
4090 // set the position of the transaction in the block
4091 nIndex = posInBlock;
4094 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4096 if (hashUnset())
4097 return 0;
4099 AssertLockHeld(cs_main);
4101 // Find the block it claims to be in
4102 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4103 if (mi == mapBlockIndex.end())
4104 return 0;
4105 CBlockIndex* pindex = (*mi).second;
4106 if (!pindex || !chainActive.Contains(pindex))
4107 return 0;
4109 pindexRet = pindex;
4110 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4113 int CMerkleTx::GetBlocksToMaturity() const
4115 if (!IsCoinBase())
4116 return 0;
4117 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4121 bool CWalletTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4123 // Quick check to avoid re-setting fInMempool to false
4124 if (mempool.exists(tx->GetHash())) {
4125 return false;
4128 // We must set fInMempool here - while it will be re-set to true by the
4129 // entered-mempool callback, if we did not there would be a race where a
4130 // user could call sendmoney in a loop and hit spurious out of funds errors
4131 // because we think that the transaction they just generated's change is
4132 // unavailable as we're not yet aware its in mempool.
4133 bool ret = ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4134 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
4135 fInMempool = ret;
4136 return ret;