Reject duplicate wallet filenames
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobccf5353eb7a9641eb945767c3051d38328d1a5f5
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 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
85 LOCK(cs_wallet);
86 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
87 if (it == mapWallet.end())
88 return NULL;
89 return &(it->second);
92 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
94 AssertLockHeld(cs_wallet); // mapKeyMetadata
95 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
97 CKey secret;
99 // Create new metadata
100 int64_t nCreationTime = GetTime();
101 CKeyMetadata metadata(nCreationTime);
103 // use HD key derivation if HD was enabled during wallet creation
104 if (IsHDEnabled()) {
105 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
106 } else {
107 secret.MakeNewKey(fCompressed);
110 // Compressed public keys were introduced in version 0.6.0
111 if (fCompressed) {
112 SetMinVersion(FEATURE_COMPRPUBKEY);
115 CPubKey pubkey = secret.GetPubKey();
116 assert(secret.VerifyPubKey(pubkey));
118 mapKeyMetadata[pubkey.GetID()] = metadata;
119 UpdateTimeFirstKey(nCreationTime);
121 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
122 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
124 return pubkey;
127 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
129 // for now we use a fixed keypath scheme of m/0'/0'/k
130 CKey key; //master key seed (256bit)
131 CExtKey masterKey; //hd master key
132 CExtKey accountKey; //key at m/0'
133 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
134 CExtKey childKey; //key at m/0'/0'/<n>'
136 // try to get the master key
137 if (!GetKey(hdChain.masterKeyID, key))
138 throw std::runtime_error(std::string(__func__) + ": Master key not found");
140 masterKey.SetMaster(key.begin(), key.size());
142 // derive m/0'
143 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
144 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
146 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
147 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
148 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
150 // derive child key at next index, skip keys already known to the wallet
151 do {
152 // always derive hardened keys
153 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
154 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
155 if (internal) {
156 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
157 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
158 hdChain.nInternalChainCounter++;
160 else {
161 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
162 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
163 hdChain.nExternalChainCounter++;
165 } while (HaveKey(childKey.key.GetPubKey().GetID()));
166 secret = childKey.key;
167 metadata.hdMasterKeyID = hdChain.masterKeyID;
168 // update the chain model in the database
169 if (!walletdb.WriteHDChain(hdChain))
170 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
173 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
175 AssertLockHeld(cs_wallet); // mapKeyMetadata
177 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
178 // which is overridden below. To avoid flushes, the database handle is
179 // tunneled through to it.
180 bool needsDB = !pwalletdbEncryption;
181 if (needsDB) {
182 pwalletdbEncryption = &walletdb;
184 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
185 if (needsDB) pwalletdbEncryption = NULL;
186 return false;
188 if (needsDB) pwalletdbEncryption = NULL;
190 // check if we need to remove from watch-only
191 CScript script;
192 script = GetScriptForDestination(pubkey.GetID());
193 if (HaveWatchOnly(script)) {
194 RemoveWatchOnly(script);
196 script = GetScriptForRawPubKey(pubkey);
197 if (HaveWatchOnly(script)) {
198 RemoveWatchOnly(script);
201 if (!IsCrypted()) {
202 return walletdb.WriteKey(pubkey,
203 secret.GetPrivKey(),
204 mapKeyMetadata[pubkey.GetID()]);
206 return true;
209 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
211 CWalletDB walletdb(*dbw);
212 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
215 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
216 const std::vector<unsigned char> &vchCryptedSecret)
218 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
219 return false;
221 LOCK(cs_wallet);
222 if (pwalletdbEncryption)
223 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
224 vchCryptedSecret,
225 mapKeyMetadata[vchPubKey.GetID()]);
226 else
227 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
228 vchCryptedSecret,
229 mapKeyMetadata[vchPubKey.GetID()]);
233 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
235 AssertLockHeld(cs_wallet); // mapKeyMetadata
236 UpdateTimeFirstKey(meta.nCreateTime);
237 mapKeyMetadata[keyID] = meta;
238 return true;
241 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
243 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
247 * Update wallet first key creation time. This should be called whenever keys
248 * are added to the wallet, with the oldest key creation time.
250 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
252 AssertLockHeld(cs_wallet);
253 if (nCreateTime <= 1) {
254 // Cannot determine birthday information, so set the wallet birthday to
255 // the beginning of time.
256 nTimeFirstKey = 1;
257 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
258 nTimeFirstKey = nCreateTime;
262 bool CWallet::AddCScript(const CScript& redeemScript)
264 if (!CCryptoKeyStore::AddCScript(redeemScript))
265 return false;
266 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
269 bool CWallet::LoadCScript(const CScript& redeemScript)
271 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
272 * that never can be redeemed. However, old wallets may still contain
273 * these. Do not add them to the wallet and warn. */
274 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
276 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
277 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",
278 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
279 return true;
282 return CCryptoKeyStore::AddCScript(redeemScript);
285 bool CWallet::AddWatchOnly(const CScript& dest)
287 if (!CCryptoKeyStore::AddWatchOnly(dest))
288 return false;
289 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
290 UpdateTimeFirstKey(meta.nCreateTime);
291 NotifyWatchonlyChanged(true);
292 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
295 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
297 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
298 return AddWatchOnly(dest);
301 bool CWallet::RemoveWatchOnly(const CScript &dest)
303 AssertLockHeld(cs_wallet);
304 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
305 return false;
306 if (!HaveWatchOnly())
307 NotifyWatchonlyChanged(false);
308 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
309 return false;
311 return true;
314 bool CWallet::LoadWatchOnly(const CScript &dest)
316 return CCryptoKeyStore::AddWatchOnly(dest);
319 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
321 CCrypter crypter;
322 CKeyingMaterial _vMasterKey;
325 LOCK(cs_wallet);
326 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
328 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
329 return false;
330 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
331 continue; // try another master key
332 if (CCryptoKeyStore::Unlock(_vMasterKey))
333 return true;
336 return false;
339 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
341 bool fWasLocked = IsLocked();
344 LOCK(cs_wallet);
345 Lock();
347 CCrypter crypter;
348 CKeyingMaterial _vMasterKey;
349 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
351 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
352 return false;
353 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
354 return false;
355 if (CCryptoKeyStore::Unlock(_vMasterKey))
357 int64_t nStartTime = GetTimeMillis();
358 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
359 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
361 nStartTime = GetTimeMillis();
362 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
363 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
365 if (pMasterKey.second.nDeriveIterations < 25000)
366 pMasterKey.second.nDeriveIterations = 25000;
368 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
370 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
371 return false;
372 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
373 return false;
374 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
375 if (fWasLocked)
376 Lock();
377 return true;
382 return false;
385 void CWallet::SetBestChain(const CBlockLocator& loc)
387 CWalletDB walletdb(*dbw);
388 walletdb.WriteBestBlock(loc);
391 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
393 LOCK(cs_wallet); // nWalletVersion
394 if (nWalletVersion >= nVersion)
395 return true;
397 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
398 if (fExplicit && nVersion > nWalletMaxVersion)
399 nVersion = FEATURE_LATEST;
401 nWalletVersion = nVersion;
403 if (nVersion > nWalletMaxVersion)
404 nWalletMaxVersion = nVersion;
407 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
408 if (nWalletVersion > 40000)
409 pwalletdb->WriteMinVersion(nWalletVersion);
410 if (!pwalletdbIn)
411 delete pwalletdb;
414 return true;
417 bool CWallet::SetMaxVersion(int nVersion)
419 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
420 // cannot downgrade below current version
421 if (nWalletVersion > nVersion)
422 return false;
424 nWalletMaxVersion = nVersion;
426 return true;
429 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
431 std::set<uint256> result;
432 AssertLockHeld(cs_wallet);
434 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
435 if (it == mapWallet.end())
436 return result;
437 const CWalletTx& wtx = it->second;
439 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
441 for (const CTxIn& txin : wtx.tx->vin)
443 if (mapTxSpends.count(txin.prevout) <= 1)
444 continue; // No conflict if zero or one spends
445 range = mapTxSpends.equal_range(txin.prevout);
446 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
447 result.insert(_it->second);
449 return result;
452 bool CWallet::HasWalletSpend(const uint256& txid) const
454 AssertLockHeld(cs_wallet);
455 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
456 return (iter != mapTxSpends.end() && iter->first.hash == txid);
459 void CWallet::Flush(bool shutdown)
461 dbw->Flush(shutdown);
464 bool CWallet::Verify()
466 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
467 return true;
469 uiInterface.InitMessage(_("Verifying wallet(s)..."));
471 // Keep track of each wallet absolute path to detect duplicates.
472 std::set<fs::path> wallet_paths;
474 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
475 if (boost::filesystem::path(walletFile).filename() != walletFile) {
476 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
479 if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
480 return InitError(_("Invalid characters in -wallet filename"));
483 fs::path wallet_path = fs::absolute(walletFile, GetDataDir());
485 if (!wallet_paths.insert(wallet_path).second) {
486 return InitError(_("Duplicate -wallet filename"));
489 std::string strError;
490 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
491 return InitError(strError);
494 if (GetBoolArg("-salvagewallet", false)) {
495 // Recover readable keypairs:
496 CWallet dummyWallet;
497 std::string backup_filename;
498 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
499 return false;
503 std::string strWarning;
504 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
505 if (!strWarning.empty()) {
506 InitWarning(strWarning);
508 if (!dbV) {
509 InitError(strError);
510 return false;
514 return true;
517 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
519 // We want all the wallet transactions in range to have the same metadata as
520 // the oldest (smallest nOrderPos).
521 // So: find smallest nOrderPos:
523 int nMinOrderPos = std::numeric_limits<int>::max();
524 const CWalletTx* copyFrom = NULL;
525 for (TxSpends::iterator it = range.first; it != range.second; ++it)
527 const uint256& hash = it->second;
528 int n = mapWallet[hash].nOrderPos;
529 if (n < nMinOrderPos)
531 nMinOrderPos = n;
532 copyFrom = &mapWallet[hash];
535 // Now copy data from copyFrom to rest:
536 for (TxSpends::iterator it = range.first; it != range.second; ++it)
538 const uint256& hash = it->second;
539 CWalletTx* copyTo = &mapWallet[hash];
540 if (copyFrom == copyTo) continue;
541 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
542 copyTo->mapValue = copyFrom->mapValue;
543 copyTo->vOrderForm = copyFrom->vOrderForm;
544 // fTimeReceivedIsTxTime not copied on purpose
545 // nTimeReceived not copied on purpose
546 copyTo->nTimeSmart = copyFrom->nTimeSmart;
547 copyTo->fFromMe = copyFrom->fFromMe;
548 copyTo->strFromAccount = copyFrom->strFromAccount;
549 // nOrderPos not copied on purpose
550 // cached members not copied on purpose
555 * Outpoint is spent if any non-conflicted transaction
556 * spends it:
558 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
560 const COutPoint outpoint(hash, n);
561 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
562 range = mapTxSpends.equal_range(outpoint);
564 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
566 const uint256& wtxid = it->second;
567 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
568 if (mit != mapWallet.end()) {
569 int depth = mit->second.GetDepthInMainChain();
570 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
571 return true; // Spent
574 return false;
577 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
579 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
581 std::pair<TxSpends::iterator, TxSpends::iterator> range;
582 range = mapTxSpends.equal_range(outpoint);
583 SyncMetaData(range);
587 void CWallet::AddToSpends(const uint256& wtxid)
589 assert(mapWallet.count(wtxid));
590 CWalletTx& thisTx = mapWallet[wtxid];
591 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
592 return;
594 for (const CTxIn& txin : thisTx.tx->vin)
595 AddToSpends(txin.prevout, wtxid);
598 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
600 if (IsCrypted())
601 return false;
603 CKeyingMaterial _vMasterKey;
605 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
606 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
608 CMasterKey kMasterKey;
610 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
611 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
613 CCrypter crypter;
614 int64_t nStartTime = GetTimeMillis();
615 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
616 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
618 nStartTime = GetTimeMillis();
619 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
620 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
622 if (kMasterKey.nDeriveIterations < 25000)
623 kMasterKey.nDeriveIterations = 25000;
625 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
627 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
628 return false;
629 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
630 return false;
633 LOCK(cs_wallet);
634 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
635 assert(!pwalletdbEncryption);
636 pwalletdbEncryption = new CWalletDB(*dbw);
637 if (!pwalletdbEncryption->TxnBegin()) {
638 delete pwalletdbEncryption;
639 pwalletdbEncryption = NULL;
640 return false;
642 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
644 if (!EncryptKeys(_vMasterKey))
646 pwalletdbEncryption->TxnAbort();
647 delete pwalletdbEncryption;
648 // We now probably have half of our keys encrypted in memory, and half not...
649 // die and let the user reload the unencrypted wallet.
650 assert(false);
653 // Encryption was introduced in version 0.4.0
654 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
656 if (!pwalletdbEncryption->TxnCommit()) {
657 delete pwalletdbEncryption;
658 // We now have keys encrypted in memory, but not on disk...
659 // die to avoid confusion and let the user reload the unencrypted wallet.
660 assert(false);
663 delete pwalletdbEncryption;
664 pwalletdbEncryption = NULL;
666 Lock();
667 Unlock(strWalletPassphrase);
669 // if we are using HD, replace the HD master key (seed) with a new one
670 if (IsHDEnabled()) {
671 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
672 return false;
676 NewKeyPool();
677 Lock();
679 // Need to completely rewrite the wallet file; if we don't, bdb might keep
680 // bits of the unencrypted private key in slack space in the database file.
681 dbw->Rewrite();
684 NotifyStatusChanged(this);
686 return true;
689 DBErrors CWallet::ReorderTransactions()
691 LOCK(cs_wallet);
692 CWalletDB walletdb(*dbw);
694 // Old wallets didn't have any defined order for transactions
695 // Probably a bad idea to change the output of this
697 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
698 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
699 typedef std::multimap<int64_t, TxPair > TxItems;
700 TxItems txByTime;
702 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
704 CWalletTx* wtx = &((*it).second);
705 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
707 std::list<CAccountingEntry> acentries;
708 walletdb.ListAccountCreditDebit("", acentries);
709 for (CAccountingEntry& entry : acentries)
711 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
714 nOrderPosNext = 0;
715 std::vector<int64_t> nOrderPosOffsets;
716 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
718 CWalletTx *const pwtx = (*it).second.first;
719 CAccountingEntry *const pacentry = (*it).second.second;
720 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
722 if (nOrderPos == -1)
724 nOrderPos = nOrderPosNext++;
725 nOrderPosOffsets.push_back(nOrderPos);
727 if (pwtx)
729 if (!walletdb.WriteTx(*pwtx))
730 return DB_LOAD_FAIL;
732 else
733 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
734 return DB_LOAD_FAIL;
736 else
738 int64_t nOrderPosOff = 0;
739 for (const int64_t& nOffsetStart : nOrderPosOffsets)
741 if (nOrderPos >= nOffsetStart)
742 ++nOrderPosOff;
744 nOrderPos += nOrderPosOff;
745 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
747 if (!nOrderPosOff)
748 continue;
750 // Since we're changing the order, write it back
751 if (pwtx)
753 if (!walletdb.WriteTx(*pwtx))
754 return DB_LOAD_FAIL;
756 else
757 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
758 return DB_LOAD_FAIL;
761 walletdb.WriteOrderPosNext(nOrderPosNext);
763 return DB_LOAD_OK;
766 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
768 AssertLockHeld(cs_wallet); // nOrderPosNext
769 int64_t nRet = nOrderPosNext++;
770 if (pwalletdb) {
771 pwalletdb->WriteOrderPosNext(nOrderPosNext);
772 } else {
773 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
775 return nRet;
778 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
780 CWalletDB walletdb(*dbw);
781 if (!walletdb.TxnBegin())
782 return false;
784 int64_t nNow = GetAdjustedTime();
786 // Debit
787 CAccountingEntry debit;
788 debit.nOrderPos = IncOrderPosNext(&walletdb);
789 debit.strAccount = strFrom;
790 debit.nCreditDebit = -nAmount;
791 debit.nTime = nNow;
792 debit.strOtherAccount = strTo;
793 debit.strComment = strComment;
794 AddAccountingEntry(debit, &walletdb);
796 // Credit
797 CAccountingEntry credit;
798 credit.nOrderPos = IncOrderPosNext(&walletdb);
799 credit.strAccount = strTo;
800 credit.nCreditDebit = nAmount;
801 credit.nTime = nNow;
802 credit.strOtherAccount = strFrom;
803 credit.strComment = strComment;
804 AddAccountingEntry(credit, &walletdb);
806 if (!walletdb.TxnCommit())
807 return false;
809 return true;
812 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
814 CWalletDB walletdb(*dbw);
816 CAccount account;
817 walletdb.ReadAccount(strAccount, account);
819 if (!bForceNew) {
820 if (!account.vchPubKey.IsValid())
821 bForceNew = true;
822 else {
823 // Check if the current key has been used
824 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
825 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
826 it != mapWallet.end() && account.vchPubKey.IsValid();
827 ++it)
828 for (const CTxOut& txout : (*it).second.tx->vout)
829 if (txout.scriptPubKey == scriptPubKey) {
830 bForceNew = true;
831 break;
836 // Generate a new key
837 if (bForceNew) {
838 if (!GetKeyFromPool(account.vchPubKey, false))
839 return false;
841 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
842 walletdb.WriteAccount(strAccount, account);
845 pubKey = account.vchPubKey;
847 return true;
850 void CWallet::MarkDirty()
853 LOCK(cs_wallet);
854 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
855 item.second.MarkDirty();
859 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
861 LOCK(cs_wallet);
863 auto mi = mapWallet.find(originalHash);
865 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
866 assert(mi != mapWallet.end());
868 CWalletTx& wtx = (*mi).second;
870 // Ensure for now that we're not overwriting data
871 assert(wtx.mapValue.count("replaced_by_txid") == 0);
873 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
875 CWalletDB walletdb(*dbw, "r+");
877 bool success = true;
878 if (!walletdb.WriteTx(wtx)) {
879 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
880 success = false;
883 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
885 return success;
888 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
890 LOCK(cs_wallet);
892 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
894 uint256 hash = wtxIn.GetHash();
896 // Inserts only if not already there, returns tx inserted or tx found
897 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
898 CWalletTx& wtx = (*ret.first).second;
899 wtx.BindWallet(this);
900 bool fInsertedNew = ret.second;
901 if (fInsertedNew)
903 wtx.nTimeReceived = GetAdjustedTime();
904 wtx.nOrderPos = IncOrderPosNext(&walletdb);
905 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
906 wtx.nTimeSmart = ComputeTimeSmart(wtx);
907 AddToSpends(hash);
910 bool fUpdated = false;
911 if (!fInsertedNew)
913 // Merge
914 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
916 wtx.hashBlock = wtxIn.hashBlock;
917 fUpdated = true;
919 // If no longer abandoned, update
920 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
922 wtx.hashBlock = wtxIn.hashBlock;
923 fUpdated = true;
925 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
927 wtx.nIndex = wtxIn.nIndex;
928 fUpdated = true;
930 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
932 wtx.fFromMe = wtxIn.fFromMe;
933 fUpdated = true;
937 //// debug print
938 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
940 // Write to disk
941 if (fInsertedNew || fUpdated)
942 if (!walletdb.WriteTx(wtx))
943 return false;
945 // Break debit/credit balance caches:
946 wtx.MarkDirty();
948 // Notify UI of new or updated transaction
949 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
951 // notify an external script when a wallet transaction comes in or is updated
952 std::string strCmd = GetArg("-walletnotify", "");
954 if ( !strCmd.empty())
956 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
957 boost::thread t(runCommand, strCmd); // thread runs free
960 return true;
963 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
965 uint256 hash = wtxIn.GetHash();
967 mapWallet[hash] = wtxIn;
968 CWalletTx& wtx = mapWallet[hash];
969 wtx.BindWallet(this);
970 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
971 AddToSpends(hash);
972 for (const CTxIn& txin : wtx.tx->vin) {
973 if (mapWallet.count(txin.prevout.hash)) {
974 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
975 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
976 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
981 return true;
985 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
986 * be set when the transaction was known to be included in a block. When
987 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
988 * notifications happen and cached balances are marked dirty.
990 * If fUpdate is true, existing transactions will be updated.
991 * TODO: One exception to this is that the abandoned state is cleared under the
992 * assumption that any further notification of a transaction that was considered
993 * abandoned is an indication that it is not safe to be considered abandoned.
994 * Abandoned state should probably be more carefully tracked via different
995 * posInBlock signals or by checking mempool presence when necessary.
997 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
999 const CTransaction& tx = *ptx;
1001 AssertLockHeld(cs_wallet);
1003 if (pIndex != NULL) {
1004 for (const CTxIn& txin : tx.vin) {
1005 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1006 while (range.first != range.second) {
1007 if (range.first->second != tx.GetHash()) {
1008 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);
1009 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1011 range.first++;
1016 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1017 if (fExisted && !fUpdate) return false;
1018 if (fExisted || IsMine(tx) || IsFromMe(tx))
1020 CWalletTx wtx(this, ptx);
1022 // Get merkle branch if transaction was found in a block
1023 if (pIndex != NULL)
1024 wtx.SetMerkleBranch(pIndex, posInBlock);
1026 return AddToWallet(wtx, false);
1029 return false;
1032 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1034 LOCK2(cs_main, cs_wallet);
1035 const CWalletTx* wtx = GetWalletTx(hashTx);
1036 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1039 bool CWallet::AbandonTransaction(const uint256& hashTx)
1041 LOCK2(cs_main, cs_wallet);
1043 CWalletDB walletdb(*dbw, "r+");
1045 std::set<uint256> todo;
1046 std::set<uint256> done;
1048 // Can't mark abandoned if confirmed or in mempool
1049 assert(mapWallet.count(hashTx));
1050 CWalletTx& origtx = mapWallet[hashTx];
1051 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1052 return false;
1055 todo.insert(hashTx);
1057 while (!todo.empty()) {
1058 uint256 now = *todo.begin();
1059 todo.erase(now);
1060 done.insert(now);
1061 assert(mapWallet.count(now));
1062 CWalletTx& wtx = mapWallet[now];
1063 int currentconfirm = wtx.GetDepthInMainChain();
1064 // If the orig tx was not in block, none of its spends can be
1065 assert(currentconfirm <= 0);
1066 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1067 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1068 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1069 assert(!wtx.InMempool());
1070 wtx.nIndex = -1;
1071 wtx.setAbandoned();
1072 wtx.MarkDirty();
1073 walletdb.WriteTx(wtx);
1074 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1075 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1076 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1077 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1078 if (!done.count(iter->second)) {
1079 todo.insert(iter->second);
1081 iter++;
1083 // If a transaction changes 'conflicted' state, that changes the balance
1084 // available of the outputs it spends. So force those to be recomputed
1085 for (const CTxIn& txin : wtx.tx->vin)
1087 if (mapWallet.count(txin.prevout.hash))
1088 mapWallet[txin.prevout.hash].MarkDirty();
1093 return true;
1096 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1098 LOCK2(cs_main, cs_wallet);
1100 int conflictconfirms = 0;
1101 if (mapBlockIndex.count(hashBlock)) {
1102 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1103 if (chainActive.Contains(pindex)) {
1104 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1107 // If number of conflict confirms cannot be determined, this means
1108 // that the block is still unknown or not yet part of the main chain,
1109 // for example when loading the wallet during a reindex. Do nothing in that
1110 // case.
1111 if (conflictconfirms >= 0)
1112 return;
1114 // Do not flush the wallet here for performance reasons
1115 CWalletDB walletdb(*dbw, "r+", false);
1117 std::set<uint256> todo;
1118 std::set<uint256> done;
1120 todo.insert(hashTx);
1122 while (!todo.empty()) {
1123 uint256 now = *todo.begin();
1124 todo.erase(now);
1125 done.insert(now);
1126 assert(mapWallet.count(now));
1127 CWalletTx& wtx = mapWallet[now];
1128 int currentconfirm = wtx.GetDepthInMainChain();
1129 if (conflictconfirms < currentconfirm) {
1130 // Block is 'more conflicted' than current confirm; update.
1131 // Mark transaction as conflicted with this block.
1132 wtx.nIndex = -1;
1133 wtx.hashBlock = hashBlock;
1134 wtx.MarkDirty();
1135 walletdb.WriteTx(wtx);
1136 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1137 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1138 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1139 if (!done.count(iter->second)) {
1140 todo.insert(iter->second);
1142 iter++;
1144 // If a transaction changes 'conflicted' state, that changes the balance
1145 // available of the outputs it spends. So force those to be recomputed
1146 for (const CTxIn& txin : wtx.tx->vin)
1148 if (mapWallet.count(txin.prevout.hash))
1149 mapWallet[txin.prevout.hash].MarkDirty();
1155 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1156 const CTransaction& tx = *ptx;
1158 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1159 return; // Not one of ours
1161 // If a transaction changes 'conflicted' state, that changes the balance
1162 // available of the outputs it spends. So force those to be
1163 // recomputed, also:
1164 for (const CTxIn& txin : tx.vin)
1166 if (mapWallet.count(txin.prevout.hash))
1167 mapWallet[txin.prevout.hash].MarkDirty();
1171 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1172 LOCK2(cs_main, cs_wallet);
1173 SyncTransaction(ptx);
1176 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1177 LOCK2(cs_main, cs_wallet);
1178 // TODO: Temporarily ensure that mempool removals are notified before
1179 // connected transactions. This shouldn't matter, but the abandoned
1180 // state of transactions in our wallet is currently cleared when we
1181 // receive another notification and there is a race condition where
1182 // notification of a connected conflict might cause an outside process
1183 // to abandon a transaction and then have it inadvertently cleared by
1184 // the notification that the conflicted transaction was evicted.
1186 for (const CTransactionRef& ptx : vtxConflicted) {
1187 SyncTransaction(ptx);
1189 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1190 SyncTransaction(pblock->vtx[i], pindex, i);
1194 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1195 LOCK2(cs_main, cs_wallet);
1197 for (const CTransactionRef& ptx : pblock->vtx) {
1198 SyncTransaction(ptx);
1204 isminetype CWallet::IsMine(const CTxIn &txin) const
1207 LOCK(cs_wallet);
1208 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1209 if (mi != mapWallet.end())
1211 const CWalletTx& prev = (*mi).second;
1212 if (txin.prevout.n < prev.tx->vout.size())
1213 return IsMine(prev.tx->vout[txin.prevout.n]);
1216 return ISMINE_NO;
1219 // Note that this function doesn't distinguish between a 0-valued input,
1220 // and a not-"is mine" (according to the filter) input.
1221 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1224 LOCK(cs_wallet);
1225 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1226 if (mi != mapWallet.end())
1228 const CWalletTx& prev = (*mi).second;
1229 if (txin.prevout.n < prev.tx->vout.size())
1230 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1231 return prev.tx->vout[txin.prevout.n].nValue;
1234 return 0;
1237 isminetype CWallet::IsMine(const CTxOut& txout) const
1239 return ::IsMine(*this, txout.scriptPubKey);
1242 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1244 if (!MoneyRange(txout.nValue))
1245 throw std::runtime_error(std::string(__func__) + ": value out of range");
1246 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1249 bool CWallet::IsChange(const CTxOut& txout) const
1251 // TODO: fix handling of 'change' outputs. The assumption is that any
1252 // payment to a script that is ours, but is not in the address book
1253 // is change. That assumption is likely to break when we implement multisignature
1254 // wallets that return change back into a multi-signature-protected address;
1255 // a better way of identifying which outputs are 'the send' and which are
1256 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1257 // which output, if any, was change).
1258 if (::IsMine(*this, txout.scriptPubKey))
1260 CTxDestination address;
1261 if (!ExtractDestination(txout.scriptPubKey, address))
1262 return true;
1264 LOCK(cs_wallet);
1265 if (!mapAddressBook.count(address))
1266 return true;
1268 return false;
1271 CAmount CWallet::GetChange(const CTxOut& txout) const
1273 if (!MoneyRange(txout.nValue))
1274 throw std::runtime_error(std::string(__func__) + ": value out of range");
1275 return (IsChange(txout) ? txout.nValue : 0);
1278 bool CWallet::IsMine(const CTransaction& tx) const
1280 for (const CTxOut& txout : tx.vout)
1281 if (IsMine(txout))
1282 return true;
1283 return false;
1286 bool CWallet::IsFromMe(const CTransaction& tx) const
1288 return (GetDebit(tx, ISMINE_ALL) > 0);
1291 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1293 CAmount nDebit = 0;
1294 for (const CTxIn& txin : tx.vin)
1296 nDebit += GetDebit(txin, filter);
1297 if (!MoneyRange(nDebit))
1298 throw std::runtime_error(std::string(__func__) + ": value out of range");
1300 return nDebit;
1303 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1305 LOCK(cs_wallet);
1307 for (const CTxIn& txin : tx.vin)
1309 auto mi = mapWallet.find(txin.prevout.hash);
1310 if (mi == mapWallet.end())
1311 return false; // any unknown inputs can't be from us
1313 const CWalletTx& prev = (*mi).second;
1315 if (txin.prevout.n >= prev.tx->vout.size())
1316 return false; // invalid input!
1318 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1319 return false;
1321 return true;
1324 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1326 CAmount nCredit = 0;
1327 for (const CTxOut& txout : tx.vout)
1329 nCredit += GetCredit(txout, filter);
1330 if (!MoneyRange(nCredit))
1331 throw std::runtime_error(std::string(__func__) + ": value out of range");
1333 return nCredit;
1336 CAmount CWallet::GetChange(const CTransaction& tx) const
1338 CAmount nChange = 0;
1339 for (const CTxOut& txout : tx.vout)
1341 nChange += GetChange(txout);
1342 if (!MoneyRange(nChange))
1343 throw std::runtime_error(std::string(__func__) + ": value out of range");
1345 return nChange;
1348 CPubKey CWallet::GenerateNewHDMasterKey()
1350 CKey key;
1351 key.MakeNewKey(true);
1353 int64_t nCreationTime = GetTime();
1354 CKeyMetadata metadata(nCreationTime);
1356 // calculate the pubkey
1357 CPubKey pubkey = key.GetPubKey();
1358 assert(key.VerifyPubKey(pubkey));
1360 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1361 metadata.hdKeypath = "m";
1362 metadata.hdMasterKeyID = pubkey.GetID();
1365 LOCK(cs_wallet);
1367 // mem store the metadata
1368 mapKeyMetadata[pubkey.GetID()] = metadata;
1370 // write the key&metadata to the database
1371 if (!AddKeyPubKey(key, pubkey))
1372 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1375 return pubkey;
1378 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1380 LOCK(cs_wallet);
1381 // store the keyid (hash160) together with
1382 // the child index counter in the database
1383 // as a hdchain object
1384 CHDChain newHdChain;
1385 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1386 newHdChain.masterKeyID = pubkey.GetID();
1387 SetHDChain(newHdChain, false);
1389 return true;
1392 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1394 LOCK(cs_wallet);
1395 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1396 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1398 hdChain = chain;
1399 return true;
1402 bool CWallet::IsHDEnabled() const
1404 return !hdChain.masterKeyID.IsNull();
1407 int64_t CWalletTx::GetTxTime() const
1409 int64_t n = nTimeSmart;
1410 return n ? n : nTimeReceived;
1413 int CWalletTx::GetRequestCount() const
1415 // Returns -1 if it wasn't being tracked
1416 int nRequests = -1;
1418 LOCK(pwallet->cs_wallet);
1419 if (IsCoinBase())
1421 // Generated block
1422 if (!hashUnset())
1424 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1425 if (mi != pwallet->mapRequestCount.end())
1426 nRequests = (*mi).second;
1429 else
1431 // Did anyone request this transaction?
1432 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1433 if (mi != pwallet->mapRequestCount.end())
1435 nRequests = (*mi).second;
1437 // How about the block it's in?
1438 if (nRequests == 0 && !hashUnset())
1440 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1441 if (_mi != pwallet->mapRequestCount.end())
1442 nRequests = (*_mi).second;
1443 else
1444 nRequests = 1; // If it's in someone else's block it must have got out
1449 return nRequests;
1452 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1453 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1455 nFee = 0;
1456 listReceived.clear();
1457 listSent.clear();
1458 strSentAccount = strFromAccount;
1460 // Compute fee:
1461 CAmount nDebit = GetDebit(filter);
1462 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1464 CAmount nValueOut = tx->GetValueOut();
1465 nFee = nDebit - nValueOut;
1468 // Sent/received.
1469 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1471 const CTxOut& txout = tx->vout[i];
1472 isminetype fIsMine = pwallet->IsMine(txout);
1473 // Only need to handle txouts if AT LEAST one of these is true:
1474 // 1) they debit from us (sent)
1475 // 2) the output is to us (received)
1476 if (nDebit > 0)
1478 // Don't report 'change' txouts
1479 if (pwallet->IsChange(txout))
1480 continue;
1482 else if (!(fIsMine & filter))
1483 continue;
1485 // In either case, we need to get the destination address
1486 CTxDestination address;
1488 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1490 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1491 this->GetHash().ToString());
1492 address = CNoDestination();
1495 COutputEntry output = {address, txout.nValue, (int)i};
1497 // If we are debited by the transaction, add the output as a "sent" entry
1498 if (nDebit > 0)
1499 listSent.push_back(output);
1501 // If we are receiving the output, add it as a "received" entry
1502 if (fIsMine & filter)
1503 listReceived.push_back(output);
1509 * Scan active chain for relevant transactions after importing keys. This should
1510 * be called whenever new keys are added to the wallet, with the oldest key
1511 * creation time.
1513 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1514 * returned will be higher than startTime if relevant blocks could not be read.
1516 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1518 AssertLockHeld(cs_main);
1519 AssertLockHeld(cs_wallet);
1521 // Find starting block. May be null if nCreateTime is greater than the
1522 // highest blockchain timestamp, in which case there is nothing that needs
1523 // to be scanned.
1524 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1525 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1527 if (startBlock) {
1528 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1529 if (failedBlock) {
1530 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1533 return startTime;
1537 * Scan the block chain (starting in pindexStart) for transactions
1538 * from or to us. If fUpdate is true, found transactions that already
1539 * exist in the wallet will be updated.
1541 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1542 * possible (due to pruning or corruption), returns pointer to the most recent
1543 * block that could not be scanned.
1545 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1547 int64_t nNow = GetTime();
1548 const CChainParams& chainParams = Params();
1550 CBlockIndex* pindex = pindexStart;
1551 CBlockIndex* ret = nullptr;
1553 LOCK2(cs_main, cs_wallet);
1554 fAbortRescan = false;
1555 fScanningWallet = true;
1557 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1558 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1559 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1560 while (pindex && !fAbortRescan)
1562 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1563 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1564 if (GetTime() >= nNow + 60) {
1565 nNow = GetTime();
1566 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1569 CBlock block;
1570 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1571 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1572 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1574 } else {
1575 ret = pindex;
1577 pindex = chainActive.Next(pindex);
1579 if (pindex && fAbortRescan) {
1580 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1582 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1584 fScanningWallet = false;
1586 return ret;
1589 void CWallet::ReacceptWalletTransactions()
1591 // If transactions aren't being broadcasted, don't let them into local mempool either
1592 if (!fBroadcastTransactions)
1593 return;
1594 LOCK2(cs_main, cs_wallet);
1595 std::map<int64_t, CWalletTx*> mapSorted;
1597 // Sort pending wallet transactions based on their initial wallet insertion order
1598 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1600 const uint256& wtxid = item.first;
1601 CWalletTx& wtx = item.second;
1602 assert(wtx.GetHash() == wtxid);
1604 int nDepth = wtx.GetDepthInMainChain();
1606 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1607 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1611 // Try to add wallet transactions to memory pool
1612 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1614 CWalletTx& wtx = *(item.second);
1616 LOCK(mempool.cs);
1617 CValidationState state;
1618 wtx.AcceptToMemoryPool(maxTxFee, state);
1622 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1624 assert(pwallet->GetBroadcastTransactions());
1625 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1627 CValidationState state;
1628 /* GetDepthInMainChain already catches known conflicts. */
1629 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1630 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1631 if (connman) {
1632 CInv inv(MSG_TX, GetHash());
1633 connman->ForEachNode([&inv](CNode* pnode)
1635 pnode->PushInventory(inv);
1637 return true;
1641 return false;
1644 std::set<uint256> CWalletTx::GetConflicts() const
1646 std::set<uint256> result;
1647 if (pwallet != NULL)
1649 uint256 myHash = GetHash();
1650 result = pwallet->GetConflicts(myHash);
1651 result.erase(myHash);
1653 return result;
1656 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1658 if (tx->vin.empty())
1659 return 0;
1661 CAmount debit = 0;
1662 if(filter & ISMINE_SPENDABLE)
1664 if (fDebitCached)
1665 debit += nDebitCached;
1666 else
1668 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1669 fDebitCached = true;
1670 debit += nDebitCached;
1673 if(filter & ISMINE_WATCH_ONLY)
1675 if(fWatchDebitCached)
1676 debit += nWatchDebitCached;
1677 else
1679 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1680 fWatchDebitCached = true;
1681 debit += nWatchDebitCached;
1684 return debit;
1687 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1689 // Must wait until coinbase is safely deep enough in the chain before valuing it
1690 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1691 return 0;
1693 CAmount credit = 0;
1694 if (filter & ISMINE_SPENDABLE)
1696 // GetBalance can assume transactions in mapWallet won't change
1697 if (fCreditCached)
1698 credit += nCreditCached;
1699 else
1701 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1702 fCreditCached = true;
1703 credit += nCreditCached;
1706 if (filter & ISMINE_WATCH_ONLY)
1708 if (fWatchCreditCached)
1709 credit += nWatchCreditCached;
1710 else
1712 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1713 fWatchCreditCached = true;
1714 credit += nWatchCreditCached;
1717 return credit;
1720 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1722 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1724 if (fUseCache && fImmatureCreditCached)
1725 return nImmatureCreditCached;
1726 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1727 fImmatureCreditCached = true;
1728 return nImmatureCreditCached;
1731 return 0;
1734 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1736 if (pwallet == 0)
1737 return 0;
1739 // Must wait until coinbase is safely deep enough in the chain before valuing it
1740 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1741 return 0;
1743 if (fUseCache && fAvailableCreditCached)
1744 return nAvailableCreditCached;
1746 CAmount nCredit = 0;
1747 uint256 hashTx = GetHash();
1748 for (unsigned int i = 0; i < tx->vout.size(); i++)
1750 if (!pwallet->IsSpent(hashTx, i))
1752 const CTxOut &txout = tx->vout[i];
1753 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1754 if (!MoneyRange(nCredit))
1755 throw std::runtime_error(std::string(__func__) + " : value out of range");
1759 nAvailableCreditCached = nCredit;
1760 fAvailableCreditCached = true;
1761 return nCredit;
1764 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1766 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1768 if (fUseCache && fImmatureWatchCreditCached)
1769 return nImmatureWatchCreditCached;
1770 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1771 fImmatureWatchCreditCached = true;
1772 return nImmatureWatchCreditCached;
1775 return 0;
1778 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1780 if (pwallet == 0)
1781 return 0;
1783 // Must wait until coinbase is safely deep enough in the chain before valuing it
1784 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1785 return 0;
1787 if (fUseCache && fAvailableWatchCreditCached)
1788 return nAvailableWatchCreditCached;
1790 CAmount nCredit = 0;
1791 for (unsigned int i = 0; i < tx->vout.size(); i++)
1793 if (!pwallet->IsSpent(GetHash(), i))
1795 const CTxOut &txout = tx->vout[i];
1796 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1797 if (!MoneyRange(nCredit))
1798 throw std::runtime_error(std::string(__func__) + ": value out of range");
1802 nAvailableWatchCreditCached = nCredit;
1803 fAvailableWatchCreditCached = true;
1804 return nCredit;
1807 CAmount CWalletTx::GetChange() const
1809 if (fChangeCached)
1810 return nChangeCached;
1811 nChangeCached = pwallet->GetChange(*this);
1812 fChangeCached = true;
1813 return nChangeCached;
1816 bool CWalletTx::InMempool() const
1818 LOCK(mempool.cs);
1819 return mempool.exists(GetHash());
1822 bool CWalletTx::IsTrusted() const
1824 // Quick answer in most cases
1825 if (!CheckFinalTx(*this))
1826 return false;
1827 int nDepth = GetDepthInMainChain();
1828 if (nDepth >= 1)
1829 return true;
1830 if (nDepth < 0)
1831 return false;
1832 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1833 return false;
1835 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1836 if (!InMempool())
1837 return false;
1839 // Trusted if all inputs are from us and are in the mempool:
1840 for (const CTxIn& txin : tx->vin)
1842 // Transactions not sent by us: not trusted
1843 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1844 if (parent == NULL)
1845 return false;
1846 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1847 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1848 return false;
1850 return true;
1853 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1855 CMutableTransaction tx1 = *this->tx;
1856 CMutableTransaction tx2 = *_tx.tx;
1857 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1858 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1859 return CTransaction(tx1) == CTransaction(tx2);
1862 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1864 std::vector<uint256> result;
1866 LOCK(cs_wallet);
1867 // Sort them in chronological order
1868 std::multimap<unsigned int, CWalletTx*> mapSorted;
1869 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1871 CWalletTx& wtx = item.second;
1872 // Don't rebroadcast if newer than nTime:
1873 if (wtx.nTimeReceived > nTime)
1874 continue;
1875 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1877 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1879 CWalletTx& wtx = *item.second;
1880 if (wtx.RelayWalletTransaction(connman))
1881 result.push_back(wtx.GetHash());
1883 return result;
1886 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1888 // Do this infrequently and randomly to avoid giving away
1889 // that these are our transactions.
1890 if (GetTime() < nNextResend || !fBroadcastTransactions)
1891 return;
1892 bool fFirst = (nNextResend == 0);
1893 nNextResend = GetTime() + GetRand(30 * 60);
1894 if (fFirst)
1895 return;
1897 // Only do it if there's been a new block since last time
1898 if (nBestBlockTime < nLastResend)
1899 return;
1900 nLastResend = GetTime();
1902 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1903 // block was found:
1904 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1905 if (!relayed.empty())
1906 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1909 /** @} */ // end of mapWallet
1914 /** @defgroup Actions
1916 * @{
1920 CAmount CWallet::GetBalance() const
1922 CAmount nTotal = 0;
1924 LOCK2(cs_main, cs_wallet);
1925 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1927 const CWalletTx* pcoin = &(*it).second;
1928 if (pcoin->IsTrusted())
1929 nTotal += pcoin->GetAvailableCredit();
1933 return nTotal;
1936 CAmount CWallet::GetUnconfirmedBalance() const
1938 CAmount nTotal = 0;
1940 LOCK2(cs_main, cs_wallet);
1941 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1943 const CWalletTx* pcoin = &(*it).second;
1944 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1945 nTotal += pcoin->GetAvailableCredit();
1948 return nTotal;
1951 CAmount CWallet::GetImmatureBalance() const
1953 CAmount nTotal = 0;
1955 LOCK2(cs_main, cs_wallet);
1956 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1958 const CWalletTx* pcoin = &(*it).second;
1959 nTotal += pcoin->GetImmatureCredit();
1962 return nTotal;
1965 CAmount CWallet::GetWatchOnlyBalance() const
1967 CAmount nTotal = 0;
1969 LOCK2(cs_main, cs_wallet);
1970 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1972 const CWalletTx* pcoin = &(*it).second;
1973 if (pcoin->IsTrusted())
1974 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1978 return nTotal;
1981 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1983 CAmount nTotal = 0;
1985 LOCK2(cs_main, cs_wallet);
1986 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1988 const CWalletTx* pcoin = &(*it).second;
1989 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1990 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1993 return nTotal;
1996 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1998 CAmount nTotal = 0;
2000 LOCK2(cs_main, cs_wallet);
2001 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2003 const CWalletTx* pcoin = &(*it).second;
2004 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2007 return nTotal;
2010 // Calculate total balance in a different way from GetBalance. The biggest
2011 // difference is that GetBalance sums up all unspent TxOuts paying to the
2012 // wallet, while this sums up both spent and unspent TxOuts paying to the
2013 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2014 // also has fewer restrictions on which unconfirmed transactions are considered
2015 // trusted.
2016 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2018 LOCK2(cs_main, cs_wallet);
2020 CAmount balance = 0;
2021 for (const auto& entry : mapWallet) {
2022 const CWalletTx& wtx = entry.second;
2023 const int depth = wtx.GetDepthInMainChain();
2024 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2025 continue;
2028 // Loop through tx outputs and add incoming payments. For outgoing txs,
2029 // treat change outputs specially, as part of the amount debited.
2030 CAmount debit = wtx.GetDebit(filter);
2031 const bool outgoing = debit > 0;
2032 for (const CTxOut& out : wtx.tx->vout) {
2033 if (outgoing && IsChange(out)) {
2034 debit -= out.nValue;
2035 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2036 balance += out.nValue;
2040 // For outgoing txs, subtract amount debited.
2041 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2042 balance -= debit;
2046 if (account) {
2047 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2050 return balance;
2053 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2055 LOCK2(cs_main, cs_wallet);
2057 CAmount balance = 0;
2058 std::vector<COutput> vCoins;
2059 AvailableCoins(vCoins, true, coinControl);
2060 for (const COutput& out : vCoins) {
2061 if (out.fSpendable) {
2062 balance += out.tx->tx->vout[out.i].nValue;
2065 return balance;
2068 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
2070 vCoins.clear();
2073 LOCK2(cs_main, cs_wallet);
2075 CAmount nTotal = 0;
2077 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2079 const uint256& wtxid = it->first;
2080 const CWalletTx* pcoin = &(*it).second;
2082 if (!CheckFinalTx(*pcoin))
2083 continue;
2085 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2086 continue;
2088 int nDepth = pcoin->GetDepthInMainChain();
2089 if (nDepth < 0)
2090 continue;
2092 // We should not consider coins which aren't at least in our mempool
2093 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2094 if (nDepth == 0 && !pcoin->InMempool())
2095 continue;
2097 bool safeTx = pcoin->IsTrusted();
2099 // We should not consider coins from transactions that are replacing
2100 // other transactions.
2102 // Example: There is a transaction A which is replaced by bumpfee
2103 // transaction B. In this case, we want to prevent creation of
2104 // a transaction B' which spends an output of B.
2106 // Reason: If transaction A were initially confirmed, transactions B
2107 // and B' would no longer be valid, so the user would have to create
2108 // a new transaction C to replace B'. However, in the case of a
2109 // one-block reorg, transactions B' and C might BOTH be accepted,
2110 // when the user only wanted one of them. Specifically, there could
2111 // be a 1-block reorg away from the chain where transactions A and C
2112 // were accepted to another chain where B, B', and C were all
2113 // accepted.
2114 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2115 safeTx = false;
2118 // Similarly, we should not consider coins from transactions that
2119 // have been replaced. In the example above, we would want to prevent
2120 // creation of a transaction A' spending an output of A, because if
2121 // transaction B were initially confirmed, conflicting with A and
2122 // A', we wouldn't want to the user to create a transaction D
2123 // intending to replace A', but potentially resulting in a scenario
2124 // where A, A', and D could all be accepted (instead of just B and
2125 // D, or just A and A' like the user would want).
2126 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2127 safeTx = false;
2130 if (fOnlySafe && !safeTx) {
2131 continue;
2134 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2135 continue;
2137 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2138 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2139 continue;
2141 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2142 continue;
2144 if (IsLockedCoin((*it).first, i))
2145 continue;
2147 if (IsSpent(wtxid, i))
2148 continue;
2150 isminetype mine = IsMine(pcoin->tx->vout[i]);
2152 if (mine == ISMINE_NO) {
2153 continue;
2156 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2157 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2159 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2161 // Checks the sum amount of all UTXO's.
2162 if (nMinimumSumAmount != MAX_MONEY) {
2163 nTotal += pcoin->tx->vout[i].nValue;
2165 if (nTotal >= nMinimumSumAmount) {
2166 return;
2170 // Checks the maximum number of UTXO's.
2171 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2172 return;
2179 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2181 // TODO: Add AssertLockHeld(cs_wallet) here.
2183 // Because the return value from this function contains pointers to
2184 // CWalletTx objects, callers to this function really should acquire the
2185 // cs_wallet lock before calling it. However, the current caller doesn't
2186 // acquire this lock yet. There was an attempt to add the missing lock in
2187 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2188 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2189 // avoid adding some extra complexity to the Qt code.
2191 std::map<CTxDestination, std::vector<COutput>> result;
2193 std::vector<COutput> availableCoins;
2194 AvailableCoins(availableCoins);
2196 LOCK2(cs_main, cs_wallet);
2197 for (auto& coin : availableCoins) {
2198 CTxDestination address;
2199 if (coin.fSpendable &&
2200 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2201 result[address].emplace_back(std::move(coin));
2205 std::vector<COutPoint> lockedCoins;
2206 ListLockedCoins(lockedCoins);
2207 for (const auto& output : lockedCoins) {
2208 auto it = mapWallet.find(output.hash);
2209 if (it != mapWallet.end()) {
2210 int depth = it->second.GetDepthInMainChain();
2211 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2212 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2213 CTxDestination address;
2214 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2215 result[address].emplace_back(
2216 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2222 return result;
2225 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2227 const CTransaction* ptx = &tx;
2228 int n = output;
2229 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2230 const COutPoint& prevout = ptx->vin[0].prevout;
2231 auto it = mapWallet.find(prevout.hash);
2232 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2233 !IsMine(it->second.tx->vout[prevout.n])) {
2234 break;
2236 ptx = it->second.tx.get();
2237 n = prevout.n;
2239 return ptx->vout[n];
2242 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2243 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2245 std::vector<char> vfIncluded;
2247 vfBest.assign(vValue.size(), true);
2248 nBest = nTotalLower;
2250 FastRandomContext insecure_rand;
2252 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2254 vfIncluded.assign(vValue.size(), false);
2255 CAmount nTotal = 0;
2256 bool fReachedTarget = false;
2257 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2259 for (unsigned int i = 0; i < vValue.size(); i++)
2261 //The solver here uses a randomized algorithm,
2262 //the randomness serves no real security purpose but is just
2263 //needed to prevent degenerate behavior and it is important
2264 //that the rng is fast. We do not use a constant random sequence,
2265 //because there may be some privacy improvement by making
2266 //the selection random.
2267 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2269 nTotal += vValue[i].txout.nValue;
2270 vfIncluded[i] = true;
2271 if (nTotal >= nTargetValue)
2273 fReachedTarget = true;
2274 if (nTotal < nBest)
2276 nBest = nTotal;
2277 vfBest = vfIncluded;
2279 nTotal -= vValue[i].txout.nValue;
2280 vfIncluded[i] = false;
2288 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2289 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2291 setCoinsRet.clear();
2292 nValueRet = 0;
2294 // List of values less than target
2295 boost::optional<CInputCoin> coinLowestLarger;
2296 std::vector<CInputCoin> vValue;
2297 CAmount nTotalLower = 0;
2299 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2301 for (const COutput &output : vCoins)
2303 if (!output.fSpendable)
2304 continue;
2306 const CWalletTx *pcoin = output.tx;
2308 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2309 continue;
2311 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2312 continue;
2314 int i = output.i;
2316 CInputCoin coin = CInputCoin(pcoin, i);
2318 if (coin.txout.nValue == nTargetValue)
2320 setCoinsRet.insert(coin);
2321 nValueRet += coin.txout.nValue;
2322 return true;
2324 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2326 vValue.push_back(coin);
2327 nTotalLower += coin.txout.nValue;
2329 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2331 coinLowestLarger = coin;
2335 if (nTotalLower == nTargetValue)
2337 for (const auto& input : vValue)
2339 setCoinsRet.insert(input);
2340 nValueRet += input.txout.nValue;
2342 return true;
2345 if (nTotalLower < nTargetValue)
2347 if (!coinLowestLarger)
2348 return false;
2349 setCoinsRet.insert(coinLowestLarger.get());
2350 nValueRet += coinLowestLarger->txout.nValue;
2351 return true;
2354 // Solve subset sum by stochastic approximation
2355 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2356 std::reverse(vValue.begin(), vValue.end());
2357 std::vector<char> vfBest;
2358 CAmount nBest;
2360 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2361 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2362 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2364 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2365 // or the next bigger coin is closer), return the bigger coin
2366 if (coinLowestLarger &&
2367 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2369 setCoinsRet.insert(coinLowestLarger.get());
2370 nValueRet += coinLowestLarger->txout.nValue;
2372 else {
2373 for (unsigned int i = 0; i < vValue.size(); i++)
2374 if (vfBest[i])
2376 setCoinsRet.insert(vValue[i]);
2377 nValueRet += vValue[i].txout.nValue;
2380 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2381 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2382 for (unsigned int i = 0; i < vValue.size(); i++) {
2383 if (vfBest[i]) {
2384 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2387 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2391 return true;
2394 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2396 std::vector<COutput> vCoins(vAvailableCoins);
2398 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2399 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2401 for (const COutput& out : vCoins)
2403 if (!out.fSpendable)
2404 continue;
2405 nValueRet += out.tx->tx->vout[out.i].nValue;
2406 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2408 return (nValueRet >= nTargetValue);
2411 // calculate value from preset inputs and store them
2412 std::set<CInputCoin> setPresetCoins;
2413 CAmount nValueFromPresetInputs = 0;
2415 std::vector<COutPoint> vPresetInputs;
2416 if (coinControl)
2417 coinControl->ListSelected(vPresetInputs);
2418 for (const COutPoint& outpoint : vPresetInputs)
2420 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2421 if (it != mapWallet.end())
2423 const CWalletTx* pcoin = &it->second;
2424 // Clearly invalid input, fail
2425 if (pcoin->tx->vout.size() <= outpoint.n)
2426 return false;
2427 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2428 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2429 } else
2430 return false; // TODO: Allow non-wallet inputs
2433 // remove preset inputs from vCoins
2434 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2436 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2437 it = vCoins.erase(it);
2438 else
2439 ++it;
2442 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2443 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2445 bool res = nTargetValue <= nValueFromPresetInputs ||
2446 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2447 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2448 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2449 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2450 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2451 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2452 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2454 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2455 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2457 // add preset inputs to the total value selected
2458 nValueRet += nValueFromPresetInputs;
2460 return res;
2463 bool CWallet::SignTransaction(CMutableTransaction &tx)
2465 AssertLockHeld(cs_wallet); // mapWallet
2467 // sign the new tx
2468 CTransaction txNewConst(tx);
2469 int nIn = 0;
2470 for (const auto& input : tx.vin) {
2471 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2472 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2473 return false;
2475 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2476 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2477 SignatureData sigdata;
2478 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2479 return false;
2481 UpdateTransaction(tx, nIn, sigdata);
2482 nIn++;
2484 return true;
2487 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2489 std::vector<CRecipient> vecSend;
2491 // Turn the txout set into a CRecipient vector
2492 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2494 const CTxOut& txOut = tx.vout[idx];
2495 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2496 vecSend.push_back(recipient);
2499 coinControl.fAllowOtherInputs = true;
2501 for (const CTxIn& txin : tx.vin)
2502 coinControl.Select(txin.prevout);
2504 CReserveKey reservekey(this);
2505 CWalletTx wtx;
2506 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2507 return false;
2510 if (nChangePosInOut != -1) {
2511 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2512 // we dont have the normal Create/Commit cycle, and dont want to risk reusing change,
2513 // so just remove the key from the keypool here.
2514 reservekey.KeepKey();
2517 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2518 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2519 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2521 // Add new txins (keeping original txin scriptSig/order)
2522 for (const CTxIn& txin : wtx.tx->vin)
2524 if (!coinControl.IsSelected(txin.prevout))
2526 tx.vin.push_back(txin);
2528 if (lockUnspents)
2530 LOCK2(cs_main, cs_wallet);
2531 LockCoin(txin.prevout);
2537 return true;
2540 static CFeeRate GetDiscardRate(const CBlockPolicyEstimator& estimator)
2542 unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE);
2543 CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */);
2544 // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate
2545 discard_rate = (discard_rate == CFeeRate(0)) ? CWallet::m_discard_rate : std::min(discard_rate, CWallet::m_discard_rate);
2546 // Discard rate must be at least dustRelayFee
2547 discard_rate = std::max(discard_rate, ::dustRelayFee);
2548 return discard_rate;
2551 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2552 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2554 CAmount nValue = 0;
2555 int nChangePosRequest = nChangePosInOut;
2556 unsigned int nSubtractFeeFromAmount = 0;
2557 for (const auto& recipient : vecSend)
2559 if (nValue < 0 || recipient.nAmount < 0)
2561 strFailReason = _("Transaction amounts must not be negative");
2562 return false;
2564 nValue += recipient.nAmount;
2566 if (recipient.fSubtractFeeFromAmount)
2567 nSubtractFeeFromAmount++;
2569 if (vecSend.empty())
2571 strFailReason = _("Transaction must have at least one recipient");
2572 return false;
2575 wtxNew.fTimeReceivedIsTxTime = true;
2576 wtxNew.BindWallet(this);
2577 CMutableTransaction txNew;
2579 // Discourage fee sniping.
2581 // For a large miner the value of the transactions in the best block and
2582 // the mempool can exceed the cost of deliberately attempting to mine two
2583 // blocks to orphan the current best block. By setting nLockTime such that
2584 // only the next block can include the transaction, we discourage this
2585 // practice as the height restricted and limited blocksize gives miners
2586 // considering fee sniping fewer options for pulling off this attack.
2588 // A simple way to think about this is from the wallet's point of view we
2589 // always want the blockchain to move forward. By setting nLockTime this
2590 // way we're basically making the statement that we only want this
2591 // transaction to appear in the next block; we don't want to potentially
2592 // encourage reorgs by allowing transactions to appear at lower heights
2593 // than the next block in forks of the best chain.
2595 // Of course, the subsidy is high enough, and transaction volume low
2596 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2597 // now we ensure code won't be written that makes assumptions about
2598 // nLockTime that preclude a fix later.
2599 txNew.nLockTime = chainActive.Height();
2601 // Secondly occasionally randomly pick a nLockTime even further back, so
2602 // that transactions that are delayed after signing for whatever reason,
2603 // e.g. high-latency mix networks and some CoinJoin implementations, have
2604 // better privacy.
2605 if (GetRandInt(10) == 0)
2606 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2608 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2609 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2610 FeeCalculation feeCalc;
2611 unsigned int nBytes;
2613 std::set<CInputCoin> setCoins;
2614 LOCK2(cs_main, cs_wallet);
2616 std::vector<COutput> vAvailableCoins;
2617 AvailableCoins(vAvailableCoins, true, &coin_control);
2619 // Create change script that will be used if we need change
2620 // TODO: pass in scriptChange instead of reservekey so
2621 // change transaction isn't always pay-to-bitcoin-address
2622 CScript scriptChange;
2624 // coin control: send change to custom address
2625 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2626 scriptChange = GetScriptForDestination(coin_control.destChange);
2627 } else { // no coin control: send change to newly generated address
2628 // Note: We use a new key here to keep it from being obvious which side is the change.
2629 // The drawback is that by not reusing a previous key, the change may be lost if a
2630 // backup is restored, if the backup doesn't have the new private key for the change.
2631 // If we reused the old key, it would be possible to add code to look for and
2632 // rediscover unknown transactions that were written with keys of ours to recover
2633 // post-backup change.
2635 // Reserve a new key pair from key pool
2636 CPubKey vchPubKey;
2637 bool ret;
2638 ret = reservekey.GetReservedKey(vchPubKey, true);
2639 if (!ret)
2641 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2642 return false;
2645 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2647 CTxOut change_prototype_txout(0, scriptChange);
2648 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2650 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2651 nFeeRet = 0;
2652 bool pick_new_inputs = true;
2653 CAmount nValueIn = 0;
2654 // Start with no fee and loop until there is enough fee
2655 while (true)
2657 nChangePosInOut = nChangePosRequest;
2658 txNew.vin.clear();
2659 txNew.vout.clear();
2660 wtxNew.fFromMe = true;
2661 bool fFirst = true;
2663 CAmount nValueToSelect = nValue;
2664 if (nSubtractFeeFromAmount == 0)
2665 nValueToSelect += nFeeRet;
2666 // vouts to the payees
2667 for (const auto& recipient : vecSend)
2669 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2671 if (recipient.fSubtractFeeFromAmount)
2673 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2675 if (fFirst) // first receiver pays the remainder not divisible by output count
2677 fFirst = false;
2678 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2682 if (IsDust(txout, ::dustRelayFee))
2684 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2686 if (txout.nValue < 0)
2687 strFailReason = _("The transaction amount is too small to pay the fee");
2688 else
2689 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2691 else
2692 strFailReason = _("Transaction amount too small");
2693 return false;
2695 txNew.vout.push_back(txout);
2698 // Choose coins to use
2699 if (pick_new_inputs) {
2700 nValueIn = 0;
2701 setCoins.clear();
2702 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2704 strFailReason = _("Insufficient funds");
2705 return false;
2709 const CAmount nChange = nValueIn - nValueToSelect;
2711 if (nChange > 0)
2713 // Fill a vout to ourself
2714 CTxOut newTxOut(nChange, scriptChange);
2716 // Never create dust outputs; if we would, just
2717 // add the dust to the fee.
2718 if (IsDust(newTxOut, discard_rate))
2720 nChangePosInOut = -1;
2721 nFeeRet += nChange;
2723 else
2725 if (nChangePosInOut == -1)
2727 // Insert change txn at random position:
2728 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2730 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2732 strFailReason = _("Change index out of range");
2733 return false;
2736 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2737 txNew.vout.insert(position, newTxOut);
2739 } else {
2740 nChangePosInOut = -1;
2743 // Fill vin
2745 // Note how the sequence number is set to non-maxint so that
2746 // the nLockTime set above actually works.
2748 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2749 // we use the highest possible value in that range (maxint-2)
2750 // to avoid conflicting with other possible uses of nSequence,
2751 // and in the spirit of "smallest possible change from prior
2752 // behavior."
2753 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2754 for (const auto& coin : setCoins)
2755 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2756 nSequence));
2758 // Fill in dummy signatures for fee calculation.
2759 if (!DummySignTx(txNew, setCoins)) {
2760 strFailReason = _("Signing transaction failed");
2761 return false;
2764 nBytes = GetVirtualTransactionSize(txNew);
2766 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2767 for (auto& vin : txNew.vin) {
2768 vin.scriptSig = CScript();
2769 vin.scriptWitness.SetNull();
2772 CAmount nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2774 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2775 // because we must be at the maximum allowed fee.
2776 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2778 strFailReason = _("Transaction too large for fee policy");
2779 return false;
2782 if (nFeeRet >= nFeeNeeded) {
2783 // Reduce fee to only the needed amount if possible. This
2784 // prevents potential overpayment in fees if the coins
2785 // selected to meet nFeeNeeded result in a transaction that
2786 // requires less fee than the prior iteration.
2788 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2789 // to be addressed because it requires returning the fee to
2790 // the payees and not the change output.
2792 // If we have no change and a big enough excess fee, then
2793 // try to construct transaction again only without picking
2794 // new inputs. We now know we only need the smaller fee
2795 // (because of reduced tx size) and so we should add a
2796 // change output. Only try this once.
2797 CAmount fee_needed_for_change = GetMinimumFee(change_prototype_size, coin_control, ::mempool, ::feeEstimator, nullptr);
2798 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2799 CAmount max_excess_fee = fee_needed_for_change + minimum_value_for_change;
2800 if (nFeeRet > nFeeNeeded + max_excess_fee && nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2801 pick_new_inputs = false;
2802 nFeeRet = nFeeNeeded + fee_needed_for_change;
2803 continue;
2806 // If we have change output already, just increase it
2807 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2808 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2809 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2810 change_position->nValue += extraFeePaid;
2811 nFeeRet -= extraFeePaid;
2813 break; // Done, enough fee included.
2815 else if (!pick_new_inputs) {
2816 // This shouldn't happen, we should have had enough excess
2817 // fee to pay for the new output and still meet nFeeNeeded
2818 strFailReason = _("Transaction fee and change calculation failed");
2819 return false;
2822 // Try to reduce change to include necessary fee
2823 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2824 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2825 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2826 // Only reduce change if remaining amount is still a large enough output.
2827 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2828 change_position->nValue -= additionalFeeNeeded;
2829 nFeeRet += additionalFeeNeeded;
2830 break; // Done, able to increase fee from change
2834 // Include more fee and try again.
2835 nFeeRet = nFeeNeeded;
2836 continue;
2840 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2842 if (sign)
2844 CTransaction txNewConst(txNew);
2845 int nIn = 0;
2846 for (const auto& coin : setCoins)
2848 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2849 SignatureData sigdata;
2851 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2853 strFailReason = _("Signing transaction failed");
2854 return false;
2855 } else {
2856 UpdateTransaction(txNew, nIn, sigdata);
2859 nIn++;
2863 // Embed the constructed transaction data in wtxNew.
2864 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2866 // Limit size
2867 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2869 strFailReason = _("Transaction too large");
2870 return false;
2874 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2875 // Lastly, ensure this tx will pass the mempool's chain limits
2876 LockPoints lp;
2877 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2878 CTxMemPool::setEntries setAncestors;
2879 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2880 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2881 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2882 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2883 std::string errString;
2884 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2885 strFailReason = _("Transaction has too long of a mempool chain");
2886 return false;
2890 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",
2891 nFeeRet, nBytes, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2892 feeCalc.est.pass.start, feeCalc.est.pass.end,
2893 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2894 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2895 feeCalc.est.fail.start, feeCalc.est.fail.end,
2896 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2897 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2898 return true;
2902 * Call after CreateTransaction unless you want to abort
2904 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2907 LOCK2(cs_main, cs_wallet);
2908 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2910 // Take key pair from key pool so it won't be used again
2911 reservekey.KeepKey();
2913 // Add tx to wallet, because if it has change it's also ours,
2914 // otherwise just for transaction history.
2915 AddToWallet(wtxNew);
2917 // Notify that old coins are spent
2918 for (const CTxIn& txin : wtxNew.tx->vin)
2920 CWalletTx &coin = mapWallet[txin.prevout.hash];
2921 coin.BindWallet(this);
2922 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2926 // Track how many getdata requests our transaction gets
2927 mapRequestCount[wtxNew.GetHash()] = 0;
2929 if (fBroadcastTransactions)
2931 // Broadcast
2932 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2933 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2934 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2935 } else {
2936 wtxNew.RelayWalletTransaction(connman);
2940 return true;
2943 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2944 CWalletDB walletdb(*dbw);
2945 return walletdb.ListAccountCreditDebit(strAccount, entries);
2948 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2950 CWalletDB walletdb(*dbw);
2952 return AddAccountingEntry(acentry, &walletdb);
2955 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2957 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
2958 return false;
2961 laccentries.push_back(acentry);
2962 CAccountingEntry & entry = laccentries.back();
2963 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2965 return true;
2968 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2970 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2973 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation *feeCalc)
2975 /* User control of how to calculate fee uses the following parameter precedence:
2976 1. coin_control.m_feerate
2977 2. coin_control.m_confirm_target
2978 3. payTxFee (user-set global variable)
2979 4. nTxConfirmTarget (user-set global variable)
2980 The first parameter that is set is used.
2982 CAmount fee_needed;
2983 if (coin_control.m_feerate) { // 1.
2984 fee_needed = coin_control.m_feerate->GetFee(nTxBytes);
2985 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
2986 // Allow to override automatic min/max check over coin control instance
2987 if (coin_control.fOverrideFeeRate) return fee_needed;
2989 else if (!coin_control.m_confirm_target && ::payTxFee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for global payTxFee
2990 fee_needed = ::payTxFee.GetFee(nTxBytes);
2991 if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE;
2993 else { // 2. or 4.
2994 // We will use smart fee estimation
2995 unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : ::nTxConfirmTarget;
2996 // By default estimates are economical iff we are signaling opt-in-RBF
2997 bool conservative_estimate = !coin_control.signalRbf;
2998 // Allow to override the default fee estimate mode over the CoinControl instance
2999 if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true;
3000 else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false;
3002 fee_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate).GetFee(nTxBytes);
3003 if (fee_needed == 0) {
3004 // if we don't have enough data for estimateSmartFee, then use fallbackFee
3005 fee_needed = fallbackFee.GetFee(nTxBytes);
3006 if (feeCalc) feeCalc->reason = FeeReason::FALLBACK;
3008 // Obey mempool min fee when using smart fee estimation
3009 CAmount min_mempool_fee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nTxBytes);
3010 if (fee_needed < min_mempool_fee) {
3011 fee_needed = min_mempool_fee;
3012 if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN;
3016 // prevent user from paying a fee below minRelayTxFee or minTxFee
3017 CAmount required_fee = GetRequiredFee(nTxBytes);
3018 if (required_fee > fee_needed) {
3019 fee_needed = required_fee;
3020 if (feeCalc) feeCalc->reason = FeeReason::REQUIRED;
3022 // But always obey the maximum
3023 if (fee_needed > maxTxFee) {
3024 fee_needed = maxTxFee;
3025 if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE;
3027 return fee_needed;
3033 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3035 fFirstRunRet = false;
3036 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3037 if (nLoadWalletRet == DB_NEED_REWRITE)
3039 if (dbw->Rewrite("\x04pool"))
3041 LOCK(cs_wallet);
3042 setInternalKeyPool.clear();
3043 setExternalKeyPool.clear();
3044 // Note: can't top-up keypool here, because wallet is locked.
3045 // User will be prompted to unlock wallet the next operation
3046 // that requires a new key.
3050 if (nLoadWalletRet != DB_LOAD_OK)
3051 return nLoadWalletRet;
3052 fFirstRunRet = !vchDefaultKey.IsValid();
3054 uiInterface.LoadWallet(this);
3056 return DB_LOAD_OK;
3059 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3061 AssertLockHeld(cs_wallet); // mapWallet
3062 vchDefaultKey = CPubKey();
3063 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3064 for (uint256 hash : vHashOut)
3065 mapWallet.erase(hash);
3067 if (nZapSelectTxRet == DB_NEED_REWRITE)
3069 if (dbw->Rewrite("\x04pool"))
3071 setInternalKeyPool.clear();
3072 setExternalKeyPool.clear();
3073 // Note: can't top-up keypool here, because wallet is locked.
3074 // User will be prompted to unlock wallet the next operation
3075 // that requires a new key.
3079 if (nZapSelectTxRet != DB_LOAD_OK)
3080 return nZapSelectTxRet;
3082 MarkDirty();
3084 return DB_LOAD_OK;
3088 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3090 vchDefaultKey = CPubKey();
3091 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3092 if (nZapWalletTxRet == DB_NEED_REWRITE)
3094 if (dbw->Rewrite("\x04pool"))
3096 LOCK(cs_wallet);
3097 setInternalKeyPool.clear();
3098 setExternalKeyPool.clear();
3099 // Note: can't top-up keypool here, because wallet is locked.
3100 // User will be prompted to unlock wallet the next operation
3101 // that requires a new key.
3105 if (nZapWalletTxRet != DB_LOAD_OK)
3106 return nZapWalletTxRet;
3108 return DB_LOAD_OK;
3112 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3114 bool fUpdated = false;
3116 LOCK(cs_wallet); // mapAddressBook
3117 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3118 fUpdated = mi != mapAddressBook.end();
3119 mapAddressBook[address].name = strName;
3120 if (!strPurpose.empty()) /* update purpose only if requested */
3121 mapAddressBook[address].purpose = strPurpose;
3123 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3124 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3125 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3126 return false;
3127 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3130 bool CWallet::DelAddressBook(const CTxDestination& address)
3133 LOCK(cs_wallet); // mapAddressBook
3135 // Delete destdata tuples associated with address
3136 std::string strAddress = CBitcoinAddress(address).ToString();
3137 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3139 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3141 mapAddressBook.erase(address);
3144 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3146 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3147 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3150 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3152 CTxDestination address;
3153 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3154 auto mi = mapAddressBook.find(address);
3155 if (mi != mapAddressBook.end()) {
3156 return mi->second.name;
3159 // A scriptPubKey that doesn't have an entry in the address book is
3160 // associated with the default account ("").
3161 const static std::string DEFAULT_ACCOUNT_NAME;
3162 return DEFAULT_ACCOUNT_NAME;
3165 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3167 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3168 return false;
3169 vchDefaultKey = vchPubKey;
3170 return true;
3174 * Mark old keypool keys as used,
3175 * and generate all new keys
3177 bool CWallet::NewKeyPool()
3180 LOCK(cs_wallet);
3181 CWalletDB walletdb(*dbw);
3183 for (int64_t nIndex : setInternalKeyPool) {
3184 walletdb.ErasePool(nIndex);
3186 setInternalKeyPool.clear();
3188 for (int64_t nIndex : setExternalKeyPool) {
3189 walletdb.ErasePool(nIndex);
3191 setExternalKeyPool.clear();
3193 if (!TopUpKeyPool()) {
3194 return false;
3196 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3198 return true;
3201 size_t CWallet::KeypoolCountExternalKeys()
3203 AssertLockHeld(cs_wallet); // setExternalKeyPool
3204 return setExternalKeyPool.size();
3207 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3210 LOCK(cs_wallet);
3212 if (IsLocked())
3213 return false;
3215 // Top up key pool
3216 unsigned int nTargetSize;
3217 if (kpSize > 0)
3218 nTargetSize = kpSize;
3219 else
3220 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3222 // count amount of available keys (internal, external)
3223 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3224 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3225 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3227 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3229 // don't create extra internal keys
3230 missingInternal = 0;
3232 bool internal = false;
3233 CWalletDB walletdb(*dbw);
3234 for (int64_t i = missingInternal + missingExternal; i--;)
3236 if (i < missingInternal) {
3237 internal = true;
3240 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3241 int64_t index = ++m_max_keypool_index;
3243 if (!walletdb.WritePool(index, CKeyPool(GenerateNewKey(walletdb, internal), internal))) {
3244 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3247 if (internal) {
3248 setInternalKeyPool.insert(index);
3249 } else {
3250 setExternalKeyPool.insert(index);
3253 if (missingInternal + missingExternal > 0) {
3254 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3257 return true;
3260 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3262 nIndex = -1;
3263 keypool.vchPubKey = CPubKey();
3265 LOCK(cs_wallet);
3267 if (!IsLocked())
3268 TopUpKeyPool();
3270 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3271 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3273 // Get the oldest key
3274 if(setKeyPool.empty())
3275 return;
3277 CWalletDB walletdb(*dbw);
3279 auto it = setKeyPool.begin();
3280 nIndex = *it;
3281 setKeyPool.erase(it);
3282 if (!walletdb.ReadPool(nIndex, keypool)) {
3283 throw std::runtime_error(std::string(__func__) + ": read failed");
3285 if (!HaveKey(keypool.vchPubKey.GetID())) {
3286 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3288 if (keypool.fInternal != fReturningInternal) {
3289 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3292 assert(keypool.vchPubKey.IsValid());
3293 LogPrintf("keypool reserve %d\n", nIndex);
3297 void CWallet::KeepKey(int64_t nIndex)
3299 // Remove from key pool
3300 CWalletDB walletdb(*dbw);
3301 walletdb.ErasePool(nIndex);
3302 LogPrintf("keypool keep %d\n", nIndex);
3305 void CWallet::ReturnKey(int64_t nIndex, bool fInternal)
3307 // Return to key pool
3309 LOCK(cs_wallet);
3310 if (fInternal) {
3311 setInternalKeyPool.insert(nIndex);
3312 } else {
3313 setExternalKeyPool.insert(nIndex);
3316 LogPrintf("keypool return %d\n", nIndex);
3319 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3321 CKeyPool keypool;
3323 LOCK(cs_wallet);
3324 int64_t nIndex = 0;
3325 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3326 if (nIndex == -1)
3328 if (IsLocked()) return false;
3329 CWalletDB walletdb(*dbw);
3330 result = GenerateNewKey(walletdb, internal);
3331 return true;
3333 KeepKey(nIndex);
3334 result = keypool.vchPubKey;
3336 return true;
3339 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3340 if (setKeyPool.empty()) {
3341 return GetTime();
3344 CKeyPool keypool;
3345 int64_t nIndex = *(setKeyPool.begin());
3346 if (!walletdb.ReadPool(nIndex, keypool)) {
3347 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3349 assert(keypool.vchPubKey.IsValid());
3350 return keypool.nTime;
3353 int64_t CWallet::GetOldestKeyPoolTime()
3355 LOCK(cs_wallet);
3357 CWalletDB walletdb(*dbw);
3359 // load oldest key from keypool, get time and return
3360 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3361 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3362 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3365 return oldestKey;
3368 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3370 std::map<CTxDestination, CAmount> balances;
3373 LOCK(cs_wallet);
3374 for (const auto& walletEntry : mapWallet)
3376 const CWalletTx *pcoin = &walletEntry.second;
3378 if (!pcoin->IsTrusted())
3379 continue;
3381 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3382 continue;
3384 int nDepth = pcoin->GetDepthInMainChain();
3385 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3386 continue;
3388 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3390 CTxDestination addr;
3391 if (!IsMine(pcoin->tx->vout[i]))
3392 continue;
3393 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3394 continue;
3396 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3398 if (!balances.count(addr))
3399 balances[addr] = 0;
3400 balances[addr] += n;
3405 return balances;
3408 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3410 AssertLockHeld(cs_wallet); // mapWallet
3411 std::set< std::set<CTxDestination> > groupings;
3412 std::set<CTxDestination> grouping;
3414 for (const auto& walletEntry : mapWallet)
3416 const CWalletTx *pcoin = &walletEntry.second;
3418 if (pcoin->tx->vin.size() > 0)
3420 bool any_mine = false;
3421 // group all input addresses with each other
3422 for (CTxIn txin : pcoin->tx->vin)
3424 CTxDestination address;
3425 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3426 continue;
3427 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3428 continue;
3429 grouping.insert(address);
3430 any_mine = true;
3433 // group change with input addresses
3434 if (any_mine)
3436 for (CTxOut txout : pcoin->tx->vout)
3437 if (IsChange(txout))
3439 CTxDestination txoutAddr;
3440 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3441 continue;
3442 grouping.insert(txoutAddr);
3445 if (grouping.size() > 0)
3447 groupings.insert(grouping);
3448 grouping.clear();
3452 // group lone addrs by themselves
3453 for (const auto& txout : pcoin->tx->vout)
3454 if (IsMine(txout))
3456 CTxDestination address;
3457 if(!ExtractDestination(txout.scriptPubKey, address))
3458 continue;
3459 grouping.insert(address);
3460 groupings.insert(grouping);
3461 grouping.clear();
3465 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3466 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3467 for (std::set<CTxDestination> _grouping : groupings)
3469 // make a set of all the groups hit by this new group
3470 std::set< std::set<CTxDestination>* > hits;
3471 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3472 for (CTxDestination address : _grouping)
3473 if ((it = setmap.find(address)) != setmap.end())
3474 hits.insert((*it).second);
3476 // merge all hit groups into a new single group and delete old groups
3477 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3478 for (std::set<CTxDestination>* hit : hits)
3480 merged->insert(hit->begin(), hit->end());
3481 uniqueGroupings.erase(hit);
3482 delete hit;
3484 uniqueGroupings.insert(merged);
3486 // update setmap
3487 for (CTxDestination element : *merged)
3488 setmap[element] = merged;
3491 std::set< std::set<CTxDestination> > ret;
3492 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3494 ret.insert(*uniqueGrouping);
3495 delete uniqueGrouping;
3498 return ret;
3501 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3503 LOCK(cs_wallet);
3504 std::set<CTxDestination> result;
3505 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3507 const CTxDestination& address = item.first;
3508 const std::string& strName = item.second.name;
3509 if (strName == strAccount)
3510 result.insert(address);
3512 return result;
3515 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3517 if (nIndex == -1)
3519 CKeyPool keypool;
3520 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3521 if (nIndex != -1)
3522 vchPubKey = keypool.vchPubKey;
3523 else {
3524 return false;
3526 fInternal = keypool.fInternal;
3528 assert(vchPubKey.IsValid());
3529 pubkey = vchPubKey;
3530 return true;
3533 void CReserveKey::KeepKey()
3535 if (nIndex != -1)
3536 pwallet->KeepKey(nIndex);
3537 nIndex = -1;
3538 vchPubKey = CPubKey();
3541 void CReserveKey::ReturnKey()
3543 if (nIndex != -1) {
3544 pwallet->ReturnKey(nIndex, fInternal);
3546 nIndex = -1;
3547 vchPubKey = CPubKey();
3550 static void LoadReserveKeysToSet(std::set<CKeyID>& setAddress, const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3551 for (const int64_t& id : setKeyPool)
3553 CKeyPool keypool;
3554 if (!walletdb.ReadPool(id, keypool))
3555 throw std::runtime_error(std::string(__func__) + ": read failed");
3556 assert(keypool.vchPubKey.IsValid());
3557 CKeyID keyID = keypool.vchPubKey.GetID();
3558 setAddress.insert(keyID);
3562 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3564 setAddress.clear();
3566 CWalletDB walletdb(*dbw);
3568 LOCK2(cs_main, cs_wallet);
3569 LoadReserveKeysToSet(setAddress, setInternalKeyPool, walletdb);
3570 LoadReserveKeysToSet(setAddress, setExternalKeyPool, walletdb);
3572 for (const CKeyID& keyID : setAddress) {
3573 if (!HaveKey(keyID)) {
3574 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3579 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3581 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3582 CPubKey pubkey;
3583 if (!rKey->GetReservedKey(pubkey))
3584 return;
3586 script = rKey;
3587 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3590 void CWallet::LockCoin(const COutPoint& output)
3592 AssertLockHeld(cs_wallet); // setLockedCoins
3593 setLockedCoins.insert(output);
3596 void CWallet::UnlockCoin(const COutPoint& output)
3598 AssertLockHeld(cs_wallet); // setLockedCoins
3599 setLockedCoins.erase(output);
3602 void CWallet::UnlockAllCoins()
3604 AssertLockHeld(cs_wallet); // setLockedCoins
3605 setLockedCoins.clear();
3608 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3610 AssertLockHeld(cs_wallet); // setLockedCoins
3611 COutPoint outpt(hash, n);
3613 return (setLockedCoins.count(outpt) > 0);
3616 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3618 AssertLockHeld(cs_wallet); // setLockedCoins
3619 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3620 it != setLockedCoins.end(); it++) {
3621 COutPoint outpt = (*it);
3622 vOutpts.push_back(outpt);
3626 /** @} */ // end of Actions
3628 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3629 private:
3630 const CKeyStore &keystore;
3631 std::vector<CKeyID> &vKeys;
3633 public:
3634 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3636 void Process(const CScript &script) {
3637 txnouttype type;
3638 std::vector<CTxDestination> vDest;
3639 int nRequired;
3640 if (ExtractDestinations(script, type, vDest, nRequired)) {
3641 for (const CTxDestination &dest : vDest)
3642 boost::apply_visitor(*this, dest);
3646 void operator()(const CKeyID &keyId) {
3647 if (keystore.HaveKey(keyId))
3648 vKeys.push_back(keyId);
3651 void operator()(const CScriptID &scriptId) {
3652 CScript script;
3653 if (keystore.GetCScript(scriptId, script))
3654 Process(script);
3657 void operator()(const CNoDestination &none) {}
3660 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3661 AssertLockHeld(cs_wallet); // mapKeyMetadata
3662 mapKeyBirth.clear();
3664 // get birth times for keys with metadata
3665 for (const auto& entry : mapKeyMetadata) {
3666 if (entry.second.nCreateTime) {
3667 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3671 // map in which we'll infer heights of other keys
3672 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3673 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3674 std::set<CKeyID> setKeys;
3675 GetKeys(setKeys);
3676 for (const CKeyID &keyid : setKeys) {
3677 if (mapKeyBirth.count(keyid) == 0)
3678 mapKeyFirstBlock[keyid] = pindexMax;
3680 setKeys.clear();
3682 // if there are no such keys, we're done
3683 if (mapKeyFirstBlock.empty())
3684 return;
3686 // find first block that affects those keys, if there are any left
3687 std::vector<CKeyID> vAffected;
3688 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3689 // iterate over all wallet transactions...
3690 const CWalletTx &wtx = (*it).second;
3691 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3692 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3693 // ... which are already in a block
3694 int nHeight = blit->second->nHeight;
3695 for (const CTxOut &txout : wtx.tx->vout) {
3696 // iterate over all their outputs
3697 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3698 for (const CKeyID &keyid : vAffected) {
3699 // ... and all their affected keys
3700 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3701 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3702 rit->second = blit->second;
3704 vAffected.clear();
3709 // Extract block timestamps for those keys
3710 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3711 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3715 * Compute smart timestamp for a transaction being added to the wallet.
3717 * Logic:
3718 * - If sending a transaction, assign its timestamp to the current time.
3719 * - If receiving a transaction outside a block, assign its timestamp to the
3720 * current time.
3721 * - If receiving a block with a future timestamp, assign all its (not already
3722 * known) transactions' timestamps to the current time.
3723 * - If receiving a block with a past timestamp, before the most recent known
3724 * transaction (that we care about), assign all its (not already known)
3725 * transactions' timestamps to the same timestamp as that most-recent-known
3726 * transaction.
3727 * - If receiving a block with a past timestamp, but after the most recent known
3728 * transaction, assign all its (not already known) transactions' timestamps to
3729 * the block time.
3731 * For more information see CWalletTx::nTimeSmart,
3732 * https://bitcointalk.org/?topic=54527, or
3733 * https://github.com/bitcoin/bitcoin/pull/1393.
3735 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3737 unsigned int nTimeSmart = wtx.nTimeReceived;
3738 if (!wtx.hashUnset()) {
3739 if (mapBlockIndex.count(wtx.hashBlock)) {
3740 int64_t latestNow = wtx.nTimeReceived;
3741 int64_t latestEntry = 0;
3743 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3744 int64_t latestTolerated = latestNow + 300;
3745 const TxItems& txOrdered = wtxOrdered;
3746 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3747 CWalletTx* const pwtx = it->second.first;
3748 if (pwtx == &wtx) {
3749 continue;
3751 CAccountingEntry* const pacentry = it->second.second;
3752 int64_t nSmartTime;
3753 if (pwtx) {
3754 nSmartTime = pwtx->nTimeSmart;
3755 if (!nSmartTime) {
3756 nSmartTime = pwtx->nTimeReceived;
3758 } else {
3759 nSmartTime = pacentry->nTime;
3761 if (nSmartTime <= latestTolerated) {
3762 latestEntry = nSmartTime;
3763 if (nSmartTime > latestNow) {
3764 latestNow = nSmartTime;
3766 break;
3770 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3771 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3772 } else {
3773 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3776 return nTimeSmart;
3779 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3781 if (boost::get<CNoDestination>(&dest))
3782 return false;
3784 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3785 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3788 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3790 if (!mapAddressBook[dest].destdata.erase(key))
3791 return false;
3792 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3795 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3797 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3798 return true;
3801 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3803 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3804 if(i != mapAddressBook.end())
3806 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3807 if(j != i->second.destdata.end())
3809 if(value)
3810 *value = j->second;
3811 return true;
3814 return false;
3817 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3819 LOCK(cs_wallet);
3820 std::vector<std::string> values;
3821 for (const auto& address : mapAddressBook) {
3822 for (const auto& data : address.second.destdata) {
3823 if (!data.first.compare(0, prefix.size(), prefix)) {
3824 values.emplace_back(data.second);
3828 return values;
3831 std::string CWallet::GetWalletHelpString(bool showDebug)
3833 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3834 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3835 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3836 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3837 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3838 strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) used to discard change (to fee) if it would be dust at this fee rate (default: %s) "
3839 "Note: We will always discard up to the dust relay fee and a discard fee above that is limited by the longest target fee estimate"),
3840 CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE)));
3841 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3842 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3843 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3844 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3845 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3846 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3847 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3848 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));
3849 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));
3850 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3851 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3852 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3853 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3854 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3855 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3856 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3858 if (showDebug)
3860 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3862 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3863 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3864 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3865 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3868 return strUsage;
3871 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3873 // needed to restore wallet transaction meta data after -zapwallettxes
3874 std::vector<CWalletTx> vWtx;
3876 if (GetBoolArg("-zapwallettxes", false)) {
3877 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3879 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3880 CWallet *tempWallet = new CWallet(std::move(dbw));
3881 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3882 if (nZapWalletRet != DB_LOAD_OK) {
3883 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3884 return NULL;
3887 delete tempWallet;
3888 tempWallet = NULL;
3891 uiInterface.InitMessage(_("Loading wallet..."));
3893 int64_t nStart = GetTimeMillis();
3894 bool fFirstRun = true;
3895 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3896 CWallet *walletInstance = new CWallet(std::move(dbw));
3897 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3898 if (nLoadWalletRet != DB_LOAD_OK)
3900 if (nLoadWalletRet == DB_CORRUPT) {
3901 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3902 return NULL;
3904 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3906 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3907 " or address book entries might be missing or incorrect."),
3908 walletFile));
3910 else if (nLoadWalletRet == DB_TOO_NEW) {
3911 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3912 return NULL;
3914 else if (nLoadWalletRet == DB_NEED_REWRITE)
3916 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3917 return NULL;
3919 else {
3920 InitError(strprintf(_("Error loading %s"), walletFile));
3921 return NULL;
3925 if (GetBoolArg("-upgradewallet", fFirstRun))
3927 int nMaxVersion = GetArg("-upgradewallet", 0);
3928 if (nMaxVersion == 0) // the -upgradewallet without argument case
3930 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3931 nMaxVersion = CLIENT_VERSION;
3932 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3934 else
3935 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3936 if (nMaxVersion < walletInstance->GetVersion())
3938 InitError(_("Cannot downgrade wallet"));
3939 return NULL;
3941 walletInstance->SetMaxVersion(nMaxVersion);
3944 if (fFirstRun)
3946 // Create new keyUser and set as default key
3947 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3949 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3950 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3952 // generate a new master key
3953 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3954 if (!walletInstance->SetHDMasterKey(masterPubKey))
3955 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3957 CPubKey newDefaultKey;
3958 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3959 walletInstance->SetDefaultKey(newDefaultKey);
3960 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3961 InitError(_("Cannot write default address") += "\n");
3962 return NULL;
3966 walletInstance->SetBestChain(chainActive.GetLocator());
3968 else if (IsArgSet("-usehd")) {
3969 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3970 if (walletInstance->IsHDEnabled() && !useHD) {
3971 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3972 return NULL;
3974 if (!walletInstance->IsHDEnabled() && useHD) {
3975 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3976 return NULL;
3980 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3982 RegisterValidationInterface(walletInstance);
3984 CBlockIndex *pindexRescan = chainActive.Genesis();
3985 if (!GetBoolArg("-rescan", false))
3987 CWalletDB walletdb(*walletInstance->dbw);
3988 CBlockLocator locator;
3989 if (walletdb.ReadBestBlock(locator))
3990 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3992 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3994 //We can't rescan beyond non-pruned blocks, stop and throw an error
3995 //this might happen if a user uses an old wallet within a pruned node
3996 // or if he ran -disablewallet for a longer time, then decided to re-enable
3997 if (fPruneMode)
3999 CBlockIndex *block = chainActive.Tip();
4000 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
4001 block = block->pprev;
4003 if (pindexRescan != block) {
4004 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4005 return NULL;
4009 uiInterface.InitMessage(_("Rescanning..."));
4010 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
4012 // No need to read and scan block if block was created before
4013 // our wallet birthday (as adjusted for block time variability)
4014 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4015 pindexRescan = chainActive.Next(pindexRescan);
4018 nStart = GetTimeMillis();
4019 walletInstance->ScanForWalletTransactions(pindexRescan, true);
4020 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
4021 walletInstance->SetBestChain(chainActive.GetLocator());
4022 walletInstance->dbw->IncrementUpdateCounter();
4024 // Restore wallet transaction metadata after -zapwallettxes=1
4025 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
4027 CWalletDB walletdb(*walletInstance->dbw);
4029 for (const CWalletTx& wtxOld : vWtx)
4031 uint256 hash = wtxOld.GetHash();
4032 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4033 if (mi != walletInstance->mapWallet.end())
4035 const CWalletTx* copyFrom = &wtxOld;
4036 CWalletTx* copyTo = &mi->second;
4037 copyTo->mapValue = copyFrom->mapValue;
4038 copyTo->vOrderForm = copyFrom->vOrderForm;
4039 copyTo->nTimeReceived = copyFrom->nTimeReceived;
4040 copyTo->nTimeSmart = copyFrom->nTimeSmart;
4041 copyTo->fFromMe = copyFrom->fFromMe;
4042 copyTo->strFromAccount = copyFrom->strFromAccount;
4043 copyTo->nOrderPos = copyFrom->nOrderPos;
4044 walletdb.WriteTx(*copyTo);
4049 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
4052 LOCK(walletInstance->cs_wallet);
4053 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4054 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4055 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4058 return walletInstance;
4061 bool CWallet::InitLoadWallet()
4063 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
4064 LogPrintf("Wallet disabled!\n");
4065 return true;
4068 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
4069 CWallet * const pwallet = CreateWalletFromFile(walletFile);
4070 if (!pwallet) {
4071 return false;
4073 vpwallets.push_back(pwallet);
4076 return true;
4079 std::atomic<bool> CWallet::fFlushScheduled(false);
4081 void CWallet::postInitProcess(CScheduler& scheduler)
4083 // Add wallet transactions that aren't already in a block to mempool
4084 // Do this here as mempool requires genesis block to be loaded
4085 ReacceptWalletTransactions();
4087 // Run a thread to flush wallet periodically
4088 if (!CWallet::fFlushScheduled.exchange(true)) {
4089 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4093 bool CWallet::ParameterInteraction()
4095 SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
4096 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
4098 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
4099 return true;
4101 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
4102 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
4105 if (GetBoolArg("-salvagewallet", false)) {
4106 if (is_multiwallet) {
4107 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
4109 // Rewrite just private keys: rescan to find transactions
4110 if (SoftSetBoolArg("-rescan", true)) {
4111 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
4115 int zapwallettxes = GetArg("-zapwallettxes", 0);
4116 // -zapwallettxes implies dropping the mempool on startup
4117 if (zapwallettxes != 0 && SoftSetBoolArg("-persistmempool", false)) {
4118 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes);
4121 // -zapwallettxes implies a rescan
4122 if (zapwallettxes != 0) {
4123 if (is_multiwallet) {
4124 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
4126 if (SoftSetBoolArg("-rescan", true)) {
4127 LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes);
4131 if (is_multiwallet) {
4132 if (GetBoolArg("-upgradewallet", false)) {
4133 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
4137 if (GetBoolArg("-sysperms", false))
4138 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4139 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
4140 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4142 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4143 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4144 _("The wallet will avoid paying less than the minimum relay fee."));
4146 if (IsArgSet("-mintxfee"))
4148 CAmount n = 0;
4149 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
4150 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
4151 if (n > HIGH_TX_FEE_PER_KB)
4152 InitWarning(AmountHighWarn("-mintxfee") + " " +
4153 _("This is the minimum transaction fee you pay on every transaction."));
4154 CWallet::minTxFee = CFeeRate(n);
4156 if (IsArgSet("-fallbackfee"))
4158 CAmount nFeePerK = 0;
4159 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4160 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4161 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4162 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4163 _("This is the transaction fee you may pay when fee estimates are not available."));
4164 CWallet::fallbackFee = CFeeRate(nFeePerK);
4166 if (IsArgSet("-discardfee"))
4168 CAmount nFeePerK = 0;
4169 if (!ParseMoney(GetArg("-discardfee", ""), nFeePerK))
4170 return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), GetArg("-discardfee", "")));
4171 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4172 InitWarning(AmountHighWarn("-discardfee") + " " +
4173 _("This is the transaction fee you may discard if change is smaller than dust at this level"));
4174 CWallet::m_discard_rate = CFeeRate(nFeePerK);
4176 if (IsArgSet("-paytxfee"))
4178 CAmount nFeePerK = 0;
4179 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4180 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4181 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4182 InitWarning(AmountHighWarn("-paytxfee") + " " +
4183 _("This is the transaction fee you will pay if you send a transaction."));
4185 payTxFee = CFeeRate(nFeePerK, 1000);
4186 if (payTxFee < ::minRelayTxFee)
4188 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4189 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4192 if (IsArgSet("-maxtxfee"))
4194 CAmount nMaxFee = 0;
4195 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4196 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4197 if (nMaxFee > HIGH_MAX_TX_FEE)
4198 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4199 maxTxFee = nMaxFee;
4200 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4202 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4203 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4206 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4207 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4208 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4210 return true;
4213 bool CWallet::BackupWallet(const std::string& strDest)
4215 return dbw->Backup(strDest);
4218 CKeyPool::CKeyPool()
4220 nTime = GetTime();
4221 fInternal = false;
4224 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4226 nTime = GetTime();
4227 vchPubKey = vchPubKeyIn;
4228 fInternal = internalIn;
4231 CWalletKey::CWalletKey(int64_t nExpires)
4233 nTimeCreated = (nExpires ? GetTime() : 0);
4234 nTimeExpires = nExpires;
4237 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4239 // Update the tx's hashBlock
4240 hashBlock = pindex->GetBlockHash();
4242 // set the position of the transaction in the block
4243 nIndex = posInBlock;
4246 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4248 if (hashUnset())
4249 return 0;
4251 AssertLockHeld(cs_main);
4253 // Find the block it claims to be in
4254 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4255 if (mi == mapBlockIndex.end())
4256 return 0;
4257 CBlockIndex* pindex = (*mi).second;
4258 if (!pindex || !chainActive.Contains(pindex))
4259 return 0;
4261 pindexRet = pindex;
4262 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4265 int CMerkleTx::GetBlocksToMaturity() const
4267 if (!IsCoinBase())
4268 return 0;
4269 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4273 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4275 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);