wallet: Fix memory leak when loading a corrupted wallet file
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob3f1de5714caf4dd25ef3318f7064c46a8f629cd4
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 "init.h"
16 #include "key.h"
17 #include "keystore.h"
18 #include "validation.h"
19 #include "net.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "policy/rbf.h"
23 #include "primitives/block.h"
24 #include "primitives/transaction.h"
25 #include "script/script.h"
26 #include "script/sign.h"
27 #include "scheduler.h"
28 #include "timedata.h"
29 #include "txmempool.h"
30 #include "util.h"
31 #include "ui_interface.h"
32 #include "utilmoneystr.h"
34 #include <assert.h>
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 CNoDestination &none) {}
116 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
118 LOCK(cs_wallet);
119 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
120 if (it == mapWallet.end())
121 return nullptr;
122 return &(it->second);
125 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
127 AssertLockHeld(cs_wallet); // mapKeyMetadata
128 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
130 CKey secret;
132 // Create new metadata
133 int64_t nCreationTime = GetTime();
134 CKeyMetadata metadata(nCreationTime);
136 // use HD key derivation if HD was enabled during wallet creation
137 if (IsHDEnabled()) {
138 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
139 } else {
140 secret.MakeNewKey(fCompressed);
143 // Compressed public keys were introduced in version 0.6.0
144 if (fCompressed) {
145 SetMinVersion(FEATURE_COMPRPUBKEY);
148 CPubKey pubkey = secret.GetPubKey();
149 assert(secret.VerifyPubKey(pubkey));
151 mapKeyMetadata[pubkey.GetID()] = metadata;
152 UpdateTimeFirstKey(nCreationTime);
154 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
155 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
157 return pubkey;
160 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
162 // for now we use a fixed keypath scheme of m/0'/0'/k
163 CKey key; //master key seed (256bit)
164 CExtKey masterKey; //hd master key
165 CExtKey accountKey; //key at m/0'
166 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
167 CExtKey childKey; //key at m/0'/0'/<n>'
169 // try to get the master key
170 if (!GetKey(hdChain.masterKeyID, key))
171 throw std::runtime_error(std::string(__func__) + ": Master key not found");
173 masterKey.SetMaster(key.begin(), key.size());
175 // derive m/0'
176 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
177 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
179 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
180 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
181 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
183 // derive child key at next index, skip keys already known to the wallet
184 do {
185 // always derive hardened keys
186 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
187 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
188 if (internal) {
189 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
190 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
191 hdChain.nInternalChainCounter++;
193 else {
194 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
195 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
196 hdChain.nExternalChainCounter++;
198 } while (HaveKey(childKey.key.GetPubKey().GetID()));
199 secret = childKey.key;
200 metadata.hdMasterKeyID = hdChain.masterKeyID;
201 // update the chain model in the database
202 if (!walletdb.WriteHDChain(hdChain))
203 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
206 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
208 AssertLockHeld(cs_wallet); // mapKeyMetadata
210 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
211 // which is overridden below. To avoid flushes, the database handle is
212 // tunneled through to it.
213 bool needsDB = !pwalletdbEncryption;
214 if (needsDB) {
215 pwalletdbEncryption = &walletdb;
217 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
218 if (needsDB) pwalletdbEncryption = nullptr;
219 return false;
221 if (needsDB) pwalletdbEncryption = nullptr;
223 // check if we need to remove from watch-only
224 CScript script;
225 script = GetScriptForDestination(pubkey.GetID());
226 if (HaveWatchOnly(script)) {
227 RemoveWatchOnly(script);
229 script = GetScriptForRawPubKey(pubkey);
230 if (HaveWatchOnly(script)) {
231 RemoveWatchOnly(script);
234 if (!IsCrypted()) {
235 return walletdb.WriteKey(pubkey,
236 secret.GetPrivKey(),
237 mapKeyMetadata[pubkey.GetID()]);
239 return true;
242 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
244 CWalletDB walletdb(*dbw);
245 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
248 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
249 const std::vector<unsigned char> &vchCryptedSecret)
251 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
252 return false;
254 LOCK(cs_wallet);
255 if (pwalletdbEncryption)
256 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
257 vchCryptedSecret,
258 mapKeyMetadata[vchPubKey.GetID()]);
259 else
260 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
261 vchCryptedSecret,
262 mapKeyMetadata[vchPubKey.GetID()]);
266 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
268 AssertLockHeld(cs_wallet); // mapKeyMetadata
269 UpdateTimeFirstKey(meta.nCreateTime);
270 mapKeyMetadata[keyID] = meta;
271 return true;
274 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
276 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
280 * Update wallet first key creation time. This should be called whenever keys
281 * are added to the wallet, with the oldest key creation time.
283 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
285 AssertLockHeld(cs_wallet);
286 if (nCreateTime <= 1) {
287 // Cannot determine birthday information, so set the wallet birthday to
288 // the beginning of time.
289 nTimeFirstKey = 1;
290 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
291 nTimeFirstKey = nCreateTime;
295 bool CWallet::AddCScript(const CScript& redeemScript)
297 if (!CCryptoKeyStore::AddCScript(redeemScript))
298 return false;
299 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
302 bool CWallet::LoadCScript(const CScript& redeemScript)
304 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
305 * that never can be redeemed. However, old wallets may still contain
306 * these. Do not add them to the wallet and warn. */
307 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
309 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
310 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",
311 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
312 return true;
315 return CCryptoKeyStore::AddCScript(redeemScript);
318 bool CWallet::AddWatchOnly(const CScript& dest)
320 if (!CCryptoKeyStore::AddWatchOnly(dest))
321 return false;
322 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
323 UpdateTimeFirstKey(meta.nCreateTime);
324 NotifyWatchonlyChanged(true);
325 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
328 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
330 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
331 return AddWatchOnly(dest);
334 bool CWallet::RemoveWatchOnly(const CScript &dest)
336 AssertLockHeld(cs_wallet);
337 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
338 return false;
339 if (!HaveWatchOnly())
340 NotifyWatchonlyChanged(false);
341 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
342 return false;
344 return true;
347 bool CWallet::LoadWatchOnly(const CScript &dest)
349 return CCryptoKeyStore::AddWatchOnly(dest);
352 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
354 CCrypter crypter;
355 CKeyingMaterial _vMasterKey;
358 LOCK(cs_wallet);
359 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
361 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
362 return false;
363 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
364 continue; // try another master key
365 if (CCryptoKeyStore::Unlock(_vMasterKey))
366 return true;
369 return false;
372 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
374 bool fWasLocked = IsLocked();
377 LOCK(cs_wallet);
378 Lock();
380 CCrypter crypter;
381 CKeyingMaterial _vMasterKey;
382 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
384 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
385 return false;
386 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
387 return false;
388 if (CCryptoKeyStore::Unlock(_vMasterKey))
390 int64_t nStartTime = GetTimeMillis();
391 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
392 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
394 nStartTime = GetTimeMillis();
395 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
396 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
398 if (pMasterKey.second.nDeriveIterations < 25000)
399 pMasterKey.second.nDeriveIterations = 25000;
401 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
403 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
404 return false;
405 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
406 return false;
407 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
408 if (fWasLocked)
409 Lock();
410 return true;
415 return false;
418 void CWallet::SetBestChain(const CBlockLocator& loc)
420 CWalletDB walletdb(*dbw);
421 walletdb.WriteBestBlock(loc);
424 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
426 LOCK(cs_wallet); // nWalletVersion
427 if (nWalletVersion >= nVersion)
428 return true;
430 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
431 if (fExplicit && nVersion > nWalletMaxVersion)
432 nVersion = FEATURE_LATEST;
434 nWalletVersion = nVersion;
436 if (nVersion > nWalletMaxVersion)
437 nWalletMaxVersion = nVersion;
440 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
441 if (nWalletVersion > 40000)
442 pwalletdb->WriteMinVersion(nWalletVersion);
443 if (!pwalletdbIn)
444 delete pwalletdb;
447 return true;
450 bool CWallet::SetMaxVersion(int nVersion)
452 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
453 // cannot downgrade below current version
454 if (nWalletVersion > nVersion)
455 return false;
457 nWalletMaxVersion = nVersion;
459 return true;
462 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
464 std::set<uint256> result;
465 AssertLockHeld(cs_wallet);
467 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
468 if (it == mapWallet.end())
469 return result;
470 const CWalletTx& wtx = it->second;
472 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
474 for (const CTxIn& txin : wtx.tx->vin)
476 if (mapTxSpends.count(txin.prevout) <= 1)
477 continue; // No conflict if zero or one spends
478 range = mapTxSpends.equal_range(txin.prevout);
479 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
480 result.insert(_it->second);
482 return result;
485 bool CWallet::HasWalletSpend(const uint256& txid) const
487 AssertLockHeld(cs_wallet);
488 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
489 return (iter != mapTxSpends.end() && iter->first.hash == txid);
492 void CWallet::Flush(bool shutdown)
494 dbw->Flush(shutdown);
497 bool CWallet::Verify()
499 if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
500 return true;
502 uiInterface.InitMessage(_("Verifying wallet(s)..."));
504 // Keep track of each wallet absolute path to detect duplicates.
505 std::set<fs::path> wallet_paths;
507 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
508 if (boost::filesystem::path(walletFile).filename() != walletFile) {
509 return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
512 if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
513 return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
516 fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
518 if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
519 return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
522 if (!wallet_paths.insert(wallet_path).second) {
523 return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
526 std::string strError;
527 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
528 return InitError(strError);
531 if (gArgs.GetBoolArg("-salvagewallet", false)) {
532 // Recover readable keypairs:
533 CWallet dummyWallet;
534 std::string backup_filename;
535 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
536 return false;
540 std::string strWarning;
541 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
542 if (!strWarning.empty()) {
543 InitWarning(strWarning);
545 if (!dbV) {
546 InitError(strError);
547 return false;
551 return true;
554 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
556 // We want all the wallet transactions in range to have the same metadata as
557 // the oldest (smallest nOrderPos).
558 // So: find smallest nOrderPos:
560 int nMinOrderPos = std::numeric_limits<int>::max();
561 const CWalletTx* copyFrom = nullptr;
562 for (TxSpends::iterator it = range.first; it != range.second; ++it)
564 const uint256& hash = it->second;
565 int n = mapWallet[hash].nOrderPos;
566 if (n < nMinOrderPos)
568 nMinOrderPos = n;
569 copyFrom = &mapWallet[hash];
572 // Now copy data from copyFrom to rest:
573 for (TxSpends::iterator it = range.first; it != range.second; ++it)
575 const uint256& hash = it->second;
576 CWalletTx* copyTo = &mapWallet[hash];
577 if (copyFrom == copyTo) continue;
578 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
579 copyTo->mapValue = copyFrom->mapValue;
580 copyTo->vOrderForm = copyFrom->vOrderForm;
581 // fTimeReceivedIsTxTime not copied on purpose
582 // nTimeReceived not copied on purpose
583 copyTo->nTimeSmart = copyFrom->nTimeSmart;
584 copyTo->fFromMe = copyFrom->fFromMe;
585 copyTo->strFromAccount = copyFrom->strFromAccount;
586 // nOrderPos not copied on purpose
587 // cached members not copied on purpose
592 * Outpoint is spent if any non-conflicted transaction
593 * spends it:
595 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
597 const COutPoint outpoint(hash, n);
598 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
599 range = mapTxSpends.equal_range(outpoint);
601 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
603 const uint256& wtxid = it->second;
604 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
605 if (mit != mapWallet.end()) {
606 int depth = mit->second.GetDepthInMainChain();
607 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
608 return true; // Spent
611 return false;
614 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
616 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
618 std::pair<TxSpends::iterator, TxSpends::iterator> range;
619 range = mapTxSpends.equal_range(outpoint);
620 SyncMetaData(range);
624 void CWallet::AddToSpends(const uint256& wtxid)
626 assert(mapWallet.count(wtxid));
627 CWalletTx& thisTx = mapWallet[wtxid];
628 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
629 return;
631 for (const CTxIn& txin : thisTx.tx->vin)
632 AddToSpends(txin.prevout, wtxid);
635 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
637 if (IsCrypted())
638 return false;
640 CKeyingMaterial _vMasterKey;
642 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
643 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
645 CMasterKey kMasterKey;
647 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
648 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
650 CCrypter crypter;
651 int64_t nStartTime = GetTimeMillis();
652 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
653 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
655 nStartTime = GetTimeMillis();
656 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
657 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
659 if (kMasterKey.nDeriveIterations < 25000)
660 kMasterKey.nDeriveIterations = 25000;
662 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
664 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
665 return false;
666 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
667 return false;
670 LOCK(cs_wallet);
671 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
672 assert(!pwalletdbEncryption);
673 pwalletdbEncryption = new CWalletDB(*dbw);
674 if (!pwalletdbEncryption->TxnBegin()) {
675 delete pwalletdbEncryption;
676 pwalletdbEncryption = nullptr;
677 return false;
679 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
681 if (!EncryptKeys(_vMasterKey))
683 pwalletdbEncryption->TxnAbort();
684 delete pwalletdbEncryption;
685 // We now probably have half of our keys encrypted in memory, and half not...
686 // die and let the user reload the unencrypted wallet.
687 assert(false);
690 // Encryption was introduced in version 0.4.0
691 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
693 if (!pwalletdbEncryption->TxnCommit()) {
694 delete pwalletdbEncryption;
695 // We now have keys encrypted in memory, but not on disk...
696 // die to avoid confusion and let the user reload the unencrypted wallet.
697 assert(false);
700 delete pwalletdbEncryption;
701 pwalletdbEncryption = nullptr;
703 Lock();
704 Unlock(strWalletPassphrase);
706 // if we are using HD, replace the HD master key (seed) with a new one
707 if (IsHDEnabled()) {
708 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
709 return false;
713 NewKeyPool();
714 Lock();
716 // Need to completely rewrite the wallet file; if we don't, bdb might keep
717 // bits of the unencrypted private key in slack space in the database file.
718 dbw->Rewrite();
721 NotifyStatusChanged(this);
723 return true;
726 DBErrors CWallet::ReorderTransactions()
728 LOCK(cs_wallet);
729 CWalletDB walletdb(*dbw);
731 // Old wallets didn't have any defined order for transactions
732 // Probably a bad idea to change the output of this
734 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
735 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
736 typedef std::multimap<int64_t, TxPair > TxItems;
737 TxItems txByTime;
739 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
741 CWalletTx* wtx = &((*it).second);
742 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
744 std::list<CAccountingEntry> acentries;
745 walletdb.ListAccountCreditDebit("", acentries);
746 for (CAccountingEntry& entry : acentries)
748 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
751 nOrderPosNext = 0;
752 std::vector<int64_t> nOrderPosOffsets;
753 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
755 CWalletTx *const pwtx = (*it).second.first;
756 CAccountingEntry *const pacentry = (*it).second.second;
757 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
759 if (nOrderPos == -1)
761 nOrderPos = nOrderPosNext++;
762 nOrderPosOffsets.push_back(nOrderPos);
764 if (pwtx)
766 if (!walletdb.WriteTx(*pwtx))
767 return DB_LOAD_FAIL;
769 else
770 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
771 return DB_LOAD_FAIL;
773 else
775 int64_t nOrderPosOff = 0;
776 for (const int64_t& nOffsetStart : nOrderPosOffsets)
778 if (nOrderPos >= nOffsetStart)
779 ++nOrderPosOff;
781 nOrderPos += nOrderPosOff;
782 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
784 if (!nOrderPosOff)
785 continue;
787 // Since we're changing the order, write it back
788 if (pwtx)
790 if (!walletdb.WriteTx(*pwtx))
791 return DB_LOAD_FAIL;
793 else
794 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
795 return DB_LOAD_FAIL;
798 walletdb.WriteOrderPosNext(nOrderPosNext);
800 return DB_LOAD_OK;
803 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
805 AssertLockHeld(cs_wallet); // nOrderPosNext
806 int64_t nRet = nOrderPosNext++;
807 if (pwalletdb) {
808 pwalletdb->WriteOrderPosNext(nOrderPosNext);
809 } else {
810 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
812 return nRet;
815 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
817 CWalletDB walletdb(*dbw);
818 if (!walletdb.TxnBegin())
819 return false;
821 int64_t nNow = GetAdjustedTime();
823 // Debit
824 CAccountingEntry debit;
825 debit.nOrderPos = IncOrderPosNext(&walletdb);
826 debit.strAccount = strFrom;
827 debit.nCreditDebit = -nAmount;
828 debit.nTime = nNow;
829 debit.strOtherAccount = strTo;
830 debit.strComment = strComment;
831 AddAccountingEntry(debit, &walletdb);
833 // Credit
834 CAccountingEntry credit;
835 credit.nOrderPos = IncOrderPosNext(&walletdb);
836 credit.strAccount = strTo;
837 credit.nCreditDebit = nAmount;
838 credit.nTime = nNow;
839 credit.strOtherAccount = strFrom;
840 credit.strComment = strComment;
841 AddAccountingEntry(credit, &walletdb);
843 if (!walletdb.TxnCommit())
844 return false;
846 return true;
849 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
851 CWalletDB walletdb(*dbw);
853 CAccount account;
854 walletdb.ReadAccount(strAccount, account);
856 if (!bForceNew) {
857 if (!account.vchPubKey.IsValid())
858 bForceNew = true;
859 else {
860 // Check if the current key has been used
861 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
862 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
863 it != mapWallet.end() && account.vchPubKey.IsValid();
864 ++it)
865 for (const CTxOut& txout : (*it).second.tx->vout)
866 if (txout.scriptPubKey == scriptPubKey) {
867 bForceNew = true;
868 break;
873 // Generate a new key
874 if (bForceNew) {
875 if (!GetKeyFromPool(account.vchPubKey, false))
876 return false;
878 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
879 walletdb.WriteAccount(strAccount, account);
882 pubKey = account.vchPubKey;
884 return true;
887 void CWallet::MarkDirty()
890 LOCK(cs_wallet);
891 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
892 item.second.MarkDirty();
896 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
898 LOCK(cs_wallet);
900 auto mi = mapWallet.find(originalHash);
902 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
903 assert(mi != mapWallet.end());
905 CWalletTx& wtx = (*mi).second;
907 // Ensure for now that we're not overwriting data
908 assert(wtx.mapValue.count("replaced_by_txid") == 0);
910 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
912 CWalletDB walletdb(*dbw, "r+");
914 bool success = true;
915 if (!walletdb.WriteTx(wtx)) {
916 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
917 success = false;
920 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
922 return success;
925 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
927 LOCK(cs_wallet);
929 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
931 uint256 hash = wtxIn.GetHash();
933 // Inserts only if not already there, returns tx inserted or tx found
934 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
935 CWalletTx& wtx = (*ret.first).second;
936 wtx.BindWallet(this);
937 bool fInsertedNew = ret.second;
938 if (fInsertedNew)
940 wtx.nTimeReceived = GetAdjustedTime();
941 wtx.nOrderPos = IncOrderPosNext(&walletdb);
942 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
943 wtx.nTimeSmart = ComputeTimeSmart(wtx);
944 AddToSpends(hash);
947 bool fUpdated = false;
948 if (!fInsertedNew)
950 // Merge
951 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
953 wtx.hashBlock = wtxIn.hashBlock;
954 fUpdated = true;
956 // If no longer abandoned, update
957 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
959 wtx.hashBlock = wtxIn.hashBlock;
960 fUpdated = true;
962 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
964 wtx.nIndex = wtxIn.nIndex;
965 fUpdated = true;
967 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
969 wtx.fFromMe = wtxIn.fFromMe;
970 fUpdated = true;
974 //// debug print
975 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
977 // Write to disk
978 if (fInsertedNew || fUpdated)
979 if (!walletdb.WriteTx(wtx))
980 return false;
982 // Break debit/credit balance caches:
983 wtx.MarkDirty();
985 // Notify UI of new or updated transaction
986 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
988 // notify an external script when a wallet transaction comes in or is updated
989 std::string strCmd = gArgs.GetArg("-walletnotify", "");
991 if ( !strCmd.empty())
993 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
994 boost::thread t(runCommand, strCmd); // thread runs free
997 return true;
1000 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
1002 uint256 hash = wtxIn.GetHash();
1004 mapWallet[hash] = wtxIn;
1005 CWalletTx& wtx = mapWallet[hash];
1006 wtx.BindWallet(this);
1007 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1008 AddToSpends(hash);
1009 for (const CTxIn& txin : wtx.tx->vin) {
1010 if (mapWallet.count(txin.prevout.hash)) {
1011 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
1012 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1013 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1018 return true;
1022 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1023 * be set when the transaction was known to be included in a block. When
1024 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1025 * notifications happen and cached balances are marked dirty.
1027 * If fUpdate is true, existing transactions will be updated.
1028 * TODO: One exception to this is that the abandoned state is cleared under the
1029 * assumption that any further notification of a transaction that was considered
1030 * abandoned is an indication that it is not safe to be considered abandoned.
1031 * Abandoned state should probably be more carefully tracked via different
1032 * posInBlock signals or by checking mempool presence when necessary.
1034 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1036 const CTransaction& tx = *ptx;
1038 AssertLockHeld(cs_wallet);
1040 if (pIndex != nullptr) {
1041 for (const CTxIn& txin : tx.vin) {
1042 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1043 while (range.first != range.second) {
1044 if (range.first->second != tx.GetHash()) {
1045 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);
1046 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1048 range.first++;
1053 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1054 if (fExisted && !fUpdate) return false;
1055 if (fExisted || IsMine(tx) || IsFromMe(tx))
1057 /* Check if any keys in the wallet keypool that were supposed to be unused
1058 * have appeared in a new transaction. If so, remove those keys from the keypool.
1059 * This can happen when restoring an old wallet backup that does not contain
1060 * the mostly recently created transactions from newer versions of the wallet.
1063 // loop though all outputs
1064 for (const CTxOut& txout: tx.vout) {
1065 // extract addresses and check if they match with an unused keypool key
1066 std::vector<CKeyID> vAffected;
1067 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1068 for (const CKeyID &keyid : vAffected) {
1069 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1070 if (mi != m_pool_key_to_index.end()) {
1071 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1072 MarkReserveKeysAsUsed(mi->second);
1074 if (!TopUpKeyPool()) {
1075 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1081 CWalletTx wtx(this, ptx);
1083 // Get merkle branch if transaction was found in a block
1084 if (pIndex != nullptr)
1085 wtx.SetMerkleBranch(pIndex, posInBlock);
1087 return AddToWallet(wtx, false);
1090 return false;
1093 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1095 LOCK2(cs_main, cs_wallet);
1096 const CWalletTx* wtx = GetWalletTx(hashTx);
1097 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1100 bool CWallet::AbandonTransaction(const uint256& hashTx)
1102 LOCK2(cs_main, cs_wallet);
1104 CWalletDB walletdb(*dbw, "r+");
1106 std::set<uint256> todo;
1107 std::set<uint256> done;
1109 // Can't mark abandoned if confirmed or in mempool
1110 assert(mapWallet.count(hashTx));
1111 CWalletTx& origtx = mapWallet[hashTx];
1112 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1113 return false;
1116 todo.insert(hashTx);
1118 while (!todo.empty()) {
1119 uint256 now = *todo.begin();
1120 todo.erase(now);
1121 done.insert(now);
1122 assert(mapWallet.count(now));
1123 CWalletTx& wtx = mapWallet[now];
1124 int currentconfirm = wtx.GetDepthInMainChain();
1125 // If the orig tx was not in block, none of its spends can be
1126 assert(currentconfirm <= 0);
1127 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1128 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1129 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1130 assert(!wtx.InMempool());
1131 wtx.nIndex = -1;
1132 wtx.setAbandoned();
1133 wtx.MarkDirty();
1134 walletdb.WriteTx(wtx);
1135 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1136 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1137 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1138 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1139 if (!done.count(iter->second)) {
1140 todo.insert(iter->second);
1142 iter++;
1144 // If a transaction changes 'conflicted' state, that changes the balance
1145 // available of the outputs it spends. So force those to be recomputed
1146 for (const CTxIn& txin : wtx.tx->vin)
1148 if (mapWallet.count(txin.prevout.hash))
1149 mapWallet[txin.prevout.hash].MarkDirty();
1154 return true;
1157 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1159 LOCK2(cs_main, cs_wallet);
1161 int conflictconfirms = 0;
1162 if (mapBlockIndex.count(hashBlock)) {
1163 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1164 if (chainActive.Contains(pindex)) {
1165 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1168 // If number of conflict confirms cannot be determined, this means
1169 // that the block is still unknown or not yet part of the main chain,
1170 // for example when loading the wallet during a reindex. Do nothing in that
1171 // case.
1172 if (conflictconfirms >= 0)
1173 return;
1175 // Do not flush the wallet here for performance reasons
1176 CWalletDB walletdb(*dbw, "r+", false);
1178 std::set<uint256> todo;
1179 std::set<uint256> done;
1181 todo.insert(hashTx);
1183 while (!todo.empty()) {
1184 uint256 now = *todo.begin();
1185 todo.erase(now);
1186 done.insert(now);
1187 assert(mapWallet.count(now));
1188 CWalletTx& wtx = mapWallet[now];
1189 int currentconfirm = wtx.GetDepthInMainChain();
1190 if (conflictconfirms < currentconfirm) {
1191 // Block is 'more conflicted' than current confirm; update.
1192 // Mark transaction as conflicted with this block.
1193 wtx.nIndex = -1;
1194 wtx.hashBlock = hashBlock;
1195 wtx.MarkDirty();
1196 walletdb.WriteTx(wtx);
1197 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1198 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1199 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1200 if (!done.count(iter->second)) {
1201 todo.insert(iter->second);
1203 iter++;
1205 // If a transaction changes 'conflicted' state, that changes the balance
1206 // available of the outputs it spends. So force those to be recomputed
1207 for (const CTxIn& txin : wtx.tx->vin)
1209 if (mapWallet.count(txin.prevout.hash))
1210 mapWallet[txin.prevout.hash].MarkDirty();
1216 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1217 const CTransaction& tx = *ptx;
1219 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1220 return; // Not one of ours
1222 // If a transaction changes 'conflicted' state, that changes the balance
1223 // available of the outputs it spends. So force those to be
1224 // recomputed, also:
1225 for (const CTxIn& txin : tx.vin)
1227 if (mapWallet.count(txin.prevout.hash))
1228 mapWallet[txin.prevout.hash].MarkDirty();
1232 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1233 LOCK2(cs_main, cs_wallet);
1234 SyncTransaction(ptx);
1237 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1238 LOCK2(cs_main, cs_wallet);
1239 // TODO: Temporarily ensure that mempool removals are notified before
1240 // connected transactions. This shouldn't matter, but the abandoned
1241 // state of transactions in our wallet is currently cleared when we
1242 // receive another notification and there is a race condition where
1243 // notification of a connected conflict might cause an outside process
1244 // to abandon a transaction and then have it inadvertently cleared by
1245 // the notification that the conflicted transaction was evicted.
1247 for (const CTransactionRef& ptx : vtxConflicted) {
1248 SyncTransaction(ptx);
1250 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1251 SyncTransaction(pblock->vtx[i], pindex, i);
1255 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1256 LOCK2(cs_main, cs_wallet);
1258 for (const CTransactionRef& ptx : pblock->vtx) {
1259 SyncTransaction(ptx);
1265 isminetype CWallet::IsMine(const CTxIn &txin) const
1268 LOCK(cs_wallet);
1269 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1270 if (mi != mapWallet.end())
1272 const CWalletTx& prev = (*mi).second;
1273 if (txin.prevout.n < prev.tx->vout.size())
1274 return IsMine(prev.tx->vout[txin.prevout.n]);
1277 return ISMINE_NO;
1280 // Note that this function doesn't distinguish between a 0-valued input,
1281 // and a not-"is mine" (according to the filter) input.
1282 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1285 LOCK(cs_wallet);
1286 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1287 if (mi != mapWallet.end())
1289 const CWalletTx& prev = (*mi).second;
1290 if (txin.prevout.n < prev.tx->vout.size())
1291 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1292 return prev.tx->vout[txin.prevout.n].nValue;
1295 return 0;
1298 isminetype CWallet::IsMine(const CTxOut& txout) const
1300 return ::IsMine(*this, txout.scriptPubKey);
1303 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1305 if (!MoneyRange(txout.nValue))
1306 throw std::runtime_error(std::string(__func__) + ": value out of range");
1307 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1310 bool CWallet::IsChange(const CTxOut& txout) const
1312 // TODO: fix handling of 'change' outputs. The assumption is that any
1313 // payment to a script that is ours, but is not in the address book
1314 // is change. That assumption is likely to break when we implement multisignature
1315 // wallets that return change back into a multi-signature-protected address;
1316 // a better way of identifying which outputs are 'the send' and which are
1317 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1318 // which output, if any, was change).
1319 if (::IsMine(*this, txout.scriptPubKey))
1321 CTxDestination address;
1322 if (!ExtractDestination(txout.scriptPubKey, address))
1323 return true;
1325 LOCK(cs_wallet);
1326 if (!mapAddressBook.count(address))
1327 return true;
1329 return false;
1332 CAmount CWallet::GetChange(const CTxOut& txout) const
1334 if (!MoneyRange(txout.nValue))
1335 throw std::runtime_error(std::string(__func__) + ": value out of range");
1336 return (IsChange(txout) ? txout.nValue : 0);
1339 bool CWallet::IsMine(const CTransaction& tx) const
1341 for (const CTxOut& txout : tx.vout)
1342 if (IsMine(txout))
1343 return true;
1344 return false;
1347 bool CWallet::IsFromMe(const CTransaction& tx) const
1349 return (GetDebit(tx, ISMINE_ALL) > 0);
1352 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1354 CAmount nDebit = 0;
1355 for (const CTxIn& txin : tx.vin)
1357 nDebit += GetDebit(txin, filter);
1358 if (!MoneyRange(nDebit))
1359 throw std::runtime_error(std::string(__func__) + ": value out of range");
1361 return nDebit;
1364 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1366 LOCK(cs_wallet);
1368 for (const CTxIn& txin : tx.vin)
1370 auto mi = mapWallet.find(txin.prevout.hash);
1371 if (mi == mapWallet.end())
1372 return false; // any unknown inputs can't be from us
1374 const CWalletTx& prev = (*mi).second;
1376 if (txin.prevout.n >= prev.tx->vout.size())
1377 return false; // invalid input!
1379 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1380 return false;
1382 return true;
1385 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1387 CAmount nCredit = 0;
1388 for (const CTxOut& txout : tx.vout)
1390 nCredit += GetCredit(txout, filter);
1391 if (!MoneyRange(nCredit))
1392 throw std::runtime_error(std::string(__func__) + ": value out of range");
1394 return nCredit;
1397 CAmount CWallet::GetChange(const CTransaction& tx) const
1399 CAmount nChange = 0;
1400 for (const CTxOut& txout : tx.vout)
1402 nChange += GetChange(txout);
1403 if (!MoneyRange(nChange))
1404 throw std::runtime_error(std::string(__func__) + ": value out of range");
1406 return nChange;
1409 CPubKey CWallet::GenerateNewHDMasterKey()
1411 CKey key;
1412 key.MakeNewKey(true);
1414 int64_t nCreationTime = GetTime();
1415 CKeyMetadata metadata(nCreationTime);
1417 // calculate the pubkey
1418 CPubKey pubkey = key.GetPubKey();
1419 assert(key.VerifyPubKey(pubkey));
1421 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1422 metadata.hdKeypath = "m";
1423 metadata.hdMasterKeyID = pubkey.GetID();
1426 LOCK(cs_wallet);
1428 // mem store the metadata
1429 mapKeyMetadata[pubkey.GetID()] = metadata;
1431 // write the key&metadata to the database
1432 if (!AddKeyPubKey(key, pubkey))
1433 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1436 return pubkey;
1439 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1441 LOCK(cs_wallet);
1442 // store the keyid (hash160) together with
1443 // the child index counter in the database
1444 // as a hdchain object
1445 CHDChain newHdChain;
1446 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1447 newHdChain.masterKeyID = pubkey.GetID();
1448 SetHDChain(newHdChain, false);
1450 return true;
1453 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1455 LOCK(cs_wallet);
1456 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1457 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1459 hdChain = chain;
1460 return true;
1463 bool CWallet::IsHDEnabled() const
1465 return !hdChain.masterKeyID.IsNull();
1468 int64_t CWalletTx::GetTxTime() const
1470 int64_t n = nTimeSmart;
1471 return n ? n : nTimeReceived;
1474 int CWalletTx::GetRequestCount() const
1476 // Returns -1 if it wasn't being tracked
1477 int nRequests = -1;
1479 LOCK(pwallet->cs_wallet);
1480 if (IsCoinBase())
1482 // Generated block
1483 if (!hashUnset())
1485 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1486 if (mi != pwallet->mapRequestCount.end())
1487 nRequests = (*mi).second;
1490 else
1492 // Did anyone request this transaction?
1493 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1494 if (mi != pwallet->mapRequestCount.end())
1496 nRequests = (*mi).second;
1498 // How about the block it's in?
1499 if (nRequests == 0 && !hashUnset())
1501 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1502 if (_mi != pwallet->mapRequestCount.end())
1503 nRequests = (*_mi).second;
1504 else
1505 nRequests = 1; // If it's in someone else's block it must have got out
1510 return nRequests;
1513 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1514 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1516 nFee = 0;
1517 listReceived.clear();
1518 listSent.clear();
1519 strSentAccount = strFromAccount;
1521 // Compute fee:
1522 CAmount nDebit = GetDebit(filter);
1523 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1525 CAmount nValueOut = tx->GetValueOut();
1526 nFee = nDebit - nValueOut;
1529 // Sent/received.
1530 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1532 const CTxOut& txout = tx->vout[i];
1533 isminetype fIsMine = pwallet->IsMine(txout);
1534 // Only need to handle txouts if AT LEAST one of these is true:
1535 // 1) they debit from us (sent)
1536 // 2) the output is to us (received)
1537 if (nDebit > 0)
1539 // Don't report 'change' txouts
1540 if (pwallet->IsChange(txout))
1541 continue;
1543 else if (!(fIsMine & filter))
1544 continue;
1546 // In either case, we need to get the destination address
1547 CTxDestination address;
1549 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1551 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1552 this->GetHash().ToString());
1553 address = CNoDestination();
1556 COutputEntry output = {address, txout.nValue, (int)i};
1558 // If we are debited by the transaction, add the output as a "sent" entry
1559 if (nDebit > 0)
1560 listSent.push_back(output);
1562 // If we are receiving the output, add it as a "received" entry
1563 if (fIsMine & filter)
1564 listReceived.push_back(output);
1570 * Scan active chain for relevant transactions after importing keys. This should
1571 * be called whenever new keys are added to the wallet, with the oldest key
1572 * creation time.
1574 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1575 * returned will be higher than startTime if relevant blocks could not be read.
1577 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1579 AssertLockHeld(cs_main);
1580 AssertLockHeld(cs_wallet);
1582 // Find starting block. May be null if nCreateTime is greater than the
1583 // highest blockchain timestamp, in which case there is nothing that needs
1584 // to be scanned.
1585 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1586 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1588 if (startBlock) {
1589 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1590 if (failedBlock) {
1591 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1594 return startTime;
1598 * Scan the block chain (starting in pindexStart) for transactions
1599 * from or to us. If fUpdate is true, found transactions that already
1600 * exist in the wallet will be updated.
1602 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1603 * possible (due to pruning or corruption), returns pointer to the most recent
1604 * block that could not be scanned.
1606 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1608 int64_t nNow = GetTime();
1609 const CChainParams& chainParams = Params();
1611 CBlockIndex* pindex = pindexStart;
1612 CBlockIndex* ret = nullptr;
1614 LOCK2(cs_main, cs_wallet);
1615 fAbortRescan = false;
1616 fScanningWallet = true;
1618 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1619 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1620 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1621 while (pindex && !fAbortRescan)
1623 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1624 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1625 if (GetTime() >= nNow + 60) {
1626 nNow = GetTime();
1627 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1630 CBlock block;
1631 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1632 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1633 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1635 } else {
1636 ret = pindex;
1638 pindex = chainActive.Next(pindex);
1640 if (pindex && fAbortRescan) {
1641 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1643 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1645 fScanningWallet = false;
1647 return ret;
1650 void CWallet::ReacceptWalletTransactions()
1652 // If transactions aren't being broadcasted, don't let them into local mempool either
1653 if (!fBroadcastTransactions)
1654 return;
1655 LOCK2(cs_main, cs_wallet);
1656 std::map<int64_t, CWalletTx*> mapSorted;
1658 // Sort pending wallet transactions based on their initial wallet insertion order
1659 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1661 const uint256& wtxid = item.first;
1662 CWalletTx& wtx = item.second;
1663 assert(wtx.GetHash() == wtxid);
1665 int nDepth = wtx.GetDepthInMainChain();
1667 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1668 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1672 // Try to add wallet transactions to memory pool
1673 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1675 CWalletTx& wtx = *(item.second);
1677 LOCK(mempool.cs);
1678 CValidationState state;
1679 wtx.AcceptToMemoryPool(maxTxFee, state);
1683 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1685 assert(pwallet->GetBroadcastTransactions());
1686 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1688 CValidationState state;
1689 /* GetDepthInMainChain already catches known conflicts. */
1690 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1691 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1692 if (connman) {
1693 CInv inv(MSG_TX, GetHash());
1694 connman->ForEachNode([&inv](CNode* pnode)
1696 pnode->PushInventory(inv);
1698 return true;
1702 return false;
1705 std::set<uint256> CWalletTx::GetConflicts() const
1707 std::set<uint256> result;
1708 if (pwallet != nullptr)
1710 uint256 myHash = GetHash();
1711 result = pwallet->GetConflicts(myHash);
1712 result.erase(myHash);
1714 return result;
1717 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1719 if (tx->vin.empty())
1720 return 0;
1722 CAmount debit = 0;
1723 if(filter & ISMINE_SPENDABLE)
1725 if (fDebitCached)
1726 debit += nDebitCached;
1727 else
1729 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1730 fDebitCached = true;
1731 debit += nDebitCached;
1734 if(filter & ISMINE_WATCH_ONLY)
1736 if(fWatchDebitCached)
1737 debit += nWatchDebitCached;
1738 else
1740 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1741 fWatchDebitCached = true;
1742 debit += nWatchDebitCached;
1745 return debit;
1748 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1750 // Must wait until coinbase is safely deep enough in the chain before valuing it
1751 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1752 return 0;
1754 CAmount credit = 0;
1755 if (filter & ISMINE_SPENDABLE)
1757 // GetBalance can assume transactions in mapWallet won't change
1758 if (fCreditCached)
1759 credit += nCreditCached;
1760 else
1762 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1763 fCreditCached = true;
1764 credit += nCreditCached;
1767 if (filter & ISMINE_WATCH_ONLY)
1769 if (fWatchCreditCached)
1770 credit += nWatchCreditCached;
1771 else
1773 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1774 fWatchCreditCached = true;
1775 credit += nWatchCreditCached;
1778 return credit;
1781 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1783 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1785 if (fUseCache && fImmatureCreditCached)
1786 return nImmatureCreditCached;
1787 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1788 fImmatureCreditCached = true;
1789 return nImmatureCreditCached;
1792 return 0;
1795 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1797 if (pwallet == 0)
1798 return 0;
1800 // Must wait until coinbase is safely deep enough in the chain before valuing it
1801 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1802 return 0;
1804 if (fUseCache && fAvailableCreditCached)
1805 return nAvailableCreditCached;
1807 CAmount nCredit = 0;
1808 uint256 hashTx = GetHash();
1809 for (unsigned int i = 0; i < tx->vout.size(); i++)
1811 if (!pwallet->IsSpent(hashTx, i))
1813 const CTxOut &txout = tx->vout[i];
1814 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1815 if (!MoneyRange(nCredit))
1816 throw std::runtime_error(std::string(__func__) + " : value out of range");
1820 nAvailableCreditCached = nCredit;
1821 fAvailableCreditCached = true;
1822 return nCredit;
1825 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1827 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1829 if (fUseCache && fImmatureWatchCreditCached)
1830 return nImmatureWatchCreditCached;
1831 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1832 fImmatureWatchCreditCached = true;
1833 return nImmatureWatchCreditCached;
1836 return 0;
1839 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1841 if (pwallet == 0)
1842 return 0;
1844 // Must wait until coinbase is safely deep enough in the chain before valuing it
1845 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1846 return 0;
1848 if (fUseCache && fAvailableWatchCreditCached)
1849 return nAvailableWatchCreditCached;
1851 CAmount nCredit = 0;
1852 for (unsigned int i = 0; i < tx->vout.size(); i++)
1854 if (!pwallet->IsSpent(GetHash(), i))
1856 const CTxOut &txout = tx->vout[i];
1857 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1858 if (!MoneyRange(nCredit))
1859 throw std::runtime_error(std::string(__func__) + ": value out of range");
1863 nAvailableWatchCreditCached = nCredit;
1864 fAvailableWatchCreditCached = true;
1865 return nCredit;
1868 CAmount CWalletTx::GetChange() const
1870 if (fChangeCached)
1871 return nChangeCached;
1872 nChangeCached = pwallet->GetChange(*this);
1873 fChangeCached = true;
1874 return nChangeCached;
1877 bool CWalletTx::InMempool() const
1879 LOCK(mempool.cs);
1880 return mempool.exists(GetHash());
1883 bool CWalletTx::IsTrusted() const
1885 // Quick answer in most cases
1886 if (!CheckFinalTx(*this))
1887 return false;
1888 int nDepth = GetDepthInMainChain();
1889 if (nDepth >= 1)
1890 return true;
1891 if (nDepth < 0)
1892 return false;
1893 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1894 return false;
1896 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1897 if (!InMempool())
1898 return false;
1900 // Trusted if all inputs are from us and are in the mempool:
1901 for (const CTxIn& txin : tx->vin)
1903 // Transactions not sent by us: not trusted
1904 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1905 if (parent == nullptr)
1906 return false;
1907 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1908 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1909 return false;
1911 return true;
1914 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1916 CMutableTransaction tx1 = *this->tx;
1917 CMutableTransaction tx2 = *_tx.tx;
1918 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1919 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1920 return CTransaction(tx1) == CTransaction(tx2);
1923 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1925 std::vector<uint256> result;
1927 LOCK(cs_wallet);
1929 // Sort them in chronological order
1930 std::multimap<unsigned int, CWalletTx*> mapSorted;
1931 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1933 CWalletTx& wtx = item.second;
1934 // Don't rebroadcast if newer than nTime:
1935 if (wtx.nTimeReceived > nTime)
1936 continue;
1937 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1939 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1941 CWalletTx& wtx = *item.second;
1942 if (wtx.RelayWalletTransaction(connman))
1943 result.push_back(wtx.GetHash());
1945 return result;
1948 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1950 // Do this infrequently and randomly to avoid giving away
1951 // that these are our transactions.
1952 if (GetTime() < nNextResend || !fBroadcastTransactions)
1953 return;
1954 bool fFirst = (nNextResend == 0);
1955 nNextResend = GetTime() + GetRand(30 * 60);
1956 if (fFirst)
1957 return;
1959 // Only do it if there's been a new block since last time
1960 if (nBestBlockTime < nLastResend)
1961 return;
1962 nLastResend = GetTime();
1964 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1965 // block was found:
1966 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1967 if (!relayed.empty())
1968 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1971 /** @} */ // end of mapWallet
1976 /** @defgroup Actions
1978 * @{
1982 CAmount CWallet::GetBalance() const
1984 CAmount nTotal = 0;
1986 LOCK2(cs_main, cs_wallet);
1987 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1989 const CWalletTx* pcoin = &(*it).second;
1990 if (pcoin->IsTrusted())
1991 nTotal += pcoin->GetAvailableCredit();
1995 return nTotal;
1998 CAmount CWallet::GetUnconfirmedBalance() const
2000 CAmount nTotal = 0;
2002 LOCK2(cs_main, cs_wallet);
2003 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2005 const CWalletTx* pcoin = &(*it).second;
2006 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2007 nTotal += pcoin->GetAvailableCredit();
2010 return nTotal;
2013 CAmount CWallet::GetImmatureBalance() const
2015 CAmount nTotal = 0;
2017 LOCK2(cs_main, cs_wallet);
2018 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2020 const CWalletTx* pcoin = &(*it).second;
2021 nTotal += pcoin->GetImmatureCredit();
2024 return nTotal;
2027 CAmount CWallet::GetWatchOnlyBalance() const
2029 CAmount nTotal = 0;
2031 LOCK2(cs_main, cs_wallet);
2032 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2034 const CWalletTx* pcoin = &(*it).second;
2035 if (pcoin->IsTrusted())
2036 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2040 return nTotal;
2043 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2045 CAmount nTotal = 0;
2047 LOCK2(cs_main, cs_wallet);
2048 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2050 const CWalletTx* pcoin = &(*it).second;
2051 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2052 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2055 return nTotal;
2058 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2060 CAmount nTotal = 0;
2062 LOCK2(cs_main, cs_wallet);
2063 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2065 const CWalletTx* pcoin = &(*it).second;
2066 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2069 return nTotal;
2072 // Calculate total balance in a different way from GetBalance. The biggest
2073 // difference is that GetBalance sums up all unspent TxOuts paying to the
2074 // wallet, while this sums up both spent and unspent TxOuts paying to the
2075 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2076 // also has fewer restrictions on which unconfirmed transactions are considered
2077 // trusted.
2078 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2080 LOCK2(cs_main, cs_wallet);
2082 CAmount balance = 0;
2083 for (const auto& entry : mapWallet) {
2084 const CWalletTx& wtx = entry.second;
2085 const int depth = wtx.GetDepthInMainChain();
2086 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2087 continue;
2090 // Loop through tx outputs and add incoming payments. For outgoing txs,
2091 // treat change outputs specially, as part of the amount debited.
2092 CAmount debit = wtx.GetDebit(filter);
2093 const bool outgoing = debit > 0;
2094 for (const CTxOut& out : wtx.tx->vout) {
2095 if (outgoing && IsChange(out)) {
2096 debit -= out.nValue;
2097 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2098 balance += out.nValue;
2102 // For outgoing txs, subtract amount debited.
2103 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2104 balance -= debit;
2108 if (account) {
2109 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2112 return balance;
2115 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2117 LOCK2(cs_main, cs_wallet);
2119 CAmount balance = 0;
2120 std::vector<COutput> vCoins;
2121 AvailableCoins(vCoins, true, coinControl);
2122 for (const COutput& out : vCoins) {
2123 if (out.fSpendable) {
2124 balance += out.tx->tx->vout[out.i].nValue;
2127 return balance;
2130 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
2132 vCoins.clear();
2135 LOCK2(cs_main, cs_wallet);
2137 CAmount nTotal = 0;
2139 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2141 const uint256& wtxid = it->first;
2142 const CWalletTx* pcoin = &(*it).second;
2144 if (!CheckFinalTx(*pcoin))
2145 continue;
2147 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2148 continue;
2150 int nDepth = pcoin->GetDepthInMainChain();
2151 if (nDepth < 0)
2152 continue;
2154 // We should not consider coins which aren't at least in our mempool
2155 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2156 if (nDepth == 0 && !pcoin->InMempool())
2157 continue;
2159 bool safeTx = pcoin->IsTrusted();
2161 // We should not consider coins from transactions that are replacing
2162 // other transactions.
2164 // Example: There is a transaction A which is replaced by bumpfee
2165 // transaction B. In this case, we want to prevent creation of
2166 // a transaction B' which spends an output of B.
2168 // Reason: If transaction A were initially confirmed, transactions B
2169 // and B' would no longer be valid, so the user would have to create
2170 // a new transaction C to replace B'. However, in the case of a
2171 // one-block reorg, transactions B' and C might BOTH be accepted,
2172 // when the user only wanted one of them. Specifically, there could
2173 // be a 1-block reorg away from the chain where transactions A and C
2174 // were accepted to another chain where B, B', and C were all
2175 // accepted.
2176 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2177 safeTx = false;
2180 // Similarly, we should not consider coins from transactions that
2181 // have been replaced. In the example above, we would want to prevent
2182 // creation of a transaction A' spending an output of A, because if
2183 // transaction B were initially confirmed, conflicting with A and
2184 // A', we wouldn't want to the user to create a transaction D
2185 // intending to replace A', but potentially resulting in a scenario
2186 // where A, A', and D could all be accepted (instead of just B and
2187 // D, or just A and A' like the user would want).
2188 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2189 safeTx = false;
2192 if (fOnlySafe && !safeTx) {
2193 continue;
2196 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2197 continue;
2199 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2200 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2201 continue;
2203 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2204 continue;
2206 if (IsLockedCoin((*it).first, i))
2207 continue;
2209 if (IsSpent(wtxid, i))
2210 continue;
2212 isminetype mine = IsMine(pcoin->tx->vout[i]);
2214 if (mine == ISMINE_NO) {
2215 continue;
2218 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2219 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2221 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2223 // Checks the sum amount of all UTXO's.
2224 if (nMinimumSumAmount != MAX_MONEY) {
2225 nTotal += pcoin->tx->vout[i].nValue;
2227 if (nTotal >= nMinimumSumAmount) {
2228 return;
2232 // Checks the maximum number of UTXO's.
2233 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2234 return;
2241 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2243 // TODO: Add AssertLockHeld(cs_wallet) here.
2245 // Because the return value from this function contains pointers to
2246 // CWalletTx objects, callers to this function really should acquire the
2247 // cs_wallet lock before calling it. However, the current caller doesn't
2248 // acquire this lock yet. There was an attempt to add the missing lock in
2249 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2250 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2251 // avoid adding some extra complexity to the Qt code.
2253 std::map<CTxDestination, std::vector<COutput>> result;
2255 std::vector<COutput> availableCoins;
2256 AvailableCoins(availableCoins);
2258 LOCK2(cs_main, cs_wallet);
2259 for (auto& coin : availableCoins) {
2260 CTxDestination address;
2261 if (coin.fSpendable &&
2262 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2263 result[address].emplace_back(std::move(coin));
2267 std::vector<COutPoint> lockedCoins;
2268 ListLockedCoins(lockedCoins);
2269 for (const auto& output : lockedCoins) {
2270 auto it = mapWallet.find(output.hash);
2271 if (it != mapWallet.end()) {
2272 int depth = it->second.GetDepthInMainChain();
2273 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2274 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2275 CTxDestination address;
2276 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2277 result[address].emplace_back(
2278 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2284 return result;
2287 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2289 const CTransaction* ptx = &tx;
2290 int n = output;
2291 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2292 const COutPoint& prevout = ptx->vin[0].prevout;
2293 auto it = mapWallet.find(prevout.hash);
2294 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2295 !IsMine(it->second.tx->vout[prevout.n])) {
2296 break;
2298 ptx = it->second.tx.get();
2299 n = prevout.n;
2301 return ptx->vout[n];
2304 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2305 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2307 std::vector<char> vfIncluded;
2309 vfBest.assign(vValue.size(), true);
2310 nBest = nTotalLower;
2312 FastRandomContext insecure_rand;
2314 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2316 vfIncluded.assign(vValue.size(), false);
2317 CAmount nTotal = 0;
2318 bool fReachedTarget = false;
2319 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2321 for (unsigned int i = 0; i < vValue.size(); i++)
2323 //The solver here uses a randomized algorithm,
2324 //the randomness serves no real security purpose but is just
2325 //needed to prevent degenerate behavior and it is important
2326 //that the rng is fast. We do not use a constant random sequence,
2327 //because there may be some privacy improvement by making
2328 //the selection random.
2329 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2331 nTotal += vValue[i].txout.nValue;
2332 vfIncluded[i] = true;
2333 if (nTotal >= nTargetValue)
2335 fReachedTarget = true;
2336 if (nTotal < nBest)
2338 nBest = nTotal;
2339 vfBest = vfIncluded;
2341 nTotal -= vValue[i].txout.nValue;
2342 vfIncluded[i] = false;
2350 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2351 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2353 setCoinsRet.clear();
2354 nValueRet = 0;
2356 // List of values less than target
2357 boost::optional<CInputCoin> coinLowestLarger;
2358 std::vector<CInputCoin> vValue;
2359 CAmount nTotalLower = 0;
2361 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2363 for (const COutput &output : vCoins)
2365 if (!output.fSpendable)
2366 continue;
2368 const CWalletTx *pcoin = output.tx;
2370 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2371 continue;
2373 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2374 continue;
2376 int i = output.i;
2378 CInputCoin coin = CInputCoin(pcoin, i);
2380 if (coin.txout.nValue == nTargetValue)
2382 setCoinsRet.insert(coin);
2383 nValueRet += coin.txout.nValue;
2384 return true;
2386 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2388 vValue.push_back(coin);
2389 nTotalLower += coin.txout.nValue;
2391 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2393 coinLowestLarger = coin;
2397 if (nTotalLower == nTargetValue)
2399 for (const auto& input : vValue)
2401 setCoinsRet.insert(input);
2402 nValueRet += input.txout.nValue;
2404 return true;
2407 if (nTotalLower < nTargetValue)
2409 if (!coinLowestLarger)
2410 return false;
2411 setCoinsRet.insert(coinLowestLarger.get());
2412 nValueRet += coinLowestLarger->txout.nValue;
2413 return true;
2416 // Solve subset sum by stochastic approximation
2417 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2418 std::reverse(vValue.begin(), vValue.end());
2419 std::vector<char> vfBest;
2420 CAmount nBest;
2422 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2423 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2424 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2426 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2427 // or the next bigger coin is closer), return the bigger coin
2428 if (coinLowestLarger &&
2429 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2431 setCoinsRet.insert(coinLowestLarger.get());
2432 nValueRet += coinLowestLarger->txout.nValue;
2434 else {
2435 for (unsigned int i = 0; i < vValue.size(); i++)
2436 if (vfBest[i])
2438 setCoinsRet.insert(vValue[i]);
2439 nValueRet += vValue[i].txout.nValue;
2442 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2443 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2444 for (unsigned int i = 0; i < vValue.size(); i++) {
2445 if (vfBest[i]) {
2446 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2449 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2453 return true;
2456 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2458 std::vector<COutput> vCoins(vAvailableCoins);
2460 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2461 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2463 for (const COutput& out : vCoins)
2465 if (!out.fSpendable)
2466 continue;
2467 nValueRet += out.tx->tx->vout[out.i].nValue;
2468 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2470 return (nValueRet >= nTargetValue);
2473 // calculate value from preset inputs and store them
2474 std::set<CInputCoin> setPresetCoins;
2475 CAmount nValueFromPresetInputs = 0;
2477 std::vector<COutPoint> vPresetInputs;
2478 if (coinControl)
2479 coinControl->ListSelected(vPresetInputs);
2480 for (const COutPoint& outpoint : vPresetInputs)
2482 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2483 if (it != mapWallet.end())
2485 const CWalletTx* pcoin = &it->second;
2486 // Clearly invalid input, fail
2487 if (pcoin->tx->vout.size() <= outpoint.n)
2488 return false;
2489 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2490 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2491 } else
2492 return false; // TODO: Allow non-wallet inputs
2495 // remove preset inputs from vCoins
2496 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2498 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2499 it = vCoins.erase(it);
2500 else
2501 ++it;
2504 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2505 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2507 bool res = nTargetValue <= nValueFromPresetInputs ||
2508 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2509 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2510 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2511 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2512 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2513 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2514 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2516 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2517 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2519 // add preset inputs to the total value selected
2520 nValueRet += nValueFromPresetInputs;
2522 return res;
2525 bool CWallet::SignTransaction(CMutableTransaction &tx)
2527 AssertLockHeld(cs_wallet); // mapWallet
2529 // sign the new tx
2530 CTransaction txNewConst(tx);
2531 int nIn = 0;
2532 for (const auto& input : tx.vin) {
2533 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2534 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2535 return false;
2537 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2538 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2539 SignatureData sigdata;
2540 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2541 return false;
2543 UpdateTransaction(tx, nIn, sigdata);
2544 nIn++;
2546 return true;
2549 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2551 std::vector<CRecipient> vecSend;
2553 // Turn the txout set into a CRecipient vector
2554 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2556 const CTxOut& txOut = tx.vout[idx];
2557 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2558 vecSend.push_back(recipient);
2561 coinControl.fAllowOtherInputs = true;
2563 for (const CTxIn& txin : tx.vin)
2564 coinControl.Select(txin.prevout);
2566 CReserveKey reservekey(this);
2567 CWalletTx wtx;
2568 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2569 return false;
2572 if (nChangePosInOut != -1) {
2573 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2574 // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
2575 // so just remove the key from the keypool here.
2576 reservekey.KeepKey();
2579 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2580 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2581 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2583 // Add new txins (keeping original txin scriptSig/order)
2584 for (const CTxIn& txin : wtx.tx->vin)
2586 if (!coinControl.IsSelected(txin.prevout))
2588 tx.vin.push_back(txin);
2590 if (lockUnspents)
2592 LOCK2(cs_main, cs_wallet);
2593 LockCoin(txin.prevout);
2599 return true;
2602 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2604 unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2605 CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2606 // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2607 discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2608 // Discard rate must be at least dustRelayFee
2609 discard_rate = std::max(discard_rate, ::dustRelayFee);
2610 return discard_rate;
2613 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2614 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2616 CAmount nValue = 0;
2617 int nChangePosRequest = nChangePosInOut;
2618 unsigned int nSubtractFeeFromAmount = 0;
2619 for (const auto& recipient : vecSend)
2621 if (nValue < 0 || recipient.nAmount < 0)
2623 strFailReason = _("Transaction amounts must not be negative");
2624 return false;
2626 nValue += recipient.nAmount;
2628 if (recipient.fSubtractFeeFromAmount)
2629 nSubtractFeeFromAmount++;
2631 if (vecSend.empty())
2633 strFailReason = _("Transaction must have at least one recipient");
2634 return false;
2637 wtxNew.fTimeReceivedIsTxTime = true;
2638 wtxNew.BindWallet(this);
2639 CMutableTransaction txNew;
2641 // Discourage fee sniping.
2643 // For a large miner the value of the transactions in the best block and
2644 // the mempool can exceed the cost of deliberately attempting to mine two
2645 // blocks to orphan the current best block. By setting nLockTime such that
2646 // only the next block can include the transaction, we discourage this
2647 // practice as the height restricted and limited blocksize gives miners
2648 // considering fee sniping fewer options for pulling off this attack.
2650 // A simple way to think about this is from the wallet's point of view we
2651 // always want the blockchain to move forward. By setting nLockTime this
2652 // way we're basically making the statement that we only want this
2653 // transaction to appear in the next block; we don't want to potentially
2654 // encourage reorgs by allowing transactions to appear at lower heights
2655 // than the next block in forks of the best chain.
2657 // Of course, the subsidy is high enough, and transaction volume low
2658 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2659 // now we ensure code won't be written that makes assumptions about
2660 // nLockTime that preclude a fix later.
2661 txNew.nLockTime = chainActive.Height();
2663 // Secondly occasionally randomly pick a nLockTime even further back, so
2664 // that transactions that are delayed after signing for whatever reason,
2665 // e.g. high-latency mix networks and some CoinJoin implementations, have
2666 // better privacy.
2667 if (GetRandInt(10) == 0)
2668 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2670 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2671 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2672 FeeCalculation feeCalc;
2673 unsigned int nBytes;
2675 std::set<CInputCoin> setCoins;
2676 LOCK2(cs_main, cs_wallet);
2678 std::vector<COutput> vAvailableCoins;
2679 AvailableCoins(vAvailableCoins, true, &coin_control);
2681 // Create change script that will be used if we need change
2682 // TODO: pass in scriptChange instead of reservekey so
2683 // change transaction isn't always pay-to-bitcoin-address
2684 CScript scriptChange;
2686 // coin control: send change to custom address
2687 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2688 scriptChange = GetScriptForDestination(coin_control.destChange);
2689 } else { // no coin control: send change to newly generated address
2690 // Note: We use a new key here to keep it from being obvious which side is the change.
2691 // The drawback is that by not reusing a previous key, the change may be lost if a
2692 // backup is restored, if the backup doesn't have the new private key for the change.
2693 // If we reused the old key, it would be possible to add code to look for and
2694 // rediscover unknown transactions that were written with keys of ours to recover
2695 // post-backup change.
2697 // Reserve a new key pair from key pool
2698 CPubKey vchPubKey;
2699 bool ret;
2700 ret = reservekey.GetReservedKey(vchPubKey, true);
2701 if (!ret)
2703 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2704 return false;
2707 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2709 CTxOut change_prototype_txout(0, scriptChange);
2710 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2712 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2713 nFeeRet = 0;
2714 bool pick_new_inputs = true;
2715 CAmount nValueIn = 0;
2716 // Start with no fee and loop until there is enough fee
2717 while (true)
2719 nChangePosInOut = nChangePosRequest;
2720 txNew.vin.clear();
2721 txNew.vout.clear();
2722 wtxNew.fFromMe = true;
2723 bool fFirst = true;
2725 CAmount nValueToSelect = nValue;
2726 if (nSubtractFeeFromAmount == 0)
2727 nValueToSelect += nFeeRet;
2728 // vouts to the payees
2729 for (const auto& recipient : vecSend)
2731 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2733 if (recipient.fSubtractFeeFromAmount)
2735 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2737 if (fFirst) // first receiver pays the remainder not divisible by output count
2739 fFirst = false;
2740 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2744 if (IsDust(txout, ::dustRelayFee))
2746 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2748 if (txout.nValue < 0)
2749 strFailReason = _("The transaction amount is too small to pay the fee");
2750 else
2751 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2753 else
2754 strFailReason = _("Transaction amount too small");
2755 return false;
2757 txNew.vout.push_back(txout);
2760 // Choose coins to use
2761 if (pick_new_inputs) {
2762 nValueIn = 0;
2763 setCoins.clear();
2764 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2766 strFailReason = _("Insufficient funds");
2767 return false;
2771 const CAmount nChange = nValueIn - nValueToSelect;
2773 if (nChange > 0)
2775 // Fill a vout to ourself
2776 CTxOut newTxOut(nChange, scriptChange);
2778 // Never create dust outputs; if we would, just
2779 // add the dust to the fee.
2780 if (IsDust(newTxOut, discard_rate))
2782 nChangePosInOut = -1;
2783 nFeeRet += nChange;
2785 else
2787 if (nChangePosInOut == -1)
2789 // Insert change txn at random position:
2790 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2792 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2794 strFailReason = _("Change index out of range");
2795 return false;
2798 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2799 txNew.vout.insert(position, newTxOut);
2801 } else {
2802 nChangePosInOut = -1;
2805 // Fill vin
2807 // Note how the sequence number is set to non-maxint so that
2808 // the nLockTime set above actually works.
2810 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2811 // we use the highest possible value in that range (maxint-2)
2812 // to avoid conflicting with other possible uses of nSequence,
2813 // and in the spirit of "smallest possible change from prior
2814 // behavior."
2815 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2816 for (const auto& coin : setCoins)
2817 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2818 nSequence));
2820 // Fill in dummy signatures for fee calculation.
2821 if (!DummySignTx(txNew, setCoins)) {
2822 strFailReason = _("Signing transaction failed");
2823 return false;
2826 nBytes = GetVirtualTransactionSize(txNew);
2828 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2829 for (auto& vin : txNew.vin) {
2830 vin.scriptSig = CScript();
2831 vin.scriptWitness.SetNull();
2834 CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2836 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2837 // because we must be at the maximum allowed fee.
2838 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2840 strFailReason = _("Transaction too large for fee policy");
2841 return false;
2844 if (nFeeRet >= nFeeNeeded) {
2845 // Reduce fee to only the needed amount if possible. This
2846 // prevents potential overpayment in fees if the coins
2847 // selected to meet nFeeNeeded result in a transaction that
2848 // requires less fee than the prior iteration.
2850 // If we have no change and a big enough excess fee, then
2851 // try to construct transaction again only without picking
2852 // new inputs. We now know we only need the smaller fee
2853 // (because of reduced tx size) and so we should add a
2854 // change output. Only try this once.
2855 CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
2856 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2857 CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
2858 if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2859 pick_new_inputs = false;
2860 nFeeRet = nFeeNeeded + fee_needed_for_change;
2861 continue;
2864 // If we have change output already, just increase it
2865 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2866 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2867 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2868 change_position->nValue += extraFeePaid;
2869 nFeeRet -= extraFeePaid;
2871 break; // Done, enough fee included.
2873 else if (!pick_new_inputs) {
2874 // This shouldn't happen, we should have had enough excess
2875 // fee to pay for the new output and still meet nFeeNeeded
2876 // Or we should have just subtracted fee from recipients and
2877 // nFeeNeeded should not have changed
2878 strFailReason = _("Transaction fee and change calculation failed");
2879 return false;
2882 // Try to reduce change to include necessary fee
2883 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2884 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2885 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2886 // Only reduce change if remaining amount is still a large enough output.
2887 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2888 change_position->nValue -= additionalFeeNeeded;
2889 nFeeRet += additionalFeeNeeded;
2890 break; // Done, able to increase fee from change
2894 // If subtracting fee from recipients, we now know what fee we
2895 // need to subtract, we have no reason to reselect inputs
2896 if (nSubtractFeeFromAmount > 0) {
2897 pick_new_inputs = false;
2900 // Include more fee and try again.
2901 nFeeRet = nFeeNeeded;
2902 continue;
2906 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2908 if (sign)
2910 CTransaction txNewConst(txNew);
2911 int nIn = 0;
2912 for (const auto& coin : setCoins)
2914 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2915 SignatureData sigdata;
2917 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2919 strFailReason = _("Signing transaction failed");
2920 return false;
2921 } else {
2922 UpdateTransaction(txNew, nIn, sigdata);
2925 nIn++;
2929 // Embed the constructed transaction data in wtxNew.
2930 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2932 // Limit size
2933 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2935 strFailReason = _("Transaction too large");
2936 return false;
2940 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2941 // Lastly, ensure this tx will pass the mempool's chain limits
2942 LockPoints lp;
2943 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2944 CTxMemPool::setEntries setAncestors;
2945 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2946 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2947 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2948 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2949 std::string errString;
2950 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2951 strFailReason = _("Transaction has too long of a mempool chain");
2952 return false;
2956 LogPrintf("Fee Calculation: Fee:%d Bytes:%u 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",
2957 nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2958 feeCalc.est.pass.start, feeCalc.est.pass.end,
2959 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2960 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2961 feeCalc.est.fail.start, feeCalc.est.fail.end,
2962 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2963 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2964 return true;
2968 * Call after CreateTransaction unless you want to abort
2970 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2973 LOCK2(cs_main, cs_wallet);
2974 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2976 // Take key pair from key pool so it won't be used again
2977 reservekey.KeepKey();
2979 // Add tx to wallet, because if it has change it's also ours,
2980 // otherwise just for transaction history.
2981 AddToWallet(wtxNew);
2983 // Notify that old coins are spent
2984 for (const CTxIn& txin : wtxNew.tx->vin)
2986 CWalletTx &coin = mapWallet[txin.prevout.hash];
2987 coin.BindWallet(this);
2988 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2992 // Track how many getdata requests our transaction gets
2993 mapRequestCount[wtxNew.GetHash()] = 0;
2995 if (fBroadcastTransactions)
2997 // Broadcast
2998 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2999 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3000 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3001 } else {
3002 wtxNew.RelayWalletTransaction(connman);
3006 return true;
3009 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3010 CWalletDB walletdb(*dbw);
3011 return walletdb.ListAccountCreditDebit(strAccount, entries);
3014 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3016 CWalletDB walletdb(*dbw);
3018 return AddAccountingEntry(acentry, &walletdb);
3021 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3023 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3024 return false;
3027 laccentries.push_back(acentry);
3028 CAccountingEntry & entry = laccentries.back();
3029 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
3031 return true;
3034 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3036 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3039 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
3041 /* User control of how to calculate fee uses the following parameter precedence:
3042 1. coin_control.m_feerate
3043 2. coin_control.m_confirm_target
3044 3. payTxFee (user-set global variable)
3045 4. nTxConfirmTarget (user-set global variable)
3046 The first parameter that is set is used.
3048 CAmount fee_needed;
3049 if (coin_control.m_feerate) { // 1.
3050 fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
3051 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3052 // Allow to override automatic min/max check over coin control instance
3053 if (coin_control.fOverrideFeeRate) return fee_needed;
3055 else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
3056 fee_needed = ::payTxFee.GetFee(nTxBytes);
3057 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3059 else { // 2. or 4.
3060 // We will use smart fee estimation
3061 unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
3062 // By default estimates are economical iff we are signaling opt-in-RBF
3063 bool conservative_estimate = !coin_control.signalRbf;
3064 // Allow to override the default fee estimate mode over the CoinControl instance
3065 if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3066 else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3068 fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3069 if (fee_needed == 0) {
3070 // if we don't have enough data for estimateSmartFee, then use fallbackFee
3071 fee_needed = fallbackFee.GetFee(nTxBytes);
3072 if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3074 // Obey mempool min fee when using smart fee estimation
3075 CAmount min_mempool_fee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3076 if (fee_needed < min_mempool_fee) {
3077 fee_needed = min_mempool_fee;
3078 if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3082 // prevent user from paying a fee below minRelayTxFee or minTxFee
3083 CAmount required_fee = GetRequiredFee(nTxBytes);
3084 if (required_fee > fee_needed) {
3085 fee_needed = required_fee;
3086 if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3088 // But always obey the maximum
3089 if (fee_needed > maxTxFee) {
3090 fee_needed = maxTxFee;
3091 if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3093 return fee_needed;
3099 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3101 fFirstRunRet = false;
3102 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3103 if (nLoadWalletRet == DB_NEED_REWRITE)
3105 if (dbw->Rewrite("\x04pool"))
3107 LOCK(cs_wallet);
3108 setInternalKeyPool.clear();
3109 setExternalKeyPool.clear();
3110 m_pool_key_to_index.clear();
3111 // Note: can't top-up keypool here, because wallet is locked.
3112 // User will be prompted to unlock wallet the next operation
3113 // that requires a new key.
3117 if (nLoadWalletRet != DB_LOAD_OK)
3118 return nLoadWalletRet;
3119 fFirstRunRet = !vchDefaultKey.IsValid();
3121 uiInterface.LoadWallet(this);
3123 return DB_LOAD_OK;
3126 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3128 AssertLockHeld(cs_wallet); // mapWallet
3129 vchDefaultKey = CPubKey();
3130 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3131 for (uint256 hash : vHashOut)
3132 mapWallet.erase(hash);
3134 if (nZapSelectTxRet == DB_NEED_REWRITE)
3136 if (dbw->Rewrite("\x04pool"))
3138 setInternalKeyPool.clear();
3139 setExternalKeyPool.clear();
3140 m_pool_key_to_index.clear();
3141 // Note: can't top-up keypool here, because wallet is locked.
3142 // User will be prompted to unlock wallet the next operation
3143 // that requires a new key.
3147 if (nZapSelectTxRet != DB_LOAD_OK)
3148 return nZapSelectTxRet;
3150 MarkDirty();
3152 return DB_LOAD_OK;
3156 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3158 vchDefaultKey = CPubKey();
3159 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3160 if (nZapWalletTxRet == DB_NEED_REWRITE)
3162 if (dbw->Rewrite("\x04pool"))
3164 LOCK(cs_wallet);
3165 setInternalKeyPool.clear();
3166 setExternalKeyPool.clear();
3167 m_pool_key_to_index.clear();
3168 // Note: can't top-up keypool here, because wallet is locked.
3169 // User will be prompted to unlock wallet the next operation
3170 // that requires a new key.
3174 if (nZapWalletTxRet != DB_LOAD_OK)
3175 return nZapWalletTxRet;
3177 return DB_LOAD_OK;
3181 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3183 bool fUpdated = false;
3185 LOCK(cs_wallet); // mapAddressBook
3186 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3187 fUpdated = mi != mapAddressBook.end();
3188 mapAddressBook[address].name = strName;
3189 if (!strPurpose.empty()) /* update purpose only if requested */
3190 mapAddressBook[address].purpose = strPurpose;
3192 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3193 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3194 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3195 return false;
3196 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3199 bool CWallet::DelAddressBook(const CTxDestination& address)
3202 LOCK(cs_wallet); // mapAddressBook
3204 // Delete destdata tuples associated with address
3205 std::string strAddress = CBitcoinAddress(address).ToString();
3206 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3208 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3210 mapAddressBook.erase(address);
3213 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3215 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3216 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3219 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3221 CTxDestination address;
3222 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3223 auto mi = mapAddressBook.find(address);
3224 if (mi != mapAddressBook.end()) {
3225 return mi->second.name;
3228 // A scriptPubKey that doesn't have an entry in the address book is
3229 // associated with the default account ("").
3230 const static std::string DEFAULT_ACCOUNT_NAME;
3231 return DEFAULT_ACCOUNT_NAME;
3234 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3236 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3237 return false;
3238 vchDefaultKey = vchPubKey;
3239 return true;
3243 * Mark old keypool keys as used,
3244 * and generate all new keys
3246 bool CWallet::NewKeyPool()
3249 LOCK(cs_wallet);
3250 CWalletDB walletdb(*dbw);
3252 for (int64_t nIndex : setInternalKeyPool) {
3253 walletdb.ErasePool(nIndex);
3255 setInternalKeyPool.clear();
3257 for (int64_t nIndex : setExternalKeyPool) {
3258 walletdb.ErasePool(nIndex);
3260 setExternalKeyPool.clear();
3262 m_pool_key_to_index.clear();
3264 if (!TopUpKeyPool()) {
3265 return false;
3267 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3269 return true;
3272 size_t CWallet::KeypoolCountExternalKeys()
3274 AssertLockHeld(cs_wallet); // setExternalKeyPool
3275 return setExternalKeyPool.size();
3278 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3280 AssertLockHeld(cs_wallet);
3281 if (keypool.fInternal) {
3282 setInternalKeyPool.insert(nIndex);
3283 } else {
3284 setExternalKeyPool.insert(nIndex);
3286 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3287 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3289 // If no metadata exists yet, create a default with the pool key's
3290 // creation time. Note that this may be overwritten by actually
3291 // stored metadata for that key later, which is fine.
3292 CKeyID keyid = keypool.vchPubKey.GetID();
3293 if (mapKeyMetadata.count(keyid) == 0)
3294 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3297 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3300 LOCK(cs_wallet);
3302 if (IsLocked())
3303 return false;
3305 // Top up key pool
3306 unsigned int nTargetSize;
3307 if (kpSize > 0)
3308 nTargetSize = kpSize;
3309 else
3310 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3312 // count amount of available keys (internal, external)
3313 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3314 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3315 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3317 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3319 // don't create extra internal keys
3320 missingInternal = 0;
3322 bool internal = false;
3323 CWalletDB walletdb(*dbw);
3324 for (int64_t i = missingInternal + missingExternal; i--;)
3326 if (i < missingInternal) {
3327 internal = true;
3330 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3331 int64_t index = ++m_max_keypool_index;
3333 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3334 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3335 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3338 if (internal) {
3339 setInternalKeyPool.insert(index);
3340 } else {
3341 setExternalKeyPool.insert(index);
3343 m_pool_key_to_index[pubkey.GetID()] = index;
3345 if (missingInternal + missingExternal > 0) {
3346 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3349 return true;
3352 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3354 nIndex = -1;
3355 keypool.vchPubKey = CPubKey();
3357 LOCK(cs_wallet);
3359 if (!IsLocked())
3360 TopUpKeyPool();
3362 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3363 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3365 // Get the oldest key
3366 if(setKeyPool.empty())
3367 return;
3369 CWalletDB walletdb(*dbw);
3371 auto it = setKeyPool.begin();
3372 nIndex = *it;
3373 setKeyPool.erase(it);
3374 if (!walletdb.ReadPool(nIndex, keypool)) {
3375 throw std::runtime_error(std::string(__func__) + ": read failed");
3377 if (!HaveKey(keypool.vchPubKey.GetID())) {
3378 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3380 if (keypool.fInternal != fReturningInternal) {
3381 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3384 assert(keypool.vchPubKey.IsValid());
3385 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3386 LogPrintf("keypool reserve %d\n", nIndex);
3390 void CWallet::KeepKey(int64_t nIndex)
3392 // Remove from key pool
3393 CWalletDB walletdb(*dbw);
3394 walletdb.ErasePool(nIndex);
3395 LogPrintf("keypool keep %d\n", nIndex);
3398 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3400 // Return to key pool
3402 LOCK(cs_wallet);
3403 if (fInternal) {
3404 setInternalKeyPool.insert(nIndex);
3405 } else {
3406 setExternalKeyPool.insert(nIndex);
3408 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3410 LogPrintf("keypool return %d\n", nIndex);
3413 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3415 CKeyPool keypool;
3417 LOCK(cs_wallet);
3418 int64_t nIndex = 0;
3419 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3420 if (nIndex == -1)
3422 if (IsLocked()) return false;
3423 CWalletDB walletdb(*dbw);
3424 result = GenerateNewKey(walletdb, internal);
3425 return true;
3427 KeepKey(nIndex);
3428 result = keypool.vchPubKey;
3430 return true;
3433 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3434 if (setKeyPool.empty()) {
3435 return GetTime();
3438 CKeyPool keypool;
3439 int64_t nIndex = *(setKeyPool.begin());
3440 if (!walletdb.ReadPool(nIndex, keypool)) {
3441 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3443 assert(keypool.vchPubKey.IsValid());
3444 return keypool.nTime;
3447 int64_t CWallet::GetOldestKeyPoolTime()
3449 LOCK(cs_wallet);
3451 CWalletDB walletdb(*dbw);
3453 // load oldest key from keypool, get time and return
3454 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3455 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3456 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3459 return oldestKey;
3462 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3464 std::map<CTxDestination, CAmount> balances;
3467 LOCK(cs_wallet);
3468 for (const auto& walletEntry : mapWallet)
3470 const CWalletTx *pcoin = &walletEntry.second;
3472 if (!pcoin->IsTrusted())
3473 continue;
3475 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3476 continue;
3478 int nDepth = pcoin->GetDepthInMainChain();
3479 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3480 continue;
3482 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3484 CTxDestination addr;
3485 if (!IsMine(pcoin->tx->vout[i]))
3486 continue;
3487 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3488 continue;
3490 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3492 if (!balances.count(addr))
3493 balances[addr] = 0;
3494 balances[addr] += n;
3499 return balances;
3502 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3504 AssertLockHeld(cs_wallet); // mapWallet
3505 std::set< std::set<CTxDestination> > groupings;
3506 std::set<CTxDestination> grouping;
3508 for (const auto& walletEntry : mapWallet)
3510 const CWalletTx *pcoin = &walletEntry.second;
3512 if (pcoin->tx->vin.size() > 0)
3514 bool any_mine = false;
3515 // group all input addresses with each other
3516 for (CTxIn txin : pcoin->tx->vin)
3518 CTxDestination address;
3519 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3520 continue;
3521 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3522 continue;
3523 grouping.insert(address);
3524 any_mine = true;
3527 // group change with input addresses
3528 if (any_mine)
3530 for (CTxOut txout : pcoin->tx->vout)
3531 if (IsChange(txout))
3533 CTxDestination txoutAddr;
3534 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3535 continue;
3536 grouping.insert(txoutAddr);
3539 if (grouping.size() > 0)
3541 groupings.insert(grouping);
3542 grouping.clear();
3546 // group lone addrs by themselves
3547 for (const auto& txout : pcoin->tx->vout)
3548 if (IsMine(txout))
3550 CTxDestination address;
3551 if(!ExtractDestination(txout.scriptPubKey, address))
3552 continue;
3553 grouping.insert(address);
3554 groupings.insert(grouping);
3555 grouping.clear();
3559 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3560 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3561 for (std::set<CTxDestination> _grouping : groupings)
3563 // make a set of all the groups hit by this new group
3564 std::set< std::set<CTxDestination>* > hits;
3565 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3566 for (CTxDestination address : _grouping)
3567 if ((it = setmap.find(address)) != setmap.end())
3568 hits.insert((*it).second);
3570 // merge all hit groups into a new single group and delete old groups
3571 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3572 for (std::set<CTxDestination>* hit : hits)
3574 merged->insert(hit->begin(), hit->end());
3575 uniqueGroupings.erase(hit);
3576 delete hit;
3578 uniqueGroupings.insert(merged);
3580 // update setmap
3581 for (CTxDestination element : *merged)
3582 setmap[element] = merged;
3585 std::set< std::set<CTxDestination> > ret;
3586 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3588 ret.insert(*uniqueGrouping);
3589 delete uniqueGrouping;
3592 return ret;
3595 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3597 LOCK(cs_wallet);
3598 std::set<CTxDestination> result;
3599 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3601 const CTxDestination& address = item.first;
3602 const std::string& strName = item.second.name;
3603 if (strName == strAccount)
3604 result.insert(address);
3606 return result;
3609 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3611 if (nIndex == -1)
3613 CKeyPool keypool;
3614 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3615 if (nIndex != -1)
3616 vchPubKey = keypool.vchPubKey;
3617 else {
3618 return false;
3620 fInternal = keypool.fInternal;
3622 assert(vchPubKey.IsValid());
3623 pubkey = vchPubKey;
3624 return true;
3627 void CReserveKey::KeepKey()
3629 if (nIndex != -1)
3630 pwallet->KeepKey(nIndex);
3631 nIndex = -1;
3632 vchPubKey = CPubKey();
3635 void CReserveKey::ReturnKey()
3637 if (nIndex != -1) {
3638 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3640 nIndex = -1;
3641 vchPubKey = CPubKey();
3644 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3646 AssertLockHeld(cs_wallet);
3647 bool internal = setInternalKeyPool.count(keypool_id);
3648 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3649 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3650 auto it = setKeyPool->begin();
3652 CWalletDB walletdb(*dbw);
3653 while (it != std::end(*setKeyPool)) {
3654 const int64_t& index = *(it);
3655 if (index > keypool_id) break; // set*KeyPool is ordered
3657 CKeyPool keypool;
3658 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3659 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3661 walletdb.ErasePool(index);
3662 it = setKeyPool->erase(it);
3666 bool CWallet::HasUnusedKeys(int min_keys) const
3668 return setExternalKeyPool.size() >= min_keys && (setInternalKeyPool.size() >= min_keys || !CanSupportFeature(FEATURE_HD_SPLIT));
3671 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3673 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3674 CPubKey pubkey;
3675 if (!rKey->GetReservedKey(pubkey))
3676 return;
3678 script = rKey;
3679 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3682 void CWallet::LockCoin(const COutPoint& output)
3684 AssertLockHeld(cs_wallet); // setLockedCoins
3685 setLockedCoins.insert(output);
3688 void CWallet::UnlockCoin(const COutPoint& output)
3690 AssertLockHeld(cs_wallet); // setLockedCoins
3691 setLockedCoins.erase(output);
3694 void CWallet::UnlockAllCoins()
3696 AssertLockHeld(cs_wallet); // setLockedCoins
3697 setLockedCoins.clear();
3700 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3702 AssertLockHeld(cs_wallet); // setLockedCoins
3703 COutPoint outpt(hash, n);
3705 return (setLockedCoins.count(outpt) > 0);
3708 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3710 AssertLockHeld(cs_wallet); // setLockedCoins
3711 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3712 it != setLockedCoins.end(); it++) {
3713 COutPoint outpt = (*it);
3714 vOutpts.push_back(outpt);
3718 /** @} */ // end of Actions
3720 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3721 AssertLockHeld(cs_wallet); // mapKeyMetadata
3722 mapKeyBirth.clear();
3724 // get birth times for keys with metadata
3725 for (const auto& entry : mapKeyMetadata) {
3726 if (entry.second.nCreateTime) {
3727 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3731 // map in which we'll infer heights of other keys
3732 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3733 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3734 std::set<CKeyID> setKeys;
3735 GetKeys(setKeys);
3736 for (const CKeyID &keyid : setKeys) {
3737 if (mapKeyBirth.count(keyid) == 0)
3738 mapKeyFirstBlock[keyid] = pindexMax;
3740 setKeys.clear();
3742 // if there are no such keys, we're done
3743 if (mapKeyFirstBlock.empty())
3744 return;
3746 // find first block that affects those keys, if there are any left
3747 std::vector<CKeyID> vAffected;
3748 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3749 // iterate over all wallet transactions...
3750 const CWalletTx &wtx = (*it).second;
3751 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3752 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3753 // ... which are already in a block
3754 int nHeight = blit->second->nHeight;
3755 for (const CTxOut &txout : wtx.tx->vout) {
3756 // iterate over all their outputs
3757 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3758 for (const CKeyID &keyid : vAffected) {
3759 // ... and all their affected keys
3760 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3761 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3762 rit->second = blit->second;
3764 vAffected.clear();
3769 // Extract block timestamps for those keys
3770 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3771 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3775 * Compute smart timestamp for a transaction being added to the wallet.
3777 * Logic:
3778 * - If sending a transaction, assign its timestamp to the current time.
3779 * - If receiving a transaction outside a block, assign its timestamp to the
3780 * current time.
3781 * - If receiving a block with a future timestamp, assign all its (not already
3782 * known) transactions' timestamps to the current time.
3783 * - If receiving a block with a past timestamp, before the most recent known
3784 * transaction (that we care about), assign all its (not already known)
3785 * transactions' timestamps to the same timestamp as that most-recent-known
3786 * transaction.
3787 * - If receiving a block with a past timestamp, but after the most recent known
3788 * transaction, assign all its (not already known) transactions' timestamps to
3789 * the block time.
3791 * For more information see CWalletTx::nTimeSmart,
3792 * https://bitcointalk.org/?topic=54527, or
3793 * https://github.com/bitcoin/bitcoin/pull/1393.
3795 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3797 unsigned int nTimeSmart = wtx.nTimeReceived;
3798 if (!wtx.hashUnset()) {
3799 if (mapBlockIndex.count(wtx.hashBlock)) {
3800 int64_t latestNow = wtx.nTimeReceived;
3801 int64_t latestEntry = 0;
3803 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3804 int64_t latestTolerated = latestNow + 300;
3805 const TxItems& txOrdered = wtxOrdered;
3806 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3807 CWalletTx* const pwtx = it->second.first;
3808 if (pwtx == &wtx) {
3809 continue;
3811 CAccountingEntry* const pacentry = it->second.second;
3812 int64_t nSmartTime;
3813 if (pwtx) {
3814 nSmartTime = pwtx->nTimeSmart;
3815 if (!nSmartTime) {
3816 nSmartTime = pwtx->nTimeReceived;
3818 } else {
3819 nSmartTime = pacentry->nTime;
3821 if (nSmartTime <= latestTolerated) {
3822 latestEntry = nSmartTime;
3823 if (nSmartTime > latestNow) {
3824 latestNow = nSmartTime;
3826 break;
3830 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3831 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3832 } else {
3833 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3836 return nTimeSmart;
3839 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3841 if (boost::get<CNoDestination>(&dest))
3842 return false;
3844 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3845 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3848 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3850 if (!mapAddressBook[dest].destdata.erase(key))
3851 return false;
3852 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3855 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3857 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3858 return true;
3861 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3863 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3864 if(i != mapAddressBook.end())
3866 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3867 if(j != i->second.destdata.end())
3869 if(value)
3870 *value = j->second;
3871 return true;
3874 return false;
3877 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3879 LOCK(cs_wallet);
3880 std::vector<std::string> values;
3881 for (const auto& address : mapAddressBook) {
3882 for (const auto& data : address.second.destdata) {
3883 if (!data.first.compare(0, prefix.size(), prefix)) {
3884 values.emplace_back(data.second);
3888 return values;
3891 std::string CWallet::GetWalletHelpString(bool showDebug)
3893 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3894 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3895 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3896 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3897 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3898 strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). "
3899 "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"),
3900 CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3901 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3902 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3903 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3904 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3905 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3906 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3907 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3908 strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
3909 strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
3910 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3911 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3912 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3913 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3914 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3915 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3916 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3918 if (showDebug)
3920 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3922 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3923 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3924 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3925 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3928 return strUsage;
3931 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3933 // needed to restore wallet transaction meta data after -zapwallettxes
3934 std::vector<CWalletTx> vWtx;
3936 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3937 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3939 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3940 std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
3941 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3942 if (nZapWalletRet != DB_LOAD_OK) {
3943 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3944 return nullptr;
3948 uiInterface.InitMessage(_("Loading wallet..."));
3950 int64_t nStart = GetTimeMillis();
3951 bool fFirstRun = true;
3952 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3953 CWallet *walletInstance = new CWallet(std::move(dbw));
3954 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3955 if (nLoadWalletRet != DB_LOAD_OK)
3957 if (nLoadWalletRet == DB_CORRUPT) {
3958 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3959 return nullptr;
3961 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3963 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3964 " or address book entries might be missing or incorrect."),
3965 walletFile));
3967 else if (nLoadWalletRet == DB_TOO_NEW) {
3968 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3969 return nullptr;
3971 else if (nLoadWalletRet == DB_NEED_REWRITE)
3973 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3974 return nullptr;
3976 else {
3977 InitError(strprintf(_("Error loading %s"), walletFile));
3978 return nullptr;
3982 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3984 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3985 if (nMaxVersion == 0) // the -upgradewallet without argument case
3987 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3988 nMaxVersion = CLIENT_VERSION;
3989 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3991 else
3992 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3993 if (nMaxVersion < walletInstance->GetVersion())
3995 InitError(_("Cannot downgrade wallet"));
3996 return nullptr;
3998 walletInstance->SetMaxVersion(nMaxVersion);
4001 if (fFirstRun)
4003 // Create new keyUser and set as default key
4004 if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
4006 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
4007 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
4009 // generate a new master key
4010 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
4011 if (!walletInstance->SetHDMasterKey(masterPubKey))
4012 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
4014 CPubKey newDefaultKey;
4015 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
4016 walletInstance->SetDefaultKey(newDefaultKey);
4017 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
4018 InitError(_("Cannot write default address") += "\n");
4019 return nullptr;
4023 walletInstance->SetBestChain(chainActive.GetLocator());
4025 else if (gArgs.IsArgSet("-usehd")) {
4026 bool useHD = gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
4027 if (walletInstance->IsHDEnabled() && !useHD) {
4028 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
4029 return nullptr;
4031 if (!walletInstance->IsHDEnabled() && useHD) {
4032 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
4033 return nullptr;
4037 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
4039 RegisterValidationInterface(walletInstance);
4041 // Try to top up keypool. No-op if the wallet is locked.
4042 walletInstance->TopUpKeyPool();
4044 CBlockIndex *pindexRescan = chainActive.Genesis();
4045 if (!gArgs.GetBoolArg("-rescan", false))
4047 CWalletDB walletdb(*walletInstance->dbw);
4048 CBlockLocator locator;
4049 if (walletdb.ReadBestBlock(locator))
4050 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4052 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
4054 //We can't rescan beyond non-pruned blocks, stop and throw an error
4055 //this might happen if a user uses an old wallet within a pruned node
4056 // or if he ran -disablewallet for a longer time, then decided to re-enable
4057 if (fPruneMode)
4059 CBlockIndex *block = chainActive.Tip();
4060 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4061 block = block->pprev;
4063 if (pindexRescan != block) {
4064 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4065 return nullptr;
4069 uiInterface.InitMessage(_("Rescanning..."));
4070 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4072 // No need to read and scan block if block was created before
4073 // our wallet birthday (as adjusted for block time variability)
4074 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4075 pindexRescan = chainActive.Next(pindexRescan);
4078 nStart = GetTimeMillis();
4079 walletInstance->ScanForWalletTransactions(pindexRescan, true);
4080 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4081 walletInstance->SetBestChain(chainActive.GetLocator());
4082 walletInstance->dbw->IncrementUpdateCounter();
4084 // Restore wallet transaction metadata after -zapwallettxes=1
4085 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4087 CWalletDB walletdb(*walletInstance->dbw);
4089 for (const CWalletTx& wtxOld : vWtx)
4091 uint256 hash = wtxOld.GetHash();
4092 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4093 if (mi != walletInstance->mapWallet.end())
4095 const CWalletTx* copyFrom = &wtxOld;
4096 CWalletTx* copyTo = &mi->second;
4097 copyTo->mapValue = copyFrom->mapValue;
4098 copyTo->vOrderForm = copyFrom->vOrderForm;
4099 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4100 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4101 copyTo->fFromMe = copyFrom->fFromMe;
4102 copyTo->strFromAccount = copyFrom->strFromAccount;
4103 copyTo->nOrderPos = copyFrom->nOrderPos;
4104 walletdb.WriteTx(*copyTo);
4109 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4112 LOCK(walletInstance->cs_wallet);
4113 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4114 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4115 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4118 return walletInstance;
4121 bool CWallet::InitLoadWallet()
4123 if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4124 LogPrintf("Wallet disabled!\n");
4125 return true;
4128 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4129 CWallet * const pwallet = CreateWalletFromFile(walletFile);
4130 if (!pwallet) {
4131 return false;
4133 vpwallets.push_back(pwallet);
4136 return true;
4139 std::atomic<bool> CWallet::fFlushScheduled(false);
4141 void CWallet::postInitProcess(CScheduler& scheduler)
4143 // Add wallet transactions that aren't already in a block to mempool
4144 // Do this here as mempool requires genesis block to be loaded
4145 ReacceptWalletTransactions();
4147 // Run a thread to flush wallet periodically
4148 if (!CWallet::fFlushScheduled.exchange(true)) {
4149 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4153 bool CWallet::ParameterInteraction()
4155 gArgs.SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4156 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4158 if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4159 return true;
4161 if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
4162 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4165 if (gArgs.GetBoolArg("-salvagewallet", false)) {
4166 if (is_multiwallet) {
4167 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4169 // Rewrite just private keys: rescan to find transactions
4170 if (gArgs.SoftSetBoolArg("-rescan", true)) {
4171 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4175 int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
4176 // -zapwallettxes implies dropping the mempool on startup
4177 if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
4178 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4181 // -zapwallettxes implies a rescan
4182 if (zapwallettxes != 0) {
4183 if (is_multiwallet) {
4184 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4186 if (gArgs.SoftSetBoolArg("-rescan", true)) {
4187 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4191 if (is_multiwallet) {
4192 if (gArgs.GetBoolArg("-upgradewallet", false)) {
4193 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4197 if (gArgs.GetBoolArg("-sysperms", false))
4198 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4199 if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
4200 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4202 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4203 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4204 _("The wallet will avoid paying less than the minimum relay fee."));
4206 if (gArgs.IsArgSet("-mintxfee"))
4208 CAmount n = 0;
4209 if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n)
4210 return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
4211 if (n > HIGH_TX_FEE_PER_KB)
4212 InitWarning(AmountHighWarn("-mintxfee") + " " +
4213 _("This is the minimum transaction fee you pay on every transaction."));
4214 CWallet::minTxFee = CFeeRate(n);
4216 if (gArgs.IsArgSet("-fallbackfee"))
4218 CAmount nFeePerK = 0;
4219 if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK))
4220 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
4221 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4222 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4223 _("This is the transaction fee you may pay when fee estimates are not available."));
4224 CWallet::fallbackFee = CFeeRate(nFeePerK);
4226 if (gArgs.IsArgSet("-discardfee"))
4228 CAmount nFeePerK = 0;
4229 if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK))
4230 return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
4231 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4232 InitWarning(AmountHighWarn("-discardfee") + " " +
4233 _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4234 CWallet::m_discard_rate = CFeeRate(nFeePerK);
4236 if (gArgs.IsArgSet("-paytxfee"))
4238 CAmount nFeePerK = 0;
4239 if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK))
4240 return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
4241 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4242 InitWarning(AmountHighWarn("-paytxfee") + " " +
4243 _("This is the transaction fee you will pay if you send a transaction."));
4245 payTxFee = CFeeRate(nFeePerK, 1000);
4246 if (payTxFee < ::minRelayTxFee)
4248 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4249 gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4252 if (gArgs.IsArgSet("-maxtxfee"))
4254 CAmount nMaxFee = 0;
4255 if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
4256 return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
4257 if (nMaxFee > HIGH_MAX_TX_FEE)
4258 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4259 maxTxFee = nMaxFee;
4260 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4262 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4263 gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4266 nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4267 bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4268 fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4270 return true;
4273 bool CWallet::BackupWallet(const std::string& strDest)
4275 return dbw->Backup(strDest);
4278 CKeyPool::CKeyPool()
4280 nTime = GetTime();
4281 fInternal = false;
4284 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4286 nTime = GetTime();
4287 vchPubKey = vchPubKeyIn;
4288 fInternal = internalIn;
4291 CWalletKey::CWalletKey(int64_t nExpires)
4293 nTimeCreated = (nExpires ? GetTime() : 0);
4294 nTimeExpires = nExpires;
4297 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4299 // Update the tx's hashBlock
4300 hashBlock = pindex->GetBlockHash();
4302 // set the position of the transaction in the block
4303 nIndex = posInBlock;
4306 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4308 if (hashUnset())
4309 return 0;
4311 AssertLockHeld(cs_main);
4313 // Find the block it claims to be in
4314 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4315 if (mi == mapBlockIndex.end())
4316 return 0;
4317 CBlockIndex* pindex = (*mi).second;
4318 if (!pindex || !chainActive.Contains(pindex))
4319 return 0;
4321 pindexRet = pindex;
4322 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4325 int CMerkleTx::GetBlocksToMaturity() const
4327 if (!IsCoinBase())
4328 return 0;
4329 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4333 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4335 return ::AcceptToMemoryPool(mempool, state, tx, true, nullptr, nullptr, false, nAbsurdFee);