Document assumptions that are being made to avoid division by zero
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob6d94154da84b5a5f0d2c4ce0e44e3dba6c70d253
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 auto it = mapWallet.find(wtxid);
627 assert(it != mapWallet.end());
628 CWalletTx& thisTx = it->second;
629 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
630 return;
632 for (const CTxIn& txin : thisTx.tx->vin)
633 AddToSpends(txin.prevout, wtxid);
636 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
638 if (IsCrypted())
639 return false;
641 CKeyingMaterial _vMasterKey;
643 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
644 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
646 CMasterKey kMasterKey;
648 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
649 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
651 CCrypter crypter;
652 int64_t nStartTime = GetTimeMillis();
653 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
654 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
656 nStartTime = GetTimeMillis();
657 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
658 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
660 if (kMasterKey.nDeriveIterations < 25000)
661 kMasterKey.nDeriveIterations = 25000;
663 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
665 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
666 return false;
667 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
668 return false;
671 LOCK(cs_wallet);
672 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
673 assert(!pwalletdbEncryption);
674 pwalletdbEncryption = new CWalletDB(*dbw);
675 if (!pwalletdbEncryption->TxnBegin()) {
676 delete pwalletdbEncryption;
677 pwalletdbEncryption = nullptr;
678 return false;
680 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
682 if (!EncryptKeys(_vMasterKey))
684 pwalletdbEncryption->TxnAbort();
685 delete pwalletdbEncryption;
686 // We now probably have half of our keys encrypted in memory, and half not...
687 // die and let the user reload the unencrypted wallet.
688 assert(false);
691 // Encryption was introduced in version 0.4.0
692 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
694 if (!pwalletdbEncryption->TxnCommit()) {
695 delete pwalletdbEncryption;
696 // We now have keys encrypted in memory, but not on disk...
697 // die to avoid confusion and let the user reload the unencrypted wallet.
698 assert(false);
701 delete pwalletdbEncryption;
702 pwalletdbEncryption = nullptr;
704 Lock();
705 Unlock(strWalletPassphrase);
707 // if we are using HD, replace the HD master key (seed) with a new one
708 if (IsHDEnabled()) {
709 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
710 return false;
714 NewKeyPool();
715 Lock();
717 // Need to completely rewrite the wallet file; if we don't, bdb might keep
718 // bits of the unencrypted private key in slack space in the database file.
719 dbw->Rewrite();
722 NotifyStatusChanged(this);
724 return true;
727 DBErrors CWallet::ReorderTransactions()
729 LOCK(cs_wallet);
730 CWalletDB walletdb(*dbw);
732 // Old wallets didn't have any defined order for transactions
733 // Probably a bad idea to change the output of this
735 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
736 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
737 typedef std::multimap<int64_t, TxPair > TxItems;
738 TxItems txByTime;
740 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
742 CWalletTx* wtx = &((*it).second);
743 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
745 std::list<CAccountingEntry> acentries;
746 walletdb.ListAccountCreditDebit("", acentries);
747 for (CAccountingEntry& entry : acentries)
749 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
752 nOrderPosNext = 0;
753 std::vector<int64_t> nOrderPosOffsets;
754 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
756 CWalletTx *const pwtx = (*it).second.first;
757 CAccountingEntry *const pacentry = (*it).second.second;
758 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
760 if (nOrderPos == -1)
762 nOrderPos = nOrderPosNext++;
763 nOrderPosOffsets.push_back(nOrderPos);
765 if (pwtx)
767 if (!walletdb.WriteTx(*pwtx))
768 return DB_LOAD_FAIL;
770 else
771 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
772 return DB_LOAD_FAIL;
774 else
776 int64_t nOrderPosOff = 0;
777 for (const int64_t& nOffsetStart : nOrderPosOffsets)
779 if (nOrderPos >= nOffsetStart)
780 ++nOrderPosOff;
782 nOrderPos += nOrderPosOff;
783 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
785 if (!nOrderPosOff)
786 continue;
788 // Since we're changing the order, write it back
789 if (pwtx)
791 if (!walletdb.WriteTx(*pwtx))
792 return DB_LOAD_FAIL;
794 else
795 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
796 return DB_LOAD_FAIL;
799 walletdb.WriteOrderPosNext(nOrderPosNext);
801 return DB_LOAD_OK;
804 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
806 AssertLockHeld(cs_wallet); // nOrderPosNext
807 int64_t nRet = nOrderPosNext++;
808 if (pwalletdb) {
809 pwalletdb->WriteOrderPosNext(nOrderPosNext);
810 } else {
811 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
813 return nRet;
816 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
818 CWalletDB walletdb(*dbw);
819 if (!walletdb.TxnBegin())
820 return false;
822 int64_t nNow = GetAdjustedTime();
824 // Debit
825 CAccountingEntry debit;
826 debit.nOrderPos = IncOrderPosNext(&walletdb);
827 debit.strAccount = strFrom;
828 debit.nCreditDebit = -nAmount;
829 debit.nTime = nNow;
830 debit.strOtherAccount = strTo;
831 debit.strComment = strComment;
832 AddAccountingEntry(debit, &walletdb);
834 // Credit
835 CAccountingEntry credit;
836 credit.nOrderPos = IncOrderPosNext(&walletdb);
837 credit.strAccount = strTo;
838 credit.nCreditDebit = nAmount;
839 credit.nTime = nNow;
840 credit.strOtherAccount = strFrom;
841 credit.strComment = strComment;
842 AddAccountingEntry(credit, &walletdb);
844 if (!walletdb.TxnCommit())
845 return false;
847 return true;
850 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
852 CWalletDB walletdb(*dbw);
854 CAccount account;
855 walletdb.ReadAccount(strAccount, account);
857 if (!bForceNew) {
858 if (!account.vchPubKey.IsValid())
859 bForceNew = true;
860 else {
861 // Check if the current key has been used
862 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
863 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
864 it != mapWallet.end() && account.vchPubKey.IsValid();
865 ++it)
866 for (const CTxOut& txout : (*it).second.tx->vout)
867 if (txout.scriptPubKey == scriptPubKey) {
868 bForceNew = true;
869 break;
874 // Generate a new key
875 if (bForceNew) {
876 if (!GetKeyFromPool(account.vchPubKey, false))
877 return false;
879 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
880 walletdb.WriteAccount(strAccount, account);
883 pubKey = account.vchPubKey;
885 return true;
888 void CWallet::MarkDirty()
891 LOCK(cs_wallet);
892 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
893 item.second.MarkDirty();
897 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
899 LOCK(cs_wallet);
901 auto mi = mapWallet.find(originalHash);
903 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
904 assert(mi != mapWallet.end());
906 CWalletTx& wtx = (*mi).second;
908 // Ensure for now that we're not overwriting data
909 assert(wtx.mapValue.count("replaced_by_txid") == 0);
911 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
913 CWalletDB walletdb(*dbw, "r+");
915 bool success = true;
916 if (!walletdb.WriteTx(wtx)) {
917 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
918 success = false;
921 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
923 return success;
926 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
928 LOCK(cs_wallet);
930 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
932 uint256 hash = wtxIn.GetHash();
934 // Inserts only if not already there, returns tx inserted or tx found
935 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
936 CWalletTx& wtx = (*ret.first).second;
937 wtx.BindWallet(this);
938 bool fInsertedNew = ret.second;
939 if (fInsertedNew)
941 wtx.nTimeReceived = GetAdjustedTime();
942 wtx.nOrderPos = IncOrderPosNext(&walletdb);
943 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
944 wtx.nTimeSmart = ComputeTimeSmart(wtx);
945 AddToSpends(hash);
948 bool fUpdated = false;
949 if (!fInsertedNew)
951 // Merge
952 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
954 wtx.hashBlock = wtxIn.hashBlock;
955 fUpdated = true;
957 // If no longer abandoned, update
958 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
960 wtx.hashBlock = wtxIn.hashBlock;
961 fUpdated = true;
963 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
965 wtx.nIndex = wtxIn.nIndex;
966 fUpdated = true;
968 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
970 wtx.fFromMe = wtxIn.fFromMe;
971 fUpdated = true;
975 //// debug print
976 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
978 // Write to disk
979 if (fInsertedNew || fUpdated)
980 if (!walletdb.WriteTx(wtx))
981 return false;
983 // Break debit/credit balance caches:
984 wtx.MarkDirty();
986 // Notify UI of new or updated transaction
987 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
989 // notify an external script when a wallet transaction comes in or is updated
990 std::string strCmd = gArgs.GetArg("-walletnotify", "");
992 if ( !strCmd.empty())
994 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
995 boost::thread t(runCommand, strCmd); // thread runs free
998 return true;
1001 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
1003 uint256 hash = wtxIn.GetHash();
1005 mapWallet[hash] = wtxIn;
1006 CWalletTx& wtx = mapWallet[hash];
1007 wtx.BindWallet(this);
1008 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
1009 AddToSpends(hash);
1010 for (const CTxIn& txin : wtx.tx->vin) {
1011 auto it = mapWallet.find(txin.prevout.hash);
1012 if (it != mapWallet.end()) {
1013 CWalletTx& prevtx = it->second;
1014 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1015 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1020 return true;
1024 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1025 * be set when the transaction was known to be included in a block. When
1026 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1027 * notifications happen and cached balances are marked dirty.
1029 * If fUpdate is true, existing transactions will be updated.
1030 * TODO: One exception to this is that the abandoned state is cleared under the
1031 * assumption that any further notification of a transaction that was considered
1032 * abandoned is an indication that it is not safe to be considered abandoned.
1033 * Abandoned state should probably be more carefully tracked via different
1034 * posInBlock signals or by checking mempool presence when necessary.
1036 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1038 const CTransaction& tx = *ptx;
1040 AssertLockHeld(cs_wallet);
1042 if (pIndex != nullptr) {
1043 for (const CTxIn& txin : tx.vin) {
1044 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1045 while (range.first != range.second) {
1046 if (range.first->second != tx.GetHash()) {
1047 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);
1048 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1050 range.first++;
1055 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1056 if (fExisted && !fUpdate) return false;
1057 if (fExisted || IsMine(tx) || IsFromMe(tx))
1059 /* Check if any keys in the wallet keypool that were supposed to be unused
1060 * have appeared in a new transaction. If so, remove those keys from the keypool.
1061 * This can happen when restoring an old wallet backup that does not contain
1062 * the mostly recently created transactions from newer versions of the wallet.
1065 // loop though all outputs
1066 for (const CTxOut& txout: tx.vout) {
1067 // extract addresses and check if they match with an unused keypool key
1068 std::vector<CKeyID> vAffected;
1069 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1070 for (const CKeyID &keyid : vAffected) {
1071 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1072 if (mi != m_pool_key_to_index.end()) {
1073 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1074 MarkReserveKeysAsUsed(mi->second);
1076 if (!TopUpKeyPool()) {
1077 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1083 CWalletTx wtx(this, ptx);
1085 // Get merkle branch if transaction was found in a block
1086 if (pIndex != nullptr)
1087 wtx.SetMerkleBranch(pIndex, posInBlock);
1089 return AddToWallet(wtx, false);
1092 return false;
1095 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1097 LOCK2(cs_main, cs_wallet);
1098 const CWalletTx* wtx = GetWalletTx(hashTx);
1099 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1102 bool CWallet::AbandonTransaction(const uint256& hashTx)
1104 LOCK2(cs_main, cs_wallet);
1106 CWalletDB walletdb(*dbw, "r+");
1108 std::set<uint256> todo;
1109 std::set<uint256> done;
1111 // Can't mark abandoned if confirmed or in mempool
1112 auto it = mapWallet.find(hashTx);
1113 assert(it != mapWallet.end());
1114 CWalletTx& origtx = it->second;
1115 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1116 return false;
1119 todo.insert(hashTx);
1121 while (!todo.empty()) {
1122 uint256 now = *todo.begin();
1123 todo.erase(now);
1124 done.insert(now);
1125 auto it = mapWallet.find(now);
1126 assert(it != mapWallet.end());
1127 CWalletTx& wtx = it->second;
1128 int currentconfirm = wtx.GetDepthInMainChain();
1129 // If the orig tx was not in block, none of its spends can be
1130 assert(currentconfirm <= 0);
1131 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1132 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1133 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1134 assert(!wtx.InMempool());
1135 wtx.nIndex = -1;
1136 wtx.setAbandoned();
1137 wtx.MarkDirty();
1138 walletdb.WriteTx(wtx);
1139 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1140 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1141 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1142 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1143 if (!done.count(iter->second)) {
1144 todo.insert(iter->second);
1146 iter++;
1148 // If a transaction changes 'conflicted' state, that changes the balance
1149 // available of the outputs it spends. So force those to be recomputed
1150 for (const CTxIn& txin : wtx.tx->vin)
1152 auto it = mapWallet.find(txin.prevout.hash);
1153 if (it != mapWallet.end()) {
1154 it->second.MarkDirty();
1160 return true;
1163 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1165 LOCK2(cs_main, cs_wallet);
1167 int conflictconfirms = 0;
1168 if (mapBlockIndex.count(hashBlock)) {
1169 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1170 if (chainActive.Contains(pindex)) {
1171 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1174 // If number of conflict confirms cannot be determined, this means
1175 // that the block is still unknown or not yet part of the main chain,
1176 // for example when loading the wallet during a reindex. Do nothing in that
1177 // case.
1178 if (conflictconfirms >= 0)
1179 return;
1181 // Do not flush the wallet here for performance reasons
1182 CWalletDB walletdb(*dbw, "r+", false);
1184 std::set<uint256> todo;
1185 std::set<uint256> done;
1187 todo.insert(hashTx);
1189 while (!todo.empty()) {
1190 uint256 now = *todo.begin();
1191 todo.erase(now);
1192 done.insert(now);
1193 auto it = mapWallet.find(now);
1194 assert(it != mapWallet.end());
1195 CWalletTx& wtx = it->second;
1196 int currentconfirm = wtx.GetDepthInMainChain();
1197 if (conflictconfirms < currentconfirm) {
1198 // Block is 'more conflicted' than current confirm; update.
1199 // Mark transaction as conflicted with this block.
1200 wtx.nIndex = -1;
1201 wtx.hashBlock = hashBlock;
1202 wtx.MarkDirty();
1203 walletdb.WriteTx(wtx);
1204 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1205 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1206 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1207 if (!done.count(iter->second)) {
1208 todo.insert(iter->second);
1210 iter++;
1212 // If a transaction changes 'conflicted' state, that changes the balance
1213 // available of the outputs it spends. So force those to be recomputed
1214 for (const CTxIn& txin : wtx.tx->vin) {
1215 auto it = mapWallet.find(txin.prevout.hash);
1216 if (it != mapWallet.end()) {
1217 it->second.MarkDirty();
1224 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1225 const CTransaction& tx = *ptx;
1227 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1228 return; // Not one of ours
1230 // If a transaction changes 'conflicted' state, that changes the balance
1231 // available of the outputs it spends. So force those to be
1232 // recomputed, also:
1233 for (const CTxIn& txin : tx.vin) {
1234 auto it = mapWallet.find(txin.prevout.hash);
1235 if (it != mapWallet.end()) {
1236 it->second.MarkDirty();
1241 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1242 LOCK2(cs_main, cs_wallet);
1243 SyncTransaction(ptx);
1246 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1247 LOCK2(cs_main, cs_wallet);
1248 // TODO: Temporarily ensure that mempool removals are notified before
1249 // connected transactions. This shouldn't matter, but the abandoned
1250 // state of transactions in our wallet is currently cleared when we
1251 // receive another notification and there is a race condition where
1252 // notification of a connected conflict might cause an outside process
1253 // to abandon a transaction and then have it inadvertently cleared by
1254 // the notification that the conflicted transaction was evicted.
1256 for (const CTransactionRef& ptx : vtxConflicted) {
1257 SyncTransaction(ptx);
1259 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1260 SyncTransaction(pblock->vtx[i], pindex, i);
1264 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1265 LOCK2(cs_main, cs_wallet);
1267 for (const CTransactionRef& ptx : pblock->vtx) {
1268 SyncTransaction(ptx);
1274 isminetype CWallet::IsMine(const CTxIn &txin) const
1277 LOCK(cs_wallet);
1278 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1279 if (mi != mapWallet.end())
1281 const CWalletTx& prev = (*mi).second;
1282 if (txin.prevout.n < prev.tx->vout.size())
1283 return IsMine(prev.tx->vout[txin.prevout.n]);
1286 return ISMINE_NO;
1289 // Note that this function doesn't distinguish between a 0-valued input,
1290 // and a not-"is mine" (according to the filter) input.
1291 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1294 LOCK(cs_wallet);
1295 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1296 if (mi != mapWallet.end())
1298 const CWalletTx& prev = (*mi).second;
1299 if (txin.prevout.n < prev.tx->vout.size())
1300 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1301 return prev.tx->vout[txin.prevout.n].nValue;
1304 return 0;
1307 isminetype CWallet::IsMine(const CTxOut& txout) const
1309 return ::IsMine(*this, txout.scriptPubKey);
1312 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1314 if (!MoneyRange(txout.nValue))
1315 throw std::runtime_error(std::string(__func__) + ": value out of range");
1316 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1319 bool CWallet::IsChange(const CTxOut& txout) const
1321 // TODO: fix handling of 'change' outputs. The assumption is that any
1322 // payment to a script that is ours, but is not in the address book
1323 // is change. That assumption is likely to break when we implement multisignature
1324 // wallets that return change back into a multi-signature-protected address;
1325 // a better way of identifying which outputs are 'the send' and which are
1326 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1327 // which output, if any, was change).
1328 if (::IsMine(*this, txout.scriptPubKey))
1330 CTxDestination address;
1331 if (!ExtractDestination(txout.scriptPubKey, address))
1332 return true;
1334 LOCK(cs_wallet);
1335 if (!mapAddressBook.count(address))
1336 return true;
1338 return false;
1341 CAmount CWallet::GetChange(const CTxOut& txout) const
1343 if (!MoneyRange(txout.nValue))
1344 throw std::runtime_error(std::string(__func__) + ": value out of range");
1345 return (IsChange(txout) ? txout.nValue : 0);
1348 bool CWallet::IsMine(const CTransaction& tx) const
1350 for (const CTxOut& txout : tx.vout)
1351 if (IsMine(txout))
1352 return true;
1353 return false;
1356 bool CWallet::IsFromMe(const CTransaction& tx) const
1358 return (GetDebit(tx, ISMINE_ALL) > 0);
1361 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1363 CAmount nDebit = 0;
1364 for (const CTxIn& txin : tx.vin)
1366 nDebit += GetDebit(txin, filter);
1367 if (!MoneyRange(nDebit))
1368 throw std::runtime_error(std::string(__func__) + ": value out of range");
1370 return nDebit;
1373 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1375 LOCK(cs_wallet);
1377 for (const CTxIn& txin : tx.vin)
1379 auto mi = mapWallet.find(txin.prevout.hash);
1380 if (mi == mapWallet.end())
1381 return false; // any unknown inputs can't be from us
1383 const CWalletTx& prev = (*mi).second;
1385 if (txin.prevout.n >= prev.tx->vout.size())
1386 return false; // invalid input!
1388 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1389 return false;
1391 return true;
1394 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1396 CAmount nCredit = 0;
1397 for (const CTxOut& txout : tx.vout)
1399 nCredit += GetCredit(txout, filter);
1400 if (!MoneyRange(nCredit))
1401 throw std::runtime_error(std::string(__func__) + ": value out of range");
1403 return nCredit;
1406 CAmount CWallet::GetChange(const CTransaction& tx) const
1408 CAmount nChange = 0;
1409 for (const CTxOut& txout : tx.vout)
1411 nChange += GetChange(txout);
1412 if (!MoneyRange(nChange))
1413 throw std::runtime_error(std::string(__func__) + ": value out of range");
1415 return nChange;
1418 CPubKey CWallet::GenerateNewHDMasterKey()
1420 CKey key;
1421 key.MakeNewKey(true);
1423 int64_t nCreationTime = GetTime();
1424 CKeyMetadata metadata(nCreationTime);
1426 // calculate the pubkey
1427 CPubKey pubkey = key.GetPubKey();
1428 assert(key.VerifyPubKey(pubkey));
1430 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1431 metadata.hdKeypath = "m";
1432 metadata.hdMasterKeyID = pubkey.GetID();
1435 LOCK(cs_wallet);
1437 // mem store the metadata
1438 mapKeyMetadata[pubkey.GetID()] = metadata;
1440 // write the key&metadata to the database
1441 if (!AddKeyPubKey(key, pubkey))
1442 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1445 return pubkey;
1448 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1450 LOCK(cs_wallet);
1451 // store the keyid (hash160) together with
1452 // the child index counter in the database
1453 // as a hdchain object
1454 CHDChain newHdChain;
1455 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1456 newHdChain.masterKeyID = pubkey.GetID();
1457 SetHDChain(newHdChain, false);
1459 return true;
1462 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1464 LOCK(cs_wallet);
1465 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1466 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1468 hdChain = chain;
1469 return true;
1472 bool CWallet::IsHDEnabled() const
1474 return !hdChain.masterKeyID.IsNull();
1477 int64_t CWalletTx::GetTxTime() const
1479 int64_t n = nTimeSmart;
1480 return n ? n : nTimeReceived;
1483 int CWalletTx::GetRequestCount() const
1485 // Returns -1 if it wasn't being tracked
1486 int nRequests = -1;
1488 LOCK(pwallet->cs_wallet);
1489 if (IsCoinBase())
1491 // Generated block
1492 if (!hashUnset())
1494 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1495 if (mi != pwallet->mapRequestCount.end())
1496 nRequests = (*mi).second;
1499 else
1501 // Did anyone request this transaction?
1502 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1503 if (mi != pwallet->mapRequestCount.end())
1505 nRequests = (*mi).second;
1507 // How about the block it's in?
1508 if (nRequests == 0 && !hashUnset())
1510 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1511 if (_mi != pwallet->mapRequestCount.end())
1512 nRequests = (*_mi).second;
1513 else
1514 nRequests = 1; // If it's in someone else's block it must have got out
1519 return nRequests;
1522 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1523 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1525 nFee = 0;
1526 listReceived.clear();
1527 listSent.clear();
1528 strSentAccount = strFromAccount;
1530 // Compute fee:
1531 CAmount nDebit = GetDebit(filter);
1532 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1534 CAmount nValueOut = tx->GetValueOut();
1535 nFee = nDebit - nValueOut;
1538 // Sent/received.
1539 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1541 const CTxOut& txout = tx->vout[i];
1542 isminetype fIsMine = pwallet->IsMine(txout);
1543 // Only need to handle txouts if AT LEAST one of these is true:
1544 // 1) they debit from us (sent)
1545 // 2) the output is to us (received)
1546 if (nDebit > 0)
1548 // Don't report 'change' txouts
1549 if (pwallet->IsChange(txout))
1550 continue;
1552 else if (!(fIsMine & filter))
1553 continue;
1555 // In either case, we need to get the destination address
1556 CTxDestination address;
1558 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1560 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1561 this->GetHash().ToString());
1562 address = CNoDestination();
1565 COutputEntry output = {address, txout.nValue, (int)i};
1567 // If we are debited by the transaction, add the output as a "sent" entry
1568 if (nDebit > 0)
1569 listSent.push_back(output);
1571 // If we are receiving the output, add it as a "received" entry
1572 if (fIsMine & filter)
1573 listReceived.push_back(output);
1579 * Scan active chain for relevant transactions after importing keys. This should
1580 * be called whenever new keys are added to the wallet, with the oldest key
1581 * creation time.
1583 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1584 * returned will be higher than startTime if relevant blocks could not be read.
1586 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1588 AssertLockHeld(cs_main);
1589 AssertLockHeld(cs_wallet);
1591 // Find starting block. May be null if nCreateTime is greater than the
1592 // highest blockchain timestamp, in which case there is nothing that needs
1593 // to be scanned.
1594 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1595 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1597 if (startBlock) {
1598 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1599 if (failedBlock) {
1600 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1603 return startTime;
1607 * Scan the block chain (starting in pindexStart) for transactions
1608 * from or to us. If fUpdate is true, found transactions that already
1609 * exist in the wallet will be updated.
1611 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1612 * possible (due to pruning or corruption), returns pointer to the most recent
1613 * block that could not be scanned.
1615 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1617 int64_t nNow = GetTime();
1618 const CChainParams& chainParams = Params();
1620 CBlockIndex* pindex = pindexStart;
1621 CBlockIndex* ret = nullptr;
1623 LOCK2(cs_main, cs_wallet);
1624 fAbortRescan = false;
1625 fScanningWallet = true;
1627 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1628 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1629 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1630 while (pindex && !fAbortRescan)
1632 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1633 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1634 if (GetTime() >= nNow + 60) {
1635 nNow = GetTime();
1636 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1639 CBlock block;
1640 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1641 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1642 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1644 } else {
1645 ret = pindex;
1647 pindex = chainActive.Next(pindex);
1649 if (pindex && fAbortRescan) {
1650 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1652 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1654 fScanningWallet = false;
1656 return ret;
1659 void CWallet::ReacceptWalletTransactions()
1661 // If transactions aren't being broadcasted, don't let them into local mempool either
1662 if (!fBroadcastTransactions)
1663 return;
1664 LOCK2(cs_main, cs_wallet);
1665 std::map<int64_t, CWalletTx*> mapSorted;
1667 // Sort pending wallet transactions based on their initial wallet insertion order
1668 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1670 const uint256& wtxid = item.first;
1671 CWalletTx& wtx = item.second;
1672 assert(wtx.GetHash() == wtxid);
1674 int nDepth = wtx.GetDepthInMainChain();
1676 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1677 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1681 // Try to add wallet transactions to memory pool
1682 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1684 CWalletTx& wtx = *(item.second);
1686 LOCK(mempool.cs);
1687 CValidationState state;
1688 wtx.AcceptToMemoryPool(maxTxFee, state);
1692 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1694 assert(pwallet->GetBroadcastTransactions());
1695 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1697 CValidationState state;
1698 /* GetDepthInMainChain already catches known conflicts. */
1699 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1700 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1701 if (connman) {
1702 CInv inv(MSG_TX, GetHash());
1703 connman->ForEachNode([&inv](CNode* pnode)
1705 pnode->PushInventory(inv);
1707 return true;
1711 return false;
1714 std::set<uint256> CWalletTx::GetConflicts() const
1716 std::set<uint256> result;
1717 if (pwallet != nullptr)
1719 uint256 myHash = GetHash();
1720 result = pwallet->GetConflicts(myHash);
1721 result.erase(myHash);
1723 return result;
1726 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1728 if (tx->vin.empty())
1729 return 0;
1731 CAmount debit = 0;
1732 if(filter & ISMINE_SPENDABLE)
1734 if (fDebitCached)
1735 debit += nDebitCached;
1736 else
1738 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1739 fDebitCached = true;
1740 debit += nDebitCached;
1743 if(filter & ISMINE_WATCH_ONLY)
1745 if(fWatchDebitCached)
1746 debit += nWatchDebitCached;
1747 else
1749 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1750 fWatchDebitCached = true;
1751 debit += nWatchDebitCached;
1754 return debit;
1757 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1759 // Must wait until coinbase is safely deep enough in the chain before valuing it
1760 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1761 return 0;
1763 CAmount credit = 0;
1764 if (filter & ISMINE_SPENDABLE)
1766 // GetBalance can assume transactions in mapWallet won't change
1767 if (fCreditCached)
1768 credit += nCreditCached;
1769 else
1771 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1772 fCreditCached = true;
1773 credit += nCreditCached;
1776 if (filter & ISMINE_WATCH_ONLY)
1778 if (fWatchCreditCached)
1779 credit += nWatchCreditCached;
1780 else
1782 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1783 fWatchCreditCached = true;
1784 credit += nWatchCreditCached;
1787 return credit;
1790 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1792 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1794 if (fUseCache && fImmatureCreditCached)
1795 return nImmatureCreditCached;
1796 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1797 fImmatureCreditCached = true;
1798 return nImmatureCreditCached;
1801 return 0;
1804 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1806 if (pwallet == nullptr)
1807 return 0;
1809 // Must wait until coinbase is safely deep enough in the chain before valuing it
1810 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1811 return 0;
1813 if (fUseCache && fAvailableCreditCached)
1814 return nAvailableCreditCached;
1816 CAmount nCredit = 0;
1817 uint256 hashTx = GetHash();
1818 for (unsigned int i = 0; i < tx->vout.size(); i++)
1820 if (!pwallet->IsSpent(hashTx, i))
1822 const CTxOut &txout = tx->vout[i];
1823 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1824 if (!MoneyRange(nCredit))
1825 throw std::runtime_error(std::string(__func__) + " : value out of range");
1829 nAvailableCreditCached = nCredit;
1830 fAvailableCreditCached = true;
1831 return nCredit;
1834 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1836 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1838 if (fUseCache && fImmatureWatchCreditCached)
1839 return nImmatureWatchCreditCached;
1840 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1841 fImmatureWatchCreditCached = true;
1842 return nImmatureWatchCreditCached;
1845 return 0;
1848 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1850 if (pwallet == nullptr)
1851 return 0;
1853 // Must wait until coinbase is safely deep enough in the chain before valuing it
1854 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1855 return 0;
1857 if (fUseCache && fAvailableWatchCreditCached)
1858 return nAvailableWatchCreditCached;
1860 CAmount nCredit = 0;
1861 for (unsigned int i = 0; i < tx->vout.size(); i++)
1863 if (!pwallet->IsSpent(GetHash(), i))
1865 const CTxOut &txout = tx->vout[i];
1866 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1867 if (!MoneyRange(nCredit))
1868 throw std::runtime_error(std::string(__func__) + ": value out of range");
1872 nAvailableWatchCreditCached = nCredit;
1873 fAvailableWatchCreditCached = true;
1874 return nCredit;
1877 CAmount CWalletTx::GetChange() const
1879 if (fChangeCached)
1880 return nChangeCached;
1881 nChangeCached = pwallet->GetChange(*this);
1882 fChangeCached = true;
1883 return nChangeCached;
1886 bool CWalletTx::InMempool() const
1888 LOCK(mempool.cs);
1889 return mempool.exists(GetHash());
1892 bool CWalletTx::IsTrusted() const
1894 // Quick answer in most cases
1895 if (!CheckFinalTx(*this))
1896 return false;
1897 int nDepth = GetDepthInMainChain();
1898 if (nDepth >= 1)
1899 return true;
1900 if (nDepth < 0)
1901 return false;
1902 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1903 return false;
1905 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1906 if (!InMempool())
1907 return false;
1909 // Trusted if all inputs are from us and are in the mempool:
1910 for (const CTxIn& txin : tx->vin)
1912 // Transactions not sent by us: not trusted
1913 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1914 if (parent == nullptr)
1915 return false;
1916 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1917 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1918 return false;
1920 return true;
1923 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1925 CMutableTransaction tx1 = *this->tx;
1926 CMutableTransaction tx2 = *_tx.tx;
1927 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1928 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1929 return CTransaction(tx1) == CTransaction(tx2);
1932 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1934 std::vector<uint256> result;
1936 LOCK(cs_wallet);
1938 // Sort them in chronological order
1939 std::multimap<unsigned int, CWalletTx*> mapSorted;
1940 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1942 CWalletTx& wtx = item.second;
1943 // Don't rebroadcast if newer than nTime:
1944 if (wtx.nTimeReceived > nTime)
1945 continue;
1946 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1948 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1950 CWalletTx& wtx = *item.second;
1951 if (wtx.RelayWalletTransaction(connman))
1952 result.push_back(wtx.GetHash());
1954 return result;
1957 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1959 // Do this infrequently and randomly to avoid giving away
1960 // that these are our transactions.
1961 if (GetTime() < nNextResend || !fBroadcastTransactions)
1962 return;
1963 bool fFirst = (nNextResend == 0);
1964 nNextResend = GetTime() + GetRand(30 * 60);
1965 if (fFirst)
1966 return;
1968 // Only do it if there's been a new block since last time
1969 if (nBestBlockTime < nLastResend)
1970 return;
1971 nLastResend = GetTime();
1973 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1974 // block was found:
1975 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1976 if (!relayed.empty())
1977 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1980 /** @} */ // end of mapWallet
1985 /** @defgroup Actions
1987 * @{
1991 CAmount CWallet::GetBalance() const
1993 CAmount nTotal = 0;
1995 LOCK2(cs_main, cs_wallet);
1996 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1998 const CWalletTx* pcoin = &(*it).second;
1999 if (pcoin->IsTrusted())
2000 nTotal += pcoin->GetAvailableCredit();
2004 return nTotal;
2007 CAmount CWallet::GetUnconfirmedBalance() const
2009 CAmount nTotal = 0;
2011 LOCK2(cs_main, cs_wallet);
2012 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2014 const CWalletTx* pcoin = &(*it).second;
2015 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2016 nTotal += pcoin->GetAvailableCredit();
2019 return nTotal;
2022 CAmount CWallet::GetImmatureBalance() const
2024 CAmount nTotal = 0;
2026 LOCK2(cs_main, cs_wallet);
2027 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2029 const CWalletTx* pcoin = &(*it).second;
2030 nTotal += pcoin->GetImmatureCredit();
2033 return nTotal;
2036 CAmount CWallet::GetWatchOnlyBalance() const
2038 CAmount nTotal = 0;
2040 LOCK2(cs_main, cs_wallet);
2041 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2043 const CWalletTx* pcoin = &(*it).second;
2044 if (pcoin->IsTrusted())
2045 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2049 return nTotal;
2052 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2054 CAmount nTotal = 0;
2056 LOCK2(cs_main, cs_wallet);
2057 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2059 const CWalletTx* pcoin = &(*it).second;
2060 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2061 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2064 return nTotal;
2067 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2069 CAmount nTotal = 0;
2071 LOCK2(cs_main, cs_wallet);
2072 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2074 const CWalletTx* pcoin = &(*it).second;
2075 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2078 return nTotal;
2081 // Calculate total balance in a different way from GetBalance. The biggest
2082 // difference is that GetBalance sums up all unspent TxOuts paying to the
2083 // wallet, while this sums up both spent and unspent TxOuts paying to the
2084 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2085 // also has fewer restrictions on which unconfirmed transactions are considered
2086 // trusted.
2087 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2089 LOCK2(cs_main, cs_wallet);
2091 CAmount balance = 0;
2092 for (const auto& entry : mapWallet) {
2093 const CWalletTx& wtx = entry.second;
2094 const int depth = wtx.GetDepthInMainChain();
2095 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2096 continue;
2099 // Loop through tx outputs and add incoming payments. For outgoing txs,
2100 // treat change outputs specially, as part of the amount debited.
2101 CAmount debit = wtx.GetDebit(filter);
2102 const bool outgoing = debit > 0;
2103 for (const CTxOut& out : wtx.tx->vout) {
2104 if (outgoing && IsChange(out)) {
2105 debit -= out.nValue;
2106 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2107 balance += out.nValue;
2111 // For outgoing txs, subtract amount debited.
2112 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2113 balance -= debit;
2117 if (account) {
2118 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2121 return balance;
2124 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2126 LOCK2(cs_main, cs_wallet);
2128 CAmount balance = 0;
2129 std::vector<COutput> vCoins;
2130 AvailableCoins(vCoins, true, coinControl);
2131 for (const COutput& out : vCoins) {
2132 if (out.fSpendable) {
2133 balance += out.tx->tx->vout[out.i].nValue;
2136 return balance;
2139 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
2141 vCoins.clear();
2144 LOCK2(cs_main, cs_wallet);
2146 CAmount nTotal = 0;
2148 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2150 const uint256& wtxid = it->first;
2151 const CWalletTx* pcoin = &(*it).second;
2153 if (!CheckFinalTx(*pcoin))
2154 continue;
2156 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2157 continue;
2159 int nDepth = pcoin->GetDepthInMainChain();
2160 if (nDepth < 0)
2161 continue;
2163 // We should not consider coins which aren't at least in our mempool
2164 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2165 if (nDepth == 0 && !pcoin->InMempool())
2166 continue;
2168 bool safeTx = pcoin->IsTrusted();
2170 // We should not consider coins from transactions that are replacing
2171 // other transactions.
2173 // Example: There is a transaction A which is replaced by bumpfee
2174 // transaction B. In this case, we want to prevent creation of
2175 // a transaction B' which spends an output of B.
2177 // Reason: If transaction A were initially confirmed, transactions B
2178 // and B' would no longer be valid, so the user would have to create
2179 // a new transaction C to replace B'. However, in the case of a
2180 // one-block reorg, transactions B' and C might BOTH be accepted,
2181 // when the user only wanted one of them. Specifically, there could
2182 // be a 1-block reorg away from the chain where transactions A and C
2183 // were accepted to another chain where B, B', and C were all
2184 // accepted.
2185 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2186 safeTx = false;
2189 // Similarly, we should not consider coins from transactions that
2190 // have been replaced. In the example above, we would want to prevent
2191 // creation of a transaction A' spending an output of A, because if
2192 // transaction B were initially confirmed, conflicting with A and
2193 // A', we wouldn't want to the user to create a transaction D
2194 // intending to replace A', but potentially resulting in a scenario
2195 // where A, A', and D could all be accepted (instead of just B and
2196 // D, or just A and A' like the user would want).
2197 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2198 safeTx = false;
2201 if (fOnlySafe && !safeTx) {
2202 continue;
2205 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2206 continue;
2208 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2209 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2210 continue;
2212 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2213 continue;
2215 if (IsLockedCoin((*it).first, i))
2216 continue;
2218 if (IsSpent(wtxid, i))
2219 continue;
2221 isminetype mine = IsMine(pcoin->tx->vout[i]);
2223 if (mine == ISMINE_NO) {
2224 continue;
2227 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2228 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2230 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2232 // Checks the sum amount of all UTXO's.
2233 if (nMinimumSumAmount != MAX_MONEY) {
2234 nTotal += pcoin->tx->vout[i].nValue;
2236 if (nTotal >= nMinimumSumAmount) {
2237 return;
2241 // Checks the maximum number of UTXO's.
2242 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2243 return;
2250 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2252 // TODO: Add AssertLockHeld(cs_wallet) here.
2254 // Because the return value from this function contains pointers to
2255 // CWalletTx objects, callers to this function really should acquire the
2256 // cs_wallet lock before calling it. However, the current caller doesn't
2257 // acquire this lock yet. There was an attempt to add the missing lock in
2258 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2259 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2260 // avoid adding some extra complexity to the Qt code.
2262 std::map<CTxDestination, std::vector<COutput>> result;
2264 std::vector<COutput> availableCoins;
2265 AvailableCoins(availableCoins);
2267 LOCK2(cs_main, cs_wallet);
2268 for (auto& coin : availableCoins) {
2269 CTxDestination address;
2270 if (coin.fSpendable &&
2271 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2272 result[address].emplace_back(std::move(coin));
2276 std::vector<COutPoint> lockedCoins;
2277 ListLockedCoins(lockedCoins);
2278 for (const auto& output : lockedCoins) {
2279 auto it = mapWallet.find(output.hash);
2280 if (it != mapWallet.end()) {
2281 int depth = it->second.GetDepthInMainChain();
2282 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2283 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2284 CTxDestination address;
2285 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2286 result[address].emplace_back(
2287 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2293 return result;
2296 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2298 const CTransaction* ptx = &tx;
2299 int n = output;
2300 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2301 const COutPoint& prevout = ptx->vin[0].prevout;
2302 auto it = mapWallet.find(prevout.hash);
2303 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2304 !IsMine(it->second.tx->vout[prevout.n])) {
2305 break;
2307 ptx = it->second.tx.get();
2308 n = prevout.n;
2310 return ptx->vout[n];
2313 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2314 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2316 std::vector<char> vfIncluded;
2318 vfBest.assign(vValue.size(), true);
2319 nBest = nTotalLower;
2321 FastRandomContext insecure_rand;
2323 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2325 vfIncluded.assign(vValue.size(), false);
2326 CAmount nTotal = 0;
2327 bool fReachedTarget = false;
2328 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2330 for (unsigned int i = 0; i < vValue.size(); i++)
2332 //The solver here uses a randomized algorithm,
2333 //the randomness serves no real security purpose but is just
2334 //needed to prevent degenerate behavior and it is important
2335 //that the rng is fast. We do not use a constant random sequence,
2336 //because there may be some privacy improvement by making
2337 //the selection random.
2338 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2340 nTotal += vValue[i].txout.nValue;
2341 vfIncluded[i] = true;
2342 if (nTotal >= nTargetValue)
2344 fReachedTarget = true;
2345 if (nTotal < nBest)
2347 nBest = nTotal;
2348 vfBest = vfIncluded;
2350 nTotal -= vValue[i].txout.nValue;
2351 vfIncluded[i] = false;
2359 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2360 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2362 setCoinsRet.clear();
2363 nValueRet = 0;
2365 // List of values less than target
2366 boost::optional<CInputCoin> coinLowestLarger;
2367 std::vector<CInputCoin> vValue;
2368 CAmount nTotalLower = 0;
2370 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2372 for (const COutput &output : vCoins)
2374 if (!output.fSpendable)
2375 continue;
2377 const CWalletTx *pcoin = output.tx;
2379 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2380 continue;
2382 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2383 continue;
2385 int i = output.i;
2387 CInputCoin coin = CInputCoin(pcoin, i);
2389 if (coin.txout.nValue == nTargetValue)
2391 setCoinsRet.insert(coin);
2392 nValueRet += coin.txout.nValue;
2393 return true;
2395 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2397 vValue.push_back(coin);
2398 nTotalLower += coin.txout.nValue;
2400 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2402 coinLowestLarger = coin;
2406 if (nTotalLower == nTargetValue)
2408 for (const auto& input : vValue)
2410 setCoinsRet.insert(input);
2411 nValueRet += input.txout.nValue;
2413 return true;
2416 if (nTotalLower < nTargetValue)
2418 if (!coinLowestLarger)
2419 return false;
2420 setCoinsRet.insert(coinLowestLarger.get());
2421 nValueRet += coinLowestLarger->txout.nValue;
2422 return true;
2425 // Solve subset sum by stochastic approximation
2426 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2427 std::reverse(vValue.begin(), vValue.end());
2428 std::vector<char> vfBest;
2429 CAmount nBest;
2431 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2432 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2433 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2435 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2436 // or the next bigger coin is closer), return the bigger coin
2437 if (coinLowestLarger &&
2438 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2440 setCoinsRet.insert(coinLowestLarger.get());
2441 nValueRet += coinLowestLarger->txout.nValue;
2443 else {
2444 for (unsigned int i = 0; i < vValue.size(); i++)
2445 if (vfBest[i])
2447 setCoinsRet.insert(vValue[i]);
2448 nValueRet += vValue[i].txout.nValue;
2451 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2452 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2453 for (unsigned int i = 0; i < vValue.size(); i++) {
2454 if (vfBest[i]) {
2455 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2458 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2462 return true;
2465 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2467 std::vector<COutput> vCoins(vAvailableCoins);
2469 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2470 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2472 for (const COutput& out : vCoins)
2474 if (!out.fSpendable)
2475 continue;
2476 nValueRet += out.tx->tx->vout[out.i].nValue;
2477 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2479 return (nValueRet >= nTargetValue);
2482 // calculate value from preset inputs and store them
2483 std::set<CInputCoin> setPresetCoins;
2484 CAmount nValueFromPresetInputs = 0;
2486 std::vector<COutPoint> vPresetInputs;
2487 if (coinControl)
2488 coinControl->ListSelected(vPresetInputs);
2489 for (const COutPoint& outpoint : vPresetInputs)
2491 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2492 if (it != mapWallet.end())
2494 const CWalletTx* pcoin = &it->second;
2495 // Clearly invalid input, fail
2496 if (pcoin->tx->vout.size() <= outpoint.n)
2497 return false;
2498 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2499 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2500 } else
2501 return false; // TODO: Allow non-wallet inputs
2504 // remove preset inputs from vCoins
2505 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2507 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2508 it = vCoins.erase(it);
2509 else
2510 ++it;
2513 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2514 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2516 bool res = nTargetValue <= nValueFromPresetInputs ||
2517 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2518 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2519 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2520 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2521 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2522 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2523 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2525 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2526 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2528 // add preset inputs to the total value selected
2529 nValueRet += nValueFromPresetInputs;
2531 return res;
2534 bool CWallet::SignTransaction(CMutableTransaction &tx)
2536 AssertLockHeld(cs_wallet); // mapWallet
2538 // sign the new tx
2539 CTransaction txNewConst(tx);
2540 int nIn = 0;
2541 for (const auto& input : tx.vin) {
2542 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2543 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2544 return false;
2546 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2547 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2548 SignatureData sigdata;
2549 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2550 return false;
2552 UpdateTransaction(tx, nIn, sigdata);
2553 nIn++;
2555 return true;
2558 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2560 std::vector<CRecipient> vecSend;
2562 // Turn the txout set into a CRecipient vector
2563 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2565 const CTxOut& txOut = tx.vout[idx];
2566 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2567 vecSend.push_back(recipient);
2570 coinControl.fAllowOtherInputs = true;
2572 for (const CTxIn& txin : tx.vin)
2573 coinControl.Select(txin.prevout);
2575 CReserveKey reservekey(this);
2576 CWalletTx wtx;
2577 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2578 return false;
2581 if (nChangePosInOut != -1) {
2582 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2583 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2584 // so just remove the key from the keypool here.
2585 reservekey.KeepKey();
2588 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2589 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2590 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2592 // Add new txins (keeping original txin scriptSig/order)
2593 for (const CTxIn& txin : wtx.tx->vin)
2595 if (!coinControl.IsSelected(txin.prevout))
2597 tx.vin.push_back(txin);
2599 if (lockUnspents)
2601 LOCK2(cs_main, cs_wallet);
2602 LockCoin(txin.prevout);
2608 return true;
2611 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2613 unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2614 CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2615 // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2616 discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2617 // Discard rate must be at least dustRelayFee
2618 discard_rate = std::max(discard_rate, ::dustRelayFee);
2619 return discard_rate;
2622 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2623 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2625 CAmount nValue = 0;
2626 int nChangePosRequest = nChangePosInOut;
2627 unsigned int nSubtractFeeFromAmount = 0;
2628 for (const auto& recipient : vecSend)
2630 if (nValue < 0 || recipient.nAmount < 0)
2632 strFailReason = _("Transaction amounts must not be negative");
2633 return false;
2635 nValue += recipient.nAmount;
2637 if (recipient.fSubtractFeeFromAmount)
2638 nSubtractFeeFromAmount++;
2640 if (vecSend.empty())
2642 strFailReason = _("Transaction must have at least one recipient");
2643 return false;
2646 wtxNew.fTimeReceivedIsTxTime = true;
2647 wtxNew.BindWallet(this);
2648 CMutableTransaction txNew;
2650 // Discourage fee sniping.
2652 // For a large miner the value of the transactions in the best block and
2653 // the mempool can exceed the cost of deliberately attempting to mine two
2654 // blocks to orphan the current best block. By setting nLockTime such that
2655 // only the next block can include the transaction, we discourage this
2656 // practice as the height restricted and limited blocksize gives miners
2657 // considering fee sniping fewer options for pulling off this attack.
2659 // A simple way to think about this is from the wallet's point of view we
2660 // always want the blockchain to move forward. By setting nLockTime this
2661 // way we're basically making the statement that we only want this
2662 // transaction to appear in the next block; we don't want to potentially
2663 // encourage reorgs by allowing transactions to appear at lower heights
2664 // than the next block in forks of the best chain.
2666 // Of course, the subsidy is high enough, and transaction volume low
2667 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2668 // now we ensure code won't be written that makes assumptions about
2669 // nLockTime that preclude a fix later.
2670 txNew.nLockTime = chainActive.Height();
2672 // Secondly occasionally randomly pick a nLockTime even further back, so
2673 // that transactions that are delayed after signing for whatever reason,
2674 // e.g. high-latency mix networks and some CoinJoin implementations, have
2675 // better privacy.
2676 if (GetRandInt(10) == 0)
2677 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2679 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2680 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2681 FeeCalculation feeCalc;
2682 unsigned int nBytes;
2684 std::set<CInputCoin> setCoins;
2685 LOCK2(cs_main, cs_wallet);
2687 std::vector<COutput> vAvailableCoins;
2688 AvailableCoins(vAvailableCoins, true, &coin_control);
2690 // Create change script that will be used if we need change
2691 // TODO: pass in scriptChange instead of reservekey so
2692 // change transaction isn't always pay-to-bitcoin-address
2693 CScript scriptChange;
2695 // coin control: send change to custom address
2696 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2697 scriptChange = GetScriptForDestination(coin_control.destChange);
2698 } else { // no coin control: send change to newly generated address
2699 // Note: We use a new key here to keep it from being obvious which side is the change.
2700 // The drawback is that by not reusing a previous key, the change may be lost if a
2701 // backup is restored, if the backup doesn't have the new private key for the change.
2702 // If we reused the old key, it would be possible to add code to look for and
2703 // rediscover unknown transactions that were written with keys of ours to recover
2704 // post-backup change.
2706 // Reserve a new key pair from key pool
2707 CPubKey vchPubKey;
2708 bool ret;
2709 ret = reservekey.GetReservedKey(vchPubKey, true);
2710 if (!ret)
2712 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2713 return false;
2716 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2718 CTxOut change_prototype_txout(0, scriptChange);
2719 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2721 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2722 nFeeRet = 0;
2723 bool pick_new_inputs = true;
2724 CAmount nValueIn = 0;
2725 // Start with no fee and loop until there is enough fee
2726 while (true)
2728 nChangePosInOut = nChangePosRequest;
2729 txNew.vin.clear();
2730 txNew.vout.clear();
2731 wtxNew.fFromMe = true;
2732 bool fFirst = true;
2734 CAmount nValueToSelect = nValue;
2735 if (nSubtractFeeFromAmount == 0)
2736 nValueToSelect += nFeeRet;
2737 // vouts to the payees
2738 for (const auto& recipient : vecSend)
2740 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2742 if (recipient.fSubtractFeeFromAmount)
2744 assert(nSubtractFeeFromAmount != 0);
2745 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2747 if (fFirst) // first receiver pays the remainder not divisible by output count
2749 fFirst = false;
2750 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2754 if (IsDust(txout, ::dustRelayFee))
2756 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2758 if (txout.nValue < 0)
2759 strFailReason = _("The transaction amount is too small to pay the fee");
2760 else
2761 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2763 else
2764 strFailReason = _("Transaction amount too small");
2765 return false;
2767 txNew.vout.push_back(txout);
2770 // Choose coins to use
2771 if (pick_new_inputs) {
2772 nValueIn = 0;
2773 setCoins.clear();
2774 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2776 strFailReason = _("Insufficient funds");
2777 return false;
2781 const CAmount nChange = nValueIn - nValueToSelect;
2783 if (nChange > 0)
2785 // Fill a vout to ourself
2786 CTxOut newTxOut(nChange, scriptChange);
2788 // Never create dust outputs; if we would, just
2789 // add the dust to the fee.
2790 if (IsDust(newTxOut, discard_rate))
2792 nChangePosInOut = -1;
2793 nFeeRet += nChange;
2795 else
2797 if (nChangePosInOut == -1)
2799 // Insert change txn at random position:
2800 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2802 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2804 strFailReason = _("Change index out of range");
2805 return false;
2808 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2809 txNew.vout.insert(position, newTxOut);
2811 } else {
2812 nChangePosInOut = -1;
2815 // Fill vin
2817 // Note how the sequence number is set to non-maxint so that
2818 // the nLockTime set above actually works.
2820 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2821 // we use the highest possible value in that range (maxint-2)
2822 // to avoid conflicting with other possible uses of nSequence,
2823 // and in the spirit of "smallest possible change from prior
2824 // behavior."
2825 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2826 for (const auto& coin : setCoins)
2827 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2828 nSequence));
2830 // Fill in dummy signatures for fee calculation.
2831 if (!DummySignTx(txNew, setCoins)) {
2832 strFailReason = _("Signing transaction failed");
2833 return false;
2836 nBytes = GetVirtualTransactionSize(txNew);
2838 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2839 for (auto& vin : txNew.vin) {
2840 vin.scriptSig = CScript();
2841 vin.scriptWitness.SetNull();
2844 CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2846 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2847 // because we must be at the maximum allowed fee.
2848 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2850 strFailReason = _("Transaction too large for fee policy");
2851 return false;
2854 if (nFeeRet >= nFeeNeeded) {
2855 // Reduce fee to only the needed amount if possible. This
2856 // prevents potential overpayment in fees if the coins
2857 // selected to meet nFeeNeeded result in a transaction that
2858 // requires less fee than the prior iteration.
2860 // If we have no change and a big enough excess fee, then
2861 // try to construct transaction again only without picking
2862 // new inputs. We now know we only need the smaller fee
2863 // (because of reduced tx size) and so we should add a
2864 // change output. Only try this once.
2865 CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
2866 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2867 CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
2868 if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2869 pick_new_inputs = false;
2870 nFeeRet = nFeeNeeded + fee_needed_for_change;
2871 continue;
2874 // If we have change output already, just increase it
2875 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2876 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2877 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2878 change_position->nValue += extraFeePaid;
2879 nFeeRet -= extraFeePaid;
2881 break; // Done, enough fee included.
2883 else if (!pick_new_inputs) {
2884 // This shouldn't happen, we should have had enough excess
2885 // fee to pay for the new output and still meet nFeeNeeded
2886 // Or we should have just subtracted fee from recipients and
2887 // nFeeNeeded should not have changed
2888 strFailReason = _("Transaction fee and change calculation failed");
2889 return false;
2892 // Try to reduce change to include necessary fee
2893 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2894 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2895 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2896 // Only reduce change if remaining amount is still a large enough output.
2897 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2898 change_position->nValue -= additionalFeeNeeded;
2899 nFeeRet += additionalFeeNeeded;
2900 break; // Done, able to increase fee from change
2904 // If subtracting fee from recipients, we now know what fee we
2905 // need to subtract, we have no reason to reselect inputs
2906 if (nSubtractFeeFromAmount > 0) {
2907 pick_new_inputs = false;
2910 // Include more fee and try again.
2911 nFeeRet = nFeeNeeded;
2912 continue;
2916 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2918 if (sign)
2920 CTransaction txNewConst(txNew);
2921 int nIn = 0;
2922 for (const auto& coin : setCoins)
2924 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2925 SignatureData sigdata;
2927 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2929 strFailReason = _("Signing transaction failed");
2930 return false;
2931 } else {
2932 UpdateTransaction(txNew, nIn, sigdata);
2935 nIn++;
2939 // Embed the constructed transaction data in wtxNew.
2940 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2942 // Limit size
2943 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2945 strFailReason = _("Transaction too large");
2946 return false;
2950 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2951 // Lastly, ensure this tx will pass the mempool's chain limits
2952 LockPoints lp;
2953 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2954 CTxMemPool::setEntries setAncestors;
2955 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2956 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2957 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2958 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2959 std::string errString;
2960 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2961 strFailReason = _("Transaction has too long of a mempool chain");
2962 return false;
2966 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",
2967 nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2968 feeCalc.est.pass.start, feeCalc.est.pass.end,
2969 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2970 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2971 feeCalc.est.fail.start, feeCalc.est.fail.end,
2972 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2973 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2974 return true;
2978 * Call after CreateTransaction unless you want to abort
2980 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2983 LOCK2(cs_main, cs_wallet);
2984 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2986 // Take key pair from key pool so it won't be used again
2987 reservekey.KeepKey();
2989 // Add tx to wallet, because if it has change it's also ours,
2990 // otherwise just for transaction history.
2991 AddToWallet(wtxNew);
2993 // Notify that old coins are spent
2994 for (const CTxIn& txin : wtxNew.tx->vin)
2996 CWalletTx &coin = mapWallet[txin.prevout.hash];
2997 coin.BindWallet(this);
2998 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
3002 // Track how many getdata requests our transaction gets
3003 mapRequestCount[wtxNew.GetHash()] = 0;
3005 if (fBroadcastTransactions)
3007 // Broadcast
3008 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
3009 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
3010 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3011 } else {
3012 wtxNew.RelayWalletTransaction(connman);
3016 return true;
3019 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3020 CWalletDB walletdb(*dbw);
3021 return walletdb.ListAccountCreditDebit(strAccount, entries);
3024 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3026 CWalletDB walletdb(*dbw);
3028 return AddAccountingEntry(acentry, &walletdb);
3031 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3033 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3034 return false;
3037 laccentries.push_back(acentry);
3038 CAccountingEntry & entry = laccentries.back();
3039 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3041 return true;
3044 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3046 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3049 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
3051 /* User control of how to calculate fee uses the following parameter precedence:
3052 1. coin_control.m_feerate
3053 2. coin_control.m_confirm_target
3054 3. payTxFee (user-set global variable)
3055 4. nTxConfirmTarget (user-set global variable)
3056 The first parameter that is set is used.
3058 CAmount fee_needed;
3059 if (coin_control.m_feerate) { // 1.
3060 fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
3061 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3062 // Allow to override automatic min/max check over coin control instance
3063 if (coin_control.fOverrideFeeRate) return fee_needed;
3065 else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
3066 fee_needed = ::payTxFee.GetFee(nTxBytes);
3067 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3069 else { // 2. or 4.
3070 // We will use smart fee estimation
3071 unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
3072 // By default estimates are economical iff we are signaling opt-in-RBF
3073 bool conservative_estimate = !coin_control.signalRbf;
3074 // Allow to override the default fee estimate mode over the CoinControl instance
3075 if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3076 else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3078 fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3079 if (fee_needed == 0) {
3080 // if we don't have enough data for estimateSmartFee, then use fallbackFee
3081 fee_needed = fallbackFee.GetFee(nTxBytes);
3082 if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3084 // Obey mempool min fee when using smart fee estimation
3085 CAmount min_mempool_fee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3086 if (fee_needed < min_mempool_fee) {
3087 fee_needed = min_mempool_fee;
3088 if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3092 // prevent user from paying a fee below minRelayTxFee or minTxFee
3093 CAmount required_fee = GetRequiredFee(nTxBytes);
3094 if (required_fee > fee_needed) {
3095 fee_needed = required_fee;
3096 if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3098 // But always obey the maximum
3099 if (fee_needed > maxTxFee) {
3100 fee_needed = maxTxFee;
3101 if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3103 return fee_needed;
3109 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3111 fFirstRunRet = false;
3112 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3113 if (nLoadWalletRet == DB_NEED_REWRITE)
3115 if (dbw->Rewrite("\x04pool"))
3117 LOCK(cs_wallet);
3118 setInternalKeyPool.clear();
3119 setExternalKeyPool.clear();
3120 m_pool_key_to_index.clear();
3121 // Note: can't top-up keypool here, because wallet is locked.
3122 // User will be prompted to unlock wallet the next operation
3123 // that requires a new key.
3127 // This wallet is in its first run if all of these are empty
3128 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3130 if (nLoadWalletRet != DB_LOAD_OK)
3131 return nLoadWalletRet;
3133 uiInterface.LoadWallet(this);
3135 return DB_LOAD_OK;
3138 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3140 AssertLockHeld(cs_wallet); // mapWallet
3141 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3142 for (uint256 hash : vHashOut)
3143 mapWallet.erase(hash);
3145 if (nZapSelectTxRet == DB_NEED_REWRITE)
3147 if (dbw->Rewrite("\x04pool"))
3149 setInternalKeyPool.clear();
3150 setExternalKeyPool.clear();
3151 m_pool_key_to_index.clear();
3152 // Note: can't top-up keypool here, because wallet is locked.
3153 // User will be prompted to unlock wallet the next operation
3154 // that requires a new key.
3158 if (nZapSelectTxRet != DB_LOAD_OK)
3159 return nZapSelectTxRet;
3161 MarkDirty();
3163 return DB_LOAD_OK;
3167 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3169 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3170 if (nZapWalletTxRet == DB_NEED_REWRITE)
3172 if (dbw->Rewrite("\x04pool"))
3174 LOCK(cs_wallet);
3175 setInternalKeyPool.clear();
3176 setExternalKeyPool.clear();
3177 m_pool_key_to_index.clear();
3178 // Note: can't top-up keypool here, because wallet is locked.
3179 // User will be prompted to unlock wallet the next operation
3180 // that requires a new key.
3184 if (nZapWalletTxRet != DB_LOAD_OK)
3185 return nZapWalletTxRet;
3187 return DB_LOAD_OK;
3191 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3193 bool fUpdated = false;
3195 LOCK(cs_wallet); // mapAddressBook
3196 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3197 fUpdated = mi != mapAddressBook.end();
3198 mapAddressBook[address].name = strName;
3199 if (!strPurpose.empty()) /* update purpose only if requested */
3200 mapAddressBook[address].purpose = strPurpose;
3202 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3203 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3204 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3205 return false;
3206 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3209 bool CWallet::DelAddressBook(const CTxDestination& address)
3212 LOCK(cs_wallet); // mapAddressBook
3214 // Delete destdata tuples associated with address
3215 std::string strAddress = CBitcoinAddress(address).ToString();
3216 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3218 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3220 mapAddressBook.erase(address);
3223 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3225 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3226 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3229 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3231 CTxDestination address;
3232 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3233 auto mi = mapAddressBook.find(address);
3234 if (mi != mapAddressBook.end()) {
3235 return mi->second.name;
3238 // A scriptPubKey that doesn't have an entry in the address book is
3239 // associated with the default account ("").
3240 const static std::string DEFAULT_ACCOUNT_NAME;
3241 return DEFAULT_ACCOUNT_NAME;
3245 * Mark old keypool keys as used,
3246 * and generate all new keys
3248 bool CWallet::NewKeyPool()
3251 LOCK(cs_wallet);
3252 CWalletDB walletdb(*dbw);
3254 for (int64_t nIndex : setInternalKeyPool) {
3255 walletdb.ErasePool(nIndex);
3257 setInternalKeyPool.clear();
3259 for (int64_t nIndex : setExternalKeyPool) {
3260 walletdb.ErasePool(nIndex);
3262 setExternalKeyPool.clear();
3264 m_pool_key_to_index.clear();
3266 if (!TopUpKeyPool()) {
3267 return false;
3269 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3271 return true;
3274 size_t CWallet::KeypoolCountExternalKeys()
3276 AssertLockHeld(cs_wallet); // setExternalKeyPool
3277 return setExternalKeyPool.size();
3280 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3282 AssertLockHeld(cs_wallet);
3283 if (keypool.fInternal) {
3284 setInternalKeyPool.insert(nIndex);
3285 } else {
3286 setExternalKeyPool.insert(nIndex);
3288 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3289 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3291 // If no metadata exists yet, create a default with the pool key's
3292 // creation time. Note that this may be overwritten by actually
3293 // stored metadata for that key later, which is fine.
3294 CKeyID keyid = keypool.vchPubKey.GetID();
3295 if (mapKeyMetadata.count(keyid) == 0)
3296 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3299 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3302 LOCK(cs_wallet);
3304 if (IsLocked())
3305 return false;
3307 // Top up key pool
3308 unsigned int nTargetSize;
3309 if (kpSize > 0)
3310 nTargetSize = kpSize;
3311 else
3312 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3314 // count amount of available keys (internal, external)
3315 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3316 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3317 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3319 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3321 // don't create extra internal keys
3322 missingInternal = 0;
3324 bool internal = false;
3325 CWalletDB walletdb(*dbw);
3326 for (int64_t i = missingInternal + missingExternal; i--;)
3328 if (i < missingInternal) {
3329 internal = true;
3332 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3333 int64_t index = ++m_max_keypool_index;
3335 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3336 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3337 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3340 if (internal) {
3341 setInternalKeyPool.insert(index);
3342 } else {
3343 setExternalKeyPool.insert(index);
3345 m_pool_key_to_index[pubkey.GetID()] = index;
3347 if (missingInternal + missingExternal > 0) {
3348 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3351 return true;
3354 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3356 nIndex = -1;
3357 keypool.vchPubKey = CPubKey();
3359 LOCK(cs_wallet);
3361 if (!IsLocked())
3362 TopUpKeyPool();
3364 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3365 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3367 // Get the oldest key
3368 if(setKeyPool.empty())
3369 return;
3371 CWalletDB walletdb(*dbw);
3373 auto it = setKeyPool.begin();
3374 nIndex = *it;
3375 setKeyPool.erase(it);
3376 if (!walletdb.ReadPool(nIndex, keypool)) {
3377 throw std::runtime_error(std::string(__func__) + ": read failed");
3379 if (!HaveKey(keypool.vchPubKey.GetID())) {
3380 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3382 if (keypool.fInternal != fReturningInternal) {
3383 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3386 assert(keypool.vchPubKey.IsValid());
3387 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3388 LogPrintf("keypool reserve %d\n", nIndex);
3392 void CWallet::KeepKey(int64_t nIndex)
3394 // Remove from key pool
3395 CWalletDB walletdb(*dbw);
3396 walletdb.ErasePool(nIndex);
3397 LogPrintf("keypool keep %d\n", nIndex);
3400 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3402 // Return to key pool
3404 LOCK(cs_wallet);
3405 if (fInternal) {
3406 setInternalKeyPool.insert(nIndex);
3407 } else {
3408 setExternalKeyPool.insert(nIndex);
3410 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3412 LogPrintf("keypool return %d\n", nIndex);
3415 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3417 CKeyPool keypool;
3419 LOCK(cs_wallet);
3420 int64_t nIndex = 0;
3421 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3422 if (nIndex == -1)
3424 if (IsLocked()) return false;
3425 CWalletDB walletdb(*dbw);
3426 result = GenerateNewKey(walletdb, internal);
3427 return true;
3429 KeepKey(nIndex);
3430 result = keypool.vchPubKey;
3432 return true;
3435 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3436 if (setKeyPool.empty()) {
3437 return GetTime();
3440 CKeyPool keypool;
3441 int64_t nIndex = *(setKeyPool.begin());
3442 if (!walletdb.ReadPool(nIndex, keypool)) {
3443 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3445 assert(keypool.vchPubKey.IsValid());
3446 return keypool.nTime;
3449 int64_t CWallet::GetOldestKeyPoolTime()
3451 LOCK(cs_wallet);
3453 CWalletDB walletdb(*dbw);
3455 // load oldest key from keypool, get time and return
3456 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3457 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3458 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3461 return oldestKey;
3464 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3466 std::map<CTxDestination, CAmount> balances;
3469 LOCK(cs_wallet);
3470 for (const auto& walletEntry : mapWallet)
3472 const CWalletTx *pcoin = &walletEntry.second;
3474 if (!pcoin->IsTrusted())
3475 continue;
3477 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3478 continue;
3480 int nDepth = pcoin->GetDepthInMainChain();
3481 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3482 continue;
3484 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3486 CTxDestination addr;
3487 if (!IsMine(pcoin->tx->vout[i]))
3488 continue;
3489 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3490 continue;
3492 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3494 if (!balances.count(addr))
3495 balances[addr] = 0;
3496 balances[addr] += n;
3501 return balances;
3504 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3506 AssertLockHeld(cs_wallet); // mapWallet
3507 std::set< std::set<CTxDestination> > groupings;
3508 std::set<CTxDestination> grouping;
3510 for (const auto& walletEntry : mapWallet)
3512 const CWalletTx *pcoin = &walletEntry.second;
3514 if (pcoin->tx->vin.size() > 0)
3516 bool any_mine = false;
3517 // group all input addresses with each other
3518 for (CTxIn txin : pcoin->tx->vin)
3520 CTxDestination address;
3521 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3522 continue;
3523 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3524 continue;
3525 grouping.insert(address);
3526 any_mine = true;
3529 // group change with input addresses
3530 if (any_mine)
3532 for (CTxOut txout : pcoin->tx->vout)
3533 if (IsChange(txout))
3535 CTxDestination txoutAddr;
3536 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3537 continue;
3538 grouping.insert(txoutAddr);
3541 if (grouping.size() > 0)
3543 groupings.insert(grouping);
3544 grouping.clear();
3548 // group lone addrs by themselves
3549 for (const auto& txout : pcoin->tx->vout)
3550 if (IsMine(txout))
3552 CTxDestination address;
3553 if(!ExtractDestination(txout.scriptPubKey, address))
3554 continue;
3555 grouping.insert(address);
3556 groupings.insert(grouping);
3557 grouping.clear();
3561 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3562 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3563 for (std::set<CTxDestination> _grouping : groupings)
3565 // make a set of all the groups hit by this new group
3566 std::set< std::set<CTxDestination>* > hits;
3567 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3568 for (CTxDestination address : _grouping)
3569 if ((it = setmap.find(address)) != setmap.end())
3570 hits.insert((*it).second);
3572 // merge all hit groups into a new single group and delete old groups
3573 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3574 for (std::set<CTxDestination>* hit : hits)
3576 merged->insert(hit->begin(), hit->end());
3577 uniqueGroupings.erase(hit);
3578 delete hit;
3580 uniqueGroupings.insert(merged);
3582 // update setmap
3583 for (CTxDestination element : *merged)
3584 setmap[element] = merged;
3587 std::set< std::set<CTxDestination> > ret;
3588 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3590 ret.insert(*uniqueGrouping);
3591 delete uniqueGrouping;
3594 return ret;
3597 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3599 LOCK(cs_wallet);
3600 std::set<CTxDestination> result;
3601 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3603 const CTxDestination& address = item.first;
3604 const std::string& strName = item.second.name;
3605 if (strName == strAccount)
3606 result.insert(address);
3608 return result;
3611 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3613 if (nIndex == -1)
3615 CKeyPool keypool;
3616 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3617 if (nIndex != -1)
3618 vchPubKey = keypool.vchPubKey;
3619 else {
3620 return false;
3622 fInternal = keypool.fInternal;
3624 assert(vchPubKey.IsValid());
3625 pubkey = vchPubKey;
3626 return true;
3629 void CReserveKey::KeepKey()
3631 if (nIndex != -1)
3632 pwallet->KeepKey(nIndex);
3633 nIndex = -1;
3634 vchPubKey = CPubKey();
3637 void CReserveKey::ReturnKey()
3639 if (nIndex != -1) {
3640 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3642 nIndex = -1;
3643 vchPubKey = CPubKey();
3646 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3648 AssertLockHeld(cs_wallet);
3649 bool internal = setInternalKeyPool.count(keypool_id);
3650 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3651 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3652 auto it = setKeyPool->begin();
3654 CWalletDB walletdb(*dbw);
3655 while (it != std::end(*setKeyPool)) {
3656 const int64_t& index = *(it);
3657 if (index > keypool_id) break; // set*KeyPool is ordered
3659 CKeyPool keypool;
3660 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3661 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3663 walletdb.ErasePool(index);
3664 LogPrintf("keypool index %d removed\n", index);
3665 it = setKeyPool->erase(it);
3669 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3671 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3672 CPubKey pubkey;
3673 if (!rKey->GetReservedKey(pubkey))
3674 return;
3676 script = rKey;
3677 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3680 void CWallet::LockCoin(const COutPoint& output)
3682 AssertLockHeld(cs_wallet); // setLockedCoins
3683 setLockedCoins.insert(output);
3686 void CWallet::UnlockCoin(const COutPoint& output)
3688 AssertLockHeld(cs_wallet); // setLockedCoins
3689 setLockedCoins.erase(output);
3692 void CWallet::UnlockAllCoins()
3694 AssertLockHeld(cs_wallet); // setLockedCoins
3695 setLockedCoins.clear();
3698 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3700 AssertLockHeld(cs_wallet); // setLockedCoins
3701 COutPoint outpt(hash, n);
3703 return (setLockedCoins.count(outpt) > 0);
3706 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3708 AssertLockHeld(cs_wallet); // setLockedCoins
3709 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3710 it != setLockedCoins.end(); it++) {
3711 COutPoint outpt = (*it);
3712 vOutpts.push_back(outpt);
3716 /** @} */ // end of Actions
3718 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3719 AssertLockHeld(cs_wallet); // mapKeyMetadata
3720 mapKeyBirth.clear();
3722 // get birth times for keys with metadata
3723 for (const auto& entry : mapKeyMetadata) {
3724 if (entry.second.nCreateTime) {
3725 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3729 // map in which we'll infer heights of other keys
3730 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3731 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3732 std::set<CKeyID> setKeys;
3733 GetKeys(setKeys);
3734 for (const CKeyID &keyid : setKeys) {
3735 if (mapKeyBirth.count(keyid) == 0)
3736 mapKeyFirstBlock[keyid] = pindexMax;
3738 setKeys.clear();
3740 // if there are no such keys, we're done
3741 if (mapKeyFirstBlock.empty())
3742 return;
3744 // find first block that affects those keys, if there are any left
3745 std::vector<CKeyID> vAffected;
3746 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3747 // iterate over all wallet transactions...
3748 const CWalletTx &wtx = (*it).second;
3749 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3750 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3751 // ... which are already in a block
3752 int nHeight = blit->second->nHeight;
3753 for (const CTxOut &txout : wtx.tx->vout) {
3754 // iterate over all their outputs
3755 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3756 for (const CKeyID &keyid : vAffected) {
3757 // ... and all their affected keys
3758 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3759 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3760 rit->second = blit->second;
3762 vAffected.clear();
3767 // Extract block timestamps for those keys
3768 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3769 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3773 * Compute smart timestamp for a transaction being added to the wallet.
3775 * Logic:
3776 * - If sending a transaction, assign its timestamp to the current time.
3777 * - If receiving a transaction outside a block, assign its timestamp to the
3778 * current time.
3779 * - If receiving a block with a future timestamp, assign all its (not already
3780 * known) transactions' timestamps to the current time.
3781 * - If receiving a block with a past timestamp, before the most recent known
3782 * transaction (that we care about), assign all its (not already known)
3783 * transactions' timestamps to the same timestamp as that most-recent-known
3784 * transaction.
3785 * - If receiving a block with a past timestamp, but after the most recent known
3786 * transaction, assign all its (not already known) transactions' timestamps to
3787 * the block time.
3789 * For more information see CWalletTx::nTimeSmart,
3790 * https://bitcointalk.org/?topic=54527, or
3791 * https://github.com/bitcoin/bitcoin/pull/1393.
3793 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3795 unsigned int nTimeSmart = wtx.nTimeReceived;
3796 if (!wtx.hashUnset()) {
3797 if (mapBlockIndex.count(wtx.hashBlock)) {
3798 int64_t latestNow = wtx.nTimeReceived;
3799 int64_t latestEntry = 0;
3801 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3802 int64_t latestTolerated = latestNow + 300;
3803 const TxItems& txOrdered = wtxOrdered;
3804 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3805 CWalletTx* const pwtx = it->second.first;
3806 if (pwtx == &wtx) {
3807 continue;
3809 CAccountingEntry* const pacentry = it->second.second;
3810 int64_t nSmartTime;
3811 if (pwtx) {
3812 nSmartTime = pwtx->nTimeSmart;
3813 if (!nSmartTime) {
3814 nSmartTime = pwtx->nTimeReceived;
3816 } else {
3817 nSmartTime = pacentry->nTime;
3819 if (nSmartTime <= latestTolerated) {
3820 latestEntry = nSmartTime;
3821 if (nSmartTime > latestNow) {
3822 latestNow = nSmartTime;
3824 break;
3828 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3829 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3830 } else {
3831 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3834 return nTimeSmart;
3837 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3839 if (boost::get<CNoDestination>(&dest))
3840 return false;
3842 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3843 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3846 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3848 if (!mapAddressBook[dest].destdata.erase(key))
3849 return false;
3850 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3853 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3855 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3856 return true;
3859 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3861 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3862 if(i != mapAddressBook.end())
3864 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3865 if(j != i->second.destdata.end())
3867 if(value)
3868 *value = j->second;
3869 return true;
3872 return false;
3875 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3877 LOCK(cs_wallet);
3878 std::vector<std::string> values;
3879 for (const auto& address : mapAddressBook) {
3880 for (const auto& data : address.second.destdata) {
3881 if (!data.first.compare(0, prefix.size(), prefix)) {
3882 values.emplace_back(data.second);
3886 return values;
3889 std::string CWallet::GetWalletHelpString(bool showDebug)
3891 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3892 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3893 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3894 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3895 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3896 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). "
3897 "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"),
3898 CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3899 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3900 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3901 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3902 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3903 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3904 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3905 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3906 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));
3907 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));
3908 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3909 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3910 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3911 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3912 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3913 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3914 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3916 if (showDebug)
3918 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3920 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3921 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3922 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3923 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3926 return strUsage;
3929 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3931 // needed to restore wallet transaction meta data after -zapwallettxes
3932 std::vector<CWalletTx> vWtx;
3934 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3935 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3937 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3938 std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
3939 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3940 if (nZapWalletRet != DB_LOAD_OK) {
3941 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3942 return nullptr;
3946 uiInterface.InitMessage(_("Loading wallet..."));
3948 int64_t nStart = GetTimeMillis();
3949 bool fFirstRun = true;
3950 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3951 CWallet *walletInstance = new CWallet(std::move(dbw));
3952 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3953 if (nLoadWalletRet != DB_LOAD_OK)
3955 if (nLoadWalletRet == DB_CORRUPT) {
3956 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3957 return nullptr;
3959 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3961 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3962 " or address book entries might be missing or incorrect."),
3963 walletFile));
3965 else if (nLoadWalletRet == DB_TOO_NEW) {
3966 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3967 return nullptr;
3969 else if (nLoadWalletRet == DB_NEED_REWRITE)
3971 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3972 return nullptr;
3974 else {
3975 InitError(strprintf(_("Error loading %s"), walletFile));
3976 return nullptr;
3980 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3982 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3983 if (nMaxVersion == 0) // the -upgradewallet without argument case
3985 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3986 nMaxVersion = CLIENT_VERSION;
3987 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3989 else
3990 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3991 if (nMaxVersion < walletInstance->GetVersion())
3993 InitError(_("Cannot downgrade wallet"));
3994 return nullptr;
3996 walletInstance->SetMaxVersion(nMaxVersion);
3999 if (fFirstRun)
4001 // Create new keyUser and set as default key
4002 if (gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
4004 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
4005 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
4007 // generate a new master key
4008 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
4009 if (!walletInstance->SetHDMasterKey(masterPubKey))
4010 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
4013 // Top up the keypool
4014 if (!walletInstance->TopUpKeyPool()) {
4015 InitError(_("Unable to generate initial keys") += "\n");
4016 return NULL;
4019 walletInstance->SetBestChain(chainActive.GetLocator());
4021 else if (gArgs.IsArgSet("-usehd")) {
4022 bool useHD = gArgs.GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
4023 if (walletInstance->IsHDEnabled() && !useHD) {
4024 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
4025 return nullptr;
4027 if (!walletInstance->IsHDEnabled() && useHD) {
4028 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
4029 return nullptr;
4033 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
4035 RegisterValidationInterface(walletInstance);
4037 // Try to top up keypool. No-op if the wallet is locked.
4038 walletInstance->TopUpKeyPool();
4040 CBlockIndex *pindexRescan = chainActive.Genesis();
4041 if (!gArgs.GetBoolArg("-rescan", false))
4043 CWalletDB walletdb(*walletInstance->dbw);
4044 CBlockLocator locator;
4045 if (walletdb.ReadBestBlock(locator))
4046 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4048 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
4050 //We can't rescan beyond non-pruned blocks, stop and throw an error
4051 //this might happen if a user uses an old wallet within a pruned node
4052 // or if he ran -disablewallet for a longer time, then decided to re-enable
4053 if (fPruneMode)
4055 CBlockIndex *block = chainActive.Tip();
4056 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4057 block = block->pprev;
4059 if (pindexRescan != block) {
4060 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4061 return nullptr;
4065 uiInterface.InitMessage(_("Rescanning..."));
4066 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4068 // No need to read and scan block if block was created before
4069 // our wallet birthday (as adjusted for block time variability)
4070 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4071 pindexRescan = chainActive.Next(pindexRescan);
4074 nStart = GetTimeMillis();
4075 walletInstance->ScanForWalletTransactions(pindexRescan, true);
4076 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4077 walletInstance->SetBestChain(chainActive.GetLocator());
4078 walletInstance->dbw->IncrementUpdateCounter();
4080 // Restore wallet transaction metadata after -zapwallettxes=1
4081 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
4083 CWalletDB walletdb(*walletInstance->dbw);
4085 for (const CWalletTx& wtxOld : vWtx)
4087 uint256 hash = wtxOld.GetHash();
4088 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4089 if (mi != walletInstance->mapWallet.end())
4091 const CWalletTx* copyFrom = &wtxOld;
4092 CWalletTx* copyTo = &mi->second;
4093 copyTo->mapValue = copyFrom->mapValue;
4094 copyTo->vOrderForm = copyFrom->vOrderForm;
4095 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4096 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4097 copyTo->fFromMe = copyFrom->fFromMe;
4098 copyTo->strFromAccount = copyFrom->strFromAccount;
4099 copyTo->nOrderPos = copyFrom->nOrderPos;
4100 walletdb.WriteTx(*copyTo);
4105 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4108 LOCK(walletInstance->cs_wallet);
4109 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4110 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4111 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4114 return walletInstance;
4117 bool CWallet::InitLoadWallet()
4119 if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4120 LogPrintf("Wallet disabled!\n");
4121 return true;
4124 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4125 CWallet * const pwallet = CreateWalletFromFile(walletFile);
4126 if (!pwallet) {
4127 return false;
4129 vpwallets.push_back(pwallet);
4132 return true;
4135 std::atomic<bool> CWallet::fFlushScheduled(false);
4137 void CWallet::postInitProcess(CScheduler& scheduler)
4139 // Add wallet transactions that aren't already in a block to mempool
4140 // Do this here as mempool requires genesis block to be loaded
4141 ReacceptWalletTransactions();
4143 // Run a thread to flush wallet periodically
4144 if (!CWallet::fFlushScheduled.exchange(true)) {
4145 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4149 bool CWallet::ParameterInteraction()
4151 gArgs.SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4152 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4154 if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4155 return true;
4157 if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) {
4158 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4161 if (gArgs.GetBoolArg("-salvagewallet", false)) {
4162 if (is_multiwallet) {
4163 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4165 // Rewrite just private keys: rescan to find transactions
4166 if (gArgs.SoftSetBoolArg("-rescan", true)) {
4167 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4171 int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0);
4172 // -zapwallettxes implies dropping the mempool on startup
4173 if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) {
4174 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4177 // -zapwallettxes implies a rescan
4178 if (zapwallettxes != 0) {
4179 if (is_multiwallet) {
4180 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4182 if (gArgs.SoftSetBoolArg("-rescan", true)) {
4183 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4187 if (is_multiwallet) {
4188 if (gArgs.GetBoolArg("-upgradewallet", false)) {
4189 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4193 if (gArgs.GetBoolArg("-sysperms", false))
4194 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4195 if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false))
4196 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4198 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4199 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4200 _("The wallet will avoid paying less than the minimum relay fee."));
4202 if (gArgs.IsArgSet("-mintxfee"))
4204 CAmount n = 0;
4205 if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n)
4206 return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", "")));
4207 if (n > HIGH_TX_FEE_PER_KB)
4208 InitWarning(AmountHighWarn("-mintxfee") + " " +
4209 _("This is the minimum transaction fee you pay on every transaction."));
4210 CWallet::minTxFee = CFeeRate(n);
4212 if (gArgs.IsArgSet("-fallbackfee"))
4214 CAmount nFeePerK = 0;
4215 if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK))
4216 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", "")));
4217 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4218 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4219 _("This is the transaction fee you may pay when fee estimates are not available."));
4220 CWallet::fallbackFee = CFeeRate(nFeePerK);
4222 if (gArgs.IsArgSet("-discardfee"))
4224 CAmount nFeePerK = 0;
4225 if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK))
4226 return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", "")));
4227 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4228 InitWarning(AmountHighWarn("-discardfee") + " " +
4229 _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4230 CWallet::m_discard_rate = CFeeRate(nFeePerK);
4232 if (gArgs.IsArgSet("-paytxfee"))
4234 CAmount nFeePerK = 0;
4235 if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK))
4236 return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", "")));
4237 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4238 InitWarning(AmountHighWarn("-paytxfee") + " " +
4239 _("This is the transaction fee you will pay if you send a transaction."));
4241 payTxFee = CFeeRate(nFeePerK, 1000);
4242 if (payTxFee < ::minRelayTxFee)
4244 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4245 gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4248 if (gArgs.IsArgSet("-maxtxfee"))
4250 CAmount nMaxFee = 0;
4251 if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee))
4252 return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", "")));
4253 if (nMaxFee > HIGH_MAX_TX_FEE)
4254 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4255 maxTxFee = nMaxFee;
4256 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4258 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4259 gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4262 nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4263 bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4264 fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4266 return true;
4269 bool CWallet::BackupWallet(const std::string& strDest)
4271 return dbw->Backup(strDest);
4274 CKeyPool::CKeyPool()
4276 nTime = GetTime();
4277 fInternal = false;
4280 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4282 nTime = GetTime();
4283 vchPubKey = vchPubKeyIn;
4284 fInternal = internalIn;
4287 CWalletKey::CWalletKey(int64_t nExpires)
4289 nTimeCreated = (nExpires ? GetTime() : 0);
4290 nTimeExpires = nExpires;
4293 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4295 // Update the tx's hashBlock
4296 hashBlock = pindex->GetBlockHash();
4298 // set the position of the transaction in the block
4299 nIndex = posInBlock;
4302 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4304 if (hashUnset())
4305 return 0;
4307 AssertLockHeld(cs_main);
4309 // Find the block it claims to be in
4310 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4311 if (mi == mapBlockIndex.end())
4312 return 0;
4313 CBlockIndex* pindex = (*mi).second;
4314 if (!pindex || !chainActive.Contains(pindex))
4315 return 0;
4317 pindexRet = pindex;
4318 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4321 int CMerkleTx::GetBlocksToMaturity() const
4323 if (!IsCoinBase())
4324 return 0;
4325 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4329 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4331 return ::AcceptToMemoryPool(mempool, state, tx, true, nullptr, nullptr, false, nAbsurdFee);