[wallet] Don't hold cs_LastBlockFile while calling setBestChain
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob2ef3299c272e25829f9729ede80616f18c6b5141
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 "key.h"
16 #include "keystore.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/fees.h"
20 #include "policy/policy.h"
21 #include "policy/rbf.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "script/script.h"
25 #include "script/sign.h"
26 #include "scheduler.h"
27 #include "timedata.h"
28 #include "txmempool.h"
29 #include "util.h"
30 #include "ui_interface.h"
31 #include "utilmoneystr.h"
33 #include <assert.h>
35 #include <boost/algorithm/string/replace.hpp>
36 #include <boost/thread.hpp>
38 std::vector<CWalletRef> vpwallets;
39 /** Transaction fee set by the user */
40 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
41 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 bool fWalletRbf = DEFAULT_WALLET_RBF;
45 const char * DEFAULT_WALLET_DAT = "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
48 /**
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
53 /**
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
60 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
62 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
64 /** @defgroup mapWallet
66 * @{
69 struct CompareValueOnly
71 bool operator()(const CInputCoin& t1,
72 const CInputCoin& t2) const
74 return t1.txout.nValue < t2.txout.nValue;
78 std::string COutput::ToString() const
80 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
83 class CAffectedKeysVisitor : public boost::static_visitor<void> {
84 private:
85 const CKeyStore &keystore;
86 std::vector<CKeyID> &vKeys;
88 public:
89 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
91 void Process(const CScript &script) {
92 txnouttype type;
93 std::vector<CTxDestination> vDest;
94 int nRequired;
95 if (ExtractDestinations(script, type, vDest, nRequired)) {
96 for (const CTxDestination &dest : vDest)
97 boost::apply_visitor(*this, dest);
101 void operator()(const CKeyID &keyId) {
102 if (keystore.HaveKey(keyId))
103 vKeys.push_back(keyId);
106 void operator()(const CScriptID &scriptId) {
107 CScript script;
108 if (keystore.GetCScript(scriptId, script))
109 Process(script);
112 void operator()(const CNoDestination &none) {}
115 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
117 LOCK(cs_wallet);
118 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
119 if (it == mapWallet.end())
120 return NULL;
121 return &(it->second);
124 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
126 AssertLockHeld(cs_wallet); // mapKeyMetadata
127 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
129 CKey secret;
131 // Create new metadata
132 int64_t nCreationTime = GetTime();
133 CKeyMetadata metadata(nCreationTime);
135 // use HD key derivation if HD was enabled during wallet creation
136 if (IsHDEnabled()) {
137 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
138 } else {
139 secret.MakeNewKey(fCompressed);
142 // Compressed public keys were introduced in version 0.6.0
143 if (fCompressed) {
144 SetMinVersion(FEATURE_COMPRPUBKEY);
147 CPubKey pubkey = secret.GetPubKey();
148 assert(secret.VerifyPubKey(pubkey));
150 mapKeyMetadata[pubkey.GetID()] = metadata;
151 UpdateTimeFirstKey(nCreationTime);
153 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
154 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
156 return pubkey;
159 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
161 // for now we use a fixed keypath scheme of m/0'/0'/k
162 CKey key; //master key seed (256bit)
163 CExtKey masterKey; //hd master key
164 CExtKey accountKey; //key at m/0'
165 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
166 CExtKey childKey; //key at m/0'/0'/<n>'
168 // try to get the master key
169 if (!GetKey(hdChain.masterKeyID, key))
170 throw std::runtime_error(std::string(__func__) + ": Master key not found");
172 masterKey.SetMaster(key.begin(), key.size());
174 // derive m/0'
175 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
176 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
178 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
179 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
180 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
182 // derive child key at next index, skip keys already known to the wallet
183 do {
184 // always derive hardened keys
185 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
186 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
187 if (internal) {
188 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
189 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
190 hdChain.nInternalChainCounter++;
192 else {
193 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
194 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
195 hdChain.nExternalChainCounter++;
197 } while (HaveKey(childKey.key.GetPubKey().GetID()));
198 secret = childKey.key;
199 metadata.hdMasterKeyID = hdChain.masterKeyID;
200 // update the chain model in the database
201 if (!walletdb.WriteHDChain(hdChain))
202 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
205 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
207 AssertLockHeld(cs_wallet); // mapKeyMetadata
209 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
210 // which is overridden below. To avoid flushes, the database handle is
211 // tunneled through to it.
212 bool needsDB = !pwalletdbEncryption;
213 if (needsDB) {
214 pwalletdbEncryption = &walletdb;
216 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
217 if (needsDB) pwalletdbEncryption = NULL;
218 return false;
220 if (needsDB) pwalletdbEncryption = NULL;
222 // check if we need to remove from watch-only
223 CScript script;
224 script = GetScriptForDestination(pubkey.GetID());
225 if (HaveWatchOnly(script)) {
226 RemoveWatchOnly(script);
228 script = GetScriptForRawPubKey(pubkey);
229 if (HaveWatchOnly(script)) {
230 RemoveWatchOnly(script);
233 if (!IsCrypted()) {
234 return walletdb.WriteKey(pubkey,
235 secret.GetPrivKey(),
236 mapKeyMetadata[pubkey.GetID()]);
238 return true;
241 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
243 CWalletDB walletdb(*dbw);
244 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
247 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
248 const std::vector<unsigned char> &vchCryptedSecret)
250 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
251 return false;
253 LOCK(cs_wallet);
254 if (pwalletdbEncryption)
255 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
256 vchCryptedSecret,
257 mapKeyMetadata[vchPubKey.GetID()]);
258 else
259 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
260 vchCryptedSecret,
261 mapKeyMetadata[vchPubKey.GetID()]);
265 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
267 AssertLockHeld(cs_wallet); // mapKeyMetadata
268 UpdateTimeFirstKey(meta.nCreateTime);
269 mapKeyMetadata[keyID] = meta;
270 return true;
273 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
275 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
279 * Update wallet first key creation time. This should be called whenever keys
280 * are added to the wallet, with the oldest key creation time.
282 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
284 AssertLockHeld(cs_wallet);
285 if (nCreateTime <= 1) {
286 // Cannot determine birthday information, so set the wallet birthday to
287 // the beginning of time.
288 nTimeFirstKey = 1;
289 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
290 nTimeFirstKey = nCreateTime;
294 bool CWallet::AddCScript(const CScript& redeemScript)
296 if (!CCryptoKeyStore::AddCScript(redeemScript))
297 return false;
298 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
301 bool CWallet::LoadCScript(const CScript& redeemScript)
303 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
304 * that never can be redeemed. However, old wallets may still contain
305 * these. Do not add them to the wallet and warn. */
306 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
308 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
309 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",
310 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
311 return true;
314 return CCryptoKeyStore::AddCScript(redeemScript);
317 bool CWallet::AddWatchOnly(const CScript& dest)
319 if (!CCryptoKeyStore::AddWatchOnly(dest))
320 return false;
321 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
322 UpdateTimeFirstKey(meta.nCreateTime);
323 NotifyWatchonlyChanged(true);
324 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
327 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
329 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
330 return AddWatchOnly(dest);
333 bool CWallet::RemoveWatchOnly(const CScript &dest)
335 AssertLockHeld(cs_wallet);
336 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
337 return false;
338 if (!HaveWatchOnly())
339 NotifyWatchonlyChanged(false);
340 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
341 return false;
343 return true;
346 bool CWallet::LoadWatchOnly(const CScript &dest)
348 return CCryptoKeyStore::AddWatchOnly(dest);
351 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
353 CCrypter crypter;
354 CKeyingMaterial _vMasterKey;
357 LOCK(cs_wallet);
358 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
360 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
361 return false;
362 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
363 continue; // try another master key
364 if (CCryptoKeyStore::Unlock(_vMasterKey))
365 return true;
368 return false;
371 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
373 bool fWasLocked = IsLocked();
376 LOCK(cs_wallet);
377 Lock();
379 CCrypter crypter;
380 CKeyingMaterial _vMasterKey;
381 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
383 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
384 return false;
385 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
386 return false;
387 if (CCryptoKeyStore::Unlock(_vMasterKey))
389 int64_t nStartTime = GetTimeMillis();
390 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
391 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
393 nStartTime = GetTimeMillis();
394 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
395 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
397 if (pMasterKey.second.nDeriveIterations < 25000)
398 pMasterKey.second.nDeriveIterations = 25000;
400 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
402 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
403 return false;
404 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
405 return false;
406 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
407 if (fWasLocked)
408 Lock();
409 return true;
414 return false;
417 void CWallet::SetBestChain(const CBlockLocator& loc)
419 CWalletDB walletdb(*dbw);
420 walletdb.WriteBestBlock(loc);
423 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
425 LOCK(cs_wallet); // nWalletVersion
426 if (nWalletVersion >= nVersion)
427 return true;
429 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
430 if (fExplicit && nVersion > nWalletMaxVersion)
431 nVersion = FEATURE_LATEST;
433 nWalletVersion = nVersion;
435 if (nVersion > nWalletMaxVersion)
436 nWalletMaxVersion = nVersion;
439 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
440 if (nWalletVersion > 40000)
441 pwalletdb->WriteMinVersion(nWalletVersion);
442 if (!pwalletdbIn)
443 delete pwalletdb;
446 return true;
449 bool CWallet::SetMaxVersion(int nVersion)
451 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
452 // cannot downgrade below current version
453 if (nWalletVersion > nVersion)
454 return false;
456 nWalletMaxVersion = nVersion;
458 return true;
461 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
463 std::set<uint256> result;
464 AssertLockHeld(cs_wallet);
466 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
467 if (it == mapWallet.end())
468 return result;
469 const CWalletTx& wtx = it->second;
471 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
473 for (const CTxIn& txin : wtx.tx->vin)
475 if (mapTxSpends.count(txin.prevout) <= 1)
476 continue; // No conflict if zero or one spends
477 range = mapTxSpends.equal_range(txin.prevout);
478 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
479 result.insert(_it->second);
481 return result;
484 bool CWallet::HasWalletSpend(const uint256& txid) const
486 AssertLockHeld(cs_wallet);
487 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
488 return (iter != mapTxSpends.end() && iter->first.hash == txid);
491 void CWallet::Flush(bool shutdown)
493 dbw->Flush(shutdown);
496 bool CWallet::Verify()
498 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
499 return true;
501 uiInterface.InitMessage(_("Verifying wallet(s)..."));
503 // Keep track of each wallet absolute path to detect duplicates.
504 std::set<fs::path> wallet_paths;
506 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
507 if (boost::filesystem::path(walletFile).filename() != walletFile) {
508 return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile));
511 if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
512 return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile));
515 fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
517 if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) {
518 return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile));
521 if (!wallet_paths.insert(wallet_path).second) {
522 return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile));
525 std::string strError;
526 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
527 return InitError(strError);
530 if (GetBoolArg("-salvagewallet", false)) {
531 // Recover readable keypairs:
532 CWallet dummyWallet;
533 std::string backup_filename;
534 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
535 return false;
539 std::string strWarning;
540 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
541 if (!strWarning.empty()) {
542 InitWarning(strWarning);
544 if (!dbV) {
545 InitError(strError);
546 return false;
550 return true;
553 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
555 // We want all the wallet transactions in range to have the same metadata as
556 // the oldest (smallest nOrderPos).
557 // So: find smallest nOrderPos:
559 int nMinOrderPos = std::numeric_limits<int>::max();
560 const CWalletTx* copyFrom = NULL;
561 for (TxSpends::iterator it = range.first; it != range.second; ++it)
563 const uint256& hash = it->second;
564 int n = mapWallet[hash].nOrderPos;
565 if (n < nMinOrderPos)
567 nMinOrderPos = n;
568 copyFrom = &mapWallet[hash];
571 // Now copy data from copyFrom to rest:
572 for (TxSpends::iterator it = range.first; it != range.second; ++it)
574 const uint256& hash = it->second;
575 CWalletTx* copyTo = &mapWallet[hash];
576 if (copyFrom == copyTo) continue;
577 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
578 copyTo->mapValue = copyFrom->mapValue;
579 copyTo->vOrderForm = copyFrom->vOrderForm;
580 // fTimeReceivedIsTxTime not copied on purpose
581 // nTimeReceived not copied on purpose
582 copyTo->nTimeSmart = copyFrom->nTimeSmart;
583 copyTo->fFromMe = copyFrom->fFromMe;
584 copyTo->strFromAccount = copyFrom->strFromAccount;
585 // nOrderPos not copied on purpose
586 // cached members not copied on purpose
591 * Outpoint is spent if any non-conflicted transaction
592 * spends it:
594 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
596 const COutPoint outpoint(hash, n);
597 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
598 range = mapTxSpends.equal_range(outpoint);
600 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
602 const uint256& wtxid = it->second;
603 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
604 if (mit != mapWallet.end()) {
605 int depth = mit->second.GetDepthInMainChain();
606 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
607 return true; // Spent
610 return false;
613 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
615 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
617 std::pair<TxSpends::iterator, TxSpends::iterator> range;
618 range = mapTxSpends.equal_range(outpoint);
619 SyncMetaData(range);
623 void CWallet::AddToSpends(const uint256& wtxid)
625 assert(mapWallet.count(wtxid));
626 CWalletTx& thisTx = mapWallet[wtxid];
627 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
628 return;
630 for (const CTxIn& txin : thisTx.tx->vin)
631 AddToSpends(txin.prevout, wtxid);
634 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
636 if (IsCrypted())
637 return false;
639 CKeyingMaterial _vMasterKey;
641 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
642 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
644 CMasterKey kMasterKey;
646 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
647 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
649 CCrypter crypter;
650 int64_t nStartTime = GetTimeMillis();
651 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
652 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
654 nStartTime = GetTimeMillis();
655 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
656 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
658 if (kMasterKey.nDeriveIterations < 25000)
659 kMasterKey.nDeriveIterations = 25000;
661 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
663 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
664 return false;
665 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
666 return false;
669 LOCK(cs_wallet);
670 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
671 assert(!pwalletdbEncryption);
672 pwalletdbEncryption = new CWalletDB(*dbw);
673 if (!pwalletdbEncryption->TxnBegin()) {
674 delete pwalletdbEncryption;
675 pwalletdbEncryption = NULL;
676 return false;
678 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
680 if (!EncryptKeys(_vMasterKey))
682 pwalletdbEncryption->TxnAbort();
683 delete pwalletdbEncryption;
684 // We now probably have half of our keys encrypted in memory, and half not...
685 // die and let the user reload the unencrypted wallet.
686 assert(false);
689 // Encryption was introduced in version 0.4.0
690 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
692 if (!pwalletdbEncryption->TxnCommit()) {
693 delete pwalletdbEncryption;
694 // We now have keys encrypted in memory, but not on disk...
695 // die to avoid confusion and let the user reload the unencrypted wallet.
696 assert(false);
699 delete pwalletdbEncryption;
700 pwalletdbEncryption = NULL;
702 Lock();
703 Unlock(strWalletPassphrase);
705 // if we are using HD, replace the HD master key (seed) with a new one
706 if (IsHDEnabled()) {
707 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
708 return false;
712 NewKeyPool();
713 Lock();
715 // Need to completely rewrite the wallet file; if we don't, bdb might keep
716 // bits of the unencrypted private key in slack space in the database file.
717 dbw->Rewrite();
720 NotifyStatusChanged(this);
722 return true;
725 DBErrors CWallet::ReorderTransactions()
727 LOCK(cs_wallet);
728 CWalletDB walletdb(*dbw);
730 // Old wallets didn't have any defined order for transactions
731 // Probably a bad idea to change the output of this
733 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
734 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
735 typedef std::multimap<int64_t, TxPair > TxItems;
736 TxItems txByTime;
738 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
740 CWalletTx* wtx = &((*it).second);
741 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
743 std::list<CAccountingEntry> acentries;
744 walletdb.ListAccountCreditDebit("", acentries);
745 for (CAccountingEntry& entry : acentries)
747 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
750 nOrderPosNext = 0;
751 std::vector<int64_t> nOrderPosOffsets;
752 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
754 CWalletTx *const pwtx = (*it).second.first;
755 CAccountingEntry *const pacentry = (*it).second.second;
756 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
758 if (nOrderPos == -1)
760 nOrderPos = nOrderPosNext++;
761 nOrderPosOffsets.push_back(nOrderPos);
763 if (pwtx)
765 if (!walletdb.WriteTx(*pwtx))
766 return DB_LOAD_FAIL;
768 else
769 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
770 return DB_LOAD_FAIL;
772 else
774 int64_t nOrderPosOff = 0;
775 for (const int64_t& nOffsetStart : nOrderPosOffsets)
777 if (nOrderPos >= nOffsetStart)
778 ++nOrderPosOff;
780 nOrderPos += nOrderPosOff;
781 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
783 if (!nOrderPosOff)
784 continue;
786 // Since we're changing the order, write it back
787 if (pwtx)
789 if (!walletdb.WriteTx(*pwtx))
790 return DB_LOAD_FAIL;
792 else
793 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
794 return DB_LOAD_FAIL;
797 walletdb.WriteOrderPosNext(nOrderPosNext);
799 return DB_LOAD_OK;
802 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
804 AssertLockHeld(cs_wallet); // nOrderPosNext
805 int64_t nRet = nOrderPosNext++;
806 if (pwalletdb) {
807 pwalletdb->WriteOrderPosNext(nOrderPosNext);
808 } else {
809 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
811 return nRet;
814 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
816 CWalletDB walletdb(*dbw);
817 if (!walletdb.TxnBegin())
818 return false;
820 int64_t nNow = GetAdjustedTime();
822 // Debit
823 CAccountingEntry debit;
824 debit.nOrderPos = IncOrderPosNext(&walletdb);
825 debit.strAccount = strFrom;
826 debit.nCreditDebit = -nAmount;
827 debit.nTime = nNow;
828 debit.strOtherAccount = strTo;
829 debit.strComment = strComment;
830 AddAccountingEntry(debit, &walletdb);
832 // Credit
833 CAccountingEntry credit;
834 credit.nOrderPos = IncOrderPosNext(&walletdb);
835 credit.strAccount = strTo;
836 credit.nCreditDebit = nAmount;
837 credit.nTime = nNow;
838 credit.strOtherAccount = strFrom;
839 credit.strComment = strComment;
840 AddAccountingEntry(credit, &walletdb);
842 if (!walletdb.TxnCommit())
843 return false;
845 return true;
848 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
850 CWalletDB walletdb(*dbw);
852 CAccount account;
853 walletdb.ReadAccount(strAccount, account);
855 if (!bForceNew) {
856 if (!account.vchPubKey.IsValid())
857 bForceNew = true;
858 else {
859 // Check if the current key has been used
860 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
861 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
862 it != mapWallet.end() && account.vchPubKey.IsValid();
863 ++it)
864 for (const CTxOut& txout : (*it).second.tx->vout)
865 if (txout.scriptPubKey == scriptPubKey) {
866 bForceNew = true;
867 break;
872 // Generate a new key
873 if (bForceNew) {
874 if (!GetKeyFromPool(account.vchPubKey, false))
875 return false;
877 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
878 walletdb.WriteAccount(strAccount, account);
881 pubKey = account.vchPubKey;
883 return true;
886 void CWallet::MarkDirty()
889 LOCK(cs_wallet);
890 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
891 item.second.MarkDirty();
895 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
897 LOCK(cs_wallet);
899 auto mi = mapWallet.find(originalHash);
901 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
902 assert(mi != mapWallet.end());
904 CWalletTx& wtx = (*mi).second;
906 // Ensure for now that we're not overwriting data
907 assert(wtx.mapValue.count("replaced_by_txid") == 0);
909 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
911 CWalletDB walletdb(*dbw, "r+");
913 bool success = true;
914 if (!walletdb.WriteTx(wtx)) {
915 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
916 success = false;
919 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
921 return success;
924 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
926 LOCK(cs_wallet);
928 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
930 uint256 hash = wtxIn.GetHash();
932 // Inserts only if not already there, returns tx inserted or tx found
933 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
934 CWalletTx& wtx = (*ret.first).second;
935 wtx.BindWallet(this);
936 bool fInsertedNew = ret.second;
937 if (fInsertedNew)
939 wtx.nTimeReceived = GetAdjustedTime();
940 wtx.nOrderPos = IncOrderPosNext(&walletdb);
941 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
942 wtx.nTimeSmart = ComputeTimeSmart(wtx);
943 AddToSpends(hash);
946 bool fUpdated = false;
947 if (!fInsertedNew)
949 // Merge
950 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
952 wtx.hashBlock = wtxIn.hashBlock;
953 fUpdated = true;
955 // If no longer abandoned, update
956 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
958 wtx.hashBlock = wtxIn.hashBlock;
959 fUpdated = true;
961 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
963 wtx.nIndex = wtxIn.nIndex;
964 fUpdated = true;
966 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
968 wtx.fFromMe = wtxIn.fFromMe;
969 fUpdated = true;
973 //// debug print
974 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
976 // Write to disk
977 if (fInsertedNew || fUpdated)
978 if (!walletdb.WriteTx(wtx))
979 return false;
981 // Break debit/credit balance caches:
982 wtx.MarkDirty();
984 // Notify UI of new or updated transaction
985 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
987 // notify an external script when a wallet transaction comes in or is updated
988 std::string strCmd = GetArg("-walletnotify", "");
990 if ( !strCmd.empty())
992 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
993 boost::thread t(runCommand, strCmd); // thread runs free
996 return true;
999 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
1001 uint256 hash = wtxIn.GetHash();
1003 mapWallet[hash] = wtxIn;
1004 CWalletTx& wtx = mapWallet[hash];
1005 wtx.BindWallet(this);
1006 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
1007 AddToSpends(hash);
1008 for (const CTxIn& txin : wtx.tx->vin) {
1009 if (mapWallet.count(txin.prevout.hash)) {
1010 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
1011 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
1012 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
1017 return true;
1021 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1022 * be set when the transaction was known to be included in a block. When
1023 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
1024 * notifications happen and cached balances are marked dirty.
1026 * If fUpdate is true, existing transactions will be updated.
1027 * TODO: One exception to this is that the abandoned state is cleared under the
1028 * assumption that any further notification of a transaction that was considered
1029 * abandoned is an indication that it is not safe to be considered abandoned.
1030 * Abandoned state should probably be more carefully tracked via different
1031 * posInBlock signals or by checking mempool presence when necessary.
1033 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1035 const CTransaction& tx = *ptx;
1037 AssertLockHeld(cs_wallet);
1039 if (pIndex != NULL) {
1040 for (const CTxIn& txin : tx.vin) {
1041 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1042 while (range.first != range.second) {
1043 if (range.first->second != tx.GetHash()) {
1044 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);
1045 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1047 range.first++;
1052 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1053 if (fExisted && !fUpdate) return false;
1054 if (fExisted || IsMine(tx) || IsFromMe(tx))
1056 CWalletTx wtx(this, ptx);
1058 // Get merkle branch if transaction was found in a block
1059 if (pIndex != NULL)
1060 wtx.SetMerkleBranch(pIndex, posInBlock);
1062 return AddToWallet(wtx, false);
1065 return false;
1068 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1070 LOCK2(cs_main, cs_wallet);
1071 const CWalletTx* wtx = GetWalletTx(hashTx);
1072 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1075 bool CWallet::AbandonTransaction(const uint256& hashTx)
1077 LOCK2(cs_main, cs_wallet);
1079 CWalletDB walletdb(*dbw, "r+");
1081 std::set<uint256> todo;
1082 std::set<uint256> done;
1084 // Can't mark abandoned if confirmed or in mempool
1085 assert(mapWallet.count(hashTx));
1086 CWalletTx& origtx = mapWallet[hashTx];
1087 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1088 return false;
1091 todo.insert(hashTx);
1093 while (!todo.empty()) {
1094 uint256 now = *todo.begin();
1095 todo.erase(now);
1096 done.insert(now);
1097 assert(mapWallet.count(now));
1098 CWalletTx& wtx = mapWallet[now];
1099 int currentconfirm = wtx.GetDepthInMainChain();
1100 // If the orig tx was not in block, none of its spends can be
1101 assert(currentconfirm <= 0);
1102 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1103 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1104 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1105 assert(!wtx.InMempool());
1106 wtx.nIndex = -1;
1107 wtx.setAbandoned();
1108 wtx.MarkDirty();
1109 walletdb.WriteTx(wtx);
1110 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1111 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1112 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1113 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1114 if (!done.count(iter->second)) {
1115 todo.insert(iter->second);
1117 iter++;
1119 // If a transaction changes 'conflicted' state, that changes the balance
1120 // available of the outputs it spends. So force those to be recomputed
1121 for (const CTxIn& txin : wtx.tx->vin)
1123 if (mapWallet.count(txin.prevout.hash))
1124 mapWallet[txin.prevout.hash].MarkDirty();
1129 return true;
1132 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1134 LOCK2(cs_main, cs_wallet);
1136 int conflictconfirms = 0;
1137 if (mapBlockIndex.count(hashBlock)) {
1138 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1139 if (chainActive.Contains(pindex)) {
1140 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1143 // If number of conflict confirms cannot be determined, this means
1144 // that the block is still unknown or not yet part of the main chain,
1145 // for example when loading the wallet during a reindex. Do nothing in that
1146 // case.
1147 if (conflictconfirms >= 0)
1148 return;
1150 // Do not flush the wallet here for performance reasons
1151 CWalletDB walletdb(*dbw, "r+", false);
1153 std::set<uint256> todo;
1154 std::set<uint256> done;
1156 todo.insert(hashTx);
1158 while (!todo.empty()) {
1159 uint256 now = *todo.begin();
1160 todo.erase(now);
1161 done.insert(now);
1162 assert(mapWallet.count(now));
1163 CWalletTx& wtx = mapWallet[now];
1164 int currentconfirm = wtx.GetDepthInMainChain();
1165 if (conflictconfirms < currentconfirm) {
1166 // Block is 'more conflicted' than current confirm; update.
1167 // Mark transaction as conflicted with this block.
1168 wtx.nIndex = -1;
1169 wtx.hashBlock = hashBlock;
1170 wtx.MarkDirty();
1171 walletdb.WriteTx(wtx);
1172 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1173 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1174 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1175 if (!done.count(iter->second)) {
1176 todo.insert(iter->second);
1178 iter++;
1180 // If a transaction changes 'conflicted' state, that changes the balance
1181 // available of the outputs it spends. So force those to be recomputed
1182 for (const CTxIn& txin : wtx.tx->vin)
1184 if (mapWallet.count(txin.prevout.hash))
1185 mapWallet[txin.prevout.hash].MarkDirty();
1191 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1192 const CTransaction& tx = *ptx;
1194 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1195 return; // Not one of ours
1197 // If a transaction changes 'conflicted' state, that changes the balance
1198 // available of the outputs it spends. So force those to be
1199 // recomputed, also:
1200 for (const CTxIn& txin : tx.vin)
1202 if (mapWallet.count(txin.prevout.hash))
1203 mapWallet[txin.prevout.hash].MarkDirty();
1207 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1208 LOCK2(cs_main, cs_wallet);
1209 SyncTransaction(ptx);
1212 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1213 LOCK2(cs_main, cs_wallet);
1214 // TODO: Temporarily ensure that mempool removals are notified before
1215 // connected transactions. This shouldn't matter, but the abandoned
1216 // state of transactions in our wallet is currently cleared when we
1217 // receive another notification and there is a race condition where
1218 // notification of a connected conflict might cause an outside process
1219 // to abandon a transaction and then have it inadvertently cleared by
1220 // the notification that the conflicted transaction was evicted.
1222 for (const CTransactionRef& ptx : vtxConflicted) {
1223 SyncTransaction(ptx);
1225 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1226 SyncTransaction(pblock->vtx[i], pindex, i);
1230 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1231 LOCK2(cs_main, cs_wallet);
1233 for (const CTransactionRef& ptx : pblock->vtx) {
1234 SyncTransaction(ptx);
1240 isminetype CWallet::IsMine(const CTxIn &txin) const
1243 LOCK(cs_wallet);
1244 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1245 if (mi != mapWallet.end())
1247 const CWalletTx& prev = (*mi).second;
1248 if (txin.prevout.n < prev.tx->vout.size())
1249 return IsMine(prev.tx->vout[txin.prevout.n]);
1252 return ISMINE_NO;
1255 // Note that this function doesn't distinguish between a 0-valued input,
1256 // and a not-"is mine" (according to the filter) input.
1257 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1260 LOCK(cs_wallet);
1261 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1262 if (mi != mapWallet.end())
1264 const CWalletTx& prev = (*mi).second;
1265 if (txin.prevout.n < prev.tx->vout.size())
1266 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1267 return prev.tx->vout[txin.prevout.n].nValue;
1270 return 0;
1273 isminetype CWallet::IsMine(const CTxOut& txout) const
1275 return ::IsMine(*this, txout.scriptPubKey);
1278 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1280 if (!MoneyRange(txout.nValue))
1281 throw std::runtime_error(std::string(__func__) + ": value out of range");
1282 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1285 bool CWallet::IsChange(const CTxOut& txout) const
1287 // TODO: fix handling of 'change' outputs. The assumption is that any
1288 // payment to a script that is ours, but is not in the address book
1289 // is change. That assumption is likely to break when we implement multisignature
1290 // wallets that return change back into a multi-signature-protected address;
1291 // a better way of identifying which outputs are 'the send' and which are
1292 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1293 // which output, if any, was change).
1294 if (::IsMine(*this, txout.scriptPubKey))
1296 CTxDestination address;
1297 if (!ExtractDestination(txout.scriptPubKey, address))
1298 return true;
1300 LOCK(cs_wallet);
1301 if (!mapAddressBook.count(address))
1302 return true;
1304 return false;
1307 CAmount CWallet::GetChange(const CTxOut& txout) const
1309 if (!MoneyRange(txout.nValue))
1310 throw std::runtime_error(std::string(__func__) + ": value out of range");
1311 return (IsChange(txout) ? txout.nValue : 0);
1314 bool CWallet::IsMine(const CTransaction& tx) const
1316 for (const CTxOut& txout : tx.vout)
1317 if (IsMine(txout))
1318 return true;
1319 return false;
1322 bool CWallet::IsFromMe(const CTransaction& tx) const
1324 return (GetDebit(tx, ISMINE_ALL) > 0);
1327 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1329 CAmount nDebit = 0;
1330 for (const CTxIn& txin : tx.vin)
1332 nDebit += GetDebit(txin, filter);
1333 if (!MoneyRange(nDebit))
1334 throw std::runtime_error(std::string(__func__) + ": value out of range");
1336 return nDebit;
1339 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1341 LOCK(cs_wallet);
1343 for (const CTxIn& txin : tx.vin)
1345 auto mi = mapWallet.find(txin.prevout.hash);
1346 if (mi == mapWallet.end())
1347 return false; // any unknown inputs can't be from us
1349 const CWalletTx& prev = (*mi).second;
1351 if (txin.prevout.n >= prev.tx->vout.size())
1352 return false; // invalid input!
1354 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1355 return false;
1357 return true;
1360 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1362 CAmount nCredit = 0;
1363 for (const CTxOut& txout : tx.vout)
1365 nCredit += GetCredit(txout, filter);
1366 if (!MoneyRange(nCredit))
1367 throw std::runtime_error(std::string(__func__) + ": value out of range");
1369 return nCredit;
1372 CAmount CWallet::GetChange(const CTransaction& tx) const
1374 CAmount nChange = 0;
1375 for (const CTxOut& txout : tx.vout)
1377 nChange += GetChange(txout);
1378 if (!MoneyRange(nChange))
1379 throw std::runtime_error(std::string(__func__) + ": value out of range");
1381 return nChange;
1384 CPubKey CWallet::GenerateNewHDMasterKey()
1386 CKey key;
1387 key.MakeNewKey(true);
1389 int64_t nCreationTime = GetTime();
1390 CKeyMetadata metadata(nCreationTime);
1392 // calculate the pubkey
1393 CPubKey pubkey = key.GetPubKey();
1394 assert(key.VerifyPubKey(pubkey));
1396 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1397 metadata.hdKeypath = "m";
1398 metadata.hdMasterKeyID = pubkey.GetID();
1401 LOCK(cs_wallet);
1403 // mem store the metadata
1404 mapKeyMetadata[pubkey.GetID()] = metadata;
1406 // write the key&metadata to the database
1407 if (!AddKeyPubKey(key, pubkey))
1408 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1411 return pubkey;
1414 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1416 LOCK(cs_wallet);
1417 // store the keyid (hash160) together with
1418 // the child index counter in the database
1419 // as a hdchain object
1420 CHDChain newHdChain;
1421 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1422 newHdChain.masterKeyID = pubkey.GetID();
1423 SetHDChain(newHdChain, false);
1425 return true;
1428 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1430 LOCK(cs_wallet);
1431 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1432 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1434 hdChain = chain;
1435 return true;
1438 bool CWallet::IsHDEnabled() const
1440 return !hdChain.masterKeyID.IsNull();
1443 int64_t CWalletTx::GetTxTime() const
1445 int64_t n = nTimeSmart;
1446 return n ? n : nTimeReceived;
1449 int CWalletTx::GetRequestCount() const
1451 // Returns -1 if it wasn't being tracked
1452 int nRequests = -1;
1454 LOCK(pwallet->cs_wallet);
1455 if (IsCoinBase())
1457 // Generated block
1458 if (!hashUnset())
1460 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1461 if (mi != pwallet->mapRequestCount.end())
1462 nRequests = (*mi).second;
1465 else
1467 // Did anyone request this transaction?
1468 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1469 if (mi != pwallet->mapRequestCount.end())
1471 nRequests = (*mi).second;
1473 // How about the block it's in?
1474 if (nRequests == 0 && !hashUnset())
1476 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1477 if (_mi != pwallet->mapRequestCount.end())
1478 nRequests = (*_mi).second;
1479 else
1480 nRequests = 1; // If it's in someone else's block it must have got out
1485 return nRequests;
1488 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1489 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1491 nFee = 0;
1492 listReceived.clear();
1493 listSent.clear();
1494 strSentAccount = strFromAccount;
1496 // Compute fee:
1497 CAmount nDebit = GetDebit(filter);
1498 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1500 CAmount nValueOut = tx->GetValueOut();
1501 nFee = nDebit - nValueOut;
1504 // Sent/received.
1505 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1507 const CTxOut& txout = tx->vout[i];
1508 isminetype fIsMine = pwallet->IsMine(txout);
1509 // Only need to handle txouts if AT LEAST one of these is true:
1510 // 1) they debit from us (sent)
1511 // 2) the output is to us (received)
1512 if (nDebit > 0)
1514 // Don't report 'change' txouts
1515 if (pwallet->IsChange(txout))
1516 continue;
1518 else if (!(fIsMine & filter))
1519 continue;
1521 // In either case, we need to get the destination address
1522 CTxDestination address;
1524 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1526 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1527 this->GetHash().ToString());
1528 address = CNoDestination();
1531 COutputEntry output = {address, txout.nValue, (int)i};
1533 // If we are debited by the transaction, add the output as a "sent" entry
1534 if (nDebit > 0)
1535 listSent.push_back(output);
1537 // If we are receiving the output, add it as a "received" entry
1538 if (fIsMine & filter)
1539 listReceived.push_back(output);
1545 * Scan active chain for relevant transactions after importing keys. This should
1546 * be called whenever new keys are added to the wallet, with the oldest key
1547 * creation time.
1549 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1550 * returned will be higher than startTime if relevant blocks could not be read.
1552 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1554 AssertLockHeld(cs_main);
1555 AssertLockHeld(cs_wallet);
1557 // Find starting block. May be null if nCreateTime is greater than the
1558 // highest blockchain timestamp, in which case there is nothing that needs
1559 // to be scanned.
1560 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1561 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1563 if (startBlock) {
1564 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1565 if (failedBlock) {
1566 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1569 return startTime;
1573 * Scan the block chain (starting in pindexStart) for transactions
1574 * from or to us. If fUpdate is true, found transactions that already
1575 * exist in the wallet will be updated.
1577 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1578 * possible (due to pruning or corruption), returns pointer to the most recent
1579 * block that could not be scanned.
1581 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1583 int64_t nNow = GetTime();
1584 const CChainParams& chainParams = Params();
1586 CBlockIndex* pindex = pindexStart;
1587 CBlockIndex* ret = nullptr;
1589 LOCK2(cs_main, cs_wallet);
1590 fAbortRescan = false;
1591 fScanningWallet = true;
1593 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1594 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1595 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1596 while (pindex && !fAbortRescan)
1598 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1599 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1600 if (GetTime() >= nNow + 60) {
1601 nNow = GetTime();
1602 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1605 CBlock block;
1606 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1607 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1608 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1610 } else {
1611 ret = pindex;
1613 pindex = chainActive.Next(pindex);
1615 if (pindex && fAbortRescan) {
1616 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1618 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1620 fScanningWallet = false;
1622 return ret;
1625 void CWallet::ReacceptWalletTransactions()
1627 // If transactions aren't being broadcasted, don't let them into local mempool either
1628 if (!fBroadcastTransactions)
1629 return;
1630 LOCK2(cs_main, cs_wallet);
1631 std::map<int64_t, CWalletTx*> mapSorted;
1633 // Sort pending wallet transactions based on their initial wallet insertion order
1634 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1636 const uint256& wtxid = item.first;
1637 CWalletTx& wtx = item.second;
1638 assert(wtx.GetHash() == wtxid);
1640 int nDepth = wtx.GetDepthInMainChain();
1642 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1643 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1647 // Try to add wallet transactions to memory pool
1648 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1650 CWalletTx& wtx = *(item.second);
1652 LOCK(mempool.cs);
1653 CValidationState state;
1654 wtx.AcceptToMemoryPool(maxTxFee, state);
1658 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1660 assert(pwallet->GetBroadcastTransactions());
1661 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1663 CValidationState state;
1664 /* GetDepthInMainChain already catches known conflicts. */
1665 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1666 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1667 if (connman) {
1668 CInv inv(MSG_TX, GetHash());
1669 connman->ForEachNode([&inv](CNode* pnode)
1671 pnode->PushInventory(inv);
1673 return true;
1677 return false;
1680 std::set<uint256> CWalletTx::GetConflicts() const
1682 std::set<uint256> result;
1683 if (pwallet != NULL)
1685 uint256 myHash = GetHash();
1686 result = pwallet->GetConflicts(myHash);
1687 result.erase(myHash);
1689 return result;
1692 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1694 if (tx->vin.empty())
1695 return 0;
1697 CAmount debit = 0;
1698 if(filter & ISMINE_SPENDABLE)
1700 if (fDebitCached)
1701 debit += nDebitCached;
1702 else
1704 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1705 fDebitCached = true;
1706 debit += nDebitCached;
1709 if(filter & ISMINE_WATCH_ONLY)
1711 if(fWatchDebitCached)
1712 debit += nWatchDebitCached;
1713 else
1715 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1716 fWatchDebitCached = true;
1717 debit += nWatchDebitCached;
1720 return debit;
1723 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1725 // Must wait until coinbase is safely deep enough in the chain before valuing it
1726 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1727 return 0;
1729 CAmount credit = 0;
1730 if (filter & ISMINE_SPENDABLE)
1732 // GetBalance can assume transactions in mapWallet won't change
1733 if (fCreditCached)
1734 credit += nCreditCached;
1735 else
1737 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1738 fCreditCached = true;
1739 credit += nCreditCached;
1742 if (filter & ISMINE_WATCH_ONLY)
1744 if (fWatchCreditCached)
1745 credit += nWatchCreditCached;
1746 else
1748 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1749 fWatchCreditCached = true;
1750 credit += nWatchCreditCached;
1753 return credit;
1756 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1758 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1760 if (fUseCache && fImmatureCreditCached)
1761 return nImmatureCreditCached;
1762 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1763 fImmatureCreditCached = true;
1764 return nImmatureCreditCached;
1767 return 0;
1770 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1772 if (pwallet == 0)
1773 return 0;
1775 // Must wait until coinbase is safely deep enough in the chain before valuing it
1776 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1777 return 0;
1779 if (fUseCache && fAvailableCreditCached)
1780 return nAvailableCreditCached;
1782 CAmount nCredit = 0;
1783 uint256 hashTx = GetHash();
1784 for (unsigned int i = 0; i < tx->vout.size(); i++)
1786 if (!pwallet->IsSpent(hashTx, i))
1788 const CTxOut &txout = tx->vout[i];
1789 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1790 if (!MoneyRange(nCredit))
1791 throw std::runtime_error(std::string(__func__) + " : value out of range");
1795 nAvailableCreditCached = nCredit;
1796 fAvailableCreditCached = true;
1797 return nCredit;
1800 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1802 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1804 if (fUseCache && fImmatureWatchCreditCached)
1805 return nImmatureWatchCreditCached;
1806 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1807 fImmatureWatchCreditCached = true;
1808 return nImmatureWatchCreditCached;
1811 return 0;
1814 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1816 if (pwallet == 0)
1817 return 0;
1819 // Must wait until coinbase is safely deep enough in the chain before valuing it
1820 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1821 return 0;
1823 if (fUseCache && fAvailableWatchCreditCached)
1824 return nAvailableWatchCreditCached;
1826 CAmount nCredit = 0;
1827 for (unsigned int i = 0; i < tx->vout.size(); i++)
1829 if (!pwallet->IsSpent(GetHash(), i))
1831 const CTxOut &txout = tx->vout[i];
1832 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1833 if (!MoneyRange(nCredit))
1834 throw std::runtime_error(std::string(__func__) + ": value out of range");
1838 nAvailableWatchCreditCached = nCredit;
1839 fAvailableWatchCreditCached = true;
1840 return nCredit;
1843 CAmount CWalletTx::GetChange() const
1845 if (fChangeCached)
1846 return nChangeCached;
1847 nChangeCached = pwallet->GetChange(*this);
1848 fChangeCached = true;
1849 return nChangeCached;
1852 bool CWalletTx::InMempool() const
1854 LOCK(mempool.cs);
1855 return mempool.exists(GetHash());
1858 bool CWalletTx::IsTrusted() const
1860 // Quick answer in most cases
1861 if (!CheckFinalTx(*this))
1862 return false;
1863 int nDepth = GetDepthInMainChain();
1864 if (nDepth >= 1)
1865 return true;
1866 if (nDepth < 0)
1867 return false;
1868 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1869 return false;
1871 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1872 if (!InMempool())
1873 return false;
1875 // Trusted if all inputs are from us and are in the mempool:
1876 for (const CTxIn& txin : tx->vin)
1878 // Transactions not sent by us: not trusted
1879 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1880 if (parent == NULL)
1881 return false;
1882 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1883 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1884 return false;
1886 return true;
1889 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1891 CMutableTransaction tx1 = *this->tx;
1892 CMutableTransaction tx2 = *_tx.tx;
1893 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1894 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1895 return CTransaction(tx1) == CTransaction(tx2);
1898 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1900 std::vector<uint256> result;
1902 LOCK(cs_wallet);
1903 // Sort them in chronological order
1904 std::multimap<unsigned int, CWalletTx*> mapSorted;
1905 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1907 CWalletTx& wtx = item.second;
1908 // Don't rebroadcast if newer than nTime:
1909 if (wtx.nTimeReceived > nTime)
1910 continue;
1911 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1913 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1915 CWalletTx& wtx = *item.second;
1916 if (wtx.RelayWalletTransaction(connman))
1917 result.push_back(wtx.GetHash());
1919 return result;
1922 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1924 // Do this infrequently and randomly to avoid giving away
1925 // that these are our transactions.
1926 if (GetTime() < nNextResend || !fBroadcastTransactions)
1927 return;
1928 bool fFirst = (nNextResend == 0);
1929 nNextResend = GetTime() + GetRand(30 * 60);
1930 if (fFirst)
1931 return;
1933 // Only do it if there's been a new block since last time
1934 if (nBestBlockTime < nLastResend)
1935 return;
1936 nLastResend = GetTime();
1938 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1939 // block was found:
1940 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1941 if (!relayed.empty())
1942 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1945 /** @} */ // end of mapWallet
1950 /** @defgroup Actions
1952 * @{
1956 CAmount CWallet::GetBalance() const
1958 CAmount nTotal = 0;
1960 LOCK2(cs_main, cs_wallet);
1961 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1963 const CWalletTx* pcoin = &(*it).second;
1964 if (pcoin->IsTrusted())
1965 nTotal += pcoin->GetAvailableCredit();
1969 return nTotal;
1972 CAmount CWallet::GetUnconfirmedBalance() const
1974 CAmount nTotal = 0;
1976 LOCK2(cs_main, cs_wallet);
1977 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1979 const CWalletTx* pcoin = &(*it).second;
1980 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1981 nTotal += pcoin->GetAvailableCredit();
1984 return nTotal;
1987 CAmount CWallet::GetImmatureBalance() const
1989 CAmount nTotal = 0;
1991 LOCK2(cs_main, cs_wallet);
1992 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1994 const CWalletTx* pcoin = &(*it).second;
1995 nTotal += pcoin->GetImmatureCredit();
1998 return nTotal;
2001 CAmount CWallet::GetWatchOnlyBalance() const
2003 CAmount nTotal = 0;
2005 LOCK2(cs_main, cs_wallet);
2006 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2008 const CWalletTx* pcoin = &(*it).second;
2009 if (pcoin->IsTrusted())
2010 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2014 return nTotal;
2017 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2019 CAmount nTotal = 0;
2021 LOCK2(cs_main, cs_wallet);
2022 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2024 const CWalletTx* pcoin = &(*it).second;
2025 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2026 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2029 return nTotal;
2032 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2034 CAmount nTotal = 0;
2036 LOCK2(cs_main, cs_wallet);
2037 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2039 const CWalletTx* pcoin = &(*it).second;
2040 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2043 return nTotal;
2046 // Calculate total balance in a different way from GetBalance. The biggest
2047 // difference is that GetBalance sums up all unspent TxOuts paying to the
2048 // wallet, while this sums up both spent and unspent TxOuts paying to the
2049 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2050 // also has fewer restrictions on which unconfirmed transactions are considered
2051 // trusted.
2052 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2054 LOCK2(cs_main, cs_wallet);
2056 CAmount balance = 0;
2057 for (const auto& entry : mapWallet) {
2058 const CWalletTx& wtx = entry.second;
2059 const int depth = wtx.GetDepthInMainChain();
2060 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2061 continue;
2064 // Loop through tx outputs and add incoming payments. For outgoing txs,
2065 // treat change outputs specially, as part of the amount debited.
2066 CAmount debit = wtx.GetDebit(filter);
2067 const bool outgoing = debit > 0;
2068 for (const CTxOut& out : wtx.tx->vout) {
2069 if (outgoing && IsChange(out)) {
2070 debit -= out.nValue;
2071 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2072 balance += out.nValue;
2076 // For outgoing txs, subtract amount debited.
2077 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2078 balance -= debit;
2082 if (account) {
2083 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2086 return balance;
2089 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2091 LOCK2(cs_main, cs_wallet);
2093 CAmount balance = 0;
2094 std::vector<COutput> vCoins;
2095 AvailableCoins(vCoins, true, coinControl);
2096 for (const COutput& out : vCoins) {
2097 if (out.fSpendable) {
2098 balance += out.tx->tx->vout[out.i].nValue;
2101 return balance;
2104 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
2106 vCoins.clear();
2109 LOCK2(cs_main, cs_wallet);
2111 CAmount nTotal = 0;
2113 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2115 const uint256& wtxid = it->first;
2116 const CWalletTx* pcoin = &(*it).second;
2118 if (!CheckFinalTx(*pcoin))
2119 continue;
2121 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2122 continue;
2124 int nDepth = pcoin->GetDepthInMainChain();
2125 if (nDepth < 0)
2126 continue;
2128 // We should not consider coins which aren't at least in our mempool
2129 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2130 if (nDepth == 0 && !pcoin->InMempool())
2131 continue;
2133 bool safeTx = pcoin->IsTrusted();
2135 // We should not consider coins from transactions that are replacing
2136 // other transactions.
2138 // Example: There is a transaction A which is replaced by bumpfee
2139 // transaction B. In this case, we want to prevent creation of
2140 // a transaction B' which spends an output of B.
2142 // Reason: If transaction A were initially confirmed, transactions B
2143 // and B' would no longer be valid, so the user would have to create
2144 // a new transaction C to replace B'. However, in the case of a
2145 // one-block reorg, transactions B' and C might BOTH be accepted,
2146 // when the user only wanted one of them. Specifically, there could
2147 // be a 1-block reorg away from the chain where transactions A and C
2148 // were accepted to another chain where B, B', and C were all
2149 // accepted.
2150 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2151 safeTx = false;
2154 // Similarly, we should not consider coins from transactions that
2155 // have been replaced. In the example above, we would want to prevent
2156 // creation of a transaction A' spending an output of A, because if
2157 // transaction B were initially confirmed, conflicting with A and
2158 // A', we wouldn't want to the user to create a transaction D
2159 // intending to replace A', but potentially resulting in a scenario
2160 // where A, A', and D could all be accepted (instead of just B and
2161 // D, or just A and A' like the user would want).
2162 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2163 safeTx = false;
2166 if (fOnlySafe && !safeTx) {
2167 continue;
2170 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2171 continue;
2173 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2174 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2175 continue;
2177 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2178 continue;
2180 if (IsLockedCoin((*it).first, i))
2181 continue;
2183 if (IsSpent(wtxid, i))
2184 continue;
2186 isminetype mine = IsMine(pcoin->tx->vout[i]);
2188 if (mine == ISMINE_NO) {
2189 continue;
2192 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2193 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2195 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2197 // Checks the sum amount of all UTXO's.
2198 if (nMinimumSumAmount != MAX_MONEY) {
2199 nTotal += pcoin->tx->vout[i].nValue;
2201 if (nTotal >= nMinimumSumAmount) {
2202 return;
2206 // Checks the maximum number of UTXO's.
2207 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2208 return;
2215 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2217 // TODO: Add AssertLockHeld(cs_wallet) here.
2219 // Because the return value from this function contains pointers to
2220 // CWalletTx objects, callers to this function really should acquire the
2221 // cs_wallet lock before calling it. However, the current caller doesn't
2222 // acquire this lock yet. There was an attempt to add the missing lock in
2223 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2224 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2225 // avoid adding some extra complexity to the Qt code.
2227 std::map<CTxDestination, std::vector<COutput>> result;
2229 std::vector<COutput> availableCoins;
2230 AvailableCoins(availableCoins);
2232 LOCK2(cs_main, cs_wallet);
2233 for (auto& coin : availableCoins) {
2234 CTxDestination address;
2235 if (coin.fSpendable &&
2236 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2237 result[address].emplace_back(std::move(coin));
2241 std::vector<COutPoint> lockedCoins;
2242 ListLockedCoins(lockedCoins);
2243 for (const auto& output : lockedCoins) {
2244 auto it = mapWallet.find(output.hash);
2245 if (it != mapWallet.end()) {
2246 int depth = it->second.GetDepthInMainChain();
2247 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2248 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2249 CTxDestination address;
2250 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2251 result[address].emplace_back(
2252 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2258 return result;
2261 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2263 const CTransaction* ptx = &tx;
2264 int n = output;
2265 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2266 const COutPoint& prevout = ptx->vin[0].prevout;
2267 auto it = mapWallet.find(prevout.hash);
2268 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2269 !IsMine(it->second.tx->vout[prevout.n])) {
2270 break;
2272 ptx = it->second.tx.get();
2273 n = prevout.n;
2275 return ptx->vout[n];
2278 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2279 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2281 std::vector<char> vfIncluded;
2283 vfBest.assign(vValue.size(), true);
2284 nBest = nTotalLower;
2286 FastRandomContext insecure_rand;
2288 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2290 vfIncluded.assign(vValue.size(), false);
2291 CAmount nTotal = 0;
2292 bool fReachedTarget = false;
2293 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2295 for (unsigned int i = 0; i < vValue.size(); i++)
2297 //The solver here uses a randomized algorithm,
2298 //the randomness serves no real security purpose but is just
2299 //needed to prevent degenerate behavior and it is important
2300 //that the rng is fast. We do not use a constant random sequence,
2301 //because there may be some privacy improvement by making
2302 //the selection random.
2303 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2305 nTotal += vValue[i].txout.nValue;
2306 vfIncluded[i] = true;
2307 if (nTotal >= nTargetValue)
2309 fReachedTarget = true;
2310 if (nTotal < nBest)
2312 nBest = nTotal;
2313 vfBest = vfIncluded;
2315 nTotal -= vValue[i].txout.nValue;
2316 vfIncluded[i] = false;
2324 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2325 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2327 setCoinsRet.clear();
2328 nValueRet = 0;
2330 // List of values less than target
2331 boost::optional<CInputCoin> coinLowestLarger;
2332 std::vector<CInputCoin> vValue;
2333 CAmount nTotalLower = 0;
2335 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2337 for (const COutput &output : vCoins)
2339 if (!output.fSpendable)
2340 continue;
2342 const CWalletTx *pcoin = output.tx;
2344 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2345 continue;
2347 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2348 continue;
2350 int i = output.i;
2352 CInputCoin coin = CInputCoin(pcoin, i);
2354 if (coin.txout.nValue == nTargetValue)
2356 setCoinsRet.insert(coin);
2357 nValueRet += coin.txout.nValue;
2358 return true;
2360 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2362 vValue.push_back(coin);
2363 nTotalLower += coin.txout.nValue;
2365 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2367 coinLowestLarger = coin;
2371 if (nTotalLower == nTargetValue)
2373 for (const auto& input : vValue)
2375 setCoinsRet.insert(input);
2376 nValueRet += input.txout.nValue;
2378 return true;
2381 if (nTotalLower < nTargetValue)
2383 if (!coinLowestLarger)
2384 return false;
2385 setCoinsRet.insert(coinLowestLarger.get());
2386 nValueRet += coinLowestLarger->txout.nValue;
2387 return true;
2390 // Solve subset sum by stochastic approximation
2391 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2392 std::reverse(vValue.begin(), vValue.end());
2393 std::vector<char> vfBest;
2394 CAmount nBest;
2396 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2397 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2398 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2400 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2401 // or the next bigger coin is closer), return the bigger coin
2402 if (coinLowestLarger &&
2403 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2405 setCoinsRet.insert(coinLowestLarger.get());
2406 nValueRet += coinLowestLarger->txout.nValue;
2408 else {
2409 for (unsigned int i = 0; i < vValue.size(); i++)
2410 if (vfBest[i])
2412 setCoinsRet.insert(vValue[i]);
2413 nValueRet += vValue[i].txout.nValue;
2416 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2417 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2418 for (unsigned int i = 0; i < vValue.size(); i++) {
2419 if (vfBest[i]) {
2420 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2423 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2427 return true;
2430 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2432 std::vector<COutput> vCoins(vAvailableCoins);
2434 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2435 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2437 for (const COutput& out : vCoins)
2439 if (!out.fSpendable)
2440 continue;
2441 nValueRet += out.tx->tx->vout[out.i].nValue;
2442 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2444 return (nValueRet >= nTargetValue);
2447 // calculate value from preset inputs and store them
2448 std::set<CInputCoin> setPresetCoins;
2449 CAmount nValueFromPresetInputs = 0;
2451 std::vector<COutPoint> vPresetInputs;
2452 if (coinControl)
2453 coinControl->ListSelected(vPresetInputs);
2454 for (const COutPoint& outpoint : vPresetInputs)
2456 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2457 if (it != mapWallet.end())
2459 const CWalletTx* pcoin = &it->second;
2460 // Clearly invalid input, fail
2461 if (pcoin->tx->vout.size() <= outpoint.n)
2462 return false;
2463 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2464 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2465 } else
2466 return false; // TODO: Allow non-wallet inputs
2469 // remove preset inputs from vCoins
2470 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2472 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2473 it = vCoins.erase(it);
2474 else
2475 ++it;
2478 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2479 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2481 bool res = nTargetValue <= nValueFromPresetInputs ||
2482 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2483 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2484 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2485 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2486 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2487 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2488 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2490 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2491 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2493 // add preset inputs to the total value selected
2494 nValueRet += nValueFromPresetInputs;
2496 return res;
2499 bool CWallet::SignTransaction(CMutableTransaction &tx)
2501 AssertLockHeld(cs_wallet); // mapWallet
2503 // sign the new tx
2504 CTransaction txNewConst(tx);
2505 int nIn = 0;
2506 for (const auto& input : tx.vin) {
2507 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2508 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2509 return false;
2511 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2512 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2513 SignatureData sigdata;
2514 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2515 return false;
2517 UpdateTransaction(tx, nIn, sigdata);
2518 nIn++;
2520 return true;
2523 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2525 std::vector<CRecipient> vecSend;
2527 // Turn the txout set into a CRecipient vector
2528 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2530 const CTxOut& txOut = tx.vout[idx];
2531 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2532 vecSend.push_back(recipient);
2535 coinControl.fAllowOtherInputs = true;
2537 for (const CTxIn& txin : tx.vin)
2538 coinControl.Select(txin.prevout);
2540 CReserveKey reservekey(this);
2541 CWalletTx wtx;
2542 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2543 return false;
2546 if (nChangePosInOut != -1) {
2547 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2548 // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
2549 // so just remove the key from the keypool here.
2550 reservekey.KeepKey();
2553 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2554 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2555 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2557 // Add new txins (keeping original txin scriptSig/order)
2558 for (const CTxIn& txin : wtx.tx->vin)
2560 if (!coinControl.IsSelected(txin.prevout))
2562 tx.vin.push_back(txin);
2564 if (lockUnspents)
2566 LOCK2(cs_main, cs_wallet);
2567 LockCoin(txin.prevout);
2573 return true;
2576 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2578 unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2579 CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2580 // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2581 discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2582 // Discard rate must be at least dustRelayFee
2583 discard_rate = std::max(discard_rate, ::dustRelayFee);
2584 return discard_rate;
2587 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2588 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2590 CAmount nValue = 0;
2591 int nChangePosRequest = nChangePosInOut;
2592 unsigned int nSubtractFeeFromAmount = 0;
2593 for (const auto& recipient : vecSend)
2595 if (nValue < 0 || recipient.nAmount < 0)
2597 strFailReason = _("Transaction amounts must not be negative");
2598 return false;
2600 nValue += recipient.nAmount;
2602 if (recipient.fSubtractFeeFromAmount)
2603 nSubtractFeeFromAmount++;
2605 if (vecSend.empty())
2607 strFailReason = _("Transaction must have at least one recipient");
2608 return false;
2611 wtxNew.fTimeReceivedIsTxTime = true;
2612 wtxNew.BindWallet(this);
2613 CMutableTransaction txNew;
2615 // Discourage fee sniping.
2617 // For a large miner the value of the transactions in the best block and
2618 // the mempool can exceed the cost of deliberately attempting to mine two
2619 // blocks to orphan the current best block. By setting nLockTime such that
2620 // only the next block can include the transaction, we discourage this
2621 // practice as the height restricted and limited blocksize gives miners
2622 // considering fee sniping fewer options for pulling off this attack.
2624 // A simple way to think about this is from the wallet's point of view we
2625 // always want the blockchain to move forward. By setting nLockTime this
2626 // way we're basically making the statement that we only want this
2627 // transaction to appear in the next block; we don't want to potentially
2628 // encourage reorgs by allowing transactions to appear at lower heights
2629 // than the next block in forks of the best chain.
2631 // Of course, the subsidy is high enough, and transaction volume low
2632 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2633 // now we ensure code won't be written that makes assumptions about
2634 // nLockTime that preclude a fix later.
2635 txNew.nLockTime = chainActive.Height();
2637 // Secondly occasionally randomly pick a nLockTime even further back, so
2638 // that transactions that are delayed after signing for whatever reason,
2639 // e.g. high-latency mix networks and some CoinJoin implementations, have
2640 // better privacy.
2641 if (GetRandInt(10) == 0)
2642 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2644 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2645 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2646 FeeCalculation feeCalc;
2647 unsigned int nBytes;
2649 std::set<CInputCoin> setCoins;
2650 LOCK2(cs_main, cs_wallet);
2652 std::vector<COutput> vAvailableCoins;
2653 AvailableCoins(vAvailableCoins, true, &coin_control);
2655 // Create change script that will be used if we need change
2656 // TODO: pass in scriptChange instead of reservekey so
2657 // change transaction isn't always pay-to-bitcoin-address
2658 CScript scriptChange;
2660 // coin control: send change to custom address
2661 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2662 scriptChange = GetScriptForDestination(coin_control.destChange);
2663 } else { // no coin control: send change to newly generated address
2664 // Note: We use a new key here to keep it from being obvious which side is the change.
2665 // The drawback is that by not reusing a previous key, the change may be lost if a
2666 // backup is restored, if the backup doesn't have the new private key for the change.
2667 // If we reused the old key, it would be possible to add code to look for and
2668 // rediscover unknown transactions that were written with keys of ours to recover
2669 // post-backup change.
2671 // Reserve a new key pair from key pool
2672 CPubKey vchPubKey;
2673 bool ret;
2674 ret = reservekey.GetReservedKey(vchPubKey, true);
2675 if (!ret)
2677 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2678 return false;
2681 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2683 CTxOut change_prototype_txout(0, scriptChange);
2684 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2686 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2687 nFeeRet = 0;
2688 bool pick_new_inputs = true;
2689 CAmount nValueIn = 0;
2690 // Start with no fee and loop until there is enough fee
2691 while (true)
2693 nChangePosInOut = nChangePosRequest;
2694 txNew.vin.clear();
2695 txNew.vout.clear();
2696 wtxNew.fFromMe = true;
2697 bool fFirst = true;
2699 CAmount nValueToSelect = nValue;
2700 if (nSubtractFeeFromAmount == 0)
2701 nValueToSelect += nFeeRet;
2702 // vouts to the payees
2703 for (const auto& recipient : vecSend)
2705 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2707 if (recipient.fSubtractFeeFromAmount)
2709 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2711 if (fFirst) // first receiver pays the remainder not divisible by output count
2713 fFirst = false;
2714 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2718 if (IsDust(txout, ::dustRelayFee))
2720 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2722 if (txout.nValue < 0)
2723 strFailReason = _("The transaction amount is too small to pay the fee");
2724 else
2725 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2727 else
2728 strFailReason = _("Transaction amount too small");
2729 return false;
2731 txNew.vout.push_back(txout);
2734 // Choose coins to use
2735 if (pick_new_inputs) {
2736 nValueIn = 0;
2737 setCoins.clear();
2738 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2740 strFailReason = _("Insufficient funds");
2741 return false;
2745 const CAmount nChange = nValueIn - nValueToSelect;
2747 if (nChange > 0)
2749 // Fill a vout to ourself
2750 CTxOut newTxOut(nChange, scriptChange);
2752 // Never create dust outputs; if we would, just
2753 // add the dust to the fee.
2754 if (IsDust(newTxOut, discard_rate))
2756 nChangePosInOut = -1;
2757 nFeeRet += nChange;
2759 else
2761 if (nChangePosInOut == -1)
2763 // Insert change txn at random position:
2764 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2766 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2768 strFailReason = _("Change index out of range");
2769 return false;
2772 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2773 txNew.vout.insert(position, newTxOut);
2775 } else {
2776 nChangePosInOut = -1;
2779 // Fill vin
2781 // Note how the sequence number is set to non-maxint so that
2782 // the nLockTime set above actually works.
2784 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2785 // we use the highest possible value in that range (maxint-2)
2786 // to avoid conflicting with other possible uses of nSequence,
2787 // and in the spirit of "smallest possible change from prior
2788 // behavior."
2789 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2790 for (const auto& coin : setCoins)
2791 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2792 nSequence));
2794 // Fill in dummy signatures for fee calculation.
2795 if (!DummySignTx(txNew, setCoins)) {
2796 strFailReason = _("Signing transaction failed");
2797 return false;
2800 nBytes = GetVirtualTransactionSize(txNew);
2802 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2803 for (auto& vin : txNew.vin) {
2804 vin.scriptSig = CScript();
2805 vin.scriptWitness.SetNull();
2808 CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2810 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2811 // because we must be at the maximum allowed fee.
2812 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2814 strFailReason = _("Transaction too large for fee policy");
2815 return false;
2818 if (nFeeRet >= nFeeNeeded) {
2819 // Reduce fee to only the needed amount if possible. This
2820 // prevents potential overpayment in fees if the coins
2821 // selected to meet nFeeNeeded result in a transaction that
2822 // requires less fee than the prior iteration.
2824 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2825 // to be addressed because it requires returning the fee to
2826 // the payees and not the change output.
2828 // If we have no change and a big enough excess fee, then
2829 // try to construct transaction again only without picking
2830 // new inputs. We now know we only need the smaller fee
2831 // (because of reduced tx size) and so we should add a
2832 // change output. Only try this once.
2833 CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
2834 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2835 CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
2836 if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2837 pick_new_inputs = false;
2838 nFeeRet = nFeeNeeded + fee_needed_for_change;
2839 continue;
2842 // If we have change output already, just increase it
2843 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2844 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2845 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2846 change_position->nValue += extraFeePaid;
2847 nFeeRet -= extraFeePaid;
2849 break; // Done, enough fee included.
2851 else if (!pick_new_inputs) {
2852 // This shouldn't happen, we should have had enough excess
2853 // fee to pay for the new output and still meet nFeeNeeded
2854 strFailReason = _("Transaction fee and change calculation failed");
2855 return false;
2858 // Try to reduce change to include necessary fee
2859 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2860 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2861 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2862 // Only reduce change if remaining amount is still a large enough output.
2863 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2864 change_position->nValue -= additionalFeeNeeded;
2865 nFeeRet += additionalFeeNeeded;
2866 break; // Done, able to increase fee from change
2870 // Include more fee and try again.
2871 nFeeRet = nFeeNeeded;
2872 continue;
2876 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2878 if (sign)
2880 CTransaction txNewConst(txNew);
2881 int nIn = 0;
2882 for (const auto& coin : setCoins)
2884 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2885 SignatureData sigdata;
2887 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2889 strFailReason = _("Signing transaction failed");
2890 return false;
2891 } else {
2892 UpdateTransaction(txNew, nIn, sigdata);
2895 nIn++;
2899 // Embed the constructed transaction data in wtxNew.
2900 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2902 // Limit size
2903 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2905 strFailReason = _("Transaction too large");
2906 return false;
2910 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2911 // Lastly, ensure this tx will pass the mempool's chain limits
2912 LockPoints lp;
2913 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2914 CTxMemPool::setEntries setAncestors;
2915 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2916 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2917 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2918 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2919 std::string errString;
2920 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2921 strFailReason = _("Transaction has too long of a mempool chain");
2922 return false;
2926 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",
2927 nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2928 feeCalc.est.pass.start, feeCalc.est.pass.end,
2929 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2930 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2931 feeCalc.est.fail.start, feeCalc.est.fail.end,
2932 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2933 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2934 return true;
2938 * Call after CreateTransaction unless you want to abort
2940 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2943 LOCK2(cs_main, cs_wallet);
2944 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2946 // Take key pair from key pool so it won't be used again
2947 reservekey.KeepKey();
2949 // Add tx to wallet, because if it has change it's also ours,
2950 // otherwise just for transaction history.
2951 AddToWallet(wtxNew);
2953 // Notify that old coins are spent
2954 for (const CTxIn& txin : wtxNew.tx->vin)
2956 CWalletTx &coin = mapWallet[txin.prevout.hash];
2957 coin.BindWallet(this);
2958 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2962 // Track how many getdata requests our transaction gets
2963 mapRequestCount[wtxNew.GetHash()] = 0;
2965 if (fBroadcastTransactions)
2967 // Broadcast
2968 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2969 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2970 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2971 } else {
2972 wtxNew.RelayWalletTransaction(connman);
2976 return true;
2979 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2980 CWalletDB walletdb(*dbw);
2981 return walletdb.ListAccountCreditDebit(strAccount, entries);
2984 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2986 CWalletDB walletdb(*dbw);
2988 return AddAccountingEntry(acentry, &walletdb);
2991 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2993 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
2994 return false;
2997 laccentries.push_back(acentry);
2998 CAccountingEntry & entry = laccentries.back();
2999 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
3001 return true;
3004 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
3006 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
3009 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
3011 /* User control of how to calculate fee uses the following parameter precedence:
3012 1. coin_control.m_feerate
3013 2. coin_control.m_confirm_target
3014 3. payTxFee (user-set global variable)
3015 4. nTxConfirmTarget (user-set global variable)
3016 The first parameter that is set is used.
3018 CAmount fee_needed;
3019 if (coin_control.m_feerate) { // 1.
3020 fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
3021 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3022 // Allow to override automatic min/max check over coin control instance
3023 if (coin_control.fOverrideFeeRate) return fee_needed;
3025 else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
3026 fee_needed = ::payTxFee.GetFee(nTxBytes);
3027 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
3029 else { // 2. or 4.
3030 // We will use smart fee estimation
3031 unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
3032 // By default estimates are economical iff we are signaling opt-in-RBF
3033 bool conservative_estimate = !coin_control.signalRbf;
3034 // Allow to override the default fee estimate mode over the CoinControl instance
3035 if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3036 else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3038 fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3039 if (fee_needed == 0) {
3040 // if we don't have enough data for estimateSmartFee, then use fallbackFee
3041 fee_needed = fallbackFee.GetFee(nTxBytes);
3042 if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3044 // Obey mempool min fee when using smart fee estimation
3045 CAmount min_mempool_fee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3046 if (fee_needed < min_mempool_fee) {
3047 fee_needed = min_mempool_fee;
3048 if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3052 // prevent user from paying a fee below minRelayTxFee or minTxFee
3053 CAmount required_fee = GetRequiredFee(nTxBytes);
3054 if (required_fee > fee_needed) {
3055 fee_needed = required_fee;
3056 if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3058 // But always obey the maximum
3059 if (fee_needed > maxTxFee) {
3060 fee_needed = maxTxFee;
3061 if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3063 return fee_needed;
3069 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3071 fFirstRunRet = false;
3072 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3073 if (nLoadWalletRet == DB_NEED_REWRITE)
3075 if (dbw->Rewrite("\x04pool"))
3077 LOCK(cs_wallet);
3078 setInternalKeyPool.clear();
3079 setExternalKeyPool.clear();
3080 // Note: can't top-up keypool here, because wallet is locked.
3081 // User will be prompted to unlock wallet the next operation
3082 // that requires a new key.
3086 if (nLoadWalletRet != DB_LOAD_OK)
3087 return nLoadWalletRet;
3088 fFirstRunRet = !vchDefaultKey.IsValid();
3090 uiInterface.LoadWallet(this);
3092 return DB_LOAD_OK;
3095 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3097 AssertLockHeld(cs_wallet); // mapWallet
3098 vchDefaultKey = CPubKey();
3099 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3100 for (uint256 hash : vHashOut)
3101 mapWallet.erase(hash);
3103 if (nZapSelectTxRet == DB_NEED_REWRITE)
3105 if (dbw->Rewrite("\x04pool"))
3107 setInternalKeyPool.clear();
3108 setExternalKeyPool.clear();
3109 // Note: can't top-up keypool here, because wallet is locked.
3110 // User will be prompted to unlock wallet the next operation
3111 // that requires a new key.
3115 if (nZapSelectTxRet != DB_LOAD_OK)
3116 return nZapSelectTxRet;
3118 MarkDirty();
3120 return DB_LOAD_OK;
3124 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3126 vchDefaultKey = CPubKey();
3127 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3128 if (nZapWalletTxRet == DB_NEED_REWRITE)
3130 if (dbw->Rewrite("\x04pool"))
3132 LOCK(cs_wallet);
3133 setInternalKeyPool.clear();
3134 setExternalKeyPool.clear();
3135 // Note: can't top-up keypool here, because wallet is locked.
3136 // User will be prompted to unlock wallet the next operation
3137 // that requires a new key.
3141 if (nZapWalletTxRet != DB_LOAD_OK)
3142 return nZapWalletTxRet;
3144 return DB_LOAD_OK;
3148 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3150 bool fUpdated = false;
3152 LOCK(cs_wallet); // mapAddressBook
3153 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3154 fUpdated = mi != mapAddressBook.end();
3155 mapAddressBook[address].name = strName;
3156 if (!strPurpose.empty()) /* update purpose only if requested */
3157 mapAddressBook[address].purpose = strPurpose;
3159 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3160 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3161 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3162 return false;
3163 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3166 bool CWallet::DelAddressBook(const CTxDestination& address)
3169 LOCK(cs_wallet); // mapAddressBook
3171 // Delete destdata tuples associated with address
3172 std::string strAddress = CBitcoinAddress(address).ToString();
3173 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3175 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3177 mapAddressBook.erase(address);
3180 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3182 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3183 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3186 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3188 CTxDestination address;
3189 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3190 auto mi = mapAddressBook.find(address);
3191 if (mi != mapAddressBook.end()) {
3192 return mi->second.name;
3195 // A scriptPubKey that doesn't have an entry in the address book is
3196 // associated with the default account ("").
3197 const static std::string DEFAULT_ACCOUNT_NAME;
3198 return DEFAULT_ACCOUNT_NAME;
3201 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3203 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3204 return false;
3205 vchDefaultKey = vchPubKey;
3206 return true;
3210 * Mark old keypool keys as used,
3211 * and generate all new keys
3213 bool CWallet::NewKeyPool()
3216 LOCK(cs_wallet);
3217 CWalletDB walletdb(*dbw);
3219 for (int64_t nIndex : setInternalKeyPool) {
3220 walletdb.ErasePool(nIndex);
3222 setInternalKeyPool.clear();
3224 for (int64_t nIndex : setExternalKeyPool) {
3225 walletdb.ErasePool(nIndex);
3227 setExternalKeyPool.clear();
3229 if (!TopUpKeyPool()) {
3230 return false;
3232 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3234 return true;
3237 size_t CWallet::KeypoolCountExternalKeys()
3239 AssertLockHeld(cs_wallet); // setExternalKeyPool
3240 return setExternalKeyPool.size();
3243 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3245 if (keypool.fInternal) {
3246 setInternalKeyPool.insert(nIndex);
3247 } else {
3248 setExternalKeyPool.insert(nIndex);
3250 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3252 // If no metadata exists yet, create a default with the pool key's
3253 // creation time. Note that this may be overwritten by actually
3254 // stored metadata for that key later, which is fine.
3255 CKeyID keyid = keypool.vchPubKey.GetID();
3256 if (mapKeyMetadata.count(keyid) == 0)
3257 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3260 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3263 LOCK(cs_wallet);
3265 if (IsLocked())
3266 return false;
3268 // Top up key pool
3269 unsigned int nTargetSize;
3270 if (kpSize > 0)
3271 nTargetSize = kpSize;
3272 else
3273 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3275 // count amount of available keys (internal, external)
3276 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3277 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3278 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3280 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3282 // don't create extra internal keys
3283 missingInternal = 0;
3285 bool internal = false;
3286 CWalletDB walletdb(*dbw);
3287 for (int64_t i = missingInternal + missingExternal; i--;)
3289 if (i < missingInternal) {
3290 internal = true;
3293 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3294 int64_t index = ++m_max_keypool_index;
3296 if (!walletdb.WritePool(index, CKeyPool(GenerateNewKey(walletdb, internal), internal))) {
3297 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3300 if (internal) {
3301 setInternalKeyPool.insert(index);
3302 } else {
3303 setExternalKeyPool.insert(index);
3306 if (missingInternal + missingExternal > 0) {
3307 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3310 return true;
3313 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3315 nIndex = -1;
3316 keypool.vchPubKey = CPubKey();
3318 LOCK(cs_wallet);
3320 if (!IsLocked())
3321 TopUpKeyPool();
3323 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3324 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3326 // Get the oldest key
3327 if(setKeyPool.empty())
3328 return;
3330 CWalletDB walletdb(*dbw);
3332 auto it = setKeyPool.begin();
3333 nIndex = *it;
3334 setKeyPool.erase(it);
3335 if (!walletdb.ReadPool(nIndex, keypool)) {
3336 throw std::runtime_error(std::string(__func__) + ": read failed");
3338 if (!HaveKey(keypool.vchPubKey.GetID())) {
3339 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3341 if (keypool.fInternal != fReturningInternal) {
3342 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3345 assert(keypool.vchPubKey.IsValid());
3346 LogPrintf("keypool reserve %d\n", nIndex);
3350 void CWallet::KeepKey(int64_t nIndex)
3352 // Remove from key pool
3353 CWalletDB walletdb(*dbw);
3354 walletdb.ErasePool(nIndex);
3355 LogPrintf("keypool keep %d\n", nIndex);
3358 void CWallet::ReturnKey(int64_t nIndex, bool fInternal)
3360 // Return to key pool
3362 LOCK(cs_wallet);
3363 if (fInternal) {
3364 setInternalKeyPool.insert(nIndex);
3365 } else {
3366 setExternalKeyPool.insert(nIndex);
3369 LogPrintf("keypool return %d\n", nIndex);
3372 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3374 CKeyPool keypool;
3376 LOCK(cs_wallet);
3377 int64_t nIndex = 0;
3378 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3379 if (nIndex == -1)
3381 if (IsLocked()) return false;
3382 CWalletDB walletdb(*dbw);
3383 result = GenerateNewKey(walletdb, internal);
3384 return true;
3386 KeepKey(nIndex);
3387 result = keypool.vchPubKey;
3389 return true;
3392 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3393 if (setKeyPool.empty()) {
3394 return GetTime();
3397 CKeyPool keypool;
3398 int64_t nIndex = *(setKeyPool.begin());
3399 if (!walletdb.ReadPool(nIndex, keypool)) {
3400 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3402 assert(keypool.vchPubKey.IsValid());
3403 return keypool.nTime;
3406 int64_t CWallet::GetOldestKeyPoolTime()
3408 LOCK(cs_wallet);
3410 CWalletDB walletdb(*dbw);
3412 // load oldest key from keypool, get time and return
3413 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3414 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3415 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3418 return oldestKey;
3421 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3423 std::map<CTxDestination, CAmount> balances;
3426 LOCK(cs_wallet);
3427 for (const auto& walletEntry : mapWallet)
3429 const CWalletTx *pcoin = &walletEntry.second;
3431 if (!pcoin->IsTrusted())
3432 continue;
3434 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3435 continue;
3437 int nDepth = pcoin->GetDepthInMainChain();
3438 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3439 continue;
3441 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3443 CTxDestination addr;
3444 if (!IsMine(pcoin->tx->vout[i]))
3445 continue;
3446 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3447 continue;
3449 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3451 if (!balances.count(addr))
3452 balances[addr] = 0;
3453 balances[addr] += n;
3458 return balances;
3461 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3463 AssertLockHeld(cs_wallet); // mapWallet
3464 std::set< std::set<CTxDestination> > groupings;
3465 std::set<CTxDestination> grouping;
3467 for (const auto& walletEntry : mapWallet)
3469 const CWalletTx *pcoin = &walletEntry.second;
3471 if (pcoin->tx->vin.size() > 0)
3473 bool any_mine = false;
3474 // group all input addresses with each other
3475 for (CTxIn txin : pcoin->tx->vin)
3477 CTxDestination address;
3478 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3479 continue;
3480 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3481 continue;
3482 grouping.insert(address);
3483 any_mine = true;
3486 // group change with input addresses
3487 if (any_mine)
3489 for (CTxOut txout : pcoin->tx->vout)
3490 if (IsChange(txout))
3492 CTxDestination txoutAddr;
3493 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3494 continue;
3495 grouping.insert(txoutAddr);
3498 if (grouping.size() > 0)
3500 groupings.insert(grouping);
3501 grouping.clear();
3505 // group lone addrs by themselves
3506 for (const auto& txout : pcoin->tx->vout)
3507 if (IsMine(txout))
3509 CTxDestination address;
3510 if(!ExtractDestination(txout.scriptPubKey, address))
3511 continue;
3512 grouping.insert(address);
3513 groupings.insert(grouping);
3514 grouping.clear();
3518 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3519 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3520 for (std::set<CTxDestination> _grouping : groupings)
3522 // make a set of all the groups hit by this new group
3523 std::set< std::set<CTxDestination>* > hits;
3524 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3525 for (CTxDestination address : _grouping)
3526 if ((it = setmap.find(address)) != setmap.end())
3527 hits.insert((*it).second);
3529 // merge all hit groups into a new single group and delete old groups
3530 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3531 for (std::set<CTxDestination>* hit : hits)
3533 merged->insert(hit->begin(), hit->end());
3534 uniqueGroupings.erase(hit);
3535 delete hit;
3537 uniqueGroupings.insert(merged);
3539 // update setmap
3540 for (CTxDestination element : *merged)
3541 setmap[element] = merged;
3544 std::set< std::set<CTxDestination> > ret;
3545 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3547 ret.insert(*uniqueGrouping);
3548 delete uniqueGrouping;
3551 return ret;
3554 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3556 LOCK(cs_wallet);
3557 std::set<CTxDestination> result;
3558 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3560 const CTxDestination& address = item.first;
3561 const std::string& strName = item.second.name;
3562 if (strName == strAccount)
3563 result.insert(address);
3565 return result;
3568 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3570 if (nIndex == -1)
3572 CKeyPool keypool;
3573 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3574 if (nIndex != -1)
3575 vchPubKey = keypool.vchPubKey;
3576 else {
3577 return false;
3579 fInternal = keypool.fInternal;
3581 assert(vchPubKey.IsValid());
3582 pubkey = vchPubKey;
3583 return true;
3586 void CReserveKey::KeepKey()
3588 if (nIndex != -1)
3589 pwallet->KeepKey(nIndex);
3590 nIndex = -1;
3591 vchPubKey = CPubKey();
3594 void CReserveKey::ReturnKey()
3596 if (nIndex != -1) {
3597 pwallet->ReturnKey(nIndex, fInternal);
3599 nIndex = -1;
3600 vchPubKey = CPubKey();
3603 static void LoadReserveKeysToSet(std::set<CKeyID>& setAddress, const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3604 for (const int64_t& id : setKeyPool)
3606 CKeyPool keypool;
3607 if (!walletdb.ReadPool(id, keypool))
3608 throw std::runtime_error(std::string(__func__) + ": read failed");
3609 assert(keypool.vchPubKey.IsValid());
3610 CKeyID keyID = keypool.vchPubKey.GetID();
3611 setAddress.insert(keyID);
3615 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3617 setAddress.clear();
3619 CWalletDB walletdb(*dbw);
3621 LOCK2(cs_main, cs_wallet);
3622 LoadReserveKeysToSet(setAddress, setInternalKeyPool, walletdb);
3623 LoadReserveKeysToSet(setAddress, setExternalKeyPool, walletdb);
3625 for (const CKeyID& keyID : setAddress) {
3626 if (!HaveKey(keyID)) {
3627 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3632 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3634 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3635 CPubKey pubkey;
3636 if (!rKey->GetReservedKey(pubkey))
3637 return;
3639 script = rKey;
3640 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3643 void CWallet::LockCoin(const COutPoint& output)
3645 AssertLockHeld(cs_wallet); // setLockedCoins
3646 setLockedCoins.insert(output);
3649 void CWallet::UnlockCoin(const COutPoint& output)
3651 AssertLockHeld(cs_wallet); // setLockedCoins
3652 setLockedCoins.erase(output);
3655 void CWallet::UnlockAllCoins()
3657 AssertLockHeld(cs_wallet); // setLockedCoins
3658 setLockedCoins.clear();
3661 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3663 AssertLockHeld(cs_wallet); // setLockedCoins
3664 COutPoint outpt(hash, n);
3666 return (setLockedCoins.count(outpt) > 0);
3669 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3671 AssertLockHeld(cs_wallet); // setLockedCoins
3672 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3673 it != setLockedCoins.end(); it++) {
3674 COutPoint outpt = (*it);
3675 vOutpts.push_back(outpt);
3679 /** @} */ // end of Actions
3681 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3682 AssertLockHeld(cs_wallet); // mapKeyMetadata
3683 mapKeyBirth.clear();
3685 // get birth times for keys with metadata
3686 for (const auto& entry : mapKeyMetadata) {
3687 if (entry.second.nCreateTime) {
3688 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3692 // map in which we'll infer heights of other keys
3693 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3694 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3695 std::set<CKeyID> setKeys;
3696 GetKeys(setKeys);
3697 for (const CKeyID &keyid : setKeys) {
3698 if (mapKeyBirth.count(keyid) == 0)
3699 mapKeyFirstBlock[keyid] = pindexMax;
3701 setKeys.clear();
3703 // if there are no such keys, we're done
3704 if (mapKeyFirstBlock.empty())
3705 return;
3707 // find first block that affects those keys, if there are any left
3708 std::vector<CKeyID> vAffected;
3709 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3710 // iterate over all wallet transactions...
3711 const CWalletTx &wtx = (*it).second;
3712 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3713 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3714 // ... which are already in a block
3715 int nHeight = blit->second->nHeight;
3716 for (const CTxOut &txout : wtx.tx->vout) {
3717 // iterate over all their outputs
3718 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3719 for (const CKeyID &keyid : vAffected) {
3720 // ... and all their affected keys
3721 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3722 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3723 rit->second = blit->second;
3725 vAffected.clear();
3730 // Extract block timestamps for those keys
3731 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3732 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3736 * Compute smart timestamp for a transaction being added to the wallet.
3738 * Logic:
3739 * - If sending a transaction, assign its timestamp to the current time.
3740 * - If receiving a transaction outside a block, assign its timestamp to the
3741 * current time.
3742 * - If receiving a block with a future timestamp, assign all its (not already
3743 * known) transactions' timestamps to the current time.
3744 * - If receiving a block with a past timestamp, before the most recent known
3745 * transaction (that we care about), assign all its (not already known)
3746 * transactions' timestamps to the same timestamp as that most-recent-known
3747 * transaction.
3748 * - If receiving a block with a past timestamp, but after the most recent known
3749 * transaction, assign all its (not already known) transactions' timestamps to
3750 * the block time.
3752 * For more information see CWalletTx::nTimeSmart,
3753 * https://bitcointalk.org/?topic=54527, or
3754 * https://github.com/bitcoin/bitcoin/pull/1393.
3756 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3758 unsigned int nTimeSmart = wtx.nTimeReceived;
3759 if (!wtx.hashUnset()) {
3760 if (mapBlockIndex.count(wtx.hashBlock)) {
3761 int64_t latestNow = wtx.nTimeReceived;
3762 int64_t latestEntry = 0;
3764 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3765 int64_t latestTolerated = latestNow + 300;
3766 const TxItems& txOrdered = wtxOrdered;
3767 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3768 CWalletTx* const pwtx = it->second.first;
3769 if (pwtx == &wtx) {
3770 continue;
3772 CAccountingEntry* const pacentry = it->second.second;
3773 int64_t nSmartTime;
3774 if (pwtx) {
3775 nSmartTime = pwtx->nTimeSmart;
3776 if (!nSmartTime) {
3777 nSmartTime = pwtx->nTimeReceived;
3779 } else {
3780 nSmartTime = pacentry->nTime;
3782 if (nSmartTime <= latestTolerated) {
3783 latestEntry = nSmartTime;
3784 if (nSmartTime > latestNow) {
3785 latestNow = nSmartTime;
3787 break;
3791 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3792 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3793 } else {
3794 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3797 return nTimeSmart;
3800 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3802 if (boost::get<CNoDestination>(&dest))
3803 return false;
3805 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3806 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3809 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3811 if (!mapAddressBook[dest].destdata.erase(key))
3812 return false;
3813 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3816 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3818 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3819 return true;
3822 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3824 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3825 if(i != mapAddressBook.end())
3827 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3828 if(j != i->second.destdata.end())
3830 if(value)
3831 *value = j->second;
3832 return true;
3835 return false;
3838 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3840 LOCK(cs_wallet);
3841 std::vector<std::string> values;
3842 for (const auto& address : mapAddressBook) {
3843 for (const auto& data : address.second.destdata) {
3844 if (!data.first.compare(0, prefix.size(), prefix)) {
3845 values.emplace_back(data.second);
3849 return values;
3852 std::string CWallet::GetWalletHelpString(bool showDebug)
3854 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3855 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3856 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3857 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3858 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3859 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). "
3860 "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"),
3861 CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3862 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3863 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3864 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3865 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3866 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3867 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3868 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3869 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));
3870 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));
3871 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3872 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3873 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3874 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3875 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3876 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3877 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3879 if (showDebug)
3881 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3883 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3884 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3885 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3886 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3889 return strUsage;
3892 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3894 // needed to restore wallet transaction meta data after -zapwallettxes
3895 std::vector<CWalletTx> vWtx;
3897 if (GetBoolArg("-zapwallettxes", false)) {
3898 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3900 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3901 CWallet *tempWallet = new CWallet(std::move(dbw));
3902 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3903 if (nZapWalletRet != DB_LOAD_OK) {
3904 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3905 return NULL;
3908 delete tempWallet;
3909 tempWallet = NULL;
3912 uiInterface.InitMessage(_("Loading wallet..."));
3914 int64_t nStart = GetTimeMillis();
3915 bool fFirstRun = true;
3916 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3917 CWallet *walletInstance = new CWallet(std::move(dbw));
3918 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3919 if (nLoadWalletRet != DB_LOAD_OK)
3921 if (nLoadWalletRet == DB_CORRUPT) {
3922 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3923 return NULL;
3925 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3927 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3928 " or address book entries might be missing or incorrect."),
3929 walletFile));
3931 else if (nLoadWalletRet == DB_TOO_NEW) {
3932 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3933 return NULL;
3935 else if (nLoadWalletRet == DB_NEED_REWRITE)
3937 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3938 return NULL;
3940 else {
3941 InitError(strprintf(_("Error loading %s"), walletFile));
3942 return NULL;
3946 if (GetBoolArg("-upgradewallet", fFirstRun))
3948 int nMaxVersion = GetArg("-upgradewallet", 0);
3949 if (nMaxVersion == 0) // the -upgradewallet without argument case
3951 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3952 nMaxVersion = CLIENT_VERSION;
3953 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3955 else
3956 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3957 if (nMaxVersion < walletInstance->GetVersion())
3959 InitError(_("Cannot downgrade wallet"));
3960 return NULL;
3962 walletInstance->SetMaxVersion(nMaxVersion);
3965 if (fFirstRun)
3967 // Create new keyUser and set as default key
3968 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3970 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3971 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3973 // generate a new master key
3974 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3975 if (!walletInstance->SetHDMasterKey(masterPubKey))
3976 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3978 CPubKey newDefaultKey;
3979 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3980 walletInstance->SetDefaultKey(newDefaultKey);
3981 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3982 InitError(_("Cannot write default address") += "\n");
3983 return NULL;
3987 walletInstance->SetBestChain(chainActive.GetLocator());
3989 else if (IsArgSet("-usehd")) {
3990 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3991 if (walletInstance->IsHDEnabled() && !useHD) {
3992 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3993 return NULL;
3995 if (!walletInstance->IsHDEnabled() && useHD) {
3996 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3997 return NULL;
4001 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
4003 RegisterValidationInterface(walletInstance);
4005 CBlockIndex *pindexRescan = chainActive.Genesis();
4006 if (!GetBoolArg("-rescan", false))
4008 CWalletDB walletdb(*walletInstance->dbw);
4009 CBlockLocator locator;
4010 if (walletdb.ReadBestBlock(locator))
4011 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
4013 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
4015 //We can't rescan beyond non-pruned blocks, stop and throw an error
4016 //this might happen if a user uses an old wallet within a pruned node
4017 // or if he ran -disablewallet for a longer time, then decided to re-enable
4018 if (fPruneMode)
4020 CBlockIndex *block = chainActive.Tip();
4021 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4022 block = block->pprev;
4024 if (pindexRescan != block) {
4025 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4026 return NULL;
4030 uiInterface.InitMessage(_("Rescanning..."));
4031 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4033 // No need to read and scan block if block was created before
4034 // our wallet birthday (as adjusted for block time variability)
4035 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4036 pindexRescan = chainActive.Next(pindexRescan);
4039 nStart = GetTimeMillis();
4040 walletInstance->ScanForWalletTransactions(pindexRescan, true);
4041 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4042 walletInstance->SetBestChain(chainActive.GetLocator());
4043 walletInstance->dbw->IncrementUpdateCounter();
4045 // Restore wallet transaction metadata after -zapwallettxes=1
4046 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
4048 CWalletDB walletdb(*walletInstance->dbw);
4050 for (const CWalletTx& wtxOld : vWtx)
4052 uint256 hash = wtxOld.GetHash();
4053 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4054 if (mi != walletInstance->mapWallet.end())
4056 const CWalletTx* copyFrom = &wtxOld;
4057 CWalletTx* copyTo = &mi->second;
4058 copyTo->mapValue = copyFrom->mapValue;
4059 copyTo->vOrderForm = copyFrom->vOrderForm;
4060 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4061 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4062 copyTo->fFromMe = copyFrom->fFromMe;
4063 copyTo->strFromAccount = copyFrom->strFromAccount;
4064 copyTo->nOrderPos = copyFrom->nOrderPos;
4065 walletdb.WriteTx(*copyTo);
4070 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4073 LOCK(walletInstance->cs_wallet);
4074 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4075 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4076 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4079 return walletInstance;
4082 bool CWallet::InitLoadWallet()
4084 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4085 LogPrintf("Wallet disabled!\n");
4086 return true;
4089 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4090 CWallet * const pwallet = CreateWalletFromFile(walletFile);
4091 if (!pwallet) {
4092 return false;
4094 vpwallets.push_back(pwallet);
4097 return true;
4100 std::atomic<bool> CWallet::fFlushScheduled(false);
4102 void CWallet::postInitProcess(CScheduler& scheduler)
4104 // Add wallet transactions that aren't already in a block to mempool
4105 // Do this here as mempool requires genesis block to be loaded
4106 ReacceptWalletTransactions();
4108 // Run a thread to flush wallet periodically
4109 if (!CWallet::fFlushScheduled.exchange(true)) {
4110 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4114 bool CWallet::ParameterInteraction()
4116 SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4117 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4119 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4120 return true;
4122 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
4123 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4126 if (GetBoolArg("-salvagewallet", false)) {
4127 if (is_multiwallet) {
4128 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4130 // Rewrite just private keys: rescan to find transactions
4131 if (SoftSetBoolArg("-rescan", true)) {
4132 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4136 int zapwallettxes = GetArg("-zapwallettxes", 0);
4137 // -zapwallettxes implies dropping the mempool on startup
4138 if (zapwallettxes != 0 && SoftSetBoolArg("-persistmempool", false)) {
4139 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4142 // -zapwallettxes implies a rescan
4143 if (zapwallettxes != 0) {
4144 if (is_multiwallet) {
4145 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4147 if (SoftSetBoolArg("-rescan", true)) {
4148 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4152 if (is_multiwallet) {
4153 if (GetBoolArg("-upgradewallet", false)) {
4154 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4158 if (GetBoolArg("-sysperms", false))
4159 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4160 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
4161 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4163 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4164 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4165 _("The wallet will avoid paying less than the minimum relay fee."));
4167 if (IsArgSet("-mintxfee"))
4169 CAmount n = 0;
4170 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
4171 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
4172 if (n > HIGH_TX_FEE_PER_KB)
4173 InitWarning(AmountHighWarn("-mintxfee") + " " +
4174 _("This is the minimum transaction fee you pay on every transaction."));
4175 CWallet::minTxFee = CFeeRate(n);
4177 if (IsArgSet("-fallbackfee"))
4179 CAmount nFeePerK = 0;
4180 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4181 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4182 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4183 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4184 _("This is the transaction fee you may pay when fee estimates are not available."));
4185 CWallet::fallbackFee = CFeeRate(nFeePerK);
4187 if (IsArgSet("-discardfee"))
4189 CAmount nFeePerK = 0;
4190 if (!ParseMoney(GetArg("-discardfee", ""), nFeePerK))
4191 return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), GetArg("-discardfee", "")));
4192 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4193 InitWarning(AmountHighWarn("-discardfee") + " " +
4194 _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4195 CWallet::m_discard_rate = CFeeRate(nFeePerK);
4197 if (IsArgSet("-paytxfee"))
4199 CAmount nFeePerK = 0;
4200 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4201 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4202 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4203 InitWarning(AmountHighWarn("-paytxfee") + " " +
4204 _("This is the transaction fee you will pay if you send a transaction."));
4206 payTxFee = CFeeRate(nFeePerK, 1000);
4207 if (payTxFee < ::minRelayTxFee)
4209 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4210 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4213 if (IsArgSet("-maxtxfee"))
4215 CAmount nMaxFee = 0;
4216 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4217 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4218 if (nMaxFee > HIGH_MAX_TX_FEE)
4219 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4220 maxTxFee = nMaxFee;
4221 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4223 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4224 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4227 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4228 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4229 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4231 return true;
4234 bool CWallet::BackupWallet(const std::string& strDest)
4236 return dbw->Backup(strDest);
4239 CKeyPool::CKeyPool()
4241 nTime = GetTime();
4242 fInternal = false;
4245 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4247 nTime = GetTime();
4248 vchPubKey = vchPubKeyIn;
4249 fInternal = internalIn;
4252 CWalletKey::CWalletKey(int64_t nExpires)
4254 nTimeCreated = (nExpires ? GetTime() : 0);
4255 nTimeExpires = nExpires;
4258 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4260 // Update the tx's hashBlock
4261 hashBlock = pindex->GetBlockHash();
4263 // set the position of the transaction in the block
4264 nIndex = posInBlock;
4267 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4269 if (hashUnset())
4270 return 0;
4272 AssertLockHeld(cs_main);
4274 // Find the block it claims to be in
4275 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4276 if (mi == mapBlockIndex.end())
4277 return 0;
4278 CBlockIndex* pindex = (*mi).second;
4279 if (!pindex || !chainActive.Contains(pindex))
4280 return 0;
4282 pindexRet = pindex;
4283 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4286 int CMerkleTx::GetBlocksToMaturity() const
4288 if (!IsCoinBase())
4289 return 0;
4290 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4294 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4296 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);