Use MakeUnique<Db>(...)
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobdceb818b50e0ada5a1e9e2f654233d9003861877
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "wallet/wallet.h"
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "chain.h"
11 #include "wallet/coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.h"
14 #include "fs.h"
15 #include "init.h"
16 #include "key.h"
17 #include "keystore.h"
18 #include "validation.h"
19 #include "net.h"
20 #include "policy/fees.h"
21 #include "policy/policy.h"
22 #include "policy/rbf.h"
23 #include "primitives/block.h"
24 #include "primitives/transaction.h"
25 #include "script/script.h"
26 #include "script/sign.h"
27 #include "scheduler.h"
28 #include "timedata.h"
29 #include "txmempool.h"
30 #include "util.h"
31 #include "ui_interface.h"
32 #include "utilmoneystr.h"
33 #include "wallet/fees.h"
35 #include <assert.h>
37 #include <boost/algorithm/string/replace.hpp>
38 #include <boost/thread.hpp>
40 std::vector<CWalletRef> vpwallets;
41 /** Transaction fee set by the user */
42 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
43 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
44 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
45 bool fWalletRbf = DEFAULT_WALLET_RBF;
47 const char * DEFAULT_WALLET_DAT = "wallet.dat";
48 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
50 /**
51 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
52 * Override with -mintxfee
54 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
55 /**
56 * If fee estimation does not have enough data to provide estimates, use this fee instead.
57 * Has no effect if not using fee estimation
58 * Override with -fallbackfee
60 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
62 CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
64 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
66 /** @defgroup mapWallet
68 * @{
71 struct CompareValueOnly
73 bool operator()(const CInputCoin& t1,
74 const CInputCoin& t2) const
76 return t1.txout.nValue < t2.txout.nValue;
80 std::string COutput::ToString() const
82 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
85 class CAffectedKeysVisitor : public boost::static_visitor<void> {
86 private:
87 const CKeyStore &keystore;
88 std::vector<CKeyID> &vKeys;
90 public:
91 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
93 void Process(const CScript &script) {
94 txnouttype type;
95 std::vector<CTxDestination> vDest;
96 int nRequired;
97 if (ExtractDestinations(script, type, vDest, nRequired)) {
98 for (const CTxDestination &dest : vDest)
99 boost::apply_visitor(*this, dest);
103 void operator()(const CKeyID &keyId) {
104 if (keystore.HaveKey(keyId))
105 vKeys.push_back(keyId);
108 void operator()(const CScriptID &scriptId) {
109 CScript script;
110 if (keystore.GetCScript(scriptId, script))
111 Process(script);
114 void operator()(const WitnessV0ScriptHash& scriptID)
116 CScriptID id;
117 CRIPEMD160().Write(scriptID.begin(), 32).Finalize(id.begin());
118 CScript script;
119 if (keystore.GetCScript(id, script)) {
120 Process(script);
124 void operator()(const WitnessV0KeyHash& keyid)
126 CKeyID id(keyid);
127 if (keystore.HaveKey(id)) {
128 vKeys.push_back(id);
132 template<typename X>
133 void operator()(const X &none) {}
136 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
138 LOCK(cs_wallet);
139 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
140 if (it == mapWallet.end())
141 return nullptr;
142 return &(it->second);
145 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
147 AssertLockHeld(cs_wallet); // mapKeyMetadata
148 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
150 CKey secret;
152 // Create new metadata
153 int64_t nCreationTime = GetTime();
154 CKeyMetadata metadata(nCreationTime);
156 // use HD key derivation if HD was enabled during wallet creation
157 if (IsHDEnabled()) {
158 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
159 } else {
160 secret.MakeNewKey(fCompressed);
163 // Compressed public keys were introduced in version 0.6.0
164 if (fCompressed) {
165 SetMinVersion(FEATURE_COMPRPUBKEY);
168 CPubKey pubkey = secret.GetPubKey();
169 assert(secret.VerifyPubKey(pubkey));
171 mapKeyMetadata[pubkey.GetID()] = metadata;
172 UpdateTimeFirstKey(nCreationTime);
174 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
175 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
177 return pubkey;
180 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
182 // for now we use a fixed keypath scheme of m/0'/0'/k
183 CKey key; //master key seed (256bit)
184 CExtKey masterKey; //hd master key
185 CExtKey accountKey; //key at m/0'
186 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
187 CExtKey childKey; //key at m/0'/0'/<n>'
189 // try to get the master key
190 if (!GetKey(hdChain.masterKeyID, key))
191 throw std::runtime_error(std::string(__func__) + ": Master key not found");
193 masterKey.SetMaster(key.begin(), key.size());
195 // derive m/0'
196 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
197 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
199 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
200 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
201 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
203 // derive child key at next index, skip keys already known to the wallet
204 do {
205 // always derive hardened keys
206 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
207 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
208 if (internal) {
209 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
210 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
211 hdChain.nInternalChainCounter++;
213 else {
214 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
215 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
216 hdChain.nExternalChainCounter++;
218 } while (HaveKey(childKey.key.GetPubKey().GetID()));
219 secret = childKey.key;
220 metadata.hdMasterKeyID = hdChain.masterKeyID;
221 // update the chain model in the database
222 if (!walletdb.WriteHDChain(hdChain))
223 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
226 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
228 AssertLockHeld(cs_wallet); // mapKeyMetadata
230 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
231 // which is overridden below. To avoid flushes, the database handle is
232 // tunneled through to it.
233 bool needsDB = !pwalletdbEncryption;
234 if (needsDB) {
235 pwalletdbEncryption = &walletdb;
237 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
238 if (needsDB) pwalletdbEncryption = nullptr;
239 return false;
241 if (needsDB) pwalletdbEncryption = nullptr;
243 // check if we need to remove from watch-only
244 CScript script;
245 script = GetScriptForDestination(pubkey.GetID());
246 if (HaveWatchOnly(script)) {
247 RemoveWatchOnly(script);
249 script = GetScriptForRawPubKey(pubkey);
250 if (HaveWatchOnly(script)) {
251 RemoveWatchOnly(script);
254 if (!IsCrypted()) {
255 return walletdb.WriteKey(pubkey,
256 secret.GetPrivKey(),
257 mapKeyMetadata[pubkey.GetID()]);
259 return true;
262 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
264 CWalletDB walletdb(*dbw);
265 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
268 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
269 const std::vector<unsigned char> &vchCryptedSecret)
271 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
272 return false;
274 LOCK(cs_wallet);
275 if (pwalletdbEncryption)
276 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
277 vchCryptedSecret,
278 mapKeyMetadata[vchPubKey.GetID()]);
279 else
280 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
281 vchCryptedSecret,
282 mapKeyMetadata[vchPubKey.GetID()]);
286 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
288 AssertLockHeld(cs_wallet); // mapKeyMetadata
289 UpdateTimeFirstKey(meta.nCreateTime);
290 mapKeyMetadata[keyID] = meta;
291 return true;
294 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
296 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
300 * Update wallet first key creation time. This should be called whenever keys
301 * are added to the wallet, with the oldest key creation time.
303 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
305 AssertLockHeld(cs_wallet);
306 if (nCreateTime <= 1) {
307 // Cannot determine birthday information, so set the wallet birthday to
308 // the beginning of time.
309 nTimeFirstKey = 1;
310 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
311 nTimeFirstKey = nCreateTime;
315 bool CWallet::AddCScript(const CScript& redeemScript)
317 if (!CCryptoKeyStore::AddCScript(redeemScript))
318 return false;
319 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
322 bool CWallet::LoadCScript(const CScript& redeemScript)
324 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
325 * that never can be redeemed. However, old wallets may still contain
326 * these. Do not add them to the wallet and warn. */
327 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
329 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
330 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",
331 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
332 return true;
335 return CCryptoKeyStore::AddCScript(redeemScript);
338 bool CWallet::AddWatchOnly(const CScript& dest)
340 if (!CCryptoKeyStore::AddWatchOnly(dest))
341 return false;
342 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
343 UpdateTimeFirstKey(meta.nCreateTime);
344 NotifyWatchonlyChanged(true);
345 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
348 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
350 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
351 return AddWatchOnly(dest);
354 bool CWallet::RemoveWatchOnly(const CScript &dest)
356 AssertLockHeld(cs_wallet);
357 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
358 return false;
359 if (!HaveWatchOnly())
360 NotifyWatchonlyChanged(false);
361 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
362 return false;
364 return true;
367 bool CWallet::LoadWatchOnly(const CScript &dest)
369 return CCryptoKeyStore::AddWatchOnly(dest);
372 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
374 CCrypter crypter;
375 CKeyingMaterial _vMasterKey;
378 LOCK(cs_wallet);
379 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
381 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
382 return false;
383 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
384 continue; // try another master key
385 if (CCryptoKeyStore::Unlock(_vMasterKey))
386 return true;
389 return false;
392 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
394 bool fWasLocked = IsLocked();
397 LOCK(cs_wallet);
398 Lock();
400 CCrypter crypter;
401 CKeyingMaterial _vMasterKey;
402 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
404 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
405 return false;
406 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
407 return false;
408 if (CCryptoKeyStore::Unlock(_vMasterKey))
410 int64_t nStartTime = GetTimeMillis();
411 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
412 pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
414 nStartTime = GetTimeMillis();
415 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
416 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
418 if (pMasterKey.second.nDeriveIterations < 25000)
419 pMasterKey.second.nDeriveIterations = 25000;
421 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
423 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
424 return false;
425 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
426 return false;
427 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
428 if (fWasLocked)
429 Lock();
430 return true;
435 return false;
438 void CWallet::SetBestChain(const CBlockLocator& loc)
440 CWalletDB walletdb(*dbw);
441 walletdb.WriteBestBlock(loc);
444 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
446 LOCK(cs_wallet); // nWalletVersion
447 if (nWalletVersion >= nVersion)
448 return true;
450 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
451 if (fExplicit && nVersion > nWalletMaxVersion)
452 nVersion = FEATURE_LATEST;
454 nWalletVersion = nVersion;
456 if (nVersion > nWalletMaxVersion)
457 nWalletMaxVersion = nVersion;
460 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
461 if (nWalletVersion > 40000)
462 pwalletdb->WriteMinVersion(nWalletVersion);
463 if (!pwalletdbIn)
464 delete pwalletdb;
467 return true;
470 bool CWallet::SetMaxVersion(int nVersion)
472 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
473 // cannot downgrade below current version
474 if (nWalletVersion > nVersion)
475 return false;
477 nWalletMaxVersion = nVersion;
479 return true;
482 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
484 std::set<uint256> result;
485 AssertLockHeld(cs_wallet);
487 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
488 if (it == mapWallet.end())
489 return result;
490 const CWalletTx& wtx = it->second;
492 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
494 for (const CTxIn& txin : wtx.tx->vin)
496 if (mapTxSpends.count(txin.prevout) <= 1)
497 continue; // No conflict if zero or one spends
498 range = mapTxSpends.equal_range(txin.prevout);
499 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
500 result.insert(_it->second);
502 return result;
505 bool CWallet::HasWalletSpend(const uint256& txid) const
507 AssertLockHeld(cs_wallet);
508 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
509 return (iter != mapTxSpends.end() && iter->first.hash == txid);
512 void CWallet::Flush(bool shutdown)
514 dbw->Flush(shutdown);
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 = nullptr;
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];
536 assert(copyFrom);
538 // Now copy data from copyFrom to rest:
539 for (TxSpends::iterator it = range.first; it != range.second; ++it)
541 const uint256& hash = it->second;
542 CWalletTx* copyTo = &mapWallet[hash];
543 if (copyFrom == copyTo) continue;
544 assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
545 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
546 copyTo->mapValue = copyFrom->mapValue;
547 copyTo->vOrderForm = copyFrom->vOrderForm;
548 // fTimeReceivedIsTxTime not copied on purpose
549 // nTimeReceived not copied on purpose
550 copyTo->nTimeSmart = copyFrom->nTimeSmart;
551 copyTo->fFromMe = copyFrom->fFromMe;
552 copyTo->strFromAccount = copyFrom->strFromAccount;
553 // nOrderPos not copied on purpose
554 // cached members not copied on purpose
559 * Outpoint is spent if any non-conflicted transaction
560 * spends it:
562 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
564 const COutPoint outpoint(hash, n);
565 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
566 range = mapTxSpends.equal_range(outpoint);
568 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
570 const uint256& wtxid = it->second;
571 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
572 if (mit != mapWallet.end()) {
573 int depth = mit->second.GetDepthInMainChain();
574 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
575 return true; // Spent
578 return false;
581 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
583 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
585 std::pair<TxSpends::iterator, TxSpends::iterator> range;
586 range = mapTxSpends.equal_range(outpoint);
587 SyncMetaData(range);
591 void CWallet::AddToSpends(const uint256& wtxid)
593 auto it = mapWallet.find(wtxid);
594 assert(it != mapWallet.end());
595 CWalletTx& thisTx = it->second;
596 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
597 return;
599 for (const CTxIn& txin : thisTx.tx->vin)
600 AddToSpends(txin.prevout, wtxid);
603 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
605 if (IsCrypted())
606 return false;
608 CKeyingMaterial _vMasterKey;
610 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
611 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
613 CMasterKey kMasterKey;
615 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
616 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
618 CCrypter crypter;
619 int64_t nStartTime = GetTimeMillis();
620 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
621 kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
623 nStartTime = GetTimeMillis();
624 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
625 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
627 if (kMasterKey.nDeriveIterations < 25000)
628 kMasterKey.nDeriveIterations = 25000;
630 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
632 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
633 return false;
634 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
635 return false;
638 LOCK(cs_wallet);
639 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
640 assert(!pwalletdbEncryption);
641 pwalletdbEncryption = new CWalletDB(*dbw);
642 if (!pwalletdbEncryption->TxnBegin()) {
643 delete pwalletdbEncryption;
644 pwalletdbEncryption = nullptr;
645 return false;
647 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
649 if (!EncryptKeys(_vMasterKey))
651 pwalletdbEncryption->TxnAbort();
652 delete pwalletdbEncryption;
653 // We now probably have half of our keys encrypted in memory, and half not...
654 // die and let the user reload the unencrypted wallet.
655 assert(false);
658 // Encryption was introduced in version 0.4.0
659 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
661 if (!pwalletdbEncryption->TxnCommit()) {
662 delete pwalletdbEncryption;
663 // We now have keys encrypted in memory, but not on disk...
664 // die to avoid confusion and let the user reload the unencrypted wallet.
665 assert(false);
668 delete pwalletdbEncryption;
669 pwalletdbEncryption = nullptr;
671 Lock();
672 Unlock(strWalletPassphrase);
674 // if we are using HD, replace the HD master key (seed) with a new one
675 if (IsHDEnabled()) {
676 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
677 return false;
681 NewKeyPool();
682 Lock();
684 // Need to completely rewrite the wallet file; if we don't, bdb might keep
685 // bits of the unencrypted private key in slack space in the database file.
686 dbw->Rewrite();
689 NotifyStatusChanged(this);
691 return true;
694 DBErrors CWallet::ReorderTransactions()
696 LOCK(cs_wallet);
697 CWalletDB walletdb(*dbw);
699 // Old wallets didn't have any defined order for transactions
700 // Probably a bad idea to change the output of this
702 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
703 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
704 typedef std::multimap<int64_t, TxPair > TxItems;
705 TxItems txByTime;
707 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
709 CWalletTx* wtx = &((*it).second);
710 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
712 std::list<CAccountingEntry> acentries;
713 walletdb.ListAccountCreditDebit("", acentries);
714 for (CAccountingEntry& entry : acentries)
716 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
719 nOrderPosNext = 0;
720 std::vector<int64_t> nOrderPosOffsets;
721 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
723 CWalletTx *const pwtx = (*it).second.first;
724 CAccountingEntry *const pacentry = (*it).second.second;
725 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
727 if (nOrderPos == -1)
729 nOrderPos = nOrderPosNext++;
730 nOrderPosOffsets.push_back(nOrderPos);
732 if (pwtx)
734 if (!walletdb.WriteTx(*pwtx))
735 return DB_LOAD_FAIL;
737 else
738 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
739 return DB_LOAD_FAIL;
741 else
743 int64_t nOrderPosOff = 0;
744 for (const int64_t& nOffsetStart : nOrderPosOffsets)
746 if (nOrderPos >= nOffsetStart)
747 ++nOrderPosOff;
749 nOrderPos += nOrderPosOff;
750 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
752 if (!nOrderPosOff)
753 continue;
755 // Since we're changing the order, write it back
756 if (pwtx)
758 if (!walletdb.WriteTx(*pwtx))
759 return DB_LOAD_FAIL;
761 else
762 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
763 return DB_LOAD_FAIL;
766 walletdb.WriteOrderPosNext(nOrderPosNext);
768 return DB_LOAD_OK;
771 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
773 AssertLockHeld(cs_wallet); // nOrderPosNext
774 int64_t nRet = nOrderPosNext++;
775 if (pwalletdb) {
776 pwalletdb->WriteOrderPosNext(nOrderPosNext);
777 } else {
778 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
780 return nRet;
783 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
785 CWalletDB walletdb(*dbw);
786 if (!walletdb.TxnBegin())
787 return false;
789 int64_t nNow = GetAdjustedTime();
791 // Debit
792 CAccountingEntry debit;
793 debit.nOrderPos = IncOrderPosNext(&walletdb);
794 debit.strAccount = strFrom;
795 debit.nCreditDebit = -nAmount;
796 debit.nTime = nNow;
797 debit.strOtherAccount = strTo;
798 debit.strComment = strComment;
799 AddAccountingEntry(debit, &walletdb);
801 // Credit
802 CAccountingEntry credit;
803 credit.nOrderPos = IncOrderPosNext(&walletdb);
804 credit.strAccount = strTo;
805 credit.nCreditDebit = nAmount;
806 credit.nTime = nNow;
807 credit.strOtherAccount = strFrom;
808 credit.strComment = strComment;
809 AddAccountingEntry(credit, &walletdb);
811 if (!walletdb.TxnCommit())
812 return false;
814 return true;
817 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
819 CWalletDB walletdb(*dbw);
821 CAccount account;
822 walletdb.ReadAccount(strAccount, account);
824 if (!bForceNew) {
825 if (!account.vchPubKey.IsValid())
826 bForceNew = true;
827 else {
828 // Check if the current key has been used
829 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
830 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
831 it != mapWallet.end() && account.vchPubKey.IsValid();
832 ++it)
833 for (const CTxOut& txout : (*it).second.tx->vout)
834 if (txout.scriptPubKey == scriptPubKey) {
835 bForceNew = true;
836 break;
841 // Generate a new key
842 if (bForceNew) {
843 if (!GetKeyFromPool(account.vchPubKey, false))
844 return false;
846 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
847 walletdb.WriteAccount(strAccount, account);
850 pubKey = account.vchPubKey;
852 return true;
855 void CWallet::MarkDirty()
858 LOCK(cs_wallet);
859 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
860 item.second.MarkDirty();
864 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
866 LOCK(cs_wallet);
868 auto mi = mapWallet.find(originalHash);
870 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
871 assert(mi != mapWallet.end());
873 CWalletTx& wtx = (*mi).second;
875 // Ensure for now that we're not overwriting data
876 assert(wtx.mapValue.count("replaced_by_txid") == 0);
878 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
880 CWalletDB walletdb(*dbw, "r+");
882 bool success = true;
883 if (!walletdb.WriteTx(wtx)) {
884 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
885 success = false;
888 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
890 return success;
893 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
895 LOCK(cs_wallet);
897 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
899 uint256 hash = wtxIn.GetHash();
901 // Inserts only if not already there, returns tx inserted or tx found
902 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
903 CWalletTx& wtx = (*ret.first).second;
904 wtx.BindWallet(this);
905 bool fInsertedNew = ret.second;
906 if (fInsertedNew)
908 wtx.nTimeReceived = GetAdjustedTime();
909 wtx.nOrderPos = IncOrderPosNext(&walletdb);
910 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
911 wtx.nTimeSmart = ComputeTimeSmart(wtx);
912 AddToSpends(hash);
915 bool fUpdated = false;
916 if (!fInsertedNew)
918 // Merge
919 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
921 wtx.hashBlock = wtxIn.hashBlock;
922 fUpdated = true;
924 // If no longer abandoned, update
925 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
927 wtx.hashBlock = wtxIn.hashBlock;
928 fUpdated = true;
930 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
932 wtx.nIndex = wtxIn.nIndex;
933 fUpdated = true;
935 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
937 wtx.fFromMe = wtxIn.fFromMe;
938 fUpdated = true;
940 // If we have a witness-stripped version of this transaction, and we
941 // see a new version with a witness, then we must be upgrading a pre-segwit
942 // wallet. Store the new version of the transaction with the witness,
943 // as the stripped-version must be invalid.
944 // TODO: Store all versions of the transaction, instead of just one.
945 if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
946 wtx.SetTx(wtxIn.tx);
947 fUpdated = true;
951 //// debug print
952 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
954 // Write to disk
955 if (fInsertedNew || fUpdated)
956 if (!walletdb.WriteTx(wtx))
957 return false;
959 // Break debit/credit balance caches:
960 wtx.MarkDirty();
962 // Notify UI of new or updated transaction
963 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
965 // notify an external script when a wallet transaction comes in or is updated
966 std::string strCmd = gArgs.GetArg("-walletnotify", "");
968 if (!strCmd.empty())
970 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
971 boost::thread t(runCommand, strCmd); // thread runs free
974 return true;
977 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
979 uint256 hash = wtxIn.GetHash();
981 mapWallet[hash] = wtxIn;
982 CWalletTx& wtx = mapWallet[hash];
983 wtx.BindWallet(this);
984 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
985 AddToSpends(hash);
986 for (const CTxIn& txin : wtx.tx->vin) {
987 auto it = mapWallet.find(txin.prevout.hash);
988 if (it != mapWallet.end()) {
989 CWalletTx& prevtx = it->second;
990 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
991 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
996 return true;
1000 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1001 * be set when the transaction was known to be included in a block. When
1002 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1003 * notifications happen and cached balances are marked dirty.
1005 * If fUpdate is true, existing transactions will be updated.
1006 * TODO: One exception to this is that the abandoned state is cleared under the
1007 * assumption that any further notification of a transaction that was considered
1008 * abandoned is an indication that it is not safe to be considered abandoned.
1009 * Abandoned state should probably be more carefully tracked via different
1010 * posInBlock signals or by checking mempool presence when necessary.
1012 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1014 const CTransaction& tx = *ptx;
1016 AssertLockHeld(cs_wallet);
1018 if (pIndex != nullptr) {
1019 for (const CTxIn& txin : tx.vin) {
1020 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1021 while (range.first != range.second) {
1022 if (range.first->second != tx.GetHash()) {
1023 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);
1024 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1026 range.first++;
1031 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1032 if (fExisted && !fUpdate) return false;
1033 if (fExisted || IsMine(tx) || IsFromMe(tx))
1035 /* Check if any keys in the wallet keypool that were supposed to be unused
1036 * have appeared in a new transaction. If so, remove those keys from the keypool.
1037 * This can happen when restoring an old wallet backup that does not contain
1038 * the mostly recently created transactions from newer versions of the wallet.
1041 // loop though all outputs
1042 for (const CTxOut& txout: tx.vout) {
1043 // extract addresses and check if they match with an unused keypool key
1044 std::vector<CKeyID> vAffected;
1045 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1046 for (const CKeyID &keyid : vAffected) {
1047 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1048 if (mi != m_pool_key_to_index.end()) {
1049 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1050 MarkReserveKeysAsUsed(mi->second);
1052 if (!TopUpKeyPool()) {
1053 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1059 CWalletTx wtx(this, ptx);
1061 // Get merkle branch if transaction was found in a block
1062 if (pIndex != nullptr)
1063 wtx.SetMerkleBranch(pIndex, posInBlock);
1065 return AddToWallet(wtx, false);
1068 return false;
1071 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1073 LOCK2(cs_main, cs_wallet);
1074 const CWalletTx* wtx = GetWalletTx(hashTx);
1075 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1078 bool CWallet::AbandonTransaction(const uint256& hashTx)
1080 LOCK2(cs_main, cs_wallet);
1082 CWalletDB walletdb(*dbw, "r+");
1084 std::set<uint256> todo;
1085 std::set<uint256> done;
1087 // Can't mark abandoned if confirmed or in mempool
1088 auto it = mapWallet.find(hashTx);
1089 assert(it != mapWallet.end());
1090 CWalletTx& origtx = it->second;
1091 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1092 return false;
1095 todo.insert(hashTx);
1097 while (!todo.empty()) {
1098 uint256 now = *todo.begin();
1099 todo.erase(now);
1100 done.insert(now);
1101 auto it = mapWallet.find(now);
1102 assert(it != mapWallet.end());
1103 CWalletTx& wtx = it->second;
1104 int currentconfirm = wtx.GetDepthInMainChain();
1105 // If the orig tx was not in block, none of its spends can be
1106 assert(currentconfirm <= 0);
1107 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1108 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1109 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1110 assert(!wtx.InMempool());
1111 wtx.nIndex = -1;
1112 wtx.setAbandoned();
1113 wtx.MarkDirty();
1114 walletdb.WriteTx(wtx);
1115 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1116 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1117 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1118 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1119 if (!done.count(iter->second)) {
1120 todo.insert(iter->second);
1122 iter++;
1124 // If a transaction changes 'conflicted' state, that changes the balance
1125 // available of the outputs it spends. So force those to be recomputed
1126 for (const CTxIn& txin : wtx.tx->vin)
1128 auto it = mapWallet.find(txin.prevout.hash);
1129 if (it != mapWallet.end()) {
1130 it->second.MarkDirty();
1136 return true;
1139 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1141 LOCK2(cs_main, cs_wallet);
1143 int conflictconfirms = 0;
1144 if (mapBlockIndex.count(hashBlock)) {
1145 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1146 if (chainActive.Contains(pindex)) {
1147 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1150 // If number of conflict confirms cannot be determined, this means
1151 // that the block is still unknown or not yet part of the main chain,
1152 // for example when loading the wallet during a reindex. Do nothing in that
1153 // case.
1154 if (conflictconfirms >= 0)
1155 return;
1157 // Do not flush the wallet here for performance reasons
1158 CWalletDB walletdb(*dbw, "r+", false);
1160 std::set<uint256> todo;
1161 std::set<uint256> done;
1163 todo.insert(hashTx);
1165 while (!todo.empty()) {
1166 uint256 now = *todo.begin();
1167 todo.erase(now);
1168 done.insert(now);
1169 auto it = mapWallet.find(now);
1170 assert(it != mapWallet.end());
1171 CWalletTx& wtx = it->second;
1172 int currentconfirm = wtx.GetDepthInMainChain();
1173 if (conflictconfirms < currentconfirm) {
1174 // Block is 'more conflicted' than current confirm; update.
1175 // Mark transaction as conflicted with this block.
1176 wtx.nIndex = -1;
1177 wtx.hashBlock = hashBlock;
1178 wtx.MarkDirty();
1179 walletdb.WriteTx(wtx);
1180 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1181 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1182 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1183 if (!done.count(iter->second)) {
1184 todo.insert(iter->second);
1186 iter++;
1188 // If a transaction changes 'conflicted' state, that changes the balance
1189 // available of the outputs it spends. So force those to be recomputed
1190 for (const CTxIn& txin : wtx.tx->vin) {
1191 auto it = mapWallet.find(txin.prevout.hash);
1192 if (it != mapWallet.end()) {
1193 it->second.MarkDirty();
1200 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1201 const CTransaction& tx = *ptx;
1203 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1204 return; // Not one of ours
1206 // If a transaction changes 'conflicted' state, that changes the balance
1207 // available of the outputs it spends. So force those to be
1208 // recomputed, also:
1209 for (const CTxIn& txin : tx.vin) {
1210 auto it = mapWallet.find(txin.prevout.hash);
1211 if (it != mapWallet.end()) {
1212 it->second.MarkDirty();
1217 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1218 LOCK2(cs_main, cs_wallet);
1219 SyncTransaction(ptx);
1222 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1223 LOCK2(cs_main, cs_wallet);
1224 // TODO: Temporarily ensure that mempool removals are notified before
1225 // connected transactions. This shouldn't matter, but the abandoned
1226 // state of transactions in our wallet is currently cleared when we
1227 // receive another notification and there is a race condition where
1228 // notification of a connected conflict might cause an outside process
1229 // to abandon a transaction and then have it inadvertently cleared by
1230 // the notification that the conflicted transaction was evicted.
1232 for (const CTransactionRef& ptx : vtxConflicted) {
1233 SyncTransaction(ptx);
1235 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1236 SyncTransaction(pblock->vtx[i], pindex, i);
1240 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1241 LOCK2(cs_main, cs_wallet);
1243 for (const CTransactionRef& ptx : pblock->vtx) {
1244 SyncTransaction(ptx);
1250 isminetype CWallet::IsMine(const CTxIn &txin) const
1253 LOCK(cs_wallet);
1254 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1255 if (mi != mapWallet.end())
1257 const CWalletTx& prev = (*mi).second;
1258 if (txin.prevout.n < prev.tx->vout.size())
1259 return IsMine(prev.tx->vout[txin.prevout.n]);
1262 return ISMINE_NO;
1265 // Note that this function doesn't distinguish between a 0-valued input,
1266 // and a not-"is mine" (according to the filter) input.
1267 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1270 LOCK(cs_wallet);
1271 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1272 if (mi != mapWallet.end())
1274 const CWalletTx& prev = (*mi).second;
1275 if (txin.prevout.n < prev.tx->vout.size())
1276 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1277 return prev.tx->vout[txin.prevout.n].nValue;
1280 return 0;
1283 isminetype CWallet::IsMine(const CTxOut& txout) const
1285 return ::IsMine(*this, txout.scriptPubKey);
1288 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1290 if (!MoneyRange(txout.nValue))
1291 throw std::runtime_error(std::string(__func__) + ": value out of range");
1292 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1295 bool CWallet::IsChange(const CTxOut& txout) const
1297 // TODO: fix handling of 'change' outputs. The assumption is that any
1298 // payment to a script that is ours, but is not in the address book
1299 // is change. That assumption is likely to break when we implement multisignature
1300 // wallets that return change back into a multi-signature-protected address;
1301 // a better way of identifying which outputs are 'the send' and which are
1302 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1303 // which output, if any, was change).
1304 if (::IsMine(*this, txout.scriptPubKey))
1306 CTxDestination address;
1307 if (!ExtractDestination(txout.scriptPubKey, address))
1308 return true;
1310 LOCK(cs_wallet);
1311 if (!mapAddressBook.count(address))
1312 return true;
1314 return false;
1317 CAmount CWallet::GetChange(const CTxOut& txout) const
1319 if (!MoneyRange(txout.nValue))
1320 throw std::runtime_error(std::string(__func__) + ": value out of range");
1321 return (IsChange(txout) ? txout.nValue : 0);
1324 bool CWallet::IsMine(const CTransaction& tx) const
1326 for (const CTxOut& txout : tx.vout)
1327 if (IsMine(txout))
1328 return true;
1329 return false;
1332 bool CWallet::IsFromMe(const CTransaction& tx) const
1334 return (GetDebit(tx, ISMINE_ALL) > 0);
1337 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1339 CAmount nDebit = 0;
1340 for (const CTxIn& txin : tx.vin)
1342 nDebit += GetDebit(txin, filter);
1343 if (!MoneyRange(nDebit))
1344 throw std::runtime_error(std::string(__func__) + ": value out of range");
1346 return nDebit;
1349 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1351 LOCK(cs_wallet);
1353 for (const CTxIn& txin : tx.vin)
1355 auto mi = mapWallet.find(txin.prevout.hash);
1356 if (mi == mapWallet.end())
1357 return false; // any unknown inputs can't be from us
1359 const CWalletTx& prev = (*mi).second;
1361 if (txin.prevout.n >= prev.tx->vout.size())
1362 return false; // invalid input!
1364 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1365 return false;
1367 return true;
1370 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1372 CAmount nCredit = 0;
1373 for (const CTxOut& txout : tx.vout)
1375 nCredit += GetCredit(txout, filter);
1376 if (!MoneyRange(nCredit))
1377 throw std::runtime_error(std::string(__func__) + ": value out of range");
1379 return nCredit;
1382 CAmount CWallet::GetChange(const CTransaction& tx) const
1384 CAmount nChange = 0;
1385 for (const CTxOut& txout : tx.vout)
1387 nChange += GetChange(txout);
1388 if (!MoneyRange(nChange))
1389 throw std::runtime_error(std::string(__func__) + ": value out of range");
1391 return nChange;
1394 CPubKey CWallet::GenerateNewHDMasterKey()
1396 CKey key;
1397 key.MakeNewKey(true);
1399 int64_t nCreationTime = GetTime();
1400 CKeyMetadata metadata(nCreationTime);
1402 // calculate the pubkey
1403 CPubKey pubkey = key.GetPubKey();
1404 assert(key.VerifyPubKey(pubkey));
1406 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1407 metadata.hdKeypath = "m";
1408 metadata.hdMasterKeyID = pubkey.GetID();
1411 LOCK(cs_wallet);
1413 // mem store the metadata
1414 mapKeyMetadata[pubkey.GetID()] = metadata;
1416 // write the key&metadata to the database
1417 if (!AddKeyPubKey(key, pubkey))
1418 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1421 return pubkey;
1424 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1426 LOCK(cs_wallet);
1427 // store the keyid (hash160) together with
1428 // the child index counter in the database
1429 // as a hdchain object
1430 CHDChain newHdChain;
1431 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1432 newHdChain.masterKeyID = pubkey.GetID();
1433 SetHDChain(newHdChain, false);
1435 return true;
1438 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1440 LOCK(cs_wallet);
1441 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1442 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1444 hdChain = chain;
1445 return true;
1448 bool CWallet::IsHDEnabled() const
1450 return !hdChain.masterKeyID.IsNull();
1453 int64_t CWalletTx::GetTxTime() const
1455 int64_t n = nTimeSmart;
1456 return n ? n : nTimeReceived;
1459 int CWalletTx::GetRequestCount() const
1461 // Returns -1 if it wasn't being tracked
1462 int nRequests = -1;
1464 LOCK(pwallet->cs_wallet);
1465 if (IsCoinBase())
1467 // Generated block
1468 if (!hashUnset())
1470 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1471 if (mi != pwallet->mapRequestCount.end())
1472 nRequests = (*mi).second;
1475 else
1477 // Did anyone request this transaction?
1478 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1479 if (mi != pwallet->mapRequestCount.end())
1481 nRequests = (*mi).second;
1483 // How about the block it's in?
1484 if (nRequests == 0 && !hashUnset())
1486 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1487 if (_mi != pwallet->mapRequestCount.end())
1488 nRequests = (*_mi).second;
1489 else
1490 nRequests = 1; // If it's in someone else's block it must have got out
1495 return nRequests;
1498 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1499 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1501 nFee = 0;
1502 listReceived.clear();
1503 listSent.clear();
1504 strSentAccount = strFromAccount;
1506 // Compute fee:
1507 CAmount nDebit = GetDebit(filter);
1508 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1510 CAmount nValueOut = tx->GetValueOut();
1511 nFee = nDebit - nValueOut;
1514 // Sent/received.
1515 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1517 const CTxOut& txout = tx->vout[i];
1518 isminetype fIsMine = pwallet->IsMine(txout);
1519 // Only need to handle txouts if AT LEAST one of these is true:
1520 // 1) they debit from us (sent)
1521 // 2) the output is to us (received)
1522 if (nDebit > 0)
1524 // Don't report 'change' txouts
1525 if (pwallet->IsChange(txout))
1526 continue;
1528 else if (!(fIsMine & filter))
1529 continue;
1531 // In either case, we need to get the destination address
1532 CTxDestination address;
1534 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1536 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1537 this->GetHash().ToString());
1538 address = CNoDestination();
1541 COutputEntry output = {address, txout.nValue, (int)i};
1543 // If we are debited by the transaction, add the output as a "sent" entry
1544 if (nDebit > 0)
1545 listSent.push_back(output);
1547 // If we are receiving the output, add it as a "received" entry
1548 if (fIsMine & filter)
1549 listReceived.push_back(output);
1555 * Scan active chain for relevant transactions after importing keys. This should
1556 * be called whenever new keys are added to the wallet, with the oldest key
1557 * creation time.
1559 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1560 * returned will be higher than startTime if relevant blocks could not be read.
1562 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1564 AssertLockHeld(cs_main);
1565 AssertLockHeld(cs_wallet);
1567 // Find starting block. May be null if nCreateTime is greater than the
1568 // highest blockchain timestamp, in which case there is nothing that needs
1569 // to be scanned.
1570 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1571 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1573 if (startBlock) {
1574 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1575 if (failedBlock) {
1576 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1579 return startTime;
1583 * Scan the block chain (starting in pindexStart) for transactions
1584 * from or to us. If fUpdate is true, found transactions that already
1585 * exist in the wallet will be updated.
1587 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1588 * possible (due to pruning or corruption), returns pointer to the most recent
1589 * block that could not be scanned.
1591 * If pindexStop is not a nullptr, the scan will stop at the block-index
1592 * defined by pindexStop
1594 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1596 int64_t nNow = GetTime();
1597 const CChainParams& chainParams = Params();
1599 if (pindexStop) {
1600 assert(pindexStop->nHeight >= pindexStart->nHeight);
1603 CBlockIndex* pindex = pindexStart;
1604 CBlockIndex* ret = nullptr;
1606 LOCK2(cs_main, cs_wallet);
1607 fAbortRescan = false;
1608 fScanningWallet = true;
1610 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1611 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1612 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1613 while (pindex && !fAbortRescan)
1615 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1616 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1617 if (GetTime() >= nNow + 60) {
1618 nNow = GetTime();
1619 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1622 CBlock block;
1623 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1624 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1625 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1627 } else {
1628 ret = pindex;
1630 if (pindex == pindexStop) {
1631 break;
1633 pindex = chainActive.Next(pindex);
1635 if (pindex && fAbortRescan) {
1636 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1638 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1640 fScanningWallet = false;
1642 return ret;
1645 void CWallet::ReacceptWalletTransactions()
1647 // If transactions aren't being broadcasted, don't let them into local mempool either
1648 if (!fBroadcastTransactions)
1649 return;
1650 LOCK2(cs_main, cs_wallet);
1651 std::map<int64_t, CWalletTx*> mapSorted;
1653 // Sort pending wallet transactions based on their initial wallet insertion order
1654 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1656 const uint256& wtxid = item.first;
1657 CWalletTx& wtx = item.second;
1658 assert(wtx.GetHash() == wtxid);
1660 int nDepth = wtx.GetDepthInMainChain();
1662 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1663 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1667 // Try to add wallet transactions to memory pool
1668 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1670 CWalletTx& wtx = *(item.second);
1672 LOCK(mempool.cs);
1673 CValidationState state;
1674 wtx.AcceptToMemoryPool(maxTxFee, state);
1678 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1680 assert(pwallet->GetBroadcastTransactions());
1681 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1683 CValidationState state;
1684 /* GetDepthInMainChain already catches known conflicts. */
1685 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1686 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1687 if (connman) {
1688 CInv inv(MSG_TX, GetHash());
1689 connman->ForEachNode([&inv](CNode* pnode)
1691 pnode->PushInventory(inv);
1693 return true;
1697 return false;
1700 std::set<uint256> CWalletTx::GetConflicts() const
1702 std::set<uint256> result;
1703 if (pwallet != nullptr)
1705 uint256 myHash = GetHash();
1706 result = pwallet->GetConflicts(myHash);
1707 result.erase(myHash);
1709 return result;
1712 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1714 if (tx->vin.empty())
1715 return 0;
1717 CAmount debit = 0;
1718 if(filter & ISMINE_SPENDABLE)
1720 if (fDebitCached)
1721 debit += nDebitCached;
1722 else
1724 nDebitCached = pwallet->GetDebit(*tx, ISMINE_SPENDABLE);
1725 fDebitCached = true;
1726 debit += nDebitCached;
1729 if(filter & ISMINE_WATCH_ONLY)
1731 if(fWatchDebitCached)
1732 debit += nWatchDebitCached;
1733 else
1735 nWatchDebitCached = pwallet->GetDebit(*tx, ISMINE_WATCH_ONLY);
1736 fWatchDebitCached = true;
1737 debit += nWatchDebitCached;
1740 return debit;
1743 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1745 // Must wait until coinbase is safely deep enough in the chain before valuing it
1746 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1747 return 0;
1749 CAmount credit = 0;
1750 if (filter & ISMINE_SPENDABLE)
1752 // GetBalance can assume transactions in mapWallet won't change
1753 if (fCreditCached)
1754 credit += nCreditCached;
1755 else
1757 nCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1758 fCreditCached = true;
1759 credit += nCreditCached;
1762 if (filter & ISMINE_WATCH_ONLY)
1764 if (fWatchCreditCached)
1765 credit += nWatchCreditCached;
1766 else
1768 nWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1769 fWatchCreditCached = true;
1770 credit += nWatchCreditCached;
1773 return credit;
1776 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1778 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1780 if (fUseCache && fImmatureCreditCached)
1781 return nImmatureCreditCached;
1782 nImmatureCreditCached = pwallet->GetCredit(*tx, ISMINE_SPENDABLE);
1783 fImmatureCreditCached = true;
1784 return nImmatureCreditCached;
1787 return 0;
1790 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1792 if (pwallet == nullptr)
1793 return 0;
1795 // Must wait until coinbase is safely deep enough in the chain before valuing it
1796 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1797 return 0;
1799 if (fUseCache && fAvailableCreditCached)
1800 return nAvailableCreditCached;
1802 CAmount nCredit = 0;
1803 uint256 hashTx = GetHash();
1804 for (unsigned int i = 0; i < tx->vout.size(); i++)
1806 if (!pwallet->IsSpent(hashTx, i))
1808 const CTxOut &txout = tx->vout[i];
1809 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1810 if (!MoneyRange(nCredit))
1811 throw std::runtime_error(std::string(__func__) + " : value out of range");
1815 nAvailableCreditCached = nCredit;
1816 fAvailableCreditCached = true;
1817 return nCredit;
1820 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1822 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1824 if (fUseCache && fImmatureWatchCreditCached)
1825 return nImmatureWatchCreditCached;
1826 nImmatureWatchCreditCached = pwallet->GetCredit(*tx, ISMINE_WATCH_ONLY);
1827 fImmatureWatchCreditCached = true;
1828 return nImmatureWatchCreditCached;
1831 return 0;
1834 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1836 if (pwallet == nullptr)
1837 return 0;
1839 // Must wait until coinbase is safely deep enough in the chain before valuing it
1840 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1841 return 0;
1843 if (fUseCache && fAvailableWatchCreditCached)
1844 return nAvailableWatchCreditCached;
1846 CAmount nCredit = 0;
1847 for (unsigned int i = 0; i < tx->vout.size(); i++)
1849 if (!pwallet->IsSpent(GetHash(), i))
1851 const CTxOut &txout = tx->vout[i];
1852 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1853 if (!MoneyRange(nCredit))
1854 throw std::runtime_error(std::string(__func__) + ": value out of range");
1858 nAvailableWatchCreditCached = nCredit;
1859 fAvailableWatchCreditCached = true;
1860 return nCredit;
1863 CAmount CWalletTx::GetChange() const
1865 if (fChangeCached)
1866 return nChangeCached;
1867 nChangeCached = pwallet->GetChange(*tx);
1868 fChangeCached = true;
1869 return nChangeCached;
1872 bool CWalletTx::InMempool() const
1874 LOCK(mempool.cs);
1875 return mempool.exists(GetHash());
1878 bool CWalletTx::IsTrusted() const
1880 // Quick answer in most cases
1881 if (!CheckFinalTx(*tx))
1882 return false;
1883 int nDepth = GetDepthInMainChain();
1884 if (nDepth >= 1)
1885 return true;
1886 if (nDepth < 0)
1887 return false;
1888 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1889 return false;
1891 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1892 if (!InMempool())
1893 return false;
1895 // Trusted if all inputs are from us and are in the mempool:
1896 for (const CTxIn& txin : tx->vin)
1898 // Transactions not sent by us: not trusted
1899 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1900 if (parent == nullptr)
1901 return false;
1902 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1903 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1904 return false;
1906 return true;
1909 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1911 CMutableTransaction tx1 = *this->tx;
1912 CMutableTransaction tx2 = *_tx.tx;
1913 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1914 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1915 return CTransaction(tx1) == CTransaction(tx2);
1918 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1920 std::vector<uint256> result;
1922 LOCK(cs_wallet);
1924 // Sort them in chronological order
1925 std::multimap<unsigned int, CWalletTx*> mapSorted;
1926 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1928 CWalletTx& wtx = item.second;
1929 // Don't rebroadcast if newer than nTime:
1930 if (wtx.nTimeReceived > nTime)
1931 continue;
1932 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1934 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1936 CWalletTx& wtx = *item.second;
1937 if (wtx.RelayWalletTransaction(connman))
1938 result.push_back(wtx.GetHash());
1940 return result;
1943 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1945 // Do this infrequently and randomly to avoid giving away
1946 // that these are our transactions.
1947 if (GetTime() < nNextResend || !fBroadcastTransactions)
1948 return;
1949 bool fFirst = (nNextResend == 0);
1950 nNextResend = GetTime() + GetRand(30 * 60);
1951 if (fFirst)
1952 return;
1954 // Only do it if there's been a new block since last time
1955 if (nBestBlockTime < nLastResend)
1956 return;
1957 nLastResend = GetTime();
1959 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1960 // block was found:
1961 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1962 if (!relayed.empty())
1963 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1966 /** @} */ // end of mapWallet
1971 /** @defgroup Actions
1973 * @{
1977 CAmount CWallet::GetBalance() const
1979 CAmount nTotal = 0;
1981 LOCK2(cs_main, cs_wallet);
1982 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1984 const CWalletTx* pcoin = &(*it).second;
1985 if (pcoin->IsTrusted())
1986 nTotal += pcoin->GetAvailableCredit();
1990 return nTotal;
1993 CAmount CWallet::GetUnconfirmedBalance() const
1995 CAmount nTotal = 0;
1997 LOCK2(cs_main, cs_wallet);
1998 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2000 const CWalletTx* pcoin = &(*it).second;
2001 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2002 nTotal += pcoin->GetAvailableCredit();
2005 return nTotal;
2008 CAmount CWallet::GetImmatureBalance() const
2010 CAmount nTotal = 0;
2012 LOCK2(cs_main, cs_wallet);
2013 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2015 const CWalletTx* pcoin = &(*it).second;
2016 nTotal += pcoin->GetImmatureCredit();
2019 return nTotal;
2022 CAmount CWallet::GetWatchOnlyBalance() const
2024 CAmount nTotal = 0;
2026 LOCK2(cs_main, cs_wallet);
2027 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2029 const CWalletTx* pcoin = &(*it).second;
2030 if (pcoin->IsTrusted())
2031 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2035 return nTotal;
2038 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2040 CAmount nTotal = 0;
2042 LOCK2(cs_main, cs_wallet);
2043 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2045 const CWalletTx* pcoin = &(*it).second;
2046 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2047 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2050 return nTotal;
2053 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2055 CAmount nTotal = 0;
2057 LOCK2(cs_main, cs_wallet);
2058 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2060 const CWalletTx* pcoin = &(*it).second;
2061 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2064 return nTotal;
2067 // Calculate total balance in a different way from GetBalance. The biggest
2068 // difference is that GetBalance sums up all unspent TxOuts paying to the
2069 // wallet, while this sums up both spent and unspent TxOuts paying to the
2070 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2071 // also has fewer restrictions on which unconfirmed transactions are considered
2072 // trusted.
2073 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2075 LOCK2(cs_main, cs_wallet);
2077 CAmount balance = 0;
2078 for (const auto& entry : mapWallet) {
2079 const CWalletTx& wtx = entry.second;
2080 const int depth = wtx.GetDepthInMainChain();
2081 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2082 continue;
2085 // Loop through tx outputs and add incoming payments. For outgoing txs,
2086 // treat change outputs specially, as part of the amount debited.
2087 CAmount debit = wtx.GetDebit(filter);
2088 const bool outgoing = debit > 0;
2089 for (const CTxOut& out : wtx.tx->vout) {
2090 if (outgoing && IsChange(out)) {
2091 debit -= out.nValue;
2092 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2093 balance += out.nValue;
2097 // For outgoing txs, subtract amount debited.
2098 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2099 balance -= debit;
2103 if (account) {
2104 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2107 return balance;
2110 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2112 LOCK2(cs_main, cs_wallet);
2114 CAmount balance = 0;
2115 std::vector<COutput> vCoins;
2116 AvailableCoins(vCoins, true, coinControl);
2117 for (const COutput& out : vCoins) {
2118 if (out.fSpendable) {
2119 balance += out.tx->tx->vout[out.i].nValue;
2122 return balance;
2125 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
2127 vCoins.clear();
2130 LOCK2(cs_main, cs_wallet);
2132 CAmount nTotal = 0;
2134 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2136 const uint256& wtxid = it->first;
2137 const CWalletTx* pcoin = &(*it).second;
2139 if (!CheckFinalTx(*pcoin->tx))
2140 continue;
2142 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2143 continue;
2145 int nDepth = pcoin->GetDepthInMainChain();
2146 if (nDepth < 0)
2147 continue;
2149 // We should not consider coins which aren't at least in our mempool
2150 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2151 if (nDepth == 0 && !pcoin->InMempool())
2152 continue;
2154 bool safeTx = pcoin->IsTrusted();
2156 // We should not consider coins from transactions that are replacing
2157 // other transactions.
2159 // Example: There is a transaction A which is replaced by bumpfee
2160 // transaction B. In this case, we want to prevent creation of
2161 // a transaction B' which spends an output of B.
2163 // Reason: If transaction A were initially confirmed, transactions B
2164 // and B' would no longer be valid, so the user would have to create
2165 // a new transaction C to replace B'. However, in the case of a
2166 // one-block reorg, transactions B' and C might BOTH be accepted,
2167 // when the user only wanted one of them. Specifically, there could
2168 // be a 1-block reorg away from the chain where transactions A and C
2169 // were accepted to another chain where B, B', and C were all
2170 // accepted.
2171 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2172 safeTx = false;
2175 // Similarly, we should not consider coins from transactions that
2176 // have been replaced. In the example above, we would want to prevent
2177 // creation of a transaction A' spending an output of A, because if
2178 // transaction B were initially confirmed, conflicting with A and
2179 // A', we wouldn't want to the user to create a transaction D
2180 // intending to replace A', but potentially resulting in a scenario
2181 // where A, A', and D could all be accepted (instead of just B and
2182 // D, or just A and A' like the user would want).
2183 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2184 safeTx = false;
2187 if (fOnlySafe && !safeTx) {
2188 continue;
2191 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2192 continue;
2194 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2195 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2196 continue;
2198 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2199 continue;
2201 if (IsLockedCoin((*it).first, i))
2202 continue;
2204 if (IsSpent(wtxid, i))
2205 continue;
2207 isminetype mine = IsMine(pcoin->tx->vout[i]);
2209 if (mine == ISMINE_NO) {
2210 continue;
2213 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2214 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2216 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2218 // Checks the sum amount of all UTXO's.
2219 if (nMinimumSumAmount != MAX_MONEY) {
2220 nTotal += pcoin->tx->vout[i].nValue;
2222 if (nTotal >= nMinimumSumAmount) {
2223 return;
2227 // Checks the maximum number of UTXO's.
2228 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2229 return;
2236 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2238 // TODO: Add AssertLockHeld(cs_wallet) here.
2240 // Because the return value from this function contains pointers to
2241 // CWalletTx objects, callers to this function really should acquire the
2242 // cs_wallet lock before calling it. However, the current caller doesn't
2243 // acquire this lock yet. There was an attempt to add the missing lock in
2244 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2245 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2246 // avoid adding some extra complexity to the Qt code.
2248 std::map<CTxDestination, std::vector<COutput>> result;
2250 std::vector<COutput> availableCoins;
2251 AvailableCoins(availableCoins);
2253 LOCK2(cs_main, cs_wallet);
2254 for (auto& coin : availableCoins) {
2255 CTxDestination address;
2256 if (coin.fSpendable &&
2257 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2258 result[address].emplace_back(std::move(coin));
2262 std::vector<COutPoint> lockedCoins;
2263 ListLockedCoins(lockedCoins);
2264 for (const auto& output : lockedCoins) {
2265 auto it = mapWallet.find(output.hash);
2266 if (it != mapWallet.end()) {
2267 int depth = it->second.GetDepthInMainChain();
2268 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2269 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2270 CTxDestination address;
2271 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2272 result[address].emplace_back(
2273 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2279 return result;
2282 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2284 const CTransaction* ptx = &tx;
2285 int n = output;
2286 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2287 const COutPoint& prevout = ptx->vin[0].prevout;
2288 auto it = mapWallet.find(prevout.hash);
2289 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2290 !IsMine(it->second.tx->vout[prevout.n])) {
2291 break;
2293 ptx = it->second.tx.get();
2294 n = prevout.n;
2296 return ptx->vout[n];
2299 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2300 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2302 std::vector<char> vfIncluded;
2304 vfBest.assign(vValue.size(), true);
2305 nBest = nTotalLower;
2307 FastRandomContext insecure_rand;
2309 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2311 vfIncluded.assign(vValue.size(), false);
2312 CAmount nTotal = 0;
2313 bool fReachedTarget = false;
2314 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2316 for (unsigned int i = 0; i < vValue.size(); i++)
2318 //The solver here uses a randomized algorithm,
2319 //the randomness serves no real security purpose but is just
2320 //needed to prevent degenerate behavior and it is important
2321 //that the rng is fast. We do not use a constant random sequence,
2322 //because there may be some privacy improvement by making
2323 //the selection random.
2324 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2326 nTotal += vValue[i].txout.nValue;
2327 vfIncluded[i] = true;
2328 if (nTotal >= nTargetValue)
2330 fReachedTarget = true;
2331 if (nTotal < nBest)
2333 nBest = nTotal;
2334 vfBest = vfIncluded;
2336 nTotal -= vValue[i].txout.nValue;
2337 vfIncluded[i] = false;
2345 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2346 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2348 setCoinsRet.clear();
2349 nValueRet = 0;
2351 // List of values less than target
2352 boost::optional<CInputCoin> coinLowestLarger;
2353 std::vector<CInputCoin> vValue;
2354 CAmount nTotalLower = 0;
2356 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2358 for (const COutput &output : vCoins)
2360 if (!output.fSpendable)
2361 continue;
2363 const CWalletTx *pcoin = output.tx;
2365 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2366 continue;
2368 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2369 continue;
2371 int i = output.i;
2373 CInputCoin coin = CInputCoin(pcoin, i);
2375 if (coin.txout.nValue == nTargetValue)
2377 setCoinsRet.insert(coin);
2378 nValueRet += coin.txout.nValue;
2379 return true;
2381 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2383 vValue.push_back(coin);
2384 nTotalLower += coin.txout.nValue;
2386 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2388 coinLowestLarger = coin;
2392 if (nTotalLower == nTargetValue)
2394 for (const auto& input : vValue)
2396 setCoinsRet.insert(input);
2397 nValueRet += input.txout.nValue;
2399 return true;
2402 if (nTotalLower < nTargetValue)
2404 if (!coinLowestLarger)
2405 return false;
2406 setCoinsRet.insert(coinLowestLarger.get());
2407 nValueRet += coinLowestLarger->txout.nValue;
2408 return true;
2411 // Solve subset sum by stochastic approximation
2412 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2413 std::reverse(vValue.begin(), vValue.end());
2414 std::vector<char> vfBest;
2415 CAmount nBest;
2417 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2418 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2419 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2421 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2422 // or the next bigger coin is closer), return the bigger coin
2423 if (coinLowestLarger &&
2424 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2426 setCoinsRet.insert(coinLowestLarger.get());
2427 nValueRet += coinLowestLarger->txout.nValue;
2429 else {
2430 for (unsigned int i = 0; i < vValue.size(); i++)
2431 if (vfBest[i])
2433 setCoinsRet.insert(vValue[i]);
2434 nValueRet += vValue[i].txout.nValue;
2437 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2438 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2439 for (unsigned int i = 0; i < vValue.size(); i++) {
2440 if (vfBest[i]) {
2441 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2444 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2448 return true;
2451 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2453 std::vector<COutput> vCoins(vAvailableCoins);
2455 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2456 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2458 for (const COutput& out : vCoins)
2460 if (!out.fSpendable)
2461 continue;
2462 nValueRet += out.tx->tx->vout[out.i].nValue;
2463 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2465 return (nValueRet >= nTargetValue);
2468 // calculate value from preset inputs and store them
2469 std::set<CInputCoin> setPresetCoins;
2470 CAmount nValueFromPresetInputs = 0;
2472 std::vector<COutPoint> vPresetInputs;
2473 if (coinControl)
2474 coinControl->ListSelected(vPresetInputs);
2475 for (const COutPoint& outpoint : vPresetInputs)
2477 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2478 if (it != mapWallet.end())
2480 const CWalletTx* pcoin = &it->second;
2481 // Clearly invalid input, fail
2482 if (pcoin->tx->vout.size() <= outpoint.n)
2483 return false;
2484 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2485 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2486 } else
2487 return false; // TODO: Allow non-wallet inputs
2490 // remove preset inputs from vCoins
2491 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2493 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2494 it = vCoins.erase(it);
2495 else
2496 ++it;
2499 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2500 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2502 bool res = nTargetValue <= nValueFromPresetInputs ||
2503 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2504 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2505 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2506 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2507 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2508 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2509 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2511 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2512 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2514 // add preset inputs to the total value selected
2515 nValueRet += nValueFromPresetInputs;
2517 return res;
2520 bool CWallet::SignTransaction(CMutableTransaction &tx)
2522 AssertLockHeld(cs_wallet); // mapWallet
2524 // sign the new tx
2525 CTransaction txNewConst(tx);
2526 int nIn = 0;
2527 for (const auto& input : tx.vin) {
2528 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2529 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2530 return false;
2532 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2533 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2534 SignatureData sigdata;
2535 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2536 return false;
2538 UpdateTransaction(tx, nIn, sigdata);
2539 nIn++;
2541 return true;
2544 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2546 std::vector<CRecipient> vecSend;
2548 // Turn the txout set into a CRecipient vector
2549 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2551 const CTxOut& txOut = tx.vout[idx];
2552 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2553 vecSend.push_back(recipient);
2556 coinControl.fAllowOtherInputs = true;
2558 for (const CTxIn& txin : tx.vin)
2559 coinControl.Select(txin.prevout);
2561 CReserveKey reservekey(this);
2562 CWalletTx wtx;
2563 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2564 return false;
2567 if (nChangePosInOut != -1) {
2568 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2569 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2570 // so just remove the key from the keypool here.
2571 reservekey.KeepKey();
2574 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2575 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2576 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2578 // Add new txins (keeping original txin scriptSig/order)
2579 for (const CTxIn& txin : wtx.tx->vin)
2581 if (!coinControl.IsSelected(txin.prevout))
2583 tx.vin.push_back(txin);
2585 if (lockUnspents)
2587 LOCK2(cs_main, cs_wallet);
2588 LockCoin(txin.prevout);
2594 return true;
2597 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2598 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2600 CAmount nValue = 0;
2601 int nChangePosRequest = nChangePosInOut;
2602 unsigned int nSubtractFeeFromAmount = 0;
2603 for (const auto& recipient : vecSend)
2605 if (nValue < 0 || recipient.nAmount < 0)
2607 strFailReason = _("Transaction amounts must not be negative");
2608 return false;
2610 nValue += recipient.nAmount;
2612 if (recipient.fSubtractFeeFromAmount)
2613 nSubtractFeeFromAmount++;
2615 if (vecSend.empty())
2617 strFailReason = _("Transaction must have at least one recipient");
2618 return false;
2621 wtxNew.fTimeReceivedIsTxTime = true;
2622 wtxNew.BindWallet(this);
2623 CMutableTransaction txNew;
2625 // Discourage fee sniping.
2627 // For a large miner the value of the transactions in the best block and
2628 // the mempool can exceed the cost of deliberately attempting to mine two
2629 // blocks to orphan the current best block. By setting nLockTime such that
2630 // only the next block can include the transaction, we discourage this
2631 // practice as the height restricted and limited blocksize gives miners
2632 // considering fee sniping fewer options for pulling off this attack.
2634 // A simple way to think about this is from the wallet's point of view we
2635 // always want the blockchain to move forward. By setting nLockTime this
2636 // way we're basically making the statement that we only want this
2637 // transaction to appear in the next block; we don't want to potentially
2638 // encourage reorgs by allowing transactions to appear at lower heights
2639 // than the next block in forks of the best chain.
2641 // Of course, the subsidy is high enough, and transaction volume low
2642 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2643 // now we ensure code won't be written that makes assumptions about
2644 // nLockTime that preclude a fix later.
2645 txNew.nLockTime = chainActive.Height();
2647 // Secondly occasionally randomly pick a nLockTime even further back, so
2648 // that transactions that are delayed after signing for whatever reason,
2649 // e.g. high-latency mix networks and some CoinJoin implementations, have
2650 // better privacy.
2651 if (GetRandInt(10) == 0)
2652 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2654 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2655 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2656 FeeCalculation feeCalc;
2657 CAmount nFeeNeeded;
2658 unsigned int nBytes;
2660 std::set<CInputCoin> setCoins;
2661 LOCK2(cs_main, cs_wallet);
2663 std::vector<COutput> vAvailableCoins;
2664 AvailableCoins(vAvailableCoins, true, &coin_control);
2666 // Create change script that will be used if we need change
2667 // TODO: pass in scriptChange instead of reservekey so
2668 // change transaction isn't always pay-to-bitcoin-address
2669 CScript scriptChange;
2671 // coin control: send change to custom address
2672 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2673 scriptChange = GetScriptForDestination(coin_control.destChange);
2674 } else { // no coin control: send change to newly generated address
2675 // Note: We use a new key here to keep it from being obvious which side is the change.
2676 // The drawback is that by not reusing a previous key, the change may be lost if a
2677 // backup is restored, if the backup doesn't have the new private key for the change.
2678 // If we reused the old key, it would be possible to add code to look for and
2679 // rediscover unknown transactions that were written with keys of ours to recover
2680 // post-backup change.
2682 // Reserve a new key pair from key pool
2683 CPubKey vchPubKey;
2684 bool ret;
2685 ret = reservekey.GetReservedKey(vchPubKey, true);
2686 if (!ret)
2688 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2689 return false;
2692 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2694 CTxOut change_prototype_txout(0, scriptChange);
2695 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2697 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2698 nFeeRet = 0;
2699 bool pick_new_inputs = true;
2700 CAmount nValueIn = 0;
2701 // Start with no fee and loop until there is enough fee
2702 while (true)
2704 nChangePosInOut = nChangePosRequest;
2705 txNew.vin.clear();
2706 txNew.vout.clear();
2707 wtxNew.fFromMe = true;
2708 bool fFirst = true;
2710 CAmount nValueToSelect = nValue;
2711 if (nSubtractFeeFromAmount == 0)
2712 nValueToSelect += nFeeRet;
2713 // vouts to the payees
2714 for (const auto& recipient : vecSend)
2716 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2718 if (recipient.fSubtractFeeFromAmount)
2720 assert(nSubtractFeeFromAmount != 0);
2721 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2723 if (fFirst) // first receiver pays the remainder not divisible by output count
2725 fFirst = false;
2726 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2730 if (IsDust(txout, ::dustRelayFee))
2732 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2734 if (txout.nValue < 0)
2735 strFailReason = _("The transaction amount is too small to pay the fee");
2736 else
2737 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2739 else
2740 strFailReason = _("Transaction amount too small");
2741 return false;
2743 txNew.vout.push_back(txout);
2746 // Choose coins to use
2747 if (pick_new_inputs) {
2748 nValueIn = 0;
2749 setCoins.clear();
2750 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2752 strFailReason = _("Insufficient funds");
2753 return false;
2757 const CAmount nChange = nValueIn - nValueToSelect;
2759 if (nChange > 0)
2761 // Fill a vout to ourself
2762 CTxOut newTxOut(nChange, scriptChange);
2764 // Never create dust outputs; if we would, just
2765 // add the dust to the fee.
2766 if (IsDust(newTxOut, discard_rate))
2768 nChangePosInOut = -1;
2769 nFeeRet += nChange;
2771 else
2773 if (nChangePosInOut == -1)
2775 // Insert change txn at random position:
2776 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2778 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2780 strFailReason = _("Change index out of range");
2781 return false;
2784 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2785 txNew.vout.insert(position, newTxOut);
2787 } else {
2788 nChangePosInOut = -1;
2791 // Fill vin
2793 // Note how the sequence number is set to non-maxint so that
2794 // the nLockTime set above actually works.
2796 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2797 // we use the highest possible value in that range (maxint-2)
2798 // to avoid conflicting with other possible uses of nSequence,
2799 // and in the spirit of "smallest possible change from prior
2800 // behavior."
2801 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2802 for (const auto& coin : setCoins)
2803 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2804 nSequence));
2806 // Fill in dummy signatures for fee calculation.
2807 if (!DummySignTx(txNew, setCoins)) {
2808 strFailReason = _("Signing transaction failed");
2809 return false;
2812 nBytes = GetVirtualTransactionSize(txNew);
2814 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2815 for (auto& vin : txNew.vin) {
2816 vin.scriptSig = CScript();
2817 vin.scriptWitness.SetNull();
2820 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2822 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2823 // because we must be at the maximum allowed fee.
2824 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2826 strFailReason = _("Transaction too large for fee policy");
2827 return false;
2830 if (nFeeRet >= nFeeNeeded) {
2831 // Reduce fee to only the needed amount if possible. This
2832 // prevents potential overpayment in fees if the coins
2833 // selected to meet nFeeNeeded result in a transaction that
2834 // requires less fee than the prior iteration.
2836 // If we have no change and a big enough excess fee, then
2837 // try to construct transaction again only without picking
2838 // new inputs. We now know we only need the smaller fee
2839 // (because of reduced tx size) and so we should add a
2840 // change output. Only try this once.
2841 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2842 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2843 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2844 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2845 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2846 pick_new_inputs = false;
2847 nFeeRet = fee_needed_with_change;
2848 continue;
2852 // If we have change output already, just increase it
2853 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2854 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2855 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2856 change_position->nValue += extraFeePaid;
2857 nFeeRet -= extraFeePaid;
2859 break; // Done, enough fee included.
2861 else if (!pick_new_inputs) {
2862 // This shouldn't happen, we should have had enough excess
2863 // fee to pay for the new output and still meet nFeeNeeded
2864 // Or we should have just subtracted fee from recipients and
2865 // nFeeNeeded should not have changed
2866 strFailReason = _("Transaction fee and change calculation failed");
2867 return false;
2870 // Try to reduce change to include necessary fee
2871 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2872 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2873 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2874 // Only reduce change if remaining amount is still a large enough output.
2875 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2876 change_position->nValue -= additionalFeeNeeded;
2877 nFeeRet += additionalFeeNeeded;
2878 break; // Done, able to increase fee from change
2882 // If subtracting fee from recipients, we now know what fee we
2883 // need to subtract, we have no reason to reselect inputs
2884 if (nSubtractFeeFromAmount > 0) {
2885 pick_new_inputs = false;
2888 // Include more fee and try again.
2889 nFeeRet = nFeeNeeded;
2890 continue;
2894 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2896 if (sign)
2898 CTransaction txNewConst(txNew);
2899 int nIn = 0;
2900 for (const auto& coin : setCoins)
2902 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2903 SignatureData sigdata;
2905 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2907 strFailReason = _("Signing transaction failed");
2908 return false;
2909 } else {
2910 UpdateTransaction(txNew, nIn, sigdata);
2913 nIn++;
2917 // Embed the constructed transaction data in wtxNew.
2918 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2920 // Limit size
2921 if (GetTransactionWeight(*wtxNew.tx) >= MAX_STANDARD_TX_WEIGHT)
2923 strFailReason = _("Transaction too large");
2924 return false;
2928 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2929 // Lastly, ensure this tx will pass the mempool's chain limits
2930 LockPoints lp;
2931 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2932 CTxMemPool::setEntries setAncestors;
2933 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2934 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2935 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2936 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2937 std::string errString;
2938 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2939 strFailReason = _("Transaction has too long of a mempool chain");
2940 return false;
2944 LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d 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",
2945 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2946 feeCalc.est.pass.start, feeCalc.est.pass.end,
2947 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2948 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2949 feeCalc.est.fail.start, feeCalc.est.fail.end,
2950 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2951 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2952 return true;
2956 * Call after CreateTransaction unless you want to abort
2958 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2961 LOCK2(cs_main, cs_wallet);
2962 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2964 // Take key pair from key pool so it won't be used again
2965 reservekey.KeepKey();
2967 // Add tx to wallet, because if it has change it's also ours,
2968 // otherwise just for transaction history.
2969 AddToWallet(wtxNew);
2971 // Notify that old coins are spent
2972 for (const CTxIn& txin : wtxNew.tx->vin)
2974 CWalletTx &coin = mapWallet[txin.prevout.hash];
2975 coin.BindWallet(this);
2976 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2980 // Track how many getdata requests our transaction gets
2981 mapRequestCount[wtxNew.GetHash()] = 0;
2983 if (fBroadcastTransactions)
2985 // Broadcast
2986 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2987 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2988 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2989 } else {
2990 wtxNew.RelayWalletTransaction(connman);
2994 return true;
2997 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2998 CWalletDB walletdb(*dbw);
2999 return walletdb.ListAccountCreditDebit(strAccount, entries);
3002 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3004 CWalletDB walletdb(*dbw);
3006 return AddAccountingEntry(acentry, &walletdb);
3009 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3011 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3012 return false;
3015 laccentries.push_back(acentry);
3016 CAccountingEntry & entry = laccentries.back();
3017 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3019 return true;
3022 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3024 LOCK2(cs_main, cs_wallet);
3026 fFirstRunRet = false;
3027 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3028 if (nLoadWalletRet == DB_NEED_REWRITE)
3030 if (dbw->Rewrite("\x04pool"))
3032 setInternalKeyPool.clear();
3033 setExternalKeyPool.clear();
3034 m_pool_key_to_index.clear();
3035 // Note: can't top-up keypool here, because wallet is locked.
3036 // User will be prompted to unlock wallet the next operation
3037 // that requires a new key.
3041 // This wallet is in its first run if all of these are empty
3042 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3044 if (nLoadWalletRet != DB_LOAD_OK)
3045 return nLoadWalletRet;
3047 uiInterface.LoadWallet(this);
3049 return DB_LOAD_OK;
3052 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3054 AssertLockHeld(cs_wallet); // mapWallet
3055 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3056 for (uint256 hash : vHashOut)
3057 mapWallet.erase(hash);
3059 if (nZapSelectTxRet == DB_NEED_REWRITE)
3061 if (dbw->Rewrite("\x04pool"))
3063 setInternalKeyPool.clear();
3064 setExternalKeyPool.clear();
3065 m_pool_key_to_index.clear();
3066 // Note: can't top-up keypool here, because wallet is locked.
3067 // User will be prompted to unlock wallet the next operation
3068 // that requires a new key.
3072 if (nZapSelectTxRet != DB_LOAD_OK)
3073 return nZapSelectTxRet;
3075 MarkDirty();
3077 return DB_LOAD_OK;
3081 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3083 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3084 if (nZapWalletTxRet == DB_NEED_REWRITE)
3086 if (dbw->Rewrite("\x04pool"))
3088 LOCK(cs_wallet);
3089 setInternalKeyPool.clear();
3090 setExternalKeyPool.clear();
3091 m_pool_key_to_index.clear();
3092 // Note: can't top-up keypool here, because wallet is locked.
3093 // User will be prompted to unlock wallet the next operation
3094 // that requires a new key.
3098 if (nZapWalletTxRet != DB_LOAD_OK)
3099 return nZapWalletTxRet;
3101 return DB_LOAD_OK;
3105 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3107 bool fUpdated = false;
3109 LOCK(cs_wallet); // mapAddressBook
3110 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3111 fUpdated = mi != mapAddressBook.end();
3112 mapAddressBook[address].name = strName;
3113 if (!strPurpose.empty()) /* update purpose only if requested */
3114 mapAddressBook[address].purpose = strPurpose;
3116 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3117 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3118 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3119 return false;
3120 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3123 bool CWallet::DelAddressBook(const CTxDestination& address)
3126 LOCK(cs_wallet); // mapAddressBook
3128 // Delete destdata tuples associated with address
3129 std::string strAddress = EncodeDestination(address);
3130 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3132 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3134 mapAddressBook.erase(address);
3137 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3139 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3140 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3143 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3145 CTxDestination address;
3146 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3147 auto mi = mapAddressBook.find(address);
3148 if (mi != mapAddressBook.end()) {
3149 return mi->second.name;
3152 // A scriptPubKey that doesn't have an entry in the address book is
3153 // associated with the default account ("").
3154 const static std::string DEFAULT_ACCOUNT_NAME;
3155 return DEFAULT_ACCOUNT_NAME;
3159 * Mark old keypool keys as used,
3160 * and generate all new keys
3162 bool CWallet::NewKeyPool()
3165 LOCK(cs_wallet);
3166 CWalletDB walletdb(*dbw);
3168 for (int64_t nIndex : setInternalKeyPool) {
3169 walletdb.ErasePool(nIndex);
3171 setInternalKeyPool.clear();
3173 for (int64_t nIndex : setExternalKeyPool) {
3174 walletdb.ErasePool(nIndex);
3176 setExternalKeyPool.clear();
3178 m_pool_key_to_index.clear();
3180 if (!TopUpKeyPool()) {
3181 return false;
3183 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3185 return true;
3188 size_t CWallet::KeypoolCountExternalKeys()
3190 AssertLockHeld(cs_wallet); // setExternalKeyPool
3191 return setExternalKeyPool.size();
3194 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3196 AssertLockHeld(cs_wallet);
3197 if (keypool.fInternal) {
3198 setInternalKeyPool.insert(nIndex);
3199 } else {
3200 setExternalKeyPool.insert(nIndex);
3202 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3203 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3205 // If no metadata exists yet, create a default with the pool key's
3206 // creation time. Note that this may be overwritten by actually
3207 // stored metadata for that key later, which is fine.
3208 CKeyID keyid = keypool.vchPubKey.GetID();
3209 if (mapKeyMetadata.count(keyid) == 0)
3210 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3213 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3216 LOCK(cs_wallet);
3218 if (IsLocked())
3219 return false;
3221 // Top up key pool
3222 unsigned int nTargetSize;
3223 if (kpSize > 0)
3224 nTargetSize = kpSize;
3225 else
3226 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3228 // count amount of available keys (internal, external)
3229 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3230 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3231 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3233 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3235 // don't create extra internal keys
3236 missingInternal = 0;
3238 bool internal = false;
3239 CWalletDB walletdb(*dbw);
3240 for (int64_t i = missingInternal + missingExternal; i--;)
3242 if (i < missingInternal) {
3243 internal = true;
3246 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3247 int64_t index = ++m_max_keypool_index;
3249 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3250 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3251 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3254 if (internal) {
3255 setInternalKeyPool.insert(index);
3256 } else {
3257 setExternalKeyPool.insert(index);
3259 m_pool_key_to_index[pubkey.GetID()] = index;
3261 if (missingInternal + missingExternal > 0) {
3262 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3265 return true;
3268 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3270 nIndex = -1;
3271 keypool.vchPubKey = CPubKey();
3273 LOCK(cs_wallet);
3275 if (!IsLocked())
3276 TopUpKeyPool();
3278 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3279 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3281 // Get the oldest key
3282 if(setKeyPool.empty())
3283 return;
3285 CWalletDB walletdb(*dbw);
3287 auto it = setKeyPool.begin();
3288 nIndex = *it;
3289 setKeyPool.erase(it);
3290 if (!walletdb.ReadPool(nIndex, keypool)) {
3291 throw std::runtime_error(std::string(__func__) + ": read failed");
3293 if (!HaveKey(keypool.vchPubKey.GetID())) {
3294 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3296 if (keypool.fInternal != fReturningInternal) {
3297 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3300 assert(keypool.vchPubKey.IsValid());
3301 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3302 LogPrintf("keypool reserve %d\n", nIndex);
3306 void CWallet::KeepKey(int64_t nIndex)
3308 // Remove from key pool
3309 CWalletDB walletdb(*dbw);
3310 walletdb.ErasePool(nIndex);
3311 LogPrintf("keypool keep %d\n", nIndex);
3314 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3316 // Return to key pool
3318 LOCK(cs_wallet);
3319 if (fInternal) {
3320 setInternalKeyPool.insert(nIndex);
3321 } else {
3322 setExternalKeyPool.insert(nIndex);
3324 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3326 LogPrintf("keypool return %d\n", nIndex);
3329 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3331 CKeyPool keypool;
3333 LOCK(cs_wallet);
3334 int64_t nIndex = 0;
3335 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3336 if (nIndex == -1)
3338 if (IsLocked()) return false;
3339 CWalletDB walletdb(*dbw);
3340 result = GenerateNewKey(walletdb, internal);
3341 return true;
3343 KeepKey(nIndex);
3344 result = keypool.vchPubKey;
3346 return true;
3349 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3350 if (setKeyPool.empty()) {
3351 return GetTime();
3354 CKeyPool keypool;
3355 int64_t nIndex = *(setKeyPool.begin());
3356 if (!walletdb.ReadPool(nIndex, keypool)) {
3357 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3359 assert(keypool.vchPubKey.IsValid());
3360 return keypool.nTime;
3363 int64_t CWallet::GetOldestKeyPoolTime()
3365 LOCK(cs_wallet);
3367 CWalletDB walletdb(*dbw);
3369 // load oldest key from keypool, get time and return
3370 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3371 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3372 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3375 return oldestKey;
3378 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3380 std::map<CTxDestination, CAmount> balances;
3383 LOCK(cs_wallet);
3384 for (const auto& walletEntry : mapWallet)
3386 const CWalletTx *pcoin = &walletEntry.second;
3388 if (!pcoin->IsTrusted())
3389 continue;
3391 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3392 continue;
3394 int nDepth = pcoin->GetDepthInMainChain();
3395 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3396 continue;
3398 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3400 CTxDestination addr;
3401 if (!IsMine(pcoin->tx->vout[i]))
3402 continue;
3403 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3404 continue;
3406 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3408 if (!balances.count(addr))
3409 balances[addr] = 0;
3410 balances[addr] += n;
3415 return balances;
3418 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3420 AssertLockHeld(cs_wallet); // mapWallet
3421 std::set< std::set<CTxDestination> > groupings;
3422 std::set<CTxDestination> grouping;
3424 for (const auto& walletEntry : mapWallet)
3426 const CWalletTx *pcoin = &walletEntry.second;
3428 if (pcoin->tx->vin.size() > 0)
3430 bool any_mine = false;
3431 // group all input addresses with each other
3432 for (CTxIn txin : pcoin->tx->vin)
3434 CTxDestination address;
3435 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3436 continue;
3437 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3438 continue;
3439 grouping.insert(address);
3440 any_mine = true;
3443 // group change with input addresses
3444 if (any_mine)
3446 for (CTxOut txout : pcoin->tx->vout)
3447 if (IsChange(txout))
3449 CTxDestination txoutAddr;
3450 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3451 continue;
3452 grouping.insert(txoutAddr);
3455 if (grouping.size() > 0)
3457 groupings.insert(grouping);
3458 grouping.clear();
3462 // group lone addrs by themselves
3463 for (const auto& txout : pcoin->tx->vout)
3464 if (IsMine(txout))
3466 CTxDestination address;
3467 if(!ExtractDestination(txout.scriptPubKey, address))
3468 continue;
3469 grouping.insert(address);
3470 groupings.insert(grouping);
3471 grouping.clear();
3475 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3476 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3477 for (std::set<CTxDestination> _grouping : groupings)
3479 // make a set of all the groups hit by this new group
3480 std::set< std::set<CTxDestination>* > hits;
3481 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3482 for (CTxDestination address : _grouping)
3483 if ((it = setmap.find(address)) != setmap.end())
3484 hits.insert((*it).second);
3486 // merge all hit groups into a new single group and delete old groups
3487 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3488 for (std::set<CTxDestination>* hit : hits)
3490 merged->insert(hit->begin(), hit->end());
3491 uniqueGroupings.erase(hit);
3492 delete hit;
3494 uniqueGroupings.insert(merged);
3496 // update setmap
3497 for (CTxDestination element : *merged)
3498 setmap[element] = merged;
3501 std::set< std::set<CTxDestination> > ret;
3502 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3504 ret.insert(*uniqueGrouping);
3505 delete uniqueGrouping;
3508 return ret;
3511 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3513 LOCK(cs_wallet);
3514 std::set<CTxDestination> result;
3515 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3517 const CTxDestination& address = item.first;
3518 const std::string& strName = item.second.name;
3519 if (strName == strAccount)
3520 result.insert(address);
3522 return result;
3525 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3527 if (nIndex == -1)
3529 CKeyPool keypool;
3530 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3531 if (nIndex != -1)
3532 vchPubKey = keypool.vchPubKey;
3533 else {
3534 return false;
3536 fInternal = keypool.fInternal;
3538 assert(vchPubKey.IsValid());
3539 pubkey = vchPubKey;
3540 return true;
3543 void CReserveKey::KeepKey()
3545 if (nIndex != -1)
3546 pwallet->KeepKey(nIndex);
3547 nIndex = -1;
3548 vchPubKey = CPubKey();
3551 void CReserveKey::ReturnKey()
3553 if (nIndex != -1) {
3554 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3556 nIndex = -1;
3557 vchPubKey = CPubKey();
3560 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3562 AssertLockHeld(cs_wallet);
3563 bool internal = setInternalKeyPool.count(keypool_id);
3564 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3565 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3566 auto it = setKeyPool->begin();
3568 CWalletDB walletdb(*dbw);
3569 while (it != std::end(*setKeyPool)) {
3570 const int64_t& index = *(it);
3571 if (index > keypool_id) break; // set*KeyPool is ordered
3573 CKeyPool keypool;
3574 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3575 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3577 walletdb.ErasePool(index);
3578 LogPrintf("keypool index %d removed\n", index);
3579 it = setKeyPool->erase(it);
3583 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3585 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3586 CPubKey pubkey;
3587 if (!rKey->GetReservedKey(pubkey))
3588 return;
3590 script = rKey;
3591 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3594 void CWallet::LockCoin(const COutPoint& output)
3596 AssertLockHeld(cs_wallet); // setLockedCoins
3597 setLockedCoins.insert(output);
3600 void CWallet::UnlockCoin(const COutPoint& output)
3602 AssertLockHeld(cs_wallet); // setLockedCoins
3603 setLockedCoins.erase(output);
3606 void CWallet::UnlockAllCoins()
3608 AssertLockHeld(cs_wallet); // setLockedCoins
3609 setLockedCoins.clear();
3612 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3614 AssertLockHeld(cs_wallet); // setLockedCoins
3615 COutPoint outpt(hash, n);
3617 return (setLockedCoins.count(outpt) > 0);
3620 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3622 AssertLockHeld(cs_wallet); // setLockedCoins
3623 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3624 it != setLockedCoins.end(); it++) {
3625 COutPoint outpt = (*it);
3626 vOutpts.push_back(outpt);
3630 /** @} */ // end of Actions
3632 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3633 AssertLockHeld(cs_wallet); // mapKeyMetadata
3634 mapKeyBirth.clear();
3636 // get birth times for keys with metadata
3637 for (const auto& entry : mapKeyMetadata) {
3638 if (entry.second.nCreateTime) {
3639 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3643 // map in which we'll infer heights of other keys
3644 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3645 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3646 for (const CKeyID &keyid : GetKeys()) {
3647 if (mapKeyBirth.count(keyid) == 0)
3648 mapKeyFirstBlock[keyid] = pindexMax;
3651 // if there are no such keys, we're done
3652 if (mapKeyFirstBlock.empty())
3653 return;
3655 // find first block that affects those keys, if there are any left
3656 std::vector<CKeyID> vAffected;
3657 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3658 // iterate over all wallet transactions...
3659 const CWalletTx &wtx = (*it).second;
3660 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3661 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3662 // ... which are already in a block
3663 int nHeight = blit->second->nHeight;
3664 for (const CTxOut &txout : wtx.tx->vout) {
3665 // iterate over all their outputs
3666 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3667 for (const CKeyID &keyid : vAffected) {
3668 // ... and all their affected keys
3669 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3670 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3671 rit->second = blit->second;
3673 vAffected.clear();
3678 // Extract block timestamps for those keys
3679 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3680 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3684 * Compute smart timestamp for a transaction being added to the wallet.
3686 * Logic:
3687 * - If sending a transaction, assign its timestamp to the current time.
3688 * - If receiving a transaction outside a block, assign its timestamp to the
3689 * current time.
3690 * - If receiving a block with a future timestamp, assign all its (not already
3691 * known) transactions' timestamps to the current time.
3692 * - If receiving a block with a past timestamp, before the most recent known
3693 * transaction (that we care about), assign all its (not already known)
3694 * transactions' timestamps to the same timestamp as that most-recent-known
3695 * transaction.
3696 * - If receiving a block with a past timestamp, but after the most recent known
3697 * transaction, assign all its (not already known) transactions' timestamps to
3698 * the block time.
3700 * For more information see CWalletTx::nTimeSmart,
3701 * https://bitcointalk.org/?topic=54527, or
3702 * https://github.com/bitcoin/bitcoin/pull/1393.
3704 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3706 unsigned int nTimeSmart = wtx.nTimeReceived;
3707 if (!wtx.hashUnset()) {
3708 if (mapBlockIndex.count(wtx.hashBlock)) {
3709 int64_t latestNow = wtx.nTimeReceived;
3710 int64_t latestEntry = 0;
3712 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3713 int64_t latestTolerated = latestNow + 300;
3714 const TxItems& txOrdered = wtxOrdered;
3715 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3716 CWalletTx* const pwtx = it->second.first;
3717 if (pwtx == &wtx) {
3718 continue;
3720 CAccountingEntry* const pacentry = it->second.second;
3721 int64_t nSmartTime;
3722 if (pwtx) {
3723 nSmartTime = pwtx->nTimeSmart;
3724 if (!nSmartTime) {
3725 nSmartTime = pwtx->nTimeReceived;
3727 } else {
3728 nSmartTime = pacentry->nTime;
3730 if (nSmartTime <= latestTolerated) {
3731 latestEntry = nSmartTime;
3732 if (nSmartTime > latestNow) {
3733 latestNow = nSmartTime;
3735 break;
3739 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3740 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3741 } else {
3742 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3745 return nTimeSmart;
3748 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3750 if (boost::get<CNoDestination>(&dest))
3751 return false;
3753 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3754 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3757 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3759 if (!mapAddressBook[dest].destdata.erase(key))
3760 return false;
3761 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3764 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3766 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3767 return true;
3770 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3772 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3773 if(i != mapAddressBook.end())
3775 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3776 if(j != i->second.destdata.end())
3778 if(value)
3779 *value = j->second;
3780 return true;
3783 return false;
3786 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3788 LOCK(cs_wallet);
3789 std::vector<std::string> values;
3790 for (const auto& address : mapAddressBook) {
3791 for (const auto& data : address.second.destdata) {
3792 if (!data.first.compare(0, prefix.size(), prefix)) {
3793 values.emplace_back(data.second);
3797 return values;
3800 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3802 // needed to restore wallet transaction meta data after -zapwallettxes
3803 std::vector<CWalletTx> vWtx;
3805 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3806 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3808 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3809 std::unique_ptr<CWallet> tempWallet = MakeUnique<CWallet>(std::move(dbw));
3810 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3811 if (nZapWalletRet != DB_LOAD_OK) {
3812 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3813 return nullptr;
3817 uiInterface.InitMessage(_("Loading wallet..."));
3819 int64_t nStart = GetTimeMillis();
3820 bool fFirstRun = true;
3821 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3822 CWallet *walletInstance = new CWallet(std::move(dbw));
3823 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3824 if (nLoadWalletRet != DB_LOAD_OK)
3826 if (nLoadWalletRet == DB_CORRUPT) {
3827 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3828 return nullptr;
3830 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3832 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3833 " or address book entries might be missing or incorrect."),
3834 walletFile));
3836 else if (nLoadWalletRet == DB_TOO_NEW) {
3837 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3838 return nullptr;
3840 else if (nLoadWalletRet == DB_NEED_REWRITE)
3842 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3843 return nullptr;
3845 else {
3846 InitError(strprintf(_("Error loading %s"), walletFile));
3847 return nullptr;
3851 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3853 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3854 if (nMaxVersion == 0) // the -upgradewallet without argument case
3856 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3857 nMaxVersion = CLIENT_VERSION;
3858 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3860 else
3861 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3862 if (nMaxVersion < walletInstance->GetVersion())
3864 InitError(_("Cannot downgrade wallet"));
3865 return nullptr;
3867 walletInstance->SetMaxVersion(nMaxVersion);
3870 if (fFirstRun)
3872 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3873 if (!gArgs.GetBoolArg("-usehd", true)) {
3874 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3875 return nullptr;
3877 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3879 // generate a new master key
3880 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3881 if (!walletInstance->SetHDMasterKey(masterPubKey))
3882 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3884 // Top up the keypool
3885 if (!walletInstance->TopUpKeyPool()) {
3886 InitError(_("Unable to generate initial keys") += "\n");
3887 return nullptr;
3890 walletInstance->SetBestChain(chainActive.GetLocator());
3892 else if (gArgs.IsArgSet("-usehd")) {
3893 bool useHD = gArgs.GetBoolArg("-usehd", true);
3894 if (walletInstance->IsHDEnabled() && !useHD) {
3895 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3896 return nullptr;
3898 if (!walletInstance->IsHDEnabled() && useHD) {
3899 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3900 return nullptr;
3904 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3906 RegisterValidationInterface(walletInstance);
3908 // Try to top up keypool. No-op if the wallet is locked.
3909 walletInstance->TopUpKeyPool();
3911 CBlockIndex *pindexRescan = chainActive.Genesis();
3912 if (!gArgs.GetBoolArg("-rescan", false))
3914 CWalletDB walletdb(*walletInstance->dbw);
3915 CBlockLocator locator;
3916 if (walletdb.ReadBestBlock(locator))
3917 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3919 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3921 //We can't rescan beyond non-pruned blocks, stop and throw an error
3922 //this might happen if a user uses an old wallet within a pruned node
3923 // or if he ran -disablewallet for a longer time, then decided to re-enable
3924 if (fPruneMode)
3926 CBlockIndex *block = chainActive.Tip();
3927 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3928 block = block->pprev;
3930 if (pindexRescan != block) {
3931 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3932 return nullptr;
3936 uiInterface.InitMessage(_("Rescanning..."));
3937 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3939 // No need to read and scan block if block was created before
3940 // our wallet birthday (as adjusted for block time variability)
3941 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3942 pindexRescan = chainActive.Next(pindexRescan);
3945 nStart = GetTimeMillis();
3946 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
3947 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3948 walletInstance->SetBestChain(chainActive.GetLocator());
3949 walletInstance->dbw->IncrementUpdateCounter();
3951 // Restore wallet transaction metadata after -zapwallettxes=1
3952 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
3954 CWalletDB walletdb(*walletInstance->dbw);
3956 for (const CWalletTx& wtxOld : vWtx)
3958 uint256 hash = wtxOld.GetHash();
3959 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3960 if (mi != walletInstance->mapWallet.end())
3962 const CWalletTx* copyFrom = &wtxOld;
3963 CWalletTx* copyTo = &mi->second;
3964 copyTo->mapValue = copyFrom->mapValue;
3965 copyTo->vOrderForm = copyFrom->vOrderForm;
3966 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3967 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3968 copyTo->fFromMe = copyFrom->fFromMe;
3969 copyTo->strFromAccount = copyFrom->strFromAccount;
3970 copyTo->nOrderPos = copyFrom->nOrderPos;
3971 walletdb.WriteTx(*copyTo);
3976 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3979 LOCK(walletInstance->cs_wallet);
3980 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3981 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3982 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3985 return walletInstance;
3988 std::atomic<bool> CWallet::fFlushScheduled(false);
3990 void CWallet::postInitProcess(CScheduler& scheduler)
3992 // Add wallet transactions that aren't already in a block to mempool
3993 // Do this here as mempool requires genesis block to be loaded
3994 ReacceptWalletTransactions();
3996 // Run a thread to flush wallet periodically
3997 if (!CWallet::fFlushScheduled.exchange(true)) {
3998 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
4002 bool CWallet::BackupWallet(const std::string& strDest)
4004 return dbw->Backup(strDest);
4007 CKeyPool::CKeyPool()
4009 nTime = GetTime();
4010 fInternal = false;
4013 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4015 nTime = GetTime();
4016 vchPubKey = vchPubKeyIn;
4017 fInternal = internalIn;
4020 CWalletKey::CWalletKey(int64_t nExpires)
4022 nTimeCreated = (nExpires ? GetTime() : 0);
4023 nTimeExpires = nExpires;
4026 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4028 // Update the tx's hashBlock
4029 hashBlock = pindex->GetBlockHash();
4031 // set the position of the transaction in the block
4032 nIndex = posInBlock;
4035 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4037 if (hashUnset())
4038 return 0;
4040 AssertLockHeld(cs_main);
4042 // Find the block it claims to be in
4043 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4044 if (mi == mapBlockIndex.end())
4045 return 0;
4046 CBlockIndex* pindex = (*mi).second;
4047 if (!pindex || !chainActive.Contains(pindex))
4048 return 0;
4050 pindexRet = pindex;
4051 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4054 int CMerkleTx::GetBlocksToMaturity() const
4056 if (!IsCoinBase())
4057 return 0;
4058 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4062 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4064 return ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4065 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);