[wallet] keypool mark-used and topup
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobb40dcceda1782ccce9b173389d728f95e14d0993
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 NULL;
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 = NULL;
219 return false;
221 if (needsDB) pwalletdbEncryption = NULL;
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 (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 (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 = NULL;
562 for (TxSpends::iterator it = range.first; it != range.second; ++it)
564 const uint256& hash = it->second;
565 int n = mapWallet[hash].nOrderPos;
566 if (n < nMinOrderPos)
568 nMinOrderPos = n;
569 copyFrom = &mapWallet[hash];
572 // Now copy data from copyFrom to rest:
573 for (TxSpends::iterator it = range.first; it != range.second; ++it)
575 const uint256& hash = it->second;
576 CWalletTx* copyTo = &mapWallet[hash];
577 if (copyFrom == copyTo) continue;
578 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
579 copyTo->mapValue = copyFrom->mapValue;
580 copyTo->vOrderForm = copyFrom->vOrderForm;
581 // fTimeReceivedIsTxTime not copied on purpose
582 // nTimeReceived not copied on purpose
583 copyTo->nTimeSmart = copyFrom->nTimeSmart;
584 copyTo->fFromMe = copyFrom->fFromMe;
585 copyTo->strFromAccount = copyFrom->strFromAccount;
586 // nOrderPos not copied on purpose
587 // cached members not copied on purpose
592 * Outpoint is spent if any non-conflicted transaction
593 * spends it:
595 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
597 const COutPoint outpoint(hash, n);
598 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
599 range = mapTxSpends.equal_range(outpoint);
601 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
603 const uint256& wtxid = it->second;
604 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
605 if (mit != mapWallet.end()) {
606 int depth = mit->second.GetDepthInMainChain();
607 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
608 return true; // Spent
611 return false;
614 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
616 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
618 std::pair<TxSpends::iterator, TxSpends::iterator> range;
619 range = mapTxSpends.equal_range(outpoint);
620 SyncMetaData(range);
624 void CWallet::AddToSpends(const uint256& wtxid)
626 assert(mapWallet.count(wtxid));
627 CWalletTx& thisTx = mapWallet[wtxid];
628 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
629 return;
631 for (const CTxIn& txin : thisTx.tx->vin)
632 AddToSpends(txin.prevout, wtxid);
635 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
637 if (IsCrypted())
638 return false;
640 CKeyingMaterial _vMasterKey;
642 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
643 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
645 CMasterKey kMasterKey;
647 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
648 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
650 CCrypter crypter;
651 int64_t nStartTime = GetTimeMillis();
652 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
653 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
655 nStartTime = GetTimeMillis();
656 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
657 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
659 if (kMasterKey.nDeriveIterations < 25000)
660 kMasterKey.nDeriveIterations = 25000;
662 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
664 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
665 return false;
666 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
667 return false;
670 LOCK(cs_wallet);
671 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
672 assert(!pwalletdbEncryption);
673 pwalletdbEncryption = new CWalletDB(*dbw);
674 if (!pwalletdbEncryption->TxnBegin()) {
675 delete pwalletdbEncryption;
676 pwalletdbEncryption = NULL;
677 return false;
679 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
681 if (!EncryptKeys(_vMasterKey))
683 pwalletdbEncryption->TxnAbort();
684 delete pwalletdbEncryption;
685 // We now probably have half of our keys encrypted in memory, and half not...
686 // die and let the user reload the unencrypted wallet.
687 assert(false);
690 // Encryption was introduced in version 0.4.0
691 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
693 if (!pwalletdbEncryption->TxnCommit()) {
694 delete pwalletdbEncryption;
695 // We now have keys encrypted in memory, but not on disk...
696 // die to avoid confusion and let the user reload the unencrypted wallet.
697 assert(false);
700 delete pwalletdbEncryption;
701 pwalletdbEncryption = NULL;
703 Lock();
704 Unlock(strWalletPassphrase);
706 // if we are using HD, replace the HD master key (seed) with a new one
707 if (IsHDEnabled()) {
708 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
709 return false;
713 NewKeyPool();
714 Lock();
716 // Need to completely rewrite the wallet file; if we don't, bdb might keep
717 // bits of the unencrypted private key in slack space in the database file.
718 dbw->Rewrite();
721 NotifyStatusChanged(this);
723 return true;
726 DBErrors CWallet::ReorderTransactions()
728 LOCK(cs_wallet);
729 CWalletDB walletdb(*dbw);
731 // Old wallets didn't have any defined order for transactions
732 // Probably a bad idea to change the output of this
734 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
735 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
736 typedef std::multimap<int64_t, TxPair > TxItems;
737 TxItems txByTime;
739 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
741 CWalletTx* wtx = &((*it).second);
742 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
744 std::list<CAccountingEntry> acentries;
745 walletdb.ListAccountCreditDebit("", acentries);
746 for (CAccountingEntry& entry : acentries)
748 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
751 nOrderPosNext = 0;
752 std::vector<int64_t> nOrderPosOffsets;
753 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
755 CWalletTx *const pwtx = (*it).second.first;
756 CAccountingEntry *const pacentry = (*it).second.second;
757 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
759 if (nOrderPos == -1)
761 nOrderPos = nOrderPosNext++;
762 nOrderPosOffsets.push_back(nOrderPos);
764 if (pwtx)
766 if (!walletdb.WriteTx(*pwtx))
767 return DB_LOAD_FAIL;
769 else
770 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
771 return DB_LOAD_FAIL;
773 else
775 int64_t nOrderPosOff = 0;
776 for (const int64_t& nOffsetStart : nOrderPosOffsets)
778 if (nOrderPos >= nOffsetStart)
779 ++nOrderPosOff;
781 nOrderPos += nOrderPosOff;
782 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
784 if (!nOrderPosOff)
785 continue;
787 // Since we're changing the order, write it back
788 if (pwtx)
790 if (!walletdb.WriteTx(*pwtx))
791 return DB_LOAD_FAIL;
793 else
794 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
795 return DB_LOAD_FAIL;
798 walletdb.WriteOrderPosNext(nOrderPosNext);
800 return DB_LOAD_OK;
803 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
805 AssertLockHeld(cs_wallet); // nOrderPosNext
806 int64_t nRet = nOrderPosNext++;
807 if (pwalletdb) {
808 pwalletdb->WriteOrderPosNext(nOrderPosNext);
809 } else {
810 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
812 return nRet;
815 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
817 CWalletDB walletdb(*dbw);
818 if (!walletdb.TxnBegin())
819 return false;
821 int64_t nNow = GetAdjustedTime();
823 // Debit
824 CAccountingEntry debit;
825 debit.nOrderPos = IncOrderPosNext(&walletdb);
826 debit.strAccount = strFrom;
827 debit.nCreditDebit = -nAmount;
828 debit.nTime = nNow;
829 debit.strOtherAccount = strTo;
830 debit.strComment = strComment;
831 AddAccountingEntry(debit, &walletdb);
833 // Credit
834 CAccountingEntry credit;
835 credit.nOrderPos = IncOrderPosNext(&walletdb);
836 credit.strAccount = strTo;
837 credit.nCreditDebit = nAmount;
838 credit.nTime = nNow;
839 credit.strOtherAccount = strFrom;
840 credit.strComment = strComment;
841 AddAccountingEntry(credit, &walletdb);
843 if (!walletdb.TxnCommit())
844 return false;
846 return true;
849 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
851 CWalletDB walletdb(*dbw);
853 CAccount account;
854 walletdb.ReadAccount(strAccount, account);
856 if (!bForceNew) {
857 if (!account.vchPubKey.IsValid())
858 bForceNew = true;
859 else {
860 // Check if the current key has been used
861 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
862 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
863 it != mapWallet.end() && account.vchPubKey.IsValid();
864 ++it)
865 for (const CTxOut& txout : (*it).second.tx->vout)
866 if (txout.scriptPubKey == scriptPubKey) {
867 bForceNew = true;
868 break;
873 // Generate a new key
874 if (bForceNew) {
875 if (!GetKeyFromPool(account.vchPubKey, false))
876 return false;
878 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
879 walletdb.WriteAccount(strAccount, account);
882 pubKey = account.vchPubKey;
884 return true;
887 void CWallet::MarkDirty()
890 LOCK(cs_wallet);
891 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
892 item.second.MarkDirty();
896 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
898 LOCK(cs_wallet);
900 auto mi = mapWallet.find(originalHash);
902 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
903 assert(mi != mapWallet.end());
905 CWalletTx& wtx = (*mi).second;
907 // Ensure for now that we're not overwriting data
908 assert(wtx.mapValue.count("replaced_by_txid") == 0);
910 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
912 CWalletDB walletdb(*dbw, "r+");
914 bool success = true;
915 if (!walletdb.WriteTx(wtx)) {
916 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
917 success = false;
920 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
922 return success;
925 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
927 LOCK(cs_wallet);
929 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
931 uint256 hash = wtxIn.GetHash();
933 // Inserts only if not already there, returns tx inserted or tx found
934 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
935 CWalletTx& wtx = (*ret.first).second;
936 wtx.BindWallet(this);
937 bool fInsertedNew = ret.second;
938 if (fInsertedNew)
940 wtx.nTimeReceived = GetAdjustedTime();
941 wtx.nOrderPos = IncOrderPosNext(&walletdb);
942 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
943 wtx.nTimeSmart = ComputeTimeSmart(wtx);
944 AddToSpends(hash);
947 bool fUpdated = false;
948 if (!fInsertedNew)
950 // Merge
951 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
953 wtx.hashBlock = wtxIn.hashBlock;
954 fUpdated = true;
956 // If no longer abandoned, update
957 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
959 wtx.hashBlock = wtxIn.hashBlock;
960 fUpdated = true;
962 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
964 wtx.nIndex = wtxIn.nIndex;
965 fUpdated = true;
967 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
969 wtx.fFromMe = wtxIn.fFromMe;
970 fUpdated = true;
974 //// debug print
975 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
977 // Write to disk
978 if (fInsertedNew || fUpdated)
979 if (!walletdb.WriteTx(wtx))
980 return false;
982 // Break debit/credit balance caches:
983 wtx.MarkDirty();
985 // Notify UI of new or updated transaction
986 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
988 // notify an external script when a wallet transaction comes in or is updated
989 std::string strCmd = GetArg("-walletnotify", "");
991 if ( !strCmd.empty())
993 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
994 boost::thread t(runCommand, strCmd); // thread runs free
997 return true;
1000 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
1002 uint256 hash = wtxIn.GetHash();
1004 mapWallet[hash] = wtxIn;
1005 CWalletTx& wtx = mapWallet[hash];
1006 wtx.BindWallet(this);
1007 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1008 AddToSpends(hash);
1009 for (const CTxIn& txin : wtx.tx->vin) {
1010 if (mapWallet.count(txin.prevout.hash)) {
1011 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
1012 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1013 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1018 return true;
1022 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1023 * be set when the transaction was known to be included in a block. When
1024 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
1025 * notifications happen and cached balances are marked dirty.
1027 * If fUpdate is true, existing transactions will be updated.
1028 * TODO: One exception to this is that the abandoned state is cleared under the
1029 * assumption that any further notification of a transaction that was considered
1030 * abandoned is an indication that it is not safe to be considered abandoned.
1031 * Abandoned state should probably be more carefully tracked via different
1032 * posInBlock signals or by checking mempool presence when necessary.
1034 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1036 const CTransaction& tx = *ptx;
1038 AssertLockHeld(cs_wallet);
1040 if (pIndex != NULL) {
1041 for (const CTxIn& txin : tx.vin) {
1042 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1043 while (range.first != range.second) {
1044 if (range.first->second != tx.GetHash()) {
1045 LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1046 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1048 range.first++;
1053 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1054 if (fExisted && !fUpdate) return false;
1055 if (fExisted || IsMine(tx) || IsFromMe(tx))
1057 /* Check if any keys in the wallet keypool that were supposed to be unused
1058 * have appeared in a new transaction. If so, remove those keys from the keypool.
1059 * This can happen when restoring an old wallet backup that does not contain
1060 * the mostly recently created transactions from newer versions of the wallet.
1063 // loop though all outputs
1064 for (const CTxOut& txout: tx.vout) {
1065 // extract addresses and check if they match with an unused keypool key
1066 std::vector<CKeyID> vAffected;
1067 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1068 for (const CKeyID &keyid : vAffected) {
1069 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1070 if (mi != m_pool_key_to_index.end()) {
1071 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1072 MarkReserveKeysAsUsed(mi->second);
1074 if (!TopUpKeyPool()) {
1075 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1081 CWalletTx wtx(this, ptx);
1083 // Get merkle branch if transaction was found in a block
1084 if (pIndex != NULL)
1085 wtx.SetMerkleBranch(pIndex, posInBlock);
1087 return AddToWallet(wtx, false);
1090 return false;
1093 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1095 LOCK2(cs_main, cs_wallet);
1096 const CWalletTx* wtx = GetWalletTx(hashTx);
1097 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1100 bool CWallet::AbandonTransaction(const uint256& hashTx)
1102 LOCK2(cs_main, cs_wallet);
1104 CWalletDB walletdb(*dbw, "r+");
1106 std::set<uint256> todo;
1107 std::set<uint256> done;
1109 // Can't mark abandoned if confirmed or in mempool
1110 assert(mapWallet.count(hashTx));
1111 CWalletTx& origtx = mapWallet[hashTx];
1112 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1113 return false;
1116 todo.insert(hashTx);
1118 while (!todo.empty()) {
1119 uint256 now = *todo.begin();
1120 todo.erase(now);
1121 done.insert(now);
1122 assert(mapWallet.count(now));
1123 CWalletTx& wtx = mapWallet[now];
1124 int currentconfirm = wtx.GetDepthInMainChain();
1125 // If the orig tx was not in block, none of its spends can be
1126 assert(currentconfirm <= 0);
1127 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1128 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1129 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1130 assert(!wtx.InMempool());
1131 wtx.nIndex = -1;
1132 wtx.setAbandoned();
1133 wtx.MarkDirty();
1134 walletdb.WriteTx(wtx);
1135 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1136 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1137 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1138 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1139 if (!done.count(iter->second)) {
1140 todo.insert(iter->second);
1142 iter++;
1144 // If a transaction changes 'conflicted' state, that changes the balance
1145 // available of the outputs it spends. So force those to be recomputed
1146 for (const CTxIn& txin : wtx.tx->vin)
1148 if (mapWallet.count(txin.prevout.hash))
1149 mapWallet[txin.prevout.hash].MarkDirty();
1154 return true;
1157 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1159 LOCK2(cs_main, cs_wallet);
1161 int conflictconfirms = 0;
1162 if (mapBlockIndex.count(hashBlock)) {
1163 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1164 if (chainActive.Contains(pindex)) {
1165 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1168 // If number of conflict confirms cannot be determined, this means
1169 // that the block is still unknown or not yet part of the main chain,
1170 // for example when loading the wallet during a reindex. Do nothing in that
1171 // case.
1172 if (conflictconfirms >= 0)
1173 return;
1175 // Do not flush the wallet here for performance reasons
1176 CWalletDB walletdb(*dbw, "r+", false);
1178 std::set<uint256> todo;
1179 std::set<uint256> done;
1181 todo.insert(hashTx);
1183 while (!todo.empty()) {
1184 uint256 now = *todo.begin();
1185 todo.erase(now);
1186 done.insert(now);
1187 assert(mapWallet.count(now));
1188 CWalletTx& wtx = mapWallet[now];
1189 int currentconfirm = wtx.GetDepthInMainChain();
1190 if (conflictconfirms < currentconfirm) {
1191 // Block is 'more conflicted' than current confirm; update.
1192 // Mark transaction as conflicted with this block.
1193 wtx.nIndex = -1;
1194 wtx.hashBlock = hashBlock;
1195 wtx.MarkDirty();
1196 walletdb.WriteTx(wtx);
1197 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1198 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1199 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1200 if (!done.count(iter->second)) {
1201 todo.insert(iter->second);
1203 iter++;
1205 // If a transaction changes 'conflicted' state, that changes the balance
1206 // available of the outputs it spends. So force those to be recomputed
1207 for (const CTxIn& txin : wtx.tx->vin)
1209 if (mapWallet.count(txin.prevout.hash))
1210 mapWallet[txin.prevout.hash].MarkDirty();
1216 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1217 const CTransaction& tx = *ptx;
1219 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1220 return; // Not one of ours
1222 // If a transaction changes 'conflicted' state, that changes the balance
1223 // available of the outputs it spends. So force those to be
1224 // recomputed, also:
1225 for (const CTxIn& txin : tx.vin)
1227 if (mapWallet.count(txin.prevout.hash))
1228 mapWallet[txin.prevout.hash].MarkDirty();
1232 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1233 LOCK2(cs_main, cs_wallet);
1234 SyncTransaction(ptx);
1237 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1238 LOCK2(cs_main, cs_wallet);
1239 // TODO: Temporarily ensure that mempool removals are notified before
1240 // connected transactions. This shouldn't matter, but the abandoned
1241 // state of transactions in our wallet is currently cleared when we
1242 // receive another notification and there is a race condition where
1243 // notification of a connected conflict might cause an outside process
1244 // to abandon a transaction and then have it inadvertently cleared by
1245 // the notification that the conflicted transaction was evicted.
1247 for (const CTransactionRef& ptx : vtxConflicted) {
1248 SyncTransaction(ptx);
1250 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1251 SyncTransaction(pblock->vtx[i], pindex, i);
1255 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1256 LOCK2(cs_main, cs_wallet);
1258 for (const CTransactionRef& ptx : pblock->vtx) {
1259 SyncTransaction(ptx);
1265 isminetype CWallet::IsMine(const CTxIn &txin) const
1268 LOCK(cs_wallet);
1269 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1270 if (mi != mapWallet.end())
1272 const CWalletTx& prev = (*mi).second;
1273 if (txin.prevout.n < prev.tx->vout.size())
1274 return IsMine(prev.tx->vout[txin.prevout.n]);
1277 return ISMINE_NO;
1280 // Note that this function doesn't distinguish between a 0-valued input,
1281 // and a not-"is mine" (according to the filter) input.
1282 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1285 LOCK(cs_wallet);
1286 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1287 if (mi != mapWallet.end())
1289 const CWalletTx& prev = (*mi).second;
1290 if (txin.prevout.n < prev.tx->vout.size())
1291 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1292 return prev.tx->vout[txin.prevout.n].nValue;
1295 return 0;
1298 isminetype CWallet::IsMine(const CTxOut& txout) const
1300 return ::IsMine(*this, txout.scriptPubKey);
1303 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1305 if (!MoneyRange(txout.nValue))
1306 throw std::runtime_error(std::string(__func__) + ": value out of range");
1307 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1310 bool CWallet::IsChange(const CTxOut& txout) const
1312 // TODO: fix handling of 'change' outputs. The assumption is that any
1313 // payment to a script that is ours, but is not in the address book
1314 // is change. That assumption is likely to break when we implement multisignature
1315 // wallets that return change back into a multi-signature-protected address;
1316 // a better way of identifying which outputs are 'the send' and which are
1317 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1318 // which output, if any, was change).
1319 if (::IsMine(*this, txout.scriptPubKey))
1321 CTxDestination address;
1322 if (!ExtractDestination(txout.scriptPubKey, address))
1323 return true;
1325 LOCK(cs_wallet);
1326 if (!mapAddressBook.count(address))
1327 return true;
1329 return false;
1332 CAmount CWallet::GetChange(const CTxOut& txout) const
1334 if (!MoneyRange(txout.nValue))
1335 throw std::runtime_error(std::string(__func__) + ": value out of range");
1336 return (IsChange(txout) ? txout.nValue : 0);
1339 bool CWallet::IsMine(const CTransaction& tx) const
1341 for (const CTxOut& txout : tx.vout)
1342 if (IsMine(txout))
1343 return true;
1344 return false;
1347 bool CWallet::IsFromMe(const CTransaction& tx) const
1349 return (GetDebit(tx, ISMINE_ALL) > 0);
1352 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1354 CAmount nDebit = 0;
1355 for (const CTxIn& txin : tx.vin)
1357 nDebit += GetDebit(txin, filter);
1358 if (!MoneyRange(nDebit))
1359 throw std::runtime_error(std::string(__func__) + ": value out of range");
1361 return nDebit;
1364 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1366 LOCK(cs_wallet);
1368 for (const CTxIn& txin : tx.vin)
1370 auto mi = mapWallet.find(txin.prevout.hash);
1371 if (mi == mapWallet.end())
1372 return false; // any unknown inputs can't be from us
1374 const CWalletTx& prev = (*mi).second;
1376 if (txin.prevout.n >= prev.tx->vout.size())
1377 return false; // invalid input!
1379 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1380 return false;
1382 return true;
1385 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1387 CAmount nCredit = 0;
1388 for (const CTxOut& txout : tx.vout)
1390 nCredit += GetCredit(txout, filter);
1391 if (!MoneyRange(nCredit))
1392 throw std::runtime_error(std::string(__func__) + ": value out of range");
1394 return nCredit;
1397 CAmount CWallet::GetChange(const CTransaction& tx) const
1399 CAmount nChange = 0;
1400 for (const CTxOut& txout : tx.vout)
1402 nChange += GetChange(txout);
1403 if (!MoneyRange(nChange))
1404 throw std::runtime_error(std::string(__func__) + ": value out of range");
1406 return nChange;
1409 CPubKey CWallet::GenerateNewHDMasterKey()
1411 CKey key;
1412 key.MakeNewKey(true);
1414 int64_t nCreationTime = GetTime();
1415 CKeyMetadata metadata(nCreationTime);
1417 // calculate the pubkey
1418 CPubKey pubkey = key.GetPubKey();
1419 assert(key.VerifyPubKey(pubkey));
1421 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1422 metadata.hdKeypath = "m";
1423 metadata.hdMasterKeyID = pubkey.GetID();
1426 LOCK(cs_wallet);
1428 // mem store the metadata
1429 mapKeyMetadata[pubkey.GetID()] = metadata;
1431 // write the key&metadata to the database
1432 if (!AddKeyPubKey(key, pubkey))
1433 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1436 return pubkey;
1439 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1441 LOCK(cs_wallet);
1442 // store the keyid (hash160) together with
1443 // the child index counter in the database
1444 // as a hdchain object
1445 CHDChain newHdChain;
1446 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1447 newHdChain.masterKeyID = pubkey.GetID();
1448 SetHDChain(newHdChain, false);
1450 return true;
1453 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1455 LOCK(cs_wallet);
1456 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1457 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1459 hdChain = chain;
1460 return true;
1463 bool CWallet::IsHDEnabled() const
1465 return !hdChain.masterKeyID.IsNull();
1468 int64_t CWalletTx::GetTxTime() const
1470 int64_t n = nTimeSmart;
1471 return n ? n : nTimeReceived;
1474 int CWalletTx::GetRequestCount() const
1476 // Returns -1 if it wasn't being tracked
1477 int nRequests = -1;
1479 LOCK(pwallet->cs_wallet);
1480 if (IsCoinBase())
1482 // Generated block
1483 if (!hashUnset())
1485 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1486 if (mi != pwallet->mapRequestCount.end())
1487 nRequests = (*mi).second;
1490 else
1492 // Did anyone request this transaction?
1493 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1494 if (mi != pwallet->mapRequestCount.end())
1496 nRequests = (*mi).second;
1498 // How about the block it's in?
1499 if (nRequests == 0 && !hashUnset())
1501 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1502 if (_mi != pwallet->mapRequestCount.end())
1503 nRequests = (*_mi).second;
1504 else
1505 nRequests = 1; // If it's in someone else's block it must have got out
1510 return nRequests;
1513 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1514 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1516 nFee = 0;
1517 listReceived.clear();
1518 listSent.clear();
1519 strSentAccount = strFromAccount;
1521 // Compute fee:
1522 CAmount nDebit = GetDebit(filter);
1523 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1525 CAmount nValueOut = tx->GetValueOut();
1526 nFee = nDebit - nValueOut;
1529 // Sent/received.
1530 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1532 const CTxOut& txout = tx->vout[i];
1533 isminetype fIsMine = pwallet->IsMine(txout);
1534 // Only need to handle txouts if AT LEAST one of these is true:
1535 // 1) they debit from us (sent)
1536 // 2) the output is to us (received)
1537 if (nDebit > 0)
1539 // Don't report 'change' txouts
1540 if (pwallet->IsChange(txout))
1541 continue;
1543 else if (!(fIsMine & filter))
1544 continue;
1546 // In either case, we need to get the destination address
1547 CTxDestination address;
1549 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1551 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1552 this->GetHash().ToString());
1553 address = CNoDestination();
1556 COutputEntry output = {address, txout.nValue, (int)i};
1558 // If we are debited by the transaction, add the output as a "sent" entry
1559 if (nDebit > 0)
1560 listSent.push_back(output);
1562 // If we are receiving the output, add it as a "received" entry
1563 if (fIsMine & filter)
1564 listReceived.push_back(output);
1570 * Scan active chain for relevant transactions after importing keys. This should
1571 * be called whenever new keys are added to the wallet, with the oldest key
1572 * creation time.
1574 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1575 * returned will be higher than startTime if relevant blocks could not be read.
1577 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1579 AssertLockHeld(cs_main);
1580 AssertLockHeld(cs_wallet);
1582 // Find starting block. May be null if nCreateTime is greater than the
1583 // highest blockchain timestamp, in which case there is nothing that needs
1584 // to be scanned.
1585 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1586 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1588 if (startBlock) {
1589 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1590 if (failedBlock) {
1591 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1594 return startTime;
1598 * Scan the block chain (starting in pindexStart) for transactions
1599 * from or to us. If fUpdate is true, found transactions that already
1600 * exist in the wallet will be updated.
1602 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1603 * possible (due to pruning or corruption), returns pointer to the most recent
1604 * block that could not be scanned.
1606 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1608 int64_t nNow = GetTime();
1609 const CChainParams& chainParams = Params();
1611 CBlockIndex* pindex = pindexStart;
1612 CBlockIndex* ret = nullptr;
1614 LOCK2(cs_main, cs_wallet);
1615 fAbortRescan = false;
1616 fScanningWallet = true;
1618 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1619 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1620 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1621 while (pindex && !fAbortRescan)
1623 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1624 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1625 if (GetTime() >= nNow + 60) {
1626 nNow = GetTime();
1627 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1630 CBlock block;
1631 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1632 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1633 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1635 } else {
1636 ret = pindex;
1638 pindex = chainActive.Next(pindex);
1640 if (pindex && fAbortRescan) {
1641 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1643 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1645 fScanningWallet = false;
1647 return ret;
1650 void CWallet::ReacceptWalletTransactions()
1652 // If transactions aren't being broadcasted, don't let them into local mempool either
1653 if (!fBroadcastTransactions)
1654 return;
1655 LOCK2(cs_main, cs_wallet);
1656 std::map<int64_t, CWalletTx*> mapSorted;
1658 // Sort pending wallet transactions based on their initial wallet insertion order
1659 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1661 const uint256& wtxid = item.first;
1662 CWalletTx& wtx = item.second;
1663 assert(wtx.GetHash() == wtxid);
1665 int nDepth = wtx.GetDepthInMainChain();
1667 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1668 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1672 // Try to add wallet transactions to memory pool
1673 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1675 CWalletTx& wtx = *(item.second);
1677 LOCK(mempool.cs);
1678 CValidationState state;
1679 wtx.AcceptToMemoryPool(maxTxFee, state);
1683 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1685 assert(pwallet->GetBroadcastTransactions());
1686 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1688 CValidationState state;
1689 /* GetDepthInMainChain already catches known conflicts. */
1690 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1691 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1692 if (connman) {
1693 CInv inv(MSG_TX, GetHash());
1694 connman->ForEachNode([&inv](CNode* pnode)
1696 pnode->PushInventory(inv);
1698 return true;
1702 return false;
1705 std::set<uint256> CWalletTx::GetConflicts() const
1707 std::set<uint256> result;
1708 if (pwallet != NULL)
1710 uint256 myHash = GetHash();
1711 result = pwallet->GetConflicts(myHash);
1712 result.erase(myHash);
1714 return result;
1717 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1719 if (tx->vin.empty())
1720 return 0;
1722 CAmount debit = 0;
1723 if(filter & ISMINE_SPENDABLE)
1725 if (fDebitCached)
1726 debit += nDebitCached;
1727 else
1729 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1730 fDebitCached = true;
1731 debit += nDebitCached;
1734 if(filter & ISMINE_WATCH_ONLY)
1736 if(fWatchDebitCached)
1737 debit += nWatchDebitCached;
1738 else
1740 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1741 fWatchDebitCached = true;
1742 debit += nWatchDebitCached;
1745 return debit;
1748 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1750 // Must wait until coinbase is safely deep enough in the chain before valuing it
1751 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1752 return 0;
1754 CAmount credit = 0;
1755 if (filter & ISMINE_SPENDABLE)
1757 // GetBalance can assume transactions in mapWallet won't change
1758 if (fCreditCached)
1759 credit += nCreditCached;
1760 else
1762 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1763 fCreditCached = true;
1764 credit += nCreditCached;
1767 if (filter & ISMINE_WATCH_ONLY)
1769 if (fWatchCreditCached)
1770 credit += nWatchCreditCached;
1771 else
1773 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1774 fWatchCreditCached = true;
1775 credit += nWatchCreditCached;
1778 return credit;
1781 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1783 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1785 if (fUseCache && fImmatureCreditCached)
1786 return nImmatureCreditCached;
1787 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1788 fImmatureCreditCached = true;
1789 return nImmatureCreditCached;
1792 return 0;
1795 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1797 if (pwallet == 0)
1798 return 0;
1800 // Must wait until coinbase is safely deep enough in the chain before valuing it
1801 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1802 return 0;
1804 if (fUseCache && fAvailableCreditCached)
1805 return nAvailableCreditCached;
1807 CAmount nCredit = 0;
1808 uint256 hashTx = GetHash();
1809 for (unsigned int i = 0; i < tx->vout.size(); i++)
1811 if (!pwallet->IsSpent(hashTx, i))
1813 const CTxOut &txout = tx->vout[i];
1814 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1815 if (!MoneyRange(nCredit))
1816 throw std::runtime_error(std::string(__func__) + " : value out of range");
1820 nAvailableCreditCached = nCredit;
1821 fAvailableCreditCached = true;
1822 return nCredit;
1825 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1827 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1829 if (fUseCache && fImmatureWatchCreditCached)
1830 return nImmatureWatchCreditCached;
1831 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1832 fImmatureWatchCreditCached = true;
1833 return nImmatureWatchCreditCached;
1836 return 0;
1839 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1841 if (pwallet == 0)
1842 return 0;
1844 // Must wait until coinbase is safely deep enough in the chain before valuing it
1845 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1846 return 0;
1848 if (fUseCache && fAvailableWatchCreditCached)
1849 return nAvailableWatchCreditCached;
1851 CAmount nCredit = 0;
1852 for (unsigned int i = 0; i < tx->vout.size(); i++)
1854 if (!pwallet->IsSpent(GetHash(), i))
1856 const CTxOut &txout = tx->vout[i];
1857 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1858 if (!MoneyRange(nCredit))
1859 throw std::runtime_error(std::string(__func__) + ": value out of range");
1863 nAvailableWatchCreditCached = nCredit;
1864 fAvailableWatchCreditCached = true;
1865 return nCredit;
1868 CAmount CWalletTx::GetChange() const
1870 if (fChangeCached)
1871 return nChangeCached;
1872 nChangeCached = pwallet->GetChange(*this);
1873 fChangeCached = true;
1874 return nChangeCached;
1877 bool CWalletTx::InMempool() const
1879 LOCK(mempool.cs);
1880 return mempool.exists(GetHash());
1883 bool CWalletTx::IsTrusted() const
1885 // Quick answer in most cases
1886 if (!CheckFinalTx(*this))
1887 return false;
1888 int nDepth = GetDepthInMainChain();
1889 if (nDepth >= 1)
1890 return true;
1891 if (nDepth < 0)
1892 return false;
1893 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1894 return false;
1896 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1897 if (!InMempool())
1898 return false;
1900 // Trusted if all inputs are from us and are in the mempool:
1901 for (const CTxIn& txin : tx->vin)
1903 // Transactions not sent by us: not trusted
1904 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1905 if (parent == NULL)
1906 return false;
1907 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1908 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1909 return false;
1911 return true;
1914 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1916 CMutableTransaction tx1 = *this->tx;
1917 CMutableTransaction tx2 = *_tx.tx;
1918 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1919 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1920 return CTransaction(tx1) == CTransaction(tx2);
1923 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1925 std::vector<uint256> result;
1927 LOCK(cs_wallet);
1928 // Sort them in chronological order
1929 std::multimap<unsigned int, CWalletTx*> mapSorted;
1930 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1932 CWalletTx& wtx = item.second;
1933 // Don't rebroadcast if newer than nTime:
1934 if (wtx.nTimeReceived > nTime)
1935 continue;
1936 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1938 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1940 CWalletTx& wtx = *item.second;
1941 if (wtx.RelayWalletTransaction(connman))
1942 result.push_back(wtx.GetHash());
1944 return result;
1947 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1949 // Do this infrequently and randomly to avoid giving away
1950 // that these are our transactions.
1951 if (GetTime() < nNextResend || !fBroadcastTransactions)
1952 return;
1953 bool fFirst = (nNextResend == 0);
1954 nNextResend = GetTime() + GetRand(30 * 60);
1955 if (fFirst)
1956 return;
1958 // Only do it if there's been a new block since last time
1959 if (nBestBlockTime < nLastResend)
1960 return;
1961 nLastResend = GetTime();
1963 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1964 // block was found:
1965 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1966 if (!relayed.empty())
1967 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1970 /** @} */ // end of mapWallet
1975 /** @defgroup Actions
1977 * @{
1981 CAmount CWallet::GetBalance() const
1983 CAmount nTotal = 0;
1985 LOCK2(cs_main, cs_wallet);
1986 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1988 const CWalletTx* pcoin = &(*it).second;
1989 if (pcoin->IsTrusted())
1990 nTotal += pcoin->GetAvailableCredit();
1994 return nTotal;
1997 CAmount CWallet::GetUnconfirmedBalance() const
1999 CAmount nTotal = 0;
2001 LOCK2(cs_main, cs_wallet);
2002 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2004 const CWalletTx* pcoin = &(*it).second;
2005 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2006 nTotal += pcoin->GetAvailableCredit();
2009 return nTotal;
2012 CAmount CWallet::GetImmatureBalance() const
2014 CAmount nTotal = 0;
2016 LOCK2(cs_main, cs_wallet);
2017 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2019 const CWalletTx* pcoin = &(*it).second;
2020 nTotal += pcoin->GetImmatureCredit();
2023 return nTotal;
2026 CAmount CWallet::GetWatchOnlyBalance() const
2028 CAmount nTotal = 0;
2030 LOCK2(cs_main, cs_wallet);
2031 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2033 const CWalletTx* pcoin = &(*it).second;
2034 if (pcoin->IsTrusted())
2035 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2039 return nTotal;
2042 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2044 CAmount nTotal = 0;
2046 LOCK2(cs_main, cs_wallet);
2047 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2049 const CWalletTx* pcoin = &(*it).second;
2050 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2051 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2054 return nTotal;
2057 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2059 CAmount nTotal = 0;
2061 LOCK2(cs_main, cs_wallet);
2062 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2064 const CWalletTx* pcoin = &(*it).second;
2065 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2068 return nTotal;
2071 // Calculate total balance in a different way from GetBalance. The biggest
2072 // difference is that GetBalance sums up all unspent TxOuts paying to the
2073 // wallet, while this sums up both spent and unspent TxOuts paying to the
2074 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2075 // also has fewer restrictions on which unconfirmed transactions are considered
2076 // trusted.
2077 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2079 LOCK2(cs_main, cs_wallet);
2081 CAmount balance = 0;
2082 for (const auto& entry : mapWallet) {
2083 const CWalletTx& wtx = entry.second;
2084 const int depth = wtx.GetDepthInMainChain();
2085 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2086 continue;
2089 // Loop through tx outputs and add incoming payments. For outgoing txs,
2090 // treat change outputs specially, as part of the amount debited.
2091 CAmount debit = wtx.GetDebit(filter);
2092 const bool outgoing = debit > 0;
2093 for (const CTxOut& out : wtx.tx->vout) {
2094 if (outgoing && IsChange(out)) {
2095 debit -= out.nValue;
2096 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2097 balance += out.nValue;
2101 // For outgoing txs, subtract amount debited.
2102 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2103 balance -= debit;
2107 if (account) {
2108 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2111 return balance;
2114 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2116 LOCK2(cs_main, cs_wallet);
2118 CAmount balance = 0;
2119 std::vector<COutput> vCoins;
2120 AvailableCoins(vCoins, true, coinControl);
2121 for (const COutput& out : vCoins) {
2122 if (out.fSpendable) {
2123 balance += out.tx->tx->vout[out.i].nValue;
2126 return balance;
2129 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
2131 vCoins.clear();
2134 LOCK2(cs_main, cs_wallet);
2136 CAmount nTotal = 0;
2138 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2140 const uint256& wtxid = it->first;
2141 const CWalletTx* pcoin = &(*it).second;
2143 if (!CheckFinalTx(*pcoin))
2144 continue;
2146 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2147 continue;
2149 int nDepth = pcoin->GetDepthInMainChain();
2150 if (nDepth < 0)
2151 continue;
2153 // We should not consider coins which aren't at least in our mempool
2154 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2155 if (nDepth == 0 && !pcoin->InMempool())
2156 continue;
2158 bool safeTx = pcoin->IsTrusted();
2160 // We should not consider coins from transactions that are replacing
2161 // other transactions.
2163 // Example: There is a transaction A which is replaced by bumpfee
2164 // transaction B. In this case, we want to prevent creation of
2165 // a transaction B' which spends an output of B.
2167 // Reason: If transaction A were initially confirmed, transactions B
2168 // and B' would no longer be valid, so the user would have to create
2169 // a new transaction C to replace B'. However, in the case of a
2170 // one-block reorg, transactions B' and C might BOTH be accepted,
2171 // when the user only wanted one of them. Specifically, there could
2172 // be a 1-block reorg away from the chain where transactions A and C
2173 // were accepted to another chain where B, B', and C were all
2174 // accepted.
2175 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2176 safeTx = false;
2179 // Similarly, we should not consider coins from transactions that
2180 // have been replaced. In the example above, we would want to prevent
2181 // creation of a transaction A' spending an output of A, because if
2182 // transaction B were initially confirmed, conflicting with A and
2183 // A', we wouldn't want to the user to create a transaction D
2184 // intending to replace A', but potentially resulting in a scenario
2185 // where A, A', and D could all be accepted (instead of just B and
2186 // D, or just A and A' like the user would want).
2187 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2188 safeTx = false;
2191 if (fOnlySafe && !safeTx) {
2192 continue;
2195 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2196 continue;
2198 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2199 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2200 continue;
2202 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2203 continue;
2205 if (IsLockedCoin((*it).first, i))
2206 continue;
2208 if (IsSpent(wtxid, i))
2209 continue;
2211 isminetype mine = IsMine(pcoin->tx->vout[i]);
2213 if (mine == ISMINE_NO) {
2214 continue;
2217 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2218 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2220 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2222 // Checks the sum amount of all UTXO's.
2223 if (nMinimumSumAmount != MAX_MONEY) {
2224 nTotal += pcoin->tx->vout[i].nValue;
2226 if (nTotal >= nMinimumSumAmount) {
2227 return;
2231 // Checks the maximum number of UTXO's.
2232 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2233 return;
2240 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2242 // TODO: Add AssertLockHeld(cs_wallet) here.
2244 // Because the return value from this function contains pointers to
2245 // CWalletTx objects, callers to this function really should acquire the
2246 // cs_wallet lock before calling it. However, the current caller doesn't
2247 // acquire this lock yet. There was an attempt to add the missing lock in
2248 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2249 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2250 // avoid adding some extra complexity to the Qt code.
2252 std::map<CTxDestination, std::vector<COutput>> result;
2254 std::vector<COutput> availableCoins;
2255 AvailableCoins(availableCoins);
2257 LOCK2(cs_main, cs_wallet);
2258 for (auto& coin : availableCoins) {
2259 CTxDestination address;
2260 if (coin.fSpendable &&
2261 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2262 result[address].emplace_back(std::move(coin));
2266 std::vector<COutPoint> lockedCoins;
2267 ListLockedCoins(lockedCoins);
2268 for (const auto& output : lockedCoins) {
2269 auto it = mapWallet.find(output.hash);
2270 if (it != mapWallet.end()) {
2271 int depth = it->second.GetDepthInMainChain();
2272 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2273 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2274 CTxDestination address;
2275 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2276 result[address].emplace_back(
2277 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2283 return result;
2286 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2288 const CTransaction* ptx = &tx;
2289 int n = output;
2290 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2291 const COutPoint& prevout = ptx->vin[0].prevout;
2292 auto it = mapWallet.find(prevout.hash);
2293 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2294 !IsMine(it->second.tx->vout[prevout.n])) {
2295 break;
2297 ptx = it->second.tx.get();
2298 n = prevout.n;
2300 return ptx->vout[n];
2303 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2304 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2306 std::vector<char> vfIncluded;
2308 vfBest.assign(vValue.size(), true);
2309 nBest = nTotalLower;
2311 FastRandomContext insecure_rand;
2313 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2315 vfIncluded.assign(vValue.size(), false);
2316 CAmount nTotal = 0;
2317 bool fReachedTarget = false;
2318 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2320 for (unsigned int i = 0; i < vValue.size(); i++)
2322 //The solver here uses a randomized algorithm,
2323 //the randomness serves no real security purpose but is just
2324 //needed to prevent degenerate behavior and it is important
2325 //that the rng is fast. We do not use a constant random sequence,
2326 //because there may be some privacy improvement by making
2327 //the selection random.
2328 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2330 nTotal += vValue[i].txout.nValue;
2331 vfIncluded[i] = true;
2332 if (nTotal >= nTargetValue)
2334 fReachedTarget = true;
2335 if (nTotal < nBest)
2337 nBest = nTotal;
2338 vfBest = vfIncluded;
2340 nTotal -= vValue[i].txout.nValue;
2341 vfIncluded[i] = false;
2349 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2350 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2352 setCoinsRet.clear();
2353 nValueRet = 0;
2355 // List of values less than target
2356 boost::optional<CInputCoin> coinLowestLarger;
2357 std::vector<CInputCoin> vValue;
2358 CAmount nTotalLower = 0;
2360 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2362 for (const COutput &output : vCoins)
2364 if (!output.fSpendable)
2365 continue;
2367 const CWalletTx *pcoin = output.tx;
2369 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2370 continue;
2372 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2373 continue;
2375 int i = output.i;
2377 CInputCoin coin = CInputCoin(pcoin, i);
2379 if (coin.txout.nValue == nTargetValue)
2381 setCoinsRet.insert(coin);
2382 nValueRet += coin.txout.nValue;
2383 return true;
2385 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2387 vValue.push_back(coin);
2388 nTotalLower += coin.txout.nValue;
2390 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2392 coinLowestLarger = coin;
2396 if (nTotalLower == nTargetValue)
2398 for (const auto& input : vValue)
2400 setCoinsRet.insert(input);
2401 nValueRet += input.txout.nValue;
2403 return true;
2406 if (nTotalLower < nTargetValue)
2408 if (!coinLowestLarger)
2409 return false;
2410 setCoinsRet.insert(coinLowestLarger.get());
2411 nValueRet += coinLowestLarger->txout.nValue;
2412 return true;
2415 // Solve subset sum by stochastic approximation
2416 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2417 std::reverse(vValue.begin(), vValue.end());
2418 std::vector<char> vfBest;
2419 CAmount nBest;
2421 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2422 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2423 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2425 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2426 // or the next bigger coin is closer), return the bigger coin
2427 if (coinLowestLarger &&
2428 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2430 setCoinsRet.insert(coinLowestLarger.get());
2431 nValueRet += coinLowestLarger->txout.nValue;
2433 else {
2434 for (unsigned int i = 0; i < vValue.size(); i++)
2435 if (vfBest[i])
2437 setCoinsRet.insert(vValue[i]);
2438 nValueRet += vValue[i].txout.nValue;
2441 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2442 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2443 for (unsigned int i = 0; i < vValue.size(); i++) {
2444 if (vfBest[i]) {
2445 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2448 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2452 return true;
2455 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2457 std::vector<COutput> vCoins(vAvailableCoins);
2459 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2460 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2462 for (const COutput& out : vCoins)
2464 if (!out.fSpendable)
2465 continue;
2466 nValueRet += out.tx->tx->vout[out.i].nValue;
2467 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2469 return (nValueRet >= nTargetValue);
2472 // calculate value from preset inputs and store them
2473 std::set<CInputCoin> setPresetCoins;
2474 CAmount nValueFromPresetInputs = 0;
2476 std::vector<COutPoint> vPresetInputs;
2477 if (coinControl)
2478 coinControl->ListSelected(vPresetInputs);
2479 for (const COutPoint& outpoint : vPresetInputs)
2481 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2482 if (it != mapWallet.end())
2484 const CWalletTx* pcoin = &it->second;
2485 // Clearly invalid input, fail
2486 if (pcoin->tx->vout.size() <= outpoint.n)
2487 return false;
2488 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2489 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2490 } else
2491 return false; // TODO: Allow non-wallet inputs
2494 // remove preset inputs from vCoins
2495 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2497 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2498 it = vCoins.erase(it);
2499 else
2500 ++it;
2503 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2504 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2506 bool res = nTargetValue <= nValueFromPresetInputs ||
2507 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2508 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2509 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2510 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2511 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2512 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2513 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2515 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2516 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2518 // add preset inputs to the total value selected
2519 nValueRet += nValueFromPresetInputs;
2521 return res;
2524 bool CWallet::SignTransaction(CMutableTransaction &tx)
2526 AssertLockHeld(cs_wallet); // mapWallet
2528 // sign the new tx
2529 CTransaction txNewConst(tx);
2530 int nIn = 0;
2531 for (const auto& input : tx.vin) {
2532 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2533 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2534 return false;
2536 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2537 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2538 SignatureData sigdata;
2539 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2540 return false;
2542 UpdateTransaction(tx, nIn, sigdata);
2543 nIn++;
2545 return true;
2548 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2550 std::vector<CRecipient> vecSend;
2552 // Turn the txout set into a CRecipient vector
2553 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2555 const CTxOut& txOut = tx.vout[idx];
2556 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2557 vecSend.push_back(recipient);
2560 coinControl.fAllowOtherInputs = true;
2562 for (const CTxIn& txin : tx.vin)
2563 coinControl.Select(txin.prevout);
2565 CReserveKey reservekey(this);
2566 CWalletTx wtx;
2567 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2568 return false;
2571 if (nChangePosInOut != -1) {
2572 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2573 // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
2574 // so just remove the key from the keypool here.
2575 reservekey.KeepKey();
2578 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2579 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2580 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2582 // Add new txins (keeping original txin scriptSig/order)
2583 for (const CTxIn& txin : wtx.tx->vin)
2585 if (!coinControl.IsSelected(txin.prevout))
2587 tx.vin.push_back(txin);
2589 if (lockUnspents)
2591 LOCK2(cs_main, cs_wallet);
2592 LockCoin(txin.prevout);
2598 return true;
2601 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2603 unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2604 CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2605 // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2606 discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2607 // Discard rate must be at least dustRelayFee
2608 discard_rate = std::max(discard_rate, ::dustRelayFee);
2609 return discard_rate;
2612 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2613 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2615 CAmount nValue = 0;
2616 int nChangePosRequest = nChangePosInOut;
2617 unsigned int nSubtractFeeFromAmount = 0;
2618 for (const auto& recipient : vecSend)
2620 if (nValue < 0 || recipient.nAmount < 0)
2622 strFailReason = _("Transaction amounts must not be negative");
2623 return false;
2625 nValue += recipient.nAmount;
2627 if (recipient.fSubtractFeeFromAmount)
2628 nSubtractFeeFromAmount++;
2630 if (vecSend.empty())
2632 strFailReason = _("Transaction must have at least one recipient");
2633 return false;
2636 wtxNew.fTimeReceivedIsTxTime = true;
2637 wtxNew.BindWallet(this);
2638 CMutableTransaction txNew;
2640 // Discourage fee sniping.
2642 // For a large miner the value of the transactions in the best block and
2643 // the mempool can exceed the cost of deliberately attempting to mine two
2644 // blocks to orphan the current best block. By setting nLockTime such that
2645 // only the next block can include the transaction, we discourage this
2646 // practice as the height restricted and limited blocksize gives miners
2647 // considering fee sniping fewer options for pulling off this attack.
2649 // A simple way to think about this is from the wallet's point of view we
2650 // always want the blockchain to move forward. By setting nLockTime this
2651 // way we're basically making the statement that we only want this
2652 // transaction to appear in the next block; we don't want to potentially
2653 // encourage reorgs by allowing transactions to appear at lower heights
2654 // than the next block in forks of the best chain.
2656 // Of course, the subsidy is high enough, and transaction volume low
2657 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2658 // now we ensure code won't be written that makes assumptions about
2659 // nLockTime that preclude a fix later.
2660 txNew.nLockTime = chainActive.Height();
2662 // Secondly occasionally randomly pick a nLockTime even further back, so
2663 // that transactions that are delayed after signing for whatever reason,
2664 // e.g. high-latency mix networks and some CoinJoin implementations, have
2665 // better privacy.
2666 if (GetRandInt(10) == 0)
2667 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2669 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2670 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2671 FeeCalculation feeCalc;
2672 unsigned int nBytes;
2674 std::set<CInputCoin> setCoins;
2675 LOCK2(cs_main, cs_wallet);
2677 std::vector<COutput> vAvailableCoins;
2678 AvailableCoins(vAvailableCoins, true, &coin_control);
2680 // Create change script that will be used if we need change
2681 // TODO: pass in scriptChange instead of reservekey so
2682 // change transaction isn't always pay-to-bitcoin-address
2683 CScript scriptChange;
2685 // coin control: send change to custom address
2686 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2687 scriptChange = GetScriptForDestination(coin_control.destChange);
2688 } else { // no coin control: send change to newly generated address
2689 // Note: We use a new key here to keep it from being obvious which side is the change.
2690 // The drawback is that by not reusing a previous key, the change may be lost if a
2691 // backup is restored, if the backup doesn't have the new private key for the change.
2692 // If we reused the old key, it would be possible to add code to look for and
2693 // rediscover unknown transactions that were written with keys of ours to recover
2694 // post-backup change.
2696 // Reserve a new key pair from key pool
2697 CPubKey vchPubKey;
2698 bool ret;
2699 ret = reservekey.GetReservedKey(vchPubKey, true);
2700 if (!ret)
2702 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2703 return false;
2706 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2708 CTxOut change_prototype_txout(0, scriptChange);
2709 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2711 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2712 nFeeRet = 0;
2713 bool pick_new_inputs = true;
2714 CAmount nValueIn = 0;
2715 // Start with no fee and loop until there is enough fee
2716 while (true)
2718 nChangePosInOut = nChangePosRequest;
2719 txNew.vin.clear();
2720 txNew.vout.clear();
2721 wtxNew.fFromMe = true;
2722 bool fFirst = true;
2724 CAmount nValueToSelect = nValue;
2725 if (nSubtractFeeFromAmount == 0)
2726 nValueToSelect += nFeeRet;
2727 // vouts to the payees
2728 for (const auto& recipient : vecSend)
2730 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2732 if (recipient.fSubtractFeeFromAmount)
2734 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2736 if (fFirst) // first receiver pays the remainder not divisible by output count
2738 fFirst = false;
2739 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2743 if (IsDust(txout, ::dustRelayFee))
2745 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2747 if (txout.nValue < 0)
2748 strFailReason = _("The transaction amount is too small to pay the fee");
2749 else
2750 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2752 else
2753 strFailReason = _("Transaction amount too small");
2754 return false;
2756 txNew.vout.push_back(txout);
2759 // Choose coins to use
2760 if (pick_new_inputs) {
2761 nValueIn = 0;
2762 setCoins.clear();
2763 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2765 strFailReason = _("Insufficient funds");
2766 return false;
2770 const CAmount nChange = nValueIn - nValueToSelect;
2772 if (nChange > 0)
2774 // Fill a vout to ourself
2775 CTxOut newTxOut(nChange, scriptChange);
2777 // Never create dust outputs; if we would, just
2778 // add the dust to the fee.
2779 if (IsDust(newTxOut, discard_rate))
2781 nChangePosInOut = -1;
2782 nFeeRet += nChange;
2784 else
2786 if (nChangePosInOut == -1)
2788 // Insert change txn at random position:
2789 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2791 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2793 strFailReason = _("Change index out of range");
2794 return false;
2797 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2798 txNew.vout.insert(position, newTxOut);
2800 } else {
2801 nChangePosInOut = -1;
2804 // Fill vin
2806 // Note how the sequence number is set to non-maxint so that
2807 // the nLockTime set above actually works.
2809 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2810 // we use the highest possible value in that range (maxint-2)
2811 // to avoid conflicting with other possible uses of nSequence,
2812 // and in the spirit of "smallest possible change from prior
2813 // behavior."
2814 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2815 for (const auto& coin : setCoins)
2816 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2817 nSequence));
2819 // Fill in dummy signatures for fee calculation.
2820 if (!DummySignTx(txNew, setCoins)) {
2821 strFailReason = _("Signing transaction failed");
2822 return false;
2825 nBytes = GetVirtualTransactionSize(txNew);
2827 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2828 for (auto& vin : txNew.vin) {
2829 vin.scriptSig = CScript();
2830 vin.scriptWitness.SetNull();
2833 CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2835 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2836 // because we must be at the maximum allowed fee.
2837 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2839 strFailReason = _("Transaction too large for fee policy");
2840 return false;
2843 if (nFeeRet >= nFeeNeeded) {
2844 // Reduce fee to only the needed amount if possible. This
2845 // prevents potential overpayment in fees if the coins
2846 // selected to meet nFeeNeeded result in a transaction that
2847 // requires less fee than the prior iteration.
2849 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2850 // to be addressed because it requires returning the fee to
2851 // the payees and not the change output.
2853 // If we have no change and a big enough excess fee, then
2854 // try to construct transaction again only without picking
2855 // new inputs. We now know we only need the smaller fee
2856 // (because of reduced tx size) and so we should add a
2857 // change output. Only try this once.
2858 CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
2859 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2860 CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
2861 if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2862 pick_new_inputs = false;
2863 nFeeRet = nFeeNeeded + fee_needed_for_change;
2864 continue;
2867 // If we have change output already, just increase it
2868 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2869 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2870 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2871 change_position->nValue += extraFeePaid;
2872 nFeeRet -= extraFeePaid;
2874 break; // Done, enough fee included.
2876 else if (!pick_new_inputs) {
2877 // This shouldn't happen, we should have had enough excess
2878 // fee to pay for the new output and still meet nFeeNeeded
2879 strFailReason = _("Transaction fee and change calculation failed");
2880 return false;
2883 // Try to reduce change to include necessary fee
2884 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2885 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2886 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2887 // Only reduce change if remaining amount is still a large enough output.
2888 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2889 change_position->nValue -= additionalFeeNeeded;
2890 nFeeRet += additionalFeeNeeded;
2891 break; // Done, able to increase fee from change
2895 // Include more fee and try again.
2896 nFeeRet = nFeeNeeded;
2897 continue;
2901 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2903 if (sign)
2905 CTransaction txNewConst(txNew);
2906 int nIn = 0;
2907 for (const auto& coin : setCoins)
2909 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2910 SignatureData sigdata;
2912 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2914 strFailReason = _("Signing transaction failed");
2915 return false;
2916 } else {
2917 UpdateTransaction(txNew, nIn, sigdata);
2920 nIn++;
2924 // Embed the constructed transaction data in wtxNew.
2925 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2927 // Limit size
2928 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2930 strFailReason = _("Transaction too large");
2931 return false;
2935 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2936 // Lastly, ensure this tx will pass the mempool's chain limits
2937 LockPoints lp;
2938 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2939 CTxMemPool::setEntries setAncestors;
2940 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2941 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2942 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2943 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2944 std::string errString;
2945 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2946 strFailReason = _("Transaction has too long of a mempool chain");
2947 return false;
2951 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",
2952 nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2953 feeCalc.est.pass.start, feeCalc.est.pass.end,
2954 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2955 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2956 feeCalc.est.fail.start, feeCalc.est.fail.end,
2957 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2958 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2959 return true;
2963 * Call after CreateTransaction unless you want to abort
2965 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2968 LOCK2(cs_main, cs_wallet);
2969 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2971 // Take key pair from key pool so it won't be used again
2972 reservekey.KeepKey();
2974 // Add tx to wallet, because if it has change it's also ours,
2975 // otherwise just for transaction history.
2976 AddToWallet(wtxNew);
2978 // Notify that old coins are spent
2979 for (const CTxIn& txin : wtxNew.tx->vin)
2981 CWalletTx &coin = mapWallet[txin.prevout.hash];
2982 coin.BindWallet(this);
2983 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2987 // Track how many getdata requests our transaction gets
2988 mapRequestCount[wtxNew.GetHash()] = 0;
2990 if (fBroadcastTransactions)
2992 // Broadcast
2993 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2994 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2995 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2996 } else {
2997 wtxNew.RelayWalletTransaction(connman);
3001 return true;
3004 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
3005 CWalletDB walletdb(*dbw);
3006 return walletdb.ListAccountCreditDebit(strAccount, entries);
3009 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3011 CWalletDB walletdb(*dbw);
3013 return AddAccountingEntry(acentry, &walletdb);
3016 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3018 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3019 return false;
3022 laccentries.push_back(acentry);
3023 CAccountingEntry & entry = laccentries.back();
3024 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
3026 return true;
3029 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3031 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3034 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
3036 /* User control of how to calculate fee uses the following parameter precedence:
3037 1. coin_control.m_feerate
3038 2. coin_control.m_confirm_target
3039 3. payTxFee (user-set global variable)
3040 4. nTxConfirmTarget (user-set global variable)
3041 The first parameter that is set is used.
3043 CAmount fee_needed;
3044 if (coin_control.m_feerate) { // 1.
3045 fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
3046 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3047 // Allow to override automatic min/max check over coin control instance
3048 if (coin_control.fOverrideFeeRate) return fee_needed;
3050 else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
3051 fee_needed = ::payTxFee.GetFee(nTxBytes);
3052 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3054 else { // 2. or 4.
3055 // We will use smart fee estimation
3056 unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
3057 // By default estimates are economical iff we are signaling opt-in-RBF
3058 bool conservative_estimate = !coin_control.signalRbf;
3059 // Allow to override the default fee estimate mode over the CoinControl instance
3060 if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3061 else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3063 fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3064 if (fee_needed == 0) {
3065 // if we don't have enough data for estimateSmartFee, then use fallbackFee
3066 fee_needed = fallbackFee.GetFee(nTxBytes);
3067 if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3069 // Obey mempool min fee when using smart fee estimation
3070 CAmount min_mempool_fee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3071 if (fee_needed < min_mempool_fee) {
3072 fee_needed = min_mempool_fee;
3073 if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3077 // prevent user from paying a fee below minRelayTxFee or minTxFee
3078 CAmount required_fee = GetRequiredFee(nTxBytes);
3079 if (required_fee > fee_needed) {
3080 fee_needed = required_fee;
3081 if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3083 // But always obey the maximum
3084 if (fee_needed > maxTxFee) {
3085 fee_needed = maxTxFee;
3086 if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3088 return fee_needed;
3094 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3096 fFirstRunRet = false;
3097 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3098 if (nLoadWalletRet == DB_NEED_REWRITE)
3100 if (dbw->Rewrite("\x04pool"))
3102 LOCK(cs_wallet);
3103 setInternalKeyPool.clear();
3104 setExternalKeyPool.clear();
3105 m_pool_key_to_index.clear();
3106 // Note: can't top-up keypool here, because wallet is locked.
3107 // User will be prompted to unlock wallet the next operation
3108 // that requires a new key.
3112 if (nLoadWalletRet != DB_LOAD_OK)
3113 return nLoadWalletRet;
3114 fFirstRunRet = !vchDefaultKey.IsValid();
3116 uiInterface.LoadWallet(this);
3118 return DB_LOAD_OK;
3121 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3123 AssertLockHeld(cs_wallet); // mapWallet
3124 vchDefaultKey = CPubKey();
3125 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3126 for (uint256 hash : vHashOut)
3127 mapWallet.erase(hash);
3129 if (nZapSelectTxRet == DB_NEED_REWRITE)
3131 if (dbw->Rewrite("\x04pool"))
3133 setInternalKeyPool.clear();
3134 setExternalKeyPool.clear();
3135 m_pool_key_to_index.clear();
3136 // Note: can't top-up keypool here, because wallet is locked.
3137 // User will be prompted to unlock wallet the next operation
3138 // that requires a new key.
3142 if (nZapSelectTxRet != DB_LOAD_OK)
3143 return nZapSelectTxRet;
3145 MarkDirty();
3147 return DB_LOAD_OK;
3151 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3153 vchDefaultKey = CPubKey();
3154 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3155 if (nZapWalletTxRet == DB_NEED_REWRITE)
3157 if (dbw->Rewrite("\x04pool"))
3159 LOCK(cs_wallet);
3160 setInternalKeyPool.clear();
3161 setExternalKeyPool.clear();
3162 m_pool_key_to_index.clear();
3163 // Note: can't top-up keypool here, because wallet is locked.
3164 // User will be prompted to unlock wallet the next operation
3165 // that requires a new key.
3169 if (nZapWalletTxRet != DB_LOAD_OK)
3170 return nZapWalletTxRet;
3172 return DB_LOAD_OK;
3176 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3178 bool fUpdated = false;
3180 LOCK(cs_wallet); // mapAddressBook
3181 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3182 fUpdated = mi != mapAddressBook.end();
3183 mapAddressBook[address].name = strName;
3184 if (!strPurpose.empty()) /* update purpose only if requested */
3185 mapAddressBook[address].purpose = strPurpose;
3187 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3188 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3189 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3190 return false;
3191 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3194 bool CWallet::DelAddressBook(const CTxDestination& address)
3197 LOCK(cs_wallet); // mapAddressBook
3199 // Delete destdata tuples associated with address
3200 std::string strAddress = CBitcoinAddress(address).ToString();
3201 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3203 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3205 mapAddressBook.erase(address);
3208 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3210 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3211 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3214 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3216 CTxDestination address;
3217 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3218 auto mi = mapAddressBook.find(address);
3219 if (mi != mapAddressBook.end()) {
3220 return mi->second.name;
3223 // A scriptPubKey that doesn't have an entry in the address book is
3224 // associated with the default account ("").
3225 const static std::string DEFAULT_ACCOUNT_NAME;
3226 return DEFAULT_ACCOUNT_NAME;
3229 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3231 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3232 return false;
3233 vchDefaultKey = vchPubKey;
3234 return true;
3238 * Mark old keypool keys as used,
3239 * and generate all new keys
3241 bool CWallet::NewKeyPool()
3244 LOCK(cs_wallet);
3245 CWalletDB walletdb(*dbw);
3247 for (int64_t nIndex : setInternalKeyPool) {
3248 walletdb.ErasePool(nIndex);
3250 setInternalKeyPool.clear();
3252 for (int64_t nIndex : setExternalKeyPool) {
3253 walletdb.ErasePool(nIndex);
3255 setExternalKeyPool.clear();
3257 m_pool_key_to_index.clear();
3259 if (!TopUpKeyPool()) {
3260 return false;
3262 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3264 return true;
3267 size_t CWallet::KeypoolCountExternalKeys()
3269 AssertLockHeld(cs_wallet); // setExternalKeyPool
3270 return setExternalKeyPool.size();
3273 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3275 AssertLockHeld(cs_wallet);
3276 if (keypool.fInternal) {
3277 setInternalKeyPool.insert(nIndex);
3278 } else {
3279 setExternalKeyPool.insert(nIndex);
3281 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3282 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3284 // If no metadata exists yet, create a default with the pool key's
3285 // creation time. Note that this may be overwritten by actually
3286 // stored metadata for that key later, which is fine.
3287 CKeyID keyid = keypool.vchPubKey.GetID();
3288 if (mapKeyMetadata.count(keyid) == 0)
3289 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3292 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3295 LOCK(cs_wallet);
3297 if (IsLocked())
3298 return false;
3300 // Top up key pool
3301 unsigned int nTargetSize;
3302 if (kpSize > 0)
3303 nTargetSize = kpSize;
3304 else
3305 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3307 // count amount of available keys (internal, external)
3308 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3309 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3310 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3312 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3314 // don't create extra internal keys
3315 missingInternal = 0;
3317 bool internal = false;
3318 CWalletDB walletdb(*dbw);
3319 for (int64_t i = missingInternal + missingExternal; i--;)
3321 if (i < missingInternal) {
3322 internal = true;
3325 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3326 int64_t index = ++m_max_keypool_index;
3328 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3329 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3330 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3333 if (internal) {
3334 setInternalKeyPool.insert(index);
3335 } else {
3336 setExternalKeyPool.insert(index);
3338 m_pool_key_to_index[pubkey.GetID()] = index;
3340 if (missingInternal + missingExternal > 0) {
3341 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3344 return true;
3347 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3349 nIndex = -1;
3350 keypool.vchPubKey = CPubKey();
3352 LOCK(cs_wallet);
3354 if (!IsLocked())
3355 TopUpKeyPool();
3357 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3358 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3360 // Get the oldest key
3361 if(setKeyPool.empty())
3362 return;
3364 CWalletDB walletdb(*dbw);
3366 auto it = setKeyPool.begin();
3367 nIndex = *it;
3368 setKeyPool.erase(it);
3369 if (!walletdb.ReadPool(nIndex, keypool)) {
3370 throw std::runtime_error(std::string(__func__) + ": read failed");
3372 if (!HaveKey(keypool.vchPubKey.GetID())) {
3373 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3375 if (keypool.fInternal != fReturningInternal) {
3376 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3379 assert(keypool.vchPubKey.IsValid());
3380 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3381 LogPrintf("keypool reserve %d\n", nIndex);
3385 void CWallet::KeepKey(int64_t nIndex)
3387 // Remove from key pool
3388 CWalletDB walletdb(*dbw);
3389 walletdb.ErasePool(nIndex);
3390 LogPrintf("keypool keep %d\n", nIndex);
3393 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3395 // Return to key pool
3397 LOCK(cs_wallet);
3398 if (fInternal) {
3399 setInternalKeyPool.insert(nIndex);
3400 } else {
3401 setExternalKeyPool.insert(nIndex);
3403 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3405 LogPrintf("keypool return %d\n", nIndex);
3408 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3410 CKeyPool keypool;
3412 LOCK(cs_wallet);
3413 int64_t nIndex = 0;
3414 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3415 if (nIndex == -1)
3417 if (IsLocked()) return false;
3418 CWalletDB walletdb(*dbw);
3419 result = GenerateNewKey(walletdb, internal);
3420 return true;
3422 KeepKey(nIndex);
3423 result = keypool.vchPubKey;
3425 return true;
3428 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3429 if (setKeyPool.empty()) {
3430 return GetTime();
3433 CKeyPool keypool;
3434 int64_t nIndex = *(setKeyPool.begin());
3435 if (!walletdb.ReadPool(nIndex, keypool)) {
3436 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3438 assert(keypool.vchPubKey.IsValid());
3439 return keypool.nTime;
3442 int64_t CWallet::GetOldestKeyPoolTime()
3444 LOCK(cs_wallet);
3446 CWalletDB walletdb(*dbw);
3448 // load oldest key from keypool, get time and return
3449 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3450 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3451 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3454 return oldestKey;
3457 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3459 std::map<CTxDestination, CAmount> balances;
3462 LOCK(cs_wallet);
3463 for (const auto& walletEntry : mapWallet)
3465 const CWalletTx *pcoin = &walletEntry.second;
3467 if (!pcoin->IsTrusted())
3468 continue;
3470 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3471 continue;
3473 int nDepth = pcoin->GetDepthInMainChain();
3474 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3475 continue;
3477 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3479 CTxDestination addr;
3480 if (!IsMine(pcoin->tx->vout[i]))
3481 continue;
3482 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3483 continue;
3485 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3487 if (!balances.count(addr))
3488 balances[addr] = 0;
3489 balances[addr] += n;
3494 return balances;
3497 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3499 AssertLockHeld(cs_wallet); // mapWallet
3500 std::set< std::set<CTxDestination> > groupings;
3501 std::set<CTxDestination> grouping;
3503 for (const auto& walletEntry : mapWallet)
3505 const CWalletTx *pcoin = &walletEntry.second;
3507 if (pcoin->tx->vin.size() > 0)
3509 bool any_mine = false;
3510 // group all input addresses with each other
3511 for (CTxIn txin : pcoin->tx->vin)
3513 CTxDestination address;
3514 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3515 continue;
3516 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3517 continue;
3518 grouping.insert(address);
3519 any_mine = true;
3522 // group change with input addresses
3523 if (any_mine)
3525 for (CTxOut txout : pcoin->tx->vout)
3526 if (IsChange(txout))
3528 CTxDestination txoutAddr;
3529 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3530 continue;
3531 grouping.insert(txoutAddr);
3534 if (grouping.size() > 0)
3536 groupings.insert(grouping);
3537 grouping.clear();
3541 // group lone addrs by themselves
3542 for (const auto& txout : pcoin->tx->vout)
3543 if (IsMine(txout))
3545 CTxDestination address;
3546 if(!ExtractDestination(txout.scriptPubKey, address))
3547 continue;
3548 grouping.insert(address);
3549 groupings.insert(grouping);
3550 grouping.clear();
3554 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3555 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3556 for (std::set<CTxDestination> _grouping : groupings)
3558 // make a set of all the groups hit by this new group
3559 std::set< std::set<CTxDestination>* > hits;
3560 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3561 for (CTxDestination address : _grouping)
3562 if ((it = setmap.find(address)) != setmap.end())
3563 hits.insert((*it).second);
3565 // merge all hit groups into a new single group and delete old groups
3566 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3567 for (std::set<CTxDestination>* hit : hits)
3569 merged->insert(hit->begin(), hit->end());
3570 uniqueGroupings.erase(hit);
3571 delete hit;
3573 uniqueGroupings.insert(merged);
3575 // update setmap
3576 for (CTxDestination element : *merged)
3577 setmap[element] = merged;
3580 std::set< std::set<CTxDestination> > ret;
3581 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3583 ret.insert(*uniqueGrouping);
3584 delete uniqueGrouping;
3587 return ret;
3590 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3592 LOCK(cs_wallet);
3593 std::set<CTxDestination> result;
3594 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3596 const CTxDestination& address = item.first;
3597 const std::string& strName = item.second.name;
3598 if (strName == strAccount)
3599 result.insert(address);
3601 return result;
3604 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3606 if (nIndex == -1)
3608 CKeyPool keypool;
3609 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3610 if (nIndex != -1)
3611 vchPubKey = keypool.vchPubKey;
3612 else {
3613 return false;
3615 fInternal = keypool.fInternal;
3617 assert(vchPubKey.IsValid());
3618 pubkey = vchPubKey;
3619 return true;
3622 void CReserveKey::KeepKey()
3624 if (nIndex != -1)
3625 pwallet->KeepKey(nIndex);
3626 nIndex = -1;
3627 vchPubKey = CPubKey();
3630 void CReserveKey::ReturnKey()
3632 if (nIndex != -1) {
3633 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3635 nIndex = -1;
3636 vchPubKey = CPubKey();
3639 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3641 AssertLockHeld(cs_wallet);
3642 bool internal = setInternalKeyPool.count(keypool_id);
3643 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3644 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3645 auto it = setKeyPool->begin();
3647 CWalletDB walletdb(*dbw);
3648 while (it != std::end(*setKeyPool)) {
3649 const int64_t& index = *(it);
3650 if (index > keypool_id) break; // set*KeyPool is ordered
3652 CKeyPool keypool;
3653 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3654 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3656 walletdb.ErasePool(index);
3657 it = setKeyPool->erase(it);
3661 bool CWallet::HasUnusedKeys(int min_keys) const
3663 return setExternalKeyPool.size() >= min_keys && (setInternalKeyPool.size() >= min_keys || !CanSupportFeature(FEATURE_HD_SPLIT));
3666 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3668 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3669 CPubKey pubkey;
3670 if (!rKey->GetReservedKey(pubkey))
3671 return;
3673 script = rKey;
3674 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3677 void CWallet::LockCoin(const COutPoint& output)
3679 AssertLockHeld(cs_wallet); // setLockedCoins
3680 setLockedCoins.insert(output);
3683 void CWallet::UnlockCoin(const COutPoint& output)
3685 AssertLockHeld(cs_wallet); // setLockedCoins
3686 setLockedCoins.erase(output);
3689 void CWallet::UnlockAllCoins()
3691 AssertLockHeld(cs_wallet); // setLockedCoins
3692 setLockedCoins.clear();
3695 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3697 AssertLockHeld(cs_wallet); // setLockedCoins
3698 COutPoint outpt(hash, n);
3700 return (setLockedCoins.count(outpt) > 0);
3703 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3705 AssertLockHeld(cs_wallet); // setLockedCoins
3706 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3707 it != setLockedCoins.end(); it++) {
3708 COutPoint outpt = (*it);
3709 vOutpts.push_back(outpt);
3713 /** @} */ // end of Actions
3715 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3716 AssertLockHeld(cs_wallet); // mapKeyMetadata
3717 mapKeyBirth.clear();
3719 // get birth times for keys with metadata
3720 for (const auto& entry : mapKeyMetadata) {
3721 if (entry.second.nCreateTime) {
3722 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3726 // map in which we'll infer heights of other keys
3727 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3728 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3729 std::set<CKeyID> setKeys;
3730 GetKeys(setKeys);
3731 for (const CKeyID &keyid : setKeys) {
3732 if (mapKeyBirth.count(keyid) == 0)
3733 mapKeyFirstBlock[keyid] = pindexMax;
3735 setKeys.clear();
3737 // if there are no such keys, we're done
3738 if (mapKeyFirstBlock.empty())
3739 return;
3741 // find first block that affects those keys, if there are any left
3742 std::vector<CKeyID> vAffected;
3743 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3744 // iterate over all wallet transactions...
3745 const CWalletTx &wtx = (*it).second;
3746 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3747 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3748 // ... which are already in a block
3749 int nHeight = blit->second->nHeight;
3750 for (const CTxOut &txout : wtx.tx->vout) {
3751 // iterate over all their outputs
3752 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3753 for (const CKeyID &keyid : vAffected) {
3754 // ... and all their affected keys
3755 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3756 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3757 rit->second = blit->second;
3759 vAffected.clear();
3764 // Extract block timestamps for those keys
3765 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3766 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3770 * Compute smart timestamp for a transaction being added to the wallet.
3772 * Logic:
3773 * - If sending a transaction, assign its timestamp to the current time.
3774 * - If receiving a transaction outside a block, assign its timestamp to the
3775 * current time.
3776 * - If receiving a block with a future timestamp, assign all its (not already
3777 * known) transactions' timestamps to the current time.
3778 * - If receiving a block with a past timestamp, before the most recent known
3779 * transaction (that we care about), assign all its (not already known)
3780 * transactions' timestamps to the same timestamp as that most-recent-known
3781 * transaction.
3782 * - If receiving a block with a past timestamp, but after the most recent known
3783 * transaction, assign all its (not already known) transactions' timestamps to
3784 * the block time.
3786 * For more information see CWalletTx::nTimeSmart,
3787 * https://bitcointalk.org/?topic=54527, or
3788 * https://github.com/bitcoin/bitcoin/pull/1393.
3790 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3792 unsigned int nTimeSmart = wtx.nTimeReceived;
3793 if (!wtx.hashUnset()) {
3794 if (mapBlockIndex.count(wtx.hashBlock)) {
3795 int64_t latestNow = wtx.nTimeReceived;
3796 int64_t latestEntry = 0;
3798 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3799 int64_t latestTolerated = latestNow + 300;
3800 const TxItems& txOrdered = wtxOrdered;
3801 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3802 CWalletTx* const pwtx = it->second.first;
3803 if (pwtx == &wtx) {
3804 continue;
3806 CAccountingEntry* const pacentry = it->second.second;
3807 int64_t nSmartTime;
3808 if (pwtx) {
3809 nSmartTime = pwtx->nTimeSmart;
3810 if (!nSmartTime) {
3811 nSmartTime = pwtx->nTimeReceived;
3813 } else {
3814 nSmartTime = pacentry->nTime;
3816 if (nSmartTime <= latestTolerated) {
3817 latestEntry = nSmartTime;
3818 if (nSmartTime > latestNow) {
3819 latestNow = nSmartTime;
3821 break;
3825 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3826 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3827 } else {
3828 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3831 return nTimeSmart;
3834 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3836 if (boost::get<CNoDestination>(&dest))
3837 return false;
3839 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3840 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3843 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3845 if (!mapAddressBook[dest].destdata.erase(key))
3846 return false;
3847 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3850 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3852 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3853 return true;
3856 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3858 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3859 if(i != mapAddressBook.end())
3861 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3862 if(j != i->second.destdata.end())
3864 if(value)
3865 *value = j->second;
3866 return true;
3869 return false;
3872 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3874 LOCK(cs_wallet);
3875 std::vector<std::string> values;
3876 for (const auto& address : mapAddressBook) {
3877 for (const auto& data : address.second.destdata) {
3878 if (!data.first.compare(0, prefix.size(), prefix)) {
3879 values.emplace_back(data.second);
3883 return values;
3886 std::string CWallet::GetWalletHelpString(bool showDebug)
3888 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3889 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3890 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3891 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3892 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3893 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). "
3894 "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"),
3895 CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3896 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3897 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3898 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3899 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3900 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3901 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3902 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3903 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));
3904 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));
3905 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3906 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3907 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3908 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3909 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3910 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3911 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3913 if (showDebug)
3915 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3917 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3918 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3919 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3920 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3923 return strUsage;
3926 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3928 // needed to restore wallet transaction meta data after -zapwallettxes
3929 std::vector<CWalletTx> vWtx;
3931 if (GetBoolArg("-zapwallettxes", false)) {
3932 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3934 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3935 CWallet *tempWallet = new CWallet(std::move(dbw));
3936 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3937 if (nZapWalletRet != DB_LOAD_OK) {
3938 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3939 return NULL;
3942 delete tempWallet;
3943 tempWallet = NULL;
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 NULL;
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 NULL;
3969 else if (nLoadWalletRet == DB_NEED_REWRITE)
3971 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3972 return NULL;
3974 else {
3975 InitError(strprintf(_("Error loading %s"), walletFile));
3976 return NULL;
3980 if (GetBoolArg("-upgradewallet", fFirstRun))
3982 int nMaxVersion = 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 NULL;
3996 walletInstance->SetMaxVersion(nMaxVersion);
3999 if (fFirstRun)
4001 // Create new keyUser and set as default key
4002 if (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");
4012 CPubKey newDefaultKey;
4013 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
4014 walletInstance->SetDefaultKey(newDefaultKey);
4015 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
4016 InitError(_("Cannot write default address") += "\n");
4017 return NULL;
4021 walletInstance->SetBestChain(chainActive.GetLocator());
4023 else if (IsArgSet("-usehd")) {
4024 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
4025 if (walletInstance->IsHDEnabled() && !useHD) {
4026 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
4027 return NULL;
4029 if (!walletInstance->IsHDEnabled() && useHD) {
4030 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
4031 return NULL;
4035 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
4037 RegisterValidationInterface(walletInstance);
4039 // Try to top up keypool. No-op if the wallet is locked.
4040 walletInstance->TopUpKeyPool();
4042 CBlockIndex *pindexRescan = chainActive.Genesis();
4043 if (!GetBoolArg("-rescan", false))
4045 CWalletDB walletdb(*walletInstance->dbw);
4046 CBlockLocator locator;
4047 if (walletdb.ReadBestBlock(locator))
4048 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4050 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
4052 //We can't rescan beyond non-pruned blocks, stop and throw an error
4053 //this might happen if a user uses an old wallet within a pruned node
4054 // or if he ran -disablewallet for a longer time, then decided to re-enable
4055 if (fPruneMode)
4057 CBlockIndex *block = chainActive.Tip();
4058 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4059 block = block->pprev;
4061 if (pindexRescan != block) {
4062 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4063 return NULL;
4067 uiInterface.InitMessage(_("Rescanning..."));
4068 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4070 // No need to read and scan block if block was created before
4071 // our wallet birthday (as adjusted for block time variability)
4072 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4073 pindexRescan = chainActive.Next(pindexRescan);
4076 nStart = GetTimeMillis();
4077 walletInstance->ScanForWalletTransactions(pindexRescan, true);
4078 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4079 walletInstance->SetBestChain(chainActive.GetLocator());
4080 walletInstance->dbw->IncrementUpdateCounter();
4082 // Restore wallet transaction metadata after -zapwallettxes=1
4083 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
4085 CWalletDB walletdb(*walletInstance->dbw);
4087 for (const CWalletTx& wtxOld : vWtx)
4089 uint256 hash = wtxOld.GetHash();
4090 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4091 if (mi != walletInstance->mapWallet.end())
4093 const CWalletTx* copyFrom = &wtxOld;
4094 CWalletTx* copyTo = &mi->second;
4095 copyTo->mapValue = copyFrom->mapValue;
4096 copyTo->vOrderForm = copyFrom->vOrderForm;
4097 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4098 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4099 copyTo->fFromMe = copyFrom->fFromMe;
4100 copyTo->strFromAccount = copyFrom->strFromAccount;
4101 copyTo->nOrderPos = copyFrom->nOrderPos;
4102 walletdb.WriteTx(*copyTo);
4107 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4110 LOCK(walletInstance->cs_wallet);
4111 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4112 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4113 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4116 return walletInstance;
4119 bool CWallet::InitLoadWallet()
4121 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4122 LogPrintf("Wallet disabled!\n");
4123 return true;
4126 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4127 CWallet * const pwallet = CreateWalletFromFile(walletFile);
4128 if (!pwallet) {
4129 return false;
4131 vpwallets.push_back(pwallet);
4134 return true;
4137 std::atomic<bool> CWallet::fFlushScheduled(false);
4139 void CWallet::postInitProcess(CScheduler& scheduler)
4141 // Add wallet transactions that aren't already in a block to mempool
4142 // Do this here as mempool requires genesis block to be loaded
4143 ReacceptWalletTransactions();
4145 // Run a thread to flush wallet periodically
4146 if (!CWallet::fFlushScheduled.exchange(true)) {
4147 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4151 bool CWallet::ParameterInteraction()
4153 SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4154 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4156 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4157 return true;
4159 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
4160 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4163 if (GetBoolArg("-salvagewallet", false)) {
4164 if (is_multiwallet) {
4165 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4167 // Rewrite just private keys: rescan to find transactions
4168 if (SoftSetBoolArg("-rescan", true)) {
4169 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4173 int zapwallettxes = GetArg("-zapwallettxes", 0);
4174 // -zapwallettxes implies dropping the mempool on startup
4175 if (zapwallettxes != 0 && SoftSetBoolArg("-persistmempool", false)) {
4176 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4179 // -zapwallettxes implies a rescan
4180 if (zapwallettxes != 0) {
4181 if (is_multiwallet) {
4182 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4184 if (SoftSetBoolArg("-rescan", true)) {
4185 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4189 if (is_multiwallet) {
4190 if (GetBoolArg("-upgradewallet", false)) {
4191 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4195 if (GetBoolArg("-sysperms", false))
4196 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4197 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
4198 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4200 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4201 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4202 _("The wallet will avoid paying less than the minimum relay fee."));
4204 if (IsArgSet("-mintxfee"))
4206 CAmount n = 0;
4207 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
4208 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
4209 if (n > HIGH_TX_FEE_PER_KB)
4210 InitWarning(AmountHighWarn("-mintxfee") + " " +
4211 _("This is the minimum transaction fee you pay on every transaction."));
4212 CWallet::minTxFee = CFeeRate(n);
4214 if (IsArgSet("-fallbackfee"))
4216 CAmount nFeePerK = 0;
4217 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4218 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4219 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4220 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4221 _("This is the transaction fee you may pay when fee estimates are not available."));
4222 CWallet::fallbackFee = CFeeRate(nFeePerK);
4224 if (IsArgSet("-discardfee"))
4226 CAmount nFeePerK = 0;
4227 if (!ParseMoney(GetArg("-discardfee", ""), nFeePerK))
4228 return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), GetArg("-discardfee", "")));
4229 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4230 InitWarning(AmountHighWarn("-discardfee") + " " +
4231 _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4232 CWallet::m_discard_rate = CFeeRate(nFeePerK);
4234 if (IsArgSet("-paytxfee"))
4236 CAmount nFeePerK = 0;
4237 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4238 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4239 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4240 InitWarning(AmountHighWarn("-paytxfee") + " " +
4241 _("This is the transaction fee you will pay if you send a transaction."));
4243 payTxFee = CFeeRate(nFeePerK, 1000);
4244 if (payTxFee < ::minRelayTxFee)
4246 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4247 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4250 if (IsArgSet("-maxtxfee"))
4252 CAmount nMaxFee = 0;
4253 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4254 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4255 if (nMaxFee > HIGH_MAX_TX_FEE)
4256 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4257 maxTxFee = nMaxFee;
4258 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4260 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4261 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4264 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4265 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4266 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4268 return true;
4271 bool CWallet::BackupWallet(const std::string& strDest)
4273 return dbw->Backup(strDest);
4276 CKeyPool::CKeyPool()
4278 nTime = GetTime();
4279 fInternal = false;
4282 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4284 nTime = GetTime();
4285 vchPubKey = vchPubKeyIn;
4286 fInternal = internalIn;
4289 CWalletKey::CWalletKey(int64_t nExpires)
4291 nTimeCreated = (nExpires ? GetTime() : 0);
4292 nTimeExpires = nExpires;
4295 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4297 // Update the tx's hashBlock
4298 hashBlock = pindex->GetBlockHash();
4300 // set the position of the transaction in the block
4301 nIndex = posInBlock;
4304 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4306 if (hashUnset())
4307 return 0;
4309 AssertLockHeld(cs_main);
4311 // Find the block it claims to be in
4312 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4313 if (mi == mapBlockIndex.end())
4314 return 0;
4315 CBlockIndex* pindex = (*mi).second;
4316 if (!pindex || !chainActive.Contains(pindex))
4317 return 0;
4319 pindexRet = pindex;
4320 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4323 int CMerkleTx::GetBlocksToMaturity() const
4325 if (!IsCoinBase())
4326 return 0;
4327 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4331 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4333 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);