Merge #11467: Fix typos. Use nullptr instead of NULL.
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob543bef32ad9a635d0eef17a6880d37029450dca2
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];
535 // Now copy data from copyFrom to rest:
536 for (TxSpends::iterator it = range.first; it != range.second; ++it)
538 const uint256& hash = it->second;
539 CWalletTx* copyTo = &mapWallet[hash];
540 if (copyFrom == copyTo) continue;
541 assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
542 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
543 copyTo->mapValue = copyFrom->mapValue;
544 copyTo->vOrderForm = copyFrom->vOrderForm;
545 // fTimeReceivedIsTxTime not copied on purpose
546 // nTimeReceived not copied on purpose
547 copyTo->nTimeSmart = copyFrom->nTimeSmart;
548 copyTo->fFromMe = copyFrom->fFromMe;
549 copyTo->strFromAccount = copyFrom->strFromAccount;
550 // nOrderPos not copied on purpose
551 // cached members not copied on purpose
556 * Outpoint is spent if any non-conflicted transaction
557 * spends it:
559 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
561 const COutPoint outpoint(hash, n);
562 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
563 range = mapTxSpends.equal_range(outpoint);
565 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
567 const uint256& wtxid = it->second;
568 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
569 if (mit != mapWallet.end()) {
570 int depth = mit->second.GetDepthInMainChain();
571 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
572 return true; // Spent
575 return false;
578 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
580 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
582 std::pair<TxSpends::iterator, TxSpends::iterator> range;
583 range = mapTxSpends.equal_range(outpoint);
584 SyncMetaData(range);
588 void CWallet::AddToSpends(const uint256& wtxid)
590 auto it = mapWallet.find(wtxid);
591 assert(it != mapWallet.end());
592 CWalletTx& thisTx = it->second;
593 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
594 return;
596 for (const CTxIn& txin : thisTx.tx->vin)
597 AddToSpends(txin.prevout, wtxid);
600 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
602 if (IsCrypted())
603 return false;
605 CKeyingMaterial _vMasterKey;
607 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
608 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
610 CMasterKey kMasterKey;
612 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
613 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
615 CCrypter crypter;
616 int64_t nStartTime = GetTimeMillis();
617 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
618 kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
620 nStartTime = GetTimeMillis();
621 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
622 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
624 if (kMasterKey.nDeriveIterations < 25000)
625 kMasterKey.nDeriveIterations = 25000;
627 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
629 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
630 return false;
631 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
632 return false;
635 LOCK(cs_wallet);
636 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
637 assert(!pwalletdbEncryption);
638 pwalletdbEncryption = new CWalletDB(*dbw);
639 if (!pwalletdbEncryption->TxnBegin()) {
640 delete pwalletdbEncryption;
641 pwalletdbEncryption = nullptr;
642 return false;
644 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
646 if (!EncryptKeys(_vMasterKey))
648 pwalletdbEncryption->TxnAbort();
649 delete pwalletdbEncryption;
650 // We now probably have half of our keys encrypted in memory, and half not...
651 // die and let the user reload the unencrypted wallet.
652 assert(false);
655 // Encryption was introduced in version 0.4.0
656 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
658 if (!pwalletdbEncryption->TxnCommit()) {
659 delete pwalletdbEncryption;
660 // We now have keys encrypted in memory, but not on disk...
661 // die to avoid confusion and let the user reload the unencrypted wallet.
662 assert(false);
665 delete pwalletdbEncryption;
666 pwalletdbEncryption = nullptr;
668 Lock();
669 Unlock(strWalletPassphrase);
671 // if we are using HD, replace the HD master key (seed) with a new one
672 if (IsHDEnabled()) {
673 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
674 return false;
678 NewKeyPool();
679 Lock();
681 // Need to completely rewrite the wallet file; if we don't, bdb might keep
682 // bits of the unencrypted private key in slack space in the database file.
683 dbw->Rewrite();
686 NotifyStatusChanged(this);
688 return true;
691 DBErrors CWallet::ReorderTransactions()
693 LOCK(cs_wallet);
694 CWalletDB walletdb(*dbw);
696 // Old wallets didn't have any defined order for transactions
697 // Probably a bad idea to change the output of this
699 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
700 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
701 typedef std::multimap<int64_t, TxPair > TxItems;
702 TxItems txByTime;
704 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
706 CWalletTx* wtx = &((*it).second);
707 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
709 std::list<CAccountingEntry> acentries;
710 walletdb.ListAccountCreditDebit("", acentries);
711 for (CAccountingEntry& entry : acentries)
713 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
716 nOrderPosNext = 0;
717 std::vector<int64_t> nOrderPosOffsets;
718 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
720 CWalletTx *const pwtx = (*it).second.first;
721 CAccountingEntry *const pacentry = (*it).second.second;
722 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
724 if (nOrderPos == -1)
726 nOrderPos = nOrderPosNext++;
727 nOrderPosOffsets.push_back(nOrderPos);
729 if (pwtx)
731 if (!walletdb.WriteTx(*pwtx))
732 return DB_LOAD_FAIL;
734 else
735 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
736 return DB_LOAD_FAIL;
738 else
740 int64_t nOrderPosOff = 0;
741 for (const int64_t& nOffsetStart : nOrderPosOffsets)
743 if (nOrderPos >= nOffsetStart)
744 ++nOrderPosOff;
746 nOrderPos += nOrderPosOff;
747 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
749 if (!nOrderPosOff)
750 continue;
752 // Since we're changing the order, write it back
753 if (pwtx)
755 if (!walletdb.WriteTx(*pwtx))
756 return DB_LOAD_FAIL;
758 else
759 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
760 return DB_LOAD_FAIL;
763 walletdb.WriteOrderPosNext(nOrderPosNext);
765 return DB_LOAD_OK;
768 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
770 AssertLockHeld(cs_wallet); // nOrderPosNext
771 int64_t nRet = nOrderPosNext++;
772 if (pwalletdb) {
773 pwalletdb->WriteOrderPosNext(nOrderPosNext);
774 } else {
775 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
777 return nRet;
780 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
782 CWalletDB walletdb(*dbw);
783 if (!walletdb.TxnBegin())
784 return false;
786 int64_t nNow = GetAdjustedTime();
788 // Debit
789 CAccountingEntry debit;
790 debit.nOrderPos = IncOrderPosNext(&walletdb);
791 debit.strAccount = strFrom;
792 debit.nCreditDebit = -nAmount;
793 debit.nTime = nNow;
794 debit.strOtherAccount = strTo;
795 debit.strComment = strComment;
796 AddAccountingEntry(debit, &walletdb);
798 // Credit
799 CAccountingEntry credit;
800 credit.nOrderPos = IncOrderPosNext(&walletdb);
801 credit.strAccount = strTo;
802 credit.nCreditDebit = nAmount;
803 credit.nTime = nNow;
804 credit.strOtherAccount = strFrom;
805 credit.strComment = strComment;
806 AddAccountingEntry(credit, &walletdb);
808 if (!walletdb.TxnCommit())
809 return false;
811 return true;
814 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
816 CWalletDB walletdb(*dbw);
818 CAccount account;
819 walletdb.ReadAccount(strAccount, account);
821 if (!bForceNew) {
822 if (!account.vchPubKey.IsValid())
823 bForceNew = true;
824 else {
825 // Check if the current key has been used
826 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
827 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
828 it != mapWallet.end() && account.vchPubKey.IsValid();
829 ++it)
830 for (const CTxOut& txout : (*it).second.tx->vout)
831 if (txout.scriptPubKey == scriptPubKey) {
832 bForceNew = true;
833 break;
838 // Generate a new key
839 if (bForceNew) {
840 if (!GetKeyFromPool(account.vchPubKey, false))
841 return false;
843 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
844 walletdb.WriteAccount(strAccount, account);
847 pubKey = account.vchPubKey;
849 return true;
852 void CWallet::MarkDirty()
855 LOCK(cs_wallet);
856 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
857 item.second.MarkDirty();
861 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
863 LOCK(cs_wallet);
865 auto mi = mapWallet.find(originalHash);
867 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
868 assert(mi != mapWallet.end());
870 CWalletTx& wtx = (*mi).second;
872 // Ensure for now that we're not overwriting data
873 assert(wtx.mapValue.count("replaced_by_txid") == 0);
875 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
877 CWalletDB walletdb(*dbw, "r+");
879 bool success = true;
880 if (!walletdb.WriteTx(wtx)) {
881 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
882 success = false;
885 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
887 return success;
890 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
892 LOCK(cs_wallet);
894 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
896 uint256 hash = wtxIn.GetHash();
898 // Inserts only if not already there, returns tx inserted or tx found
899 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
900 CWalletTx& wtx = (*ret.first).second;
901 wtx.BindWallet(this);
902 bool fInsertedNew = ret.second;
903 if (fInsertedNew)
905 wtx.nTimeReceived = GetAdjustedTime();
906 wtx.nOrderPos = IncOrderPosNext(&walletdb);
907 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
908 wtx.nTimeSmart = ComputeTimeSmart(wtx);
909 AddToSpends(hash);
912 bool fUpdated = false;
913 if (!fInsertedNew)
915 // Merge
916 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
918 wtx.hashBlock = wtxIn.hashBlock;
919 fUpdated = true;
921 // If no longer abandoned, update
922 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
924 wtx.hashBlock = wtxIn.hashBlock;
925 fUpdated = true;
927 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
929 wtx.nIndex = wtxIn.nIndex;
930 fUpdated = true;
932 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
934 wtx.fFromMe = wtxIn.fFromMe;
935 fUpdated = true;
937 // If we have a witness-stripped version of this transaction, and we
938 // see a new version with a witness, then we must be upgrading a pre-segwit
939 // wallet. Store the new version of the transaction with the witness,
940 // as the stripped-version must be invalid.
941 // TODO: Store all versions of the transaction, instead of just one.
942 if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
943 wtx.SetTx(wtxIn.tx);
944 fUpdated = true;
948 //// debug print
949 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
951 // Write to disk
952 if (fInsertedNew || fUpdated)
953 if (!walletdb.WriteTx(wtx))
954 return false;
956 // Break debit/credit balance caches:
957 wtx.MarkDirty();
959 // Notify UI of new or updated transaction
960 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
962 // notify an external script when a wallet transaction comes in or is updated
963 std::string strCmd = gArgs.GetArg("-walletnotify", "");
965 if (!strCmd.empty())
967 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
968 boost::thread t(runCommand, strCmd); // thread runs free
971 return true;
974 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
976 uint256 hash = wtxIn.GetHash();
978 mapWallet[hash] = wtxIn;
979 CWalletTx& wtx = mapWallet[hash];
980 wtx.BindWallet(this);
981 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
982 AddToSpends(hash);
983 for (const CTxIn& txin : wtx.tx->vin) {
984 auto it = mapWallet.find(txin.prevout.hash);
985 if (it != mapWallet.end()) {
986 CWalletTx& prevtx = it->second;
987 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
988 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
993 return true;
997 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
998 * be set when the transaction was known to be included in a block. When
999 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1000 * notifications happen and cached balances are marked dirty.
1002 * If fUpdate is true, existing transactions will be updated.
1003 * TODO: One exception to this is that the abandoned state is cleared under the
1004 * assumption that any further notification of a transaction that was considered
1005 * abandoned is an indication that it is not safe to be considered abandoned.
1006 * Abandoned state should probably be more carefully tracked via different
1007 * posInBlock signals or by checking mempool presence when necessary.
1009 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
1011 const CTransaction& tx = *ptx;
1013 AssertLockHeld(cs_wallet);
1015 if (pIndex != nullptr) {
1016 for (const CTxIn& txin : tx.vin) {
1017 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
1018 while (range.first != range.second) {
1019 if (range.first->second != tx.GetHash()) {
1020 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);
1021 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
1023 range.first++;
1028 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1029 if (fExisted && !fUpdate) return false;
1030 if (fExisted || IsMine(tx) || IsFromMe(tx))
1032 /* Check if any keys in the wallet keypool that were supposed to be unused
1033 * have appeared in a new transaction. If so, remove those keys from the keypool.
1034 * This can happen when restoring an old wallet backup that does not contain
1035 * the mostly recently created transactions from newer versions of the wallet.
1038 // loop though all outputs
1039 for (const CTxOut& txout: tx.vout) {
1040 // extract addresses and check if they match with an unused keypool key
1041 std::vector<CKeyID> vAffected;
1042 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1043 for (const CKeyID &keyid : vAffected) {
1044 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1045 if (mi != m_pool_key_to_index.end()) {
1046 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1047 MarkReserveKeysAsUsed(mi->second);
1049 if (!TopUpKeyPool()) {
1050 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1056 CWalletTx wtx(this, ptx);
1058 // Get merkle branch if transaction was found in a block
1059 if (pIndex != nullptr)
1060 wtx.SetMerkleBranch(pIndex, posInBlock);
1062 return AddToWallet(wtx, false);
1065 return false;
1068 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1070 LOCK2(cs_main, cs_wallet);
1071 const CWalletTx* wtx = GetWalletTx(hashTx);
1072 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1075 bool CWallet::AbandonTransaction(const uint256& hashTx)
1077 LOCK2(cs_main, cs_wallet);
1079 CWalletDB walletdb(*dbw, "r+");
1081 std::set<uint256> todo;
1082 std::set<uint256> done;
1084 // Can't mark abandoned if confirmed or in mempool
1085 auto it = mapWallet.find(hashTx);
1086 assert(it != mapWallet.end());
1087 CWalletTx& origtx = it->second;
1088 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1089 return false;
1092 todo.insert(hashTx);
1094 while (!todo.empty()) {
1095 uint256 now = *todo.begin();
1096 todo.erase(now);
1097 done.insert(now);
1098 auto it = mapWallet.find(now);
1099 assert(it != mapWallet.end());
1100 CWalletTx& wtx = it->second;
1101 int currentconfirm = wtx.GetDepthInMainChain();
1102 // If the orig tx was not in block, none of its spends can be
1103 assert(currentconfirm <= 0);
1104 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1105 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1106 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1107 assert(!wtx.InMempool());
1108 wtx.nIndex = -1;
1109 wtx.setAbandoned();
1110 wtx.MarkDirty();
1111 walletdb.WriteTx(wtx);
1112 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1113 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1114 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1115 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1116 if (!done.count(iter->second)) {
1117 todo.insert(iter->second);
1119 iter++;
1121 // If a transaction changes 'conflicted' state, that changes the balance
1122 // available of the outputs it spends. So force those to be recomputed
1123 for (const CTxIn& txin : wtx.tx->vin)
1125 auto it = mapWallet.find(txin.prevout.hash);
1126 if (it != mapWallet.end()) {
1127 it->second.MarkDirty();
1133 return true;
1136 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1138 LOCK2(cs_main, cs_wallet);
1140 int conflictconfirms = 0;
1141 if (mapBlockIndex.count(hashBlock)) {
1142 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1143 if (chainActive.Contains(pindex)) {
1144 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1147 // If number of conflict confirms cannot be determined, this means
1148 // that the block is still unknown or not yet part of the main chain,
1149 // for example when loading the wallet during a reindex. Do nothing in that
1150 // case.
1151 if (conflictconfirms >= 0)
1152 return;
1154 // Do not flush the wallet here for performance reasons
1155 CWalletDB walletdb(*dbw, "r+", false);
1157 std::set<uint256> todo;
1158 std::set<uint256> done;
1160 todo.insert(hashTx);
1162 while (!todo.empty()) {
1163 uint256 now = *todo.begin();
1164 todo.erase(now);
1165 done.insert(now);
1166 auto it = mapWallet.find(now);
1167 assert(it != mapWallet.end());
1168 CWalletTx& wtx = it->second;
1169 int currentconfirm = wtx.GetDepthInMainChain();
1170 if (conflictconfirms < currentconfirm) {
1171 // Block is 'more conflicted' than current confirm; update.
1172 // Mark transaction as conflicted with this block.
1173 wtx.nIndex = -1;
1174 wtx.hashBlock = hashBlock;
1175 wtx.MarkDirty();
1176 walletdb.WriteTx(wtx);
1177 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1178 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1179 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1180 if (!done.count(iter->second)) {
1181 todo.insert(iter->second);
1183 iter++;
1185 // If a transaction changes 'conflicted' state, that changes the balance
1186 // available of the outputs it spends. So force those to be recomputed
1187 for (const CTxIn& txin : wtx.tx->vin) {
1188 auto it = mapWallet.find(txin.prevout.hash);
1189 if (it != mapWallet.end()) {
1190 it->second.MarkDirty();
1197 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1198 const CTransaction& tx = *ptx;
1200 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1201 return; // Not one of ours
1203 // If a transaction changes 'conflicted' state, that changes the balance
1204 // available of the outputs it spends. So force those to be
1205 // recomputed, also:
1206 for (const CTxIn& txin : tx.vin) {
1207 auto it = mapWallet.find(txin.prevout.hash);
1208 if (it != mapWallet.end()) {
1209 it->second.MarkDirty();
1214 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1215 LOCK2(cs_main, cs_wallet);
1216 SyncTransaction(ptx);
1219 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1220 LOCK2(cs_main, cs_wallet);
1221 // TODO: Temporarily ensure that mempool removals are notified before
1222 // connected transactions. This shouldn't matter, but the abandoned
1223 // state of transactions in our wallet is currently cleared when we
1224 // receive another notification and there is a race condition where
1225 // notification of a connected conflict might cause an outside process
1226 // to abandon a transaction and then have it inadvertently cleared by
1227 // the notification that the conflicted transaction was evicted.
1229 for (const CTransactionRef& ptx : vtxConflicted) {
1230 SyncTransaction(ptx);
1232 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1233 SyncTransaction(pblock->vtx[i], pindex, i);
1237 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1238 LOCK2(cs_main, cs_wallet);
1240 for (const CTransactionRef& ptx : pblock->vtx) {
1241 SyncTransaction(ptx);
1247 isminetype CWallet::IsMine(const CTxIn &txin) const
1250 LOCK(cs_wallet);
1251 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1252 if (mi != mapWallet.end())
1254 const CWalletTx& prev = (*mi).second;
1255 if (txin.prevout.n < prev.tx->vout.size())
1256 return IsMine(prev.tx->vout[txin.prevout.n]);
1259 return ISMINE_NO;
1262 // Note that this function doesn't distinguish between a 0-valued input,
1263 // and a not-"is mine" (according to the filter) input.
1264 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1267 LOCK(cs_wallet);
1268 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1269 if (mi != mapWallet.end())
1271 const CWalletTx& prev = (*mi).second;
1272 if (txin.prevout.n < prev.tx->vout.size())
1273 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1274 return prev.tx->vout[txin.prevout.n].nValue;
1277 return 0;
1280 isminetype CWallet::IsMine(const CTxOut& txout) const
1282 return ::IsMine(*this, txout.scriptPubKey);
1285 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1287 if (!MoneyRange(txout.nValue))
1288 throw std::runtime_error(std::string(__func__) + ": value out of range");
1289 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1292 bool CWallet::IsChange(const CTxOut& txout) const
1294 // TODO: fix handling of 'change' outputs. The assumption is that any
1295 // payment to a script that is ours, but is not in the address book
1296 // is change. That assumption is likely to break when we implement multisignature
1297 // wallets that return change back into a multi-signature-protected address;
1298 // a better way of identifying which outputs are 'the send' and which are
1299 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1300 // which output, if any, was change).
1301 if (::IsMine(*this, txout.scriptPubKey))
1303 CTxDestination address;
1304 if (!ExtractDestination(txout.scriptPubKey, address))
1305 return true;
1307 LOCK(cs_wallet);
1308 if (!mapAddressBook.count(address))
1309 return true;
1311 return false;
1314 CAmount CWallet::GetChange(const CTxOut& txout) const
1316 if (!MoneyRange(txout.nValue))
1317 throw std::runtime_error(std::string(__func__) + ": value out of range");
1318 return (IsChange(txout) ? txout.nValue : 0);
1321 bool CWallet::IsMine(const CTransaction& tx) const
1323 for (const CTxOut& txout : tx.vout)
1324 if (IsMine(txout))
1325 return true;
1326 return false;
1329 bool CWallet::IsFromMe(const CTransaction& tx) const
1331 return (GetDebit(tx, ISMINE_ALL) > 0);
1334 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1336 CAmount nDebit = 0;
1337 for (const CTxIn& txin : tx.vin)
1339 nDebit += GetDebit(txin, filter);
1340 if (!MoneyRange(nDebit))
1341 throw std::runtime_error(std::string(__func__) + ": value out of range");
1343 return nDebit;
1346 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1348 LOCK(cs_wallet);
1350 for (const CTxIn& txin : tx.vin)
1352 auto mi = mapWallet.find(txin.prevout.hash);
1353 if (mi == mapWallet.end())
1354 return false; // any unknown inputs can't be from us
1356 const CWalletTx& prev = (*mi).second;
1358 if (txin.prevout.n >= prev.tx->vout.size())
1359 return false; // invalid input!
1361 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1362 return false;
1364 return true;
1367 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1369 CAmount nCredit = 0;
1370 for (const CTxOut& txout : tx.vout)
1372 nCredit += GetCredit(txout, filter);
1373 if (!MoneyRange(nCredit))
1374 throw std::runtime_error(std::string(__func__) + ": value out of range");
1376 return nCredit;
1379 CAmount CWallet::GetChange(const CTransaction& tx) const
1381 CAmount nChange = 0;
1382 for (const CTxOut& txout : tx.vout)
1384 nChange += GetChange(txout);
1385 if (!MoneyRange(nChange))
1386 throw std::runtime_error(std::string(__func__) + ": value out of range");
1388 return nChange;
1391 CPubKey CWallet::GenerateNewHDMasterKey()
1393 CKey key;
1394 key.MakeNewKey(true);
1396 int64_t nCreationTime = GetTime();
1397 CKeyMetadata metadata(nCreationTime);
1399 // calculate the pubkey
1400 CPubKey pubkey = key.GetPubKey();
1401 assert(key.VerifyPubKey(pubkey));
1403 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1404 metadata.hdKeypath = "m";
1405 metadata.hdMasterKeyID = pubkey.GetID();
1408 LOCK(cs_wallet);
1410 // mem store the metadata
1411 mapKeyMetadata[pubkey.GetID()] = metadata;
1413 // write the key&metadata to the database
1414 if (!AddKeyPubKey(key, pubkey))
1415 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1418 return pubkey;
1421 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1423 LOCK(cs_wallet);
1424 // store the keyid (hash160) together with
1425 // the child index counter in the database
1426 // as a hdchain object
1427 CHDChain newHdChain;
1428 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1429 newHdChain.masterKeyID = pubkey.GetID();
1430 SetHDChain(newHdChain, false);
1432 return true;
1435 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1437 LOCK(cs_wallet);
1438 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1439 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1441 hdChain = chain;
1442 return true;
1445 bool CWallet::IsHDEnabled() const
1447 return !hdChain.masterKeyID.IsNull();
1450 int64_t CWalletTx::GetTxTime() const
1452 int64_t n = nTimeSmart;
1453 return n ? n : nTimeReceived;
1456 int CWalletTx::GetRequestCount() const
1458 // Returns -1 if it wasn't being tracked
1459 int nRequests = -1;
1461 LOCK(pwallet->cs_wallet);
1462 if (IsCoinBase())
1464 // Generated block
1465 if (!hashUnset())
1467 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1468 if (mi != pwallet->mapRequestCount.end())
1469 nRequests = (*mi).second;
1472 else
1474 // Did anyone request this transaction?
1475 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1476 if (mi != pwallet->mapRequestCount.end())
1478 nRequests = (*mi).second;
1480 // How about the block it's in?
1481 if (nRequests == 0 && !hashUnset())
1483 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1484 if (_mi != pwallet->mapRequestCount.end())
1485 nRequests = (*_mi).second;
1486 else
1487 nRequests = 1; // If it's in someone else's block it must have got out
1492 return nRequests;
1495 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1496 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1498 nFee = 0;
1499 listReceived.clear();
1500 listSent.clear();
1501 strSentAccount = strFromAccount;
1503 // Compute fee:
1504 CAmount nDebit = GetDebit(filter);
1505 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1507 CAmount nValueOut = tx->GetValueOut();
1508 nFee = nDebit - nValueOut;
1511 // Sent/received.
1512 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1514 const CTxOut& txout = tx->vout[i];
1515 isminetype fIsMine = pwallet->IsMine(txout);
1516 // Only need to handle txouts if AT LEAST one of these is true:
1517 // 1) they debit from us (sent)
1518 // 2) the output is to us (received)
1519 if (nDebit > 0)
1521 // Don't report 'change' txouts
1522 if (pwallet->IsChange(txout))
1523 continue;
1525 else if (!(fIsMine & filter))
1526 continue;
1528 // In either case, we need to get the destination address
1529 CTxDestination address;
1531 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1533 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1534 this->GetHash().ToString());
1535 address = CNoDestination();
1538 COutputEntry output = {address, txout.nValue, (int)i};
1540 // If we are debited by the transaction, add the output as a "sent" entry
1541 if (nDebit > 0)
1542 listSent.push_back(output);
1544 // If we are receiving the output, add it as a "received" entry
1545 if (fIsMine & filter)
1546 listReceived.push_back(output);
1552 * Scan active chain for relevant transactions after importing keys. This should
1553 * be called whenever new keys are added to the wallet, with the oldest key
1554 * creation time.
1556 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1557 * returned will be higher than startTime if relevant blocks could not be read.
1559 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1561 AssertLockHeld(cs_main);
1562 AssertLockHeld(cs_wallet);
1564 // Find starting block. May be null if nCreateTime is greater than the
1565 // highest blockchain timestamp, in which case there is nothing that needs
1566 // to be scanned.
1567 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1568 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1570 if (startBlock) {
1571 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
1572 if (failedBlock) {
1573 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1576 return startTime;
1580 * Scan the block chain (starting in pindexStart) for transactions
1581 * from or to us. If fUpdate is true, found transactions that already
1582 * exist in the wallet will be updated.
1584 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1585 * possible (due to pruning or corruption), returns pointer to the most recent
1586 * block that could not be scanned.
1588 * If pindexStop is not a nullptr, the scan will stop at the block-index
1589 * defined by pindexStop
1591 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
1593 int64_t nNow = GetTime();
1594 const CChainParams& chainParams = Params();
1596 if (pindexStop) {
1597 assert(pindexStop->nHeight >= pindexStart->nHeight);
1600 CBlockIndex* pindex = pindexStart;
1601 CBlockIndex* ret = nullptr;
1603 LOCK2(cs_main, cs_wallet);
1604 fAbortRescan = false;
1605 fScanningWallet = true;
1607 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1608 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1609 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1610 while (pindex && !fAbortRescan)
1612 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1613 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1614 if (GetTime() >= nNow + 60) {
1615 nNow = GetTime();
1616 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1619 CBlock block;
1620 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1621 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1622 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1624 } else {
1625 ret = pindex;
1627 if (pindex == pindexStop) {
1628 break;
1630 pindex = chainActive.Next(pindex);
1632 if (pindex && fAbortRescan) {
1633 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1635 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1637 fScanningWallet = false;
1639 return ret;
1642 void CWallet::ReacceptWalletTransactions()
1644 // If transactions aren't being broadcasted, don't let them into local mempool either
1645 if (!fBroadcastTransactions)
1646 return;
1647 LOCK2(cs_main, cs_wallet);
1648 std::map<int64_t, CWalletTx*> mapSorted;
1650 // Sort pending wallet transactions based on their initial wallet insertion order
1651 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1653 const uint256& wtxid = item.first;
1654 CWalletTx& wtx = item.second;
1655 assert(wtx.GetHash() == wtxid);
1657 int nDepth = wtx.GetDepthInMainChain();
1659 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1660 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1664 // Try to add wallet transactions to memory pool
1665 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1667 CWalletTx& wtx = *(item.second);
1669 LOCK(mempool.cs);
1670 CValidationState state;
1671 wtx.AcceptToMemoryPool(maxTxFee, state);
1675 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1677 assert(pwallet->GetBroadcastTransactions());
1678 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1680 CValidationState state;
1681 /* GetDepthInMainChain already catches known conflicts. */
1682 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1683 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1684 if (connman) {
1685 CInv inv(MSG_TX, GetHash());
1686 connman->ForEachNode([&inv](CNode* pnode)
1688 pnode->PushInventory(inv);
1690 return true;
1694 return false;
1697 std::set<uint256> CWalletTx::GetConflicts() const
1699 std::set<uint256> result;
1700 if (pwallet != nullptr)
1702 uint256 myHash = GetHash();
1703 result = pwallet->GetConflicts(myHash);
1704 result.erase(myHash);
1706 return result;
1709 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1711 if (tx->vin.empty())
1712 return 0;
1714 CAmount debit = 0;
1715 if(filter & ISMINE_SPENDABLE)
1717 if (fDebitCached)
1718 debit += nDebitCached;
1719 else
1721 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1722 fDebitCached = true;
1723 debit += nDebitCached;
1726 if(filter & ISMINE_WATCH_ONLY)
1728 if(fWatchDebitCached)
1729 debit += nWatchDebitCached;
1730 else
1732 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1733 fWatchDebitCached = true;
1734 debit += nWatchDebitCached;
1737 return debit;
1740 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1742 // Must wait until coinbase is safely deep enough in the chain before valuing it
1743 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1744 return 0;
1746 CAmount credit = 0;
1747 if (filter & ISMINE_SPENDABLE)
1749 // GetBalance can assume transactions in mapWallet won't change
1750 if (fCreditCached)
1751 credit += nCreditCached;
1752 else
1754 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1755 fCreditCached = true;
1756 credit += nCreditCached;
1759 if (filter & ISMINE_WATCH_ONLY)
1761 if (fWatchCreditCached)
1762 credit += nWatchCreditCached;
1763 else
1765 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1766 fWatchCreditCached = true;
1767 credit += nWatchCreditCached;
1770 return credit;
1773 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1775 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1777 if (fUseCache && fImmatureCreditCached)
1778 return nImmatureCreditCached;
1779 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1780 fImmatureCreditCached = true;
1781 return nImmatureCreditCached;
1784 return 0;
1787 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1789 if (pwallet == nullptr)
1790 return 0;
1792 // Must wait until coinbase is safely deep enough in the chain before valuing it
1793 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1794 return 0;
1796 if (fUseCache && fAvailableCreditCached)
1797 return nAvailableCreditCached;
1799 CAmount nCredit = 0;
1800 uint256 hashTx = GetHash();
1801 for (unsigned int i = 0; i < tx->vout.size(); i++)
1803 if (!pwallet->IsSpent(hashTx, i))
1805 const CTxOut &txout = tx->vout[i];
1806 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1807 if (!MoneyRange(nCredit))
1808 throw std::runtime_error(std::string(__func__) + " : value out of range");
1812 nAvailableCreditCached = nCredit;
1813 fAvailableCreditCached = true;
1814 return nCredit;
1817 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1819 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1821 if (fUseCache && fImmatureWatchCreditCached)
1822 return nImmatureWatchCreditCached;
1823 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1824 fImmatureWatchCreditCached = true;
1825 return nImmatureWatchCreditCached;
1828 return 0;
1831 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1833 if (pwallet == nullptr)
1834 return 0;
1836 // Must wait until coinbase is safely deep enough in the chain before valuing it
1837 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1838 return 0;
1840 if (fUseCache && fAvailableWatchCreditCached)
1841 return nAvailableWatchCreditCached;
1843 CAmount nCredit = 0;
1844 for (unsigned int i = 0; i < tx->vout.size(); i++)
1846 if (!pwallet->IsSpent(GetHash(), i))
1848 const CTxOut &txout = tx->vout[i];
1849 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1850 if (!MoneyRange(nCredit))
1851 throw std::runtime_error(std::string(__func__) + ": value out of range");
1855 nAvailableWatchCreditCached = nCredit;
1856 fAvailableWatchCreditCached = true;
1857 return nCredit;
1860 CAmount CWalletTx::GetChange() const
1862 if (fChangeCached)
1863 return nChangeCached;
1864 nChangeCached = pwallet->GetChange(*this);
1865 fChangeCached = true;
1866 return nChangeCached;
1869 bool CWalletTx::InMempool() const
1871 LOCK(mempool.cs);
1872 return mempool.exists(GetHash());
1875 bool CWalletTx::IsTrusted() const
1877 // Quick answer in most cases
1878 if (!CheckFinalTx(*this))
1879 return false;
1880 int nDepth = GetDepthInMainChain();
1881 if (nDepth >= 1)
1882 return true;
1883 if (nDepth < 0)
1884 return false;
1885 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1886 return false;
1888 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1889 if (!InMempool())
1890 return false;
1892 // Trusted if all inputs are from us and are in the mempool:
1893 for (const CTxIn& txin : tx->vin)
1895 // Transactions not sent by us: not trusted
1896 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1897 if (parent == nullptr)
1898 return false;
1899 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1900 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1901 return false;
1903 return true;
1906 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1908 CMutableTransaction tx1 = *this->tx;
1909 CMutableTransaction tx2 = *_tx.tx;
1910 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1911 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1912 return CTransaction(tx1) == CTransaction(tx2);
1915 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1917 std::vector<uint256> result;
1919 LOCK(cs_wallet);
1921 // Sort them in chronological order
1922 std::multimap<unsigned int, CWalletTx*> mapSorted;
1923 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1925 CWalletTx& wtx = item.second;
1926 // Don't rebroadcast if newer than nTime:
1927 if (wtx.nTimeReceived > nTime)
1928 continue;
1929 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1931 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1933 CWalletTx& wtx = *item.second;
1934 if (wtx.RelayWalletTransaction(connman))
1935 result.push_back(wtx.GetHash());
1937 return result;
1940 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1942 // Do this infrequently and randomly to avoid giving away
1943 // that these are our transactions.
1944 if (GetTime() < nNextResend || !fBroadcastTransactions)
1945 return;
1946 bool fFirst = (nNextResend == 0);
1947 nNextResend = GetTime() + GetRand(30 * 60);
1948 if (fFirst)
1949 return;
1951 // Only do it if there's been a new block since last time
1952 if (nBestBlockTime < nLastResend)
1953 return;
1954 nLastResend = GetTime();
1956 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1957 // block was found:
1958 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1959 if (!relayed.empty())
1960 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1963 /** @} */ // end of mapWallet
1968 /** @defgroup Actions
1970 * @{
1974 CAmount CWallet::GetBalance() const
1976 CAmount nTotal = 0;
1978 LOCK2(cs_main, cs_wallet);
1979 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1981 const CWalletTx* pcoin = &(*it).second;
1982 if (pcoin->IsTrusted())
1983 nTotal += pcoin->GetAvailableCredit();
1987 return nTotal;
1990 CAmount CWallet::GetUnconfirmedBalance() const
1992 CAmount nTotal = 0;
1994 LOCK2(cs_main, cs_wallet);
1995 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1997 const CWalletTx* pcoin = &(*it).second;
1998 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1999 nTotal += pcoin->GetAvailableCredit();
2002 return nTotal;
2005 CAmount CWallet::GetImmatureBalance() const
2007 CAmount nTotal = 0;
2009 LOCK2(cs_main, cs_wallet);
2010 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2012 const CWalletTx* pcoin = &(*it).second;
2013 nTotal += pcoin->GetImmatureCredit();
2016 return nTotal;
2019 CAmount CWallet::GetWatchOnlyBalance() const
2021 CAmount nTotal = 0;
2023 LOCK2(cs_main, cs_wallet);
2024 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2026 const CWalletTx* pcoin = &(*it).second;
2027 if (pcoin->IsTrusted())
2028 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2032 return nTotal;
2035 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
2037 CAmount nTotal = 0;
2039 LOCK2(cs_main, cs_wallet);
2040 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2042 const CWalletTx* pcoin = &(*it).second;
2043 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2044 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2047 return nTotal;
2050 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2052 CAmount nTotal = 0;
2054 LOCK2(cs_main, cs_wallet);
2055 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2057 const CWalletTx* pcoin = &(*it).second;
2058 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2061 return nTotal;
2064 // Calculate total balance in a different way from GetBalance. The biggest
2065 // difference is that GetBalance sums up all unspent TxOuts paying to the
2066 // wallet, while this sums up both spent and unspent TxOuts paying to the
2067 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2068 // also has fewer restrictions on which unconfirmed transactions are considered
2069 // trusted.
2070 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2072 LOCK2(cs_main, cs_wallet);
2074 CAmount balance = 0;
2075 for (const auto& entry : mapWallet) {
2076 const CWalletTx& wtx = entry.second;
2077 const int depth = wtx.GetDepthInMainChain();
2078 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2079 continue;
2082 // Loop through tx outputs and add incoming payments. For outgoing txs,
2083 // treat change outputs specially, as part of the amount debited.
2084 CAmount debit = wtx.GetDebit(filter);
2085 const bool outgoing = debit > 0;
2086 for (const CTxOut& out : wtx.tx->vout) {
2087 if (outgoing && IsChange(out)) {
2088 debit -= out.nValue;
2089 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2090 balance += out.nValue;
2094 // For outgoing txs, subtract amount debited.
2095 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2096 balance -= debit;
2100 if (account) {
2101 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2104 return balance;
2107 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2109 LOCK2(cs_main, cs_wallet);
2111 CAmount balance = 0;
2112 std::vector<COutput> vCoins;
2113 AvailableCoins(vCoins, true, coinControl);
2114 for (const COutput& out : vCoins) {
2115 if (out.fSpendable) {
2116 balance += out.tx->tx->vout[out.i].nValue;
2119 return balance;
2122 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
2124 vCoins.clear();
2127 LOCK2(cs_main, cs_wallet);
2129 CAmount nTotal = 0;
2131 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2133 const uint256& wtxid = it->first;
2134 const CWalletTx* pcoin = &(*it).second;
2136 if (!CheckFinalTx(*pcoin))
2137 continue;
2139 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2140 continue;
2142 int nDepth = pcoin->GetDepthInMainChain();
2143 if (nDepth < 0)
2144 continue;
2146 // We should not consider coins which aren't at least in our mempool
2147 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2148 if (nDepth == 0 && !pcoin->InMempool())
2149 continue;
2151 bool safeTx = pcoin->IsTrusted();
2153 // We should not consider coins from transactions that are replacing
2154 // other transactions.
2156 // Example: There is a transaction A which is replaced by bumpfee
2157 // transaction B. In this case, we want to prevent creation of
2158 // a transaction B' which spends an output of B.
2160 // Reason: If transaction A were initially confirmed, transactions B
2161 // and B' would no longer be valid, so the user would have to create
2162 // a new transaction C to replace B'. However, in the case of a
2163 // one-block reorg, transactions B' and C might BOTH be accepted,
2164 // when the user only wanted one of them. Specifically, there could
2165 // be a 1-block reorg away from the chain where transactions A and C
2166 // were accepted to another chain where B, B', and C were all
2167 // accepted.
2168 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2169 safeTx = false;
2172 // Similarly, we should not consider coins from transactions that
2173 // have been replaced. In the example above, we would want to prevent
2174 // creation of a transaction A' spending an output of A, because if
2175 // transaction B were initially confirmed, conflicting with A and
2176 // A', we wouldn't want to the user to create a transaction D
2177 // intending to replace A', but potentially resulting in a scenario
2178 // where A, A', and D could all be accepted (instead of just B and
2179 // D, or just A and A' like the user would want).
2180 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2181 safeTx = false;
2184 if (fOnlySafe && !safeTx) {
2185 continue;
2188 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2189 continue;
2191 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2192 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2193 continue;
2195 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2196 continue;
2198 if (IsLockedCoin((*it).first, i))
2199 continue;
2201 if (IsSpent(wtxid, i))
2202 continue;
2204 isminetype mine = IsMine(pcoin->tx->vout[i]);
2206 if (mine == ISMINE_NO) {
2207 continue;
2210 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2211 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2213 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2215 // Checks the sum amount of all UTXO's.
2216 if (nMinimumSumAmount != MAX_MONEY) {
2217 nTotal += pcoin->tx->vout[i].nValue;
2219 if (nTotal >= nMinimumSumAmount) {
2220 return;
2224 // Checks the maximum number of UTXO's.
2225 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2226 return;
2233 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2235 // TODO: Add AssertLockHeld(cs_wallet) here.
2237 // Because the return value from this function contains pointers to
2238 // CWalletTx objects, callers to this function really should acquire the
2239 // cs_wallet lock before calling it. However, the current caller doesn't
2240 // acquire this lock yet. There was an attempt to add the missing lock in
2241 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2242 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2243 // avoid adding some extra complexity to the Qt code.
2245 std::map<CTxDestination, std::vector<COutput>> result;
2247 std::vector<COutput> availableCoins;
2248 AvailableCoins(availableCoins);
2250 LOCK2(cs_main, cs_wallet);
2251 for (auto& coin : availableCoins) {
2252 CTxDestination address;
2253 if (coin.fSpendable &&
2254 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2255 result[address].emplace_back(std::move(coin));
2259 std::vector<COutPoint> lockedCoins;
2260 ListLockedCoins(lockedCoins);
2261 for (const auto& output : lockedCoins) {
2262 auto it = mapWallet.find(output.hash);
2263 if (it != mapWallet.end()) {
2264 int depth = it->second.GetDepthInMainChain();
2265 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2266 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2267 CTxDestination address;
2268 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2269 result[address].emplace_back(
2270 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2276 return result;
2279 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2281 const CTransaction* ptx = &tx;
2282 int n = output;
2283 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2284 const COutPoint& prevout = ptx->vin[0].prevout;
2285 auto it = mapWallet.find(prevout.hash);
2286 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2287 !IsMine(it->second.tx->vout[prevout.n])) {
2288 break;
2290 ptx = it->second.tx.get();
2291 n = prevout.n;
2293 return ptx->vout[n];
2296 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2297 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2299 std::vector<char> vfIncluded;
2301 vfBest.assign(vValue.size(), true);
2302 nBest = nTotalLower;
2304 FastRandomContext insecure_rand;
2306 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2308 vfIncluded.assign(vValue.size(), false);
2309 CAmount nTotal = 0;
2310 bool fReachedTarget = false;
2311 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2313 for (unsigned int i = 0; i < vValue.size(); i++)
2315 //The solver here uses a randomized algorithm,
2316 //the randomness serves no real security purpose but is just
2317 //needed to prevent degenerate behavior and it is important
2318 //that the rng is fast. We do not use a constant random sequence,
2319 //because there may be some privacy improvement by making
2320 //the selection random.
2321 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2323 nTotal += vValue[i].txout.nValue;
2324 vfIncluded[i] = true;
2325 if (nTotal >= nTargetValue)
2327 fReachedTarget = true;
2328 if (nTotal < nBest)
2330 nBest = nTotal;
2331 vfBest = vfIncluded;
2333 nTotal -= vValue[i].txout.nValue;
2334 vfIncluded[i] = false;
2342 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2343 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2345 setCoinsRet.clear();
2346 nValueRet = 0;
2348 // List of values less than target
2349 boost::optional<CInputCoin> coinLowestLarger;
2350 std::vector<CInputCoin> vValue;
2351 CAmount nTotalLower = 0;
2353 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2355 for (const COutput &output : vCoins)
2357 if (!output.fSpendable)
2358 continue;
2360 const CWalletTx *pcoin = output.tx;
2362 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2363 continue;
2365 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2366 continue;
2368 int i = output.i;
2370 CInputCoin coin = CInputCoin(pcoin, i);
2372 if (coin.txout.nValue == nTargetValue)
2374 setCoinsRet.insert(coin);
2375 nValueRet += coin.txout.nValue;
2376 return true;
2378 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2380 vValue.push_back(coin);
2381 nTotalLower += coin.txout.nValue;
2383 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2385 coinLowestLarger = coin;
2389 if (nTotalLower == nTargetValue)
2391 for (const auto& input : vValue)
2393 setCoinsRet.insert(input);
2394 nValueRet += input.txout.nValue;
2396 return true;
2399 if (nTotalLower < nTargetValue)
2401 if (!coinLowestLarger)
2402 return false;
2403 setCoinsRet.insert(coinLowestLarger.get());
2404 nValueRet += coinLowestLarger->txout.nValue;
2405 return true;
2408 // Solve subset sum by stochastic approximation
2409 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2410 std::reverse(vValue.begin(), vValue.end());
2411 std::vector<char> vfBest;
2412 CAmount nBest;
2414 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2415 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2416 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2418 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2419 // or the next bigger coin is closer), return the bigger coin
2420 if (coinLowestLarger &&
2421 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2423 setCoinsRet.insert(coinLowestLarger.get());
2424 nValueRet += coinLowestLarger->txout.nValue;
2426 else {
2427 for (unsigned int i = 0; i < vValue.size(); i++)
2428 if (vfBest[i])
2430 setCoinsRet.insert(vValue[i]);
2431 nValueRet += vValue[i].txout.nValue;
2434 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2435 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2436 for (unsigned int i = 0; i < vValue.size(); i++) {
2437 if (vfBest[i]) {
2438 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2441 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2445 return true;
2448 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2450 std::vector<COutput> vCoins(vAvailableCoins);
2452 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2453 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2455 for (const COutput& out : vCoins)
2457 if (!out.fSpendable)
2458 continue;
2459 nValueRet += out.tx->tx->vout[out.i].nValue;
2460 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2462 return (nValueRet >= nTargetValue);
2465 // calculate value from preset inputs and store them
2466 std::set<CInputCoin> setPresetCoins;
2467 CAmount nValueFromPresetInputs = 0;
2469 std::vector<COutPoint> vPresetInputs;
2470 if (coinControl)
2471 coinControl->ListSelected(vPresetInputs);
2472 for (const COutPoint& outpoint : vPresetInputs)
2474 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2475 if (it != mapWallet.end())
2477 const CWalletTx* pcoin = &it->second;
2478 // Clearly invalid input, fail
2479 if (pcoin->tx->vout.size() <= outpoint.n)
2480 return false;
2481 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2482 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2483 } else
2484 return false; // TODO: Allow non-wallet inputs
2487 // remove preset inputs from vCoins
2488 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2490 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2491 it = vCoins.erase(it);
2492 else
2493 ++it;
2496 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2497 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2499 bool res = nTargetValue <= nValueFromPresetInputs ||
2500 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2501 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2502 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2503 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2504 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2505 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2506 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2508 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2509 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2511 // add preset inputs to the total value selected
2512 nValueRet += nValueFromPresetInputs;
2514 return res;
2517 bool CWallet::SignTransaction(CMutableTransaction &tx)
2519 AssertLockHeld(cs_wallet); // mapWallet
2521 // sign the new tx
2522 CTransaction txNewConst(tx);
2523 int nIn = 0;
2524 for (const auto& input : tx.vin) {
2525 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2526 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2527 return false;
2529 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2530 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2531 SignatureData sigdata;
2532 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2533 return false;
2535 UpdateTransaction(tx, nIn, sigdata);
2536 nIn++;
2538 return true;
2541 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2543 std::vector<CRecipient> vecSend;
2545 // Turn the txout set into a CRecipient vector
2546 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2548 const CTxOut& txOut = tx.vout[idx];
2549 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2550 vecSend.push_back(recipient);
2553 coinControl.fAllowOtherInputs = true;
2555 for (const CTxIn& txin : tx.vin)
2556 coinControl.Select(txin.prevout);
2558 CReserveKey reservekey(this);
2559 CWalletTx wtx;
2560 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2561 return false;
2564 if (nChangePosInOut != -1) {
2565 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2566 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2567 // so just remove the key from the keypool here.
2568 reservekey.KeepKey();
2571 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2572 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2573 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2575 // Add new txins (keeping original txin scriptSig/order)
2576 for (const CTxIn& txin : wtx.tx->vin)
2578 if (!coinControl.IsSelected(txin.prevout))
2580 tx.vin.push_back(txin);
2582 if (lockUnspents)
2584 LOCK2(cs_main, cs_wallet);
2585 LockCoin(txin.prevout);
2591 return true;
2594 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2595 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2597 CAmount nValue = 0;
2598 int nChangePosRequest = nChangePosInOut;
2599 unsigned int nSubtractFeeFromAmount = 0;
2600 for (const auto& recipient : vecSend)
2602 if (nValue < 0 || recipient.nAmount < 0)
2604 strFailReason = _("Transaction amounts must not be negative");
2605 return false;
2607 nValue += recipient.nAmount;
2609 if (recipient.fSubtractFeeFromAmount)
2610 nSubtractFeeFromAmount++;
2612 if (vecSend.empty())
2614 strFailReason = _("Transaction must have at least one recipient");
2615 return false;
2618 wtxNew.fTimeReceivedIsTxTime = true;
2619 wtxNew.BindWallet(this);
2620 CMutableTransaction txNew;
2622 // Discourage fee sniping.
2624 // For a large miner the value of the transactions in the best block and
2625 // the mempool can exceed the cost of deliberately attempting to mine two
2626 // blocks to orphan the current best block. By setting nLockTime such that
2627 // only the next block can include the transaction, we discourage this
2628 // practice as the height restricted and limited blocksize gives miners
2629 // considering fee sniping fewer options for pulling off this attack.
2631 // A simple way to think about this is from the wallet's point of view we
2632 // always want the blockchain to move forward. By setting nLockTime this
2633 // way we're basically making the statement that we only want this
2634 // transaction to appear in the next block; we don't want to potentially
2635 // encourage reorgs by allowing transactions to appear at lower heights
2636 // than the next block in forks of the best chain.
2638 // Of course, the subsidy is high enough, and transaction volume low
2639 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2640 // now we ensure code won't be written that makes assumptions about
2641 // nLockTime that preclude a fix later.
2642 txNew.nLockTime = chainActive.Height();
2644 // Secondly occasionally randomly pick a nLockTime even further back, so
2645 // that transactions that are delayed after signing for whatever reason,
2646 // e.g. high-latency mix networks and some CoinJoin implementations, have
2647 // better privacy.
2648 if (GetRandInt(10) == 0)
2649 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2651 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2652 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2653 FeeCalculation feeCalc;
2654 CAmount nFeeNeeded;
2655 unsigned int nBytes;
2657 std::set<CInputCoin> setCoins;
2658 LOCK2(cs_main, cs_wallet);
2660 std::vector<COutput> vAvailableCoins;
2661 AvailableCoins(vAvailableCoins, true, &coin_control);
2663 // Create change script that will be used if we need change
2664 // TODO: pass in scriptChange instead of reservekey so
2665 // change transaction isn't always pay-to-bitcoin-address
2666 CScript scriptChange;
2668 // coin control: send change to custom address
2669 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2670 scriptChange = GetScriptForDestination(coin_control.destChange);
2671 } else { // no coin control: send change to newly generated address
2672 // Note: We use a new key here to keep it from being obvious which side is the change.
2673 // The drawback is that by not reusing a previous key, the change may be lost if a
2674 // backup is restored, if the backup doesn't have the new private key for the change.
2675 // If we reused the old key, it would be possible to add code to look for and
2676 // rediscover unknown transactions that were written with keys of ours to recover
2677 // post-backup change.
2679 // Reserve a new key pair from key pool
2680 CPubKey vchPubKey;
2681 bool ret;
2682 ret = reservekey.GetReservedKey(vchPubKey, true);
2683 if (!ret)
2685 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2686 return false;
2689 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2691 CTxOut change_prototype_txout(0, scriptChange);
2692 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2694 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2695 nFeeRet = 0;
2696 bool pick_new_inputs = true;
2697 CAmount nValueIn = 0;
2698 // Start with no fee and loop until there is enough fee
2699 while (true)
2701 nChangePosInOut = nChangePosRequest;
2702 txNew.vin.clear();
2703 txNew.vout.clear();
2704 wtxNew.fFromMe = true;
2705 bool fFirst = true;
2707 CAmount nValueToSelect = nValue;
2708 if (nSubtractFeeFromAmount == 0)
2709 nValueToSelect += nFeeRet;
2710 // vouts to the payees
2711 for (const auto& recipient : vecSend)
2713 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2715 if (recipient.fSubtractFeeFromAmount)
2717 assert(nSubtractFeeFromAmount != 0);
2718 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2720 if (fFirst) // first receiver pays the remainder not divisible by output count
2722 fFirst = false;
2723 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2727 if (IsDust(txout, ::dustRelayFee))
2729 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2731 if (txout.nValue < 0)
2732 strFailReason = _("The transaction amount is too small to pay the fee");
2733 else
2734 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2736 else
2737 strFailReason = _("Transaction amount too small");
2738 return false;
2740 txNew.vout.push_back(txout);
2743 // Choose coins to use
2744 if (pick_new_inputs) {
2745 nValueIn = 0;
2746 setCoins.clear();
2747 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2749 strFailReason = _("Insufficient funds");
2750 return false;
2754 const CAmount nChange = nValueIn - nValueToSelect;
2756 if (nChange > 0)
2758 // Fill a vout to ourself
2759 CTxOut newTxOut(nChange, scriptChange);
2761 // Never create dust outputs; if we would, just
2762 // add the dust to the fee.
2763 if (IsDust(newTxOut, discard_rate))
2765 nChangePosInOut = -1;
2766 nFeeRet += nChange;
2768 else
2770 if (nChangePosInOut == -1)
2772 // Insert change txn at random position:
2773 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2775 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2777 strFailReason = _("Change index out of range");
2778 return false;
2781 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2782 txNew.vout.insert(position, newTxOut);
2784 } else {
2785 nChangePosInOut = -1;
2788 // Fill vin
2790 // Note how the sequence number is set to non-maxint so that
2791 // the nLockTime set above actually works.
2793 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2794 // we use the highest possible value in that range (maxint-2)
2795 // to avoid conflicting with other possible uses of nSequence,
2796 // and in the spirit of "smallest possible change from prior
2797 // behavior."
2798 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2799 for (const auto& coin : setCoins)
2800 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2801 nSequence));
2803 // Fill in dummy signatures for fee calculation.
2804 if (!DummySignTx(txNew, setCoins)) {
2805 strFailReason = _("Signing transaction failed");
2806 return false;
2809 nBytes = GetVirtualTransactionSize(txNew);
2811 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2812 for (auto& vin : txNew.vin) {
2813 vin.scriptSig = CScript();
2814 vin.scriptWitness.SetNull();
2817 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2819 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2820 // because we must be at the maximum allowed fee.
2821 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2823 strFailReason = _("Transaction too large for fee policy");
2824 return false;
2827 if (nFeeRet >= nFeeNeeded) {
2828 // Reduce fee to only the needed amount if possible. This
2829 // prevents potential overpayment in fees if the coins
2830 // selected to meet nFeeNeeded result in a transaction that
2831 // requires less fee than the prior iteration.
2833 // If we have no change and a big enough excess fee, then
2834 // try to construct transaction again only without picking
2835 // new inputs. We now know we only need the smaller fee
2836 // (because of reduced tx size) and so we should add a
2837 // change output. Only try this once.
2838 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2839 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2840 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2841 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2842 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2843 pick_new_inputs = false;
2844 nFeeRet = fee_needed_with_change;
2845 continue;
2849 // If we have change output already, just increase it
2850 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2851 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2852 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2853 change_position->nValue += extraFeePaid;
2854 nFeeRet -= extraFeePaid;
2856 break; // Done, enough fee included.
2858 else if (!pick_new_inputs) {
2859 // This shouldn't happen, we should have had enough excess
2860 // fee to pay for the new output and still meet nFeeNeeded
2861 // Or we should have just subtracted fee from recipients and
2862 // nFeeNeeded should not have changed
2863 strFailReason = _("Transaction fee and change calculation failed");
2864 return false;
2867 // Try to reduce change to include necessary fee
2868 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2869 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2870 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2871 // Only reduce change if remaining amount is still a large enough output.
2872 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2873 change_position->nValue -= additionalFeeNeeded;
2874 nFeeRet += additionalFeeNeeded;
2875 break; // Done, able to increase fee from change
2879 // If subtracting fee from recipients, we now know what fee we
2880 // need to subtract, we have no reason to reselect inputs
2881 if (nSubtractFeeFromAmount > 0) {
2882 pick_new_inputs = false;
2885 // Include more fee and try again.
2886 nFeeRet = nFeeNeeded;
2887 continue;
2891 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2893 if (sign)
2895 CTransaction txNewConst(txNew);
2896 int nIn = 0;
2897 for (const auto& coin : setCoins)
2899 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2900 SignatureData sigdata;
2902 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2904 strFailReason = _("Signing transaction failed");
2905 return false;
2906 } else {
2907 UpdateTransaction(txNew, nIn, sigdata);
2910 nIn++;
2914 // Embed the constructed transaction data in wtxNew.
2915 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2917 // Limit size
2918 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2920 strFailReason = _("Transaction too large");
2921 return false;
2925 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2926 // Lastly, ensure this tx will pass the mempool's chain limits
2927 LockPoints lp;
2928 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2929 CTxMemPool::setEntries setAncestors;
2930 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2931 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2932 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2933 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2934 std::string errString;
2935 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2936 strFailReason = _("Transaction has too long of a mempool chain");
2937 return false;
2941 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",
2942 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2943 feeCalc.est.pass.start, feeCalc.est.pass.end,
2944 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2945 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2946 feeCalc.est.fail.start, feeCalc.est.fail.end,
2947 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2948 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2949 return true;
2953 * Call after CreateTransaction unless you want to abort
2955 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2958 LOCK2(cs_main, cs_wallet);
2959 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2961 // Take key pair from key pool so it won't be used again
2962 reservekey.KeepKey();
2964 // Add tx to wallet, because if it has change it's also ours,
2965 // otherwise just for transaction history.
2966 AddToWallet(wtxNew);
2968 // Notify that old coins are spent
2969 for (const CTxIn& txin : wtxNew.tx->vin)
2971 CWalletTx &coin = mapWallet[txin.prevout.hash];
2972 coin.BindWallet(this);
2973 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2977 // Track how many getdata requests our transaction gets
2978 mapRequestCount[wtxNew.GetHash()] = 0;
2980 if (fBroadcastTransactions)
2982 // Broadcast
2983 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2984 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2985 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2986 } else {
2987 wtxNew.RelayWalletTransaction(connman);
2991 return true;
2994 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2995 CWalletDB walletdb(*dbw);
2996 return walletdb.ListAccountCreditDebit(strAccount, entries);
2999 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
3001 CWalletDB walletdb(*dbw);
3003 return AddAccountingEntry(acentry, &walletdb);
3006 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
3008 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
3009 return false;
3012 laccentries.push_back(acentry);
3013 CAccountingEntry & entry = laccentries.back();
3014 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
3016 return true;
3019 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
3021 LOCK2(cs_main, cs_wallet);
3023 fFirstRunRet = false;
3024 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
3025 if (nLoadWalletRet == DB_NEED_REWRITE)
3027 if (dbw->Rewrite("\x04pool"))
3029 setInternalKeyPool.clear();
3030 setExternalKeyPool.clear();
3031 m_pool_key_to_index.clear();
3032 // Note: can't top-up keypool here, because wallet is locked.
3033 // User will be prompted to unlock wallet the next operation
3034 // that requires a new key.
3038 // This wallet is in its first run if all of these are empty
3039 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3041 if (nLoadWalletRet != DB_LOAD_OK)
3042 return nLoadWalletRet;
3044 uiInterface.LoadWallet(this);
3046 return DB_LOAD_OK;
3049 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3051 AssertLockHeld(cs_wallet); // mapWallet
3052 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3053 for (uint256 hash : vHashOut)
3054 mapWallet.erase(hash);
3056 if (nZapSelectTxRet == DB_NEED_REWRITE)
3058 if (dbw->Rewrite("\x04pool"))
3060 setInternalKeyPool.clear();
3061 setExternalKeyPool.clear();
3062 m_pool_key_to_index.clear();
3063 // Note: can't top-up keypool here, because wallet is locked.
3064 // User will be prompted to unlock wallet the next operation
3065 // that requires a new key.
3069 if (nZapSelectTxRet != DB_LOAD_OK)
3070 return nZapSelectTxRet;
3072 MarkDirty();
3074 return DB_LOAD_OK;
3078 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3080 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3081 if (nZapWalletTxRet == DB_NEED_REWRITE)
3083 if (dbw->Rewrite("\x04pool"))
3085 LOCK(cs_wallet);
3086 setInternalKeyPool.clear();
3087 setExternalKeyPool.clear();
3088 m_pool_key_to_index.clear();
3089 // Note: can't top-up keypool here, because wallet is locked.
3090 // User will be prompted to unlock wallet the next operation
3091 // that requires a new key.
3095 if (nZapWalletTxRet != DB_LOAD_OK)
3096 return nZapWalletTxRet;
3098 return DB_LOAD_OK;
3102 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3104 bool fUpdated = false;
3106 LOCK(cs_wallet); // mapAddressBook
3107 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3108 fUpdated = mi != mapAddressBook.end();
3109 mapAddressBook[address].name = strName;
3110 if (!strPurpose.empty()) /* update purpose only if requested */
3111 mapAddressBook[address].purpose = strPurpose;
3113 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3114 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3115 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3116 return false;
3117 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3120 bool CWallet::DelAddressBook(const CTxDestination& address)
3123 LOCK(cs_wallet); // mapAddressBook
3125 // Delete destdata tuples associated with address
3126 std::string strAddress = EncodeDestination(address);
3127 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3129 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3131 mapAddressBook.erase(address);
3134 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3136 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3137 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3140 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3142 CTxDestination address;
3143 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3144 auto mi = mapAddressBook.find(address);
3145 if (mi != mapAddressBook.end()) {
3146 return mi->second.name;
3149 // A scriptPubKey that doesn't have an entry in the address book is
3150 // associated with the default account ("").
3151 const static std::string DEFAULT_ACCOUNT_NAME;
3152 return DEFAULT_ACCOUNT_NAME;
3156 * Mark old keypool keys as used,
3157 * and generate all new keys
3159 bool CWallet::NewKeyPool()
3162 LOCK(cs_wallet);
3163 CWalletDB walletdb(*dbw);
3165 for (int64_t nIndex : setInternalKeyPool) {
3166 walletdb.ErasePool(nIndex);
3168 setInternalKeyPool.clear();
3170 for (int64_t nIndex : setExternalKeyPool) {
3171 walletdb.ErasePool(nIndex);
3173 setExternalKeyPool.clear();
3175 m_pool_key_to_index.clear();
3177 if (!TopUpKeyPool()) {
3178 return false;
3180 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3182 return true;
3185 size_t CWallet::KeypoolCountExternalKeys()
3187 AssertLockHeld(cs_wallet); // setExternalKeyPool
3188 return setExternalKeyPool.size();
3191 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3193 AssertLockHeld(cs_wallet);
3194 if (keypool.fInternal) {
3195 setInternalKeyPool.insert(nIndex);
3196 } else {
3197 setExternalKeyPool.insert(nIndex);
3199 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3200 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3202 // If no metadata exists yet, create a default with the pool key's
3203 // creation time. Note that this may be overwritten by actually
3204 // stored metadata for that key later, which is fine.
3205 CKeyID keyid = keypool.vchPubKey.GetID();
3206 if (mapKeyMetadata.count(keyid) == 0)
3207 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3210 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3213 LOCK(cs_wallet);
3215 if (IsLocked())
3216 return false;
3218 // Top up key pool
3219 unsigned int nTargetSize;
3220 if (kpSize > 0)
3221 nTargetSize = kpSize;
3222 else
3223 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3225 // count amount of available keys (internal, external)
3226 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3227 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3228 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3230 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3232 // don't create extra internal keys
3233 missingInternal = 0;
3235 bool internal = false;
3236 CWalletDB walletdb(*dbw);
3237 for (int64_t i = missingInternal + missingExternal; i--;)
3239 if (i < missingInternal) {
3240 internal = true;
3243 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3244 int64_t index = ++m_max_keypool_index;
3246 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3247 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3248 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3251 if (internal) {
3252 setInternalKeyPool.insert(index);
3253 } else {
3254 setExternalKeyPool.insert(index);
3256 m_pool_key_to_index[pubkey.GetID()] = index;
3258 if (missingInternal + missingExternal > 0) {
3259 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3262 return true;
3265 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3267 nIndex = -1;
3268 keypool.vchPubKey = CPubKey();
3270 LOCK(cs_wallet);
3272 if (!IsLocked())
3273 TopUpKeyPool();
3275 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3276 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3278 // Get the oldest key
3279 if(setKeyPool.empty())
3280 return;
3282 CWalletDB walletdb(*dbw);
3284 auto it = setKeyPool.begin();
3285 nIndex = *it;
3286 setKeyPool.erase(it);
3287 if (!walletdb.ReadPool(nIndex, keypool)) {
3288 throw std::runtime_error(std::string(__func__) + ": read failed");
3290 if (!HaveKey(keypool.vchPubKey.GetID())) {
3291 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3293 if (keypool.fInternal != fReturningInternal) {
3294 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3297 assert(keypool.vchPubKey.IsValid());
3298 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3299 LogPrintf("keypool reserve %d\n", nIndex);
3303 void CWallet::KeepKey(int64_t nIndex)
3305 // Remove from key pool
3306 CWalletDB walletdb(*dbw);
3307 walletdb.ErasePool(nIndex);
3308 LogPrintf("keypool keep %d\n", nIndex);
3311 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3313 // Return to key pool
3315 LOCK(cs_wallet);
3316 if (fInternal) {
3317 setInternalKeyPool.insert(nIndex);
3318 } else {
3319 setExternalKeyPool.insert(nIndex);
3321 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3323 LogPrintf("keypool return %d\n", nIndex);
3326 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3328 CKeyPool keypool;
3330 LOCK(cs_wallet);
3331 int64_t nIndex = 0;
3332 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3333 if (nIndex == -1)
3335 if (IsLocked()) return false;
3336 CWalletDB walletdb(*dbw);
3337 result = GenerateNewKey(walletdb, internal);
3338 return true;
3340 KeepKey(nIndex);
3341 result = keypool.vchPubKey;
3343 return true;
3346 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3347 if (setKeyPool.empty()) {
3348 return GetTime();
3351 CKeyPool keypool;
3352 int64_t nIndex = *(setKeyPool.begin());
3353 if (!walletdb.ReadPool(nIndex, keypool)) {
3354 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3356 assert(keypool.vchPubKey.IsValid());
3357 return keypool.nTime;
3360 int64_t CWallet::GetOldestKeyPoolTime()
3362 LOCK(cs_wallet);
3364 CWalletDB walletdb(*dbw);
3366 // load oldest key from keypool, get time and return
3367 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3368 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3369 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3372 return oldestKey;
3375 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3377 std::map<CTxDestination, CAmount> balances;
3380 LOCK(cs_wallet);
3381 for (const auto& walletEntry : mapWallet)
3383 const CWalletTx *pcoin = &walletEntry.second;
3385 if (!pcoin->IsTrusted())
3386 continue;
3388 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3389 continue;
3391 int nDepth = pcoin->GetDepthInMainChain();
3392 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3393 continue;
3395 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3397 CTxDestination addr;
3398 if (!IsMine(pcoin->tx->vout[i]))
3399 continue;
3400 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3401 continue;
3403 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3405 if (!balances.count(addr))
3406 balances[addr] = 0;
3407 balances[addr] += n;
3412 return balances;
3415 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3417 AssertLockHeld(cs_wallet); // mapWallet
3418 std::set< std::set<CTxDestination> > groupings;
3419 std::set<CTxDestination> grouping;
3421 for (const auto& walletEntry : mapWallet)
3423 const CWalletTx *pcoin = &walletEntry.second;
3425 if (pcoin->tx->vin.size() > 0)
3427 bool any_mine = false;
3428 // group all input addresses with each other
3429 for (CTxIn txin : pcoin->tx->vin)
3431 CTxDestination address;
3432 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3433 continue;
3434 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3435 continue;
3436 grouping.insert(address);
3437 any_mine = true;
3440 // group change with input addresses
3441 if (any_mine)
3443 for (CTxOut txout : pcoin->tx->vout)
3444 if (IsChange(txout))
3446 CTxDestination txoutAddr;
3447 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3448 continue;
3449 grouping.insert(txoutAddr);
3452 if (grouping.size() > 0)
3454 groupings.insert(grouping);
3455 grouping.clear();
3459 // group lone addrs by themselves
3460 for (const auto& txout : pcoin->tx->vout)
3461 if (IsMine(txout))
3463 CTxDestination address;
3464 if(!ExtractDestination(txout.scriptPubKey, address))
3465 continue;
3466 grouping.insert(address);
3467 groupings.insert(grouping);
3468 grouping.clear();
3472 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3473 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3474 for (std::set<CTxDestination> _grouping : groupings)
3476 // make a set of all the groups hit by this new group
3477 std::set< std::set<CTxDestination>* > hits;
3478 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3479 for (CTxDestination address : _grouping)
3480 if ((it = setmap.find(address)) != setmap.end())
3481 hits.insert((*it).second);
3483 // merge all hit groups into a new single group and delete old groups
3484 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3485 for (std::set<CTxDestination>* hit : hits)
3487 merged->insert(hit->begin(), hit->end());
3488 uniqueGroupings.erase(hit);
3489 delete hit;
3491 uniqueGroupings.insert(merged);
3493 // update setmap
3494 for (CTxDestination element : *merged)
3495 setmap[element] = merged;
3498 std::set< std::set<CTxDestination> > ret;
3499 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3501 ret.insert(*uniqueGrouping);
3502 delete uniqueGrouping;
3505 return ret;
3508 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3510 LOCK(cs_wallet);
3511 std::set<CTxDestination> result;
3512 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3514 const CTxDestination& address = item.first;
3515 const std::string& strName = item.second.name;
3516 if (strName == strAccount)
3517 result.insert(address);
3519 return result;
3522 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3524 if (nIndex == -1)
3526 CKeyPool keypool;
3527 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3528 if (nIndex != -1)
3529 vchPubKey = keypool.vchPubKey;
3530 else {
3531 return false;
3533 fInternal = keypool.fInternal;
3535 assert(vchPubKey.IsValid());
3536 pubkey = vchPubKey;
3537 return true;
3540 void CReserveKey::KeepKey()
3542 if (nIndex != -1)
3543 pwallet->KeepKey(nIndex);
3544 nIndex = -1;
3545 vchPubKey = CPubKey();
3548 void CReserveKey::ReturnKey()
3550 if (nIndex != -1) {
3551 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3553 nIndex = -1;
3554 vchPubKey = CPubKey();
3557 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3559 AssertLockHeld(cs_wallet);
3560 bool internal = setInternalKeyPool.count(keypool_id);
3561 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3562 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3563 auto it = setKeyPool->begin();
3565 CWalletDB walletdb(*dbw);
3566 while (it != std::end(*setKeyPool)) {
3567 const int64_t& index = *(it);
3568 if (index > keypool_id) break; // set*KeyPool is ordered
3570 CKeyPool keypool;
3571 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3572 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3574 walletdb.ErasePool(index);
3575 LogPrintf("keypool index %d removed\n", index);
3576 it = setKeyPool->erase(it);
3580 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3582 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3583 CPubKey pubkey;
3584 if (!rKey->GetReservedKey(pubkey))
3585 return;
3587 script = rKey;
3588 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3591 void CWallet::LockCoin(const COutPoint& output)
3593 AssertLockHeld(cs_wallet); // setLockedCoins
3594 setLockedCoins.insert(output);
3597 void CWallet::UnlockCoin(const COutPoint& output)
3599 AssertLockHeld(cs_wallet); // setLockedCoins
3600 setLockedCoins.erase(output);
3603 void CWallet::UnlockAllCoins()
3605 AssertLockHeld(cs_wallet); // setLockedCoins
3606 setLockedCoins.clear();
3609 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3611 AssertLockHeld(cs_wallet); // setLockedCoins
3612 COutPoint outpt(hash, n);
3614 return (setLockedCoins.count(outpt) > 0);
3617 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3619 AssertLockHeld(cs_wallet); // setLockedCoins
3620 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3621 it != setLockedCoins.end(); it++) {
3622 COutPoint outpt = (*it);
3623 vOutpts.push_back(outpt);
3627 /** @} */ // end of Actions
3629 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3630 AssertLockHeld(cs_wallet); // mapKeyMetadata
3631 mapKeyBirth.clear();
3633 // get birth times for keys with metadata
3634 for (const auto& entry : mapKeyMetadata) {
3635 if (entry.second.nCreateTime) {
3636 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3640 // map in which we'll infer heights of other keys
3641 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3642 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3643 for (const CKeyID &keyid : GetKeys()) {
3644 if (mapKeyBirth.count(keyid) == 0)
3645 mapKeyFirstBlock[keyid] = pindexMax;
3648 // if there are no such keys, we're done
3649 if (mapKeyFirstBlock.empty())
3650 return;
3652 // find first block that affects those keys, if there are any left
3653 std::vector<CKeyID> vAffected;
3654 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3655 // iterate over all wallet transactions...
3656 const CWalletTx &wtx = (*it).second;
3657 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3658 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3659 // ... which are already in a block
3660 int nHeight = blit->second->nHeight;
3661 for (const CTxOut &txout : wtx.tx->vout) {
3662 // iterate over all their outputs
3663 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3664 for (const CKeyID &keyid : vAffected) {
3665 // ... and all their affected keys
3666 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3667 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3668 rit->second = blit->second;
3670 vAffected.clear();
3675 // Extract block timestamps for those keys
3676 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3677 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3681 * Compute smart timestamp for a transaction being added to the wallet.
3683 * Logic:
3684 * - If sending a transaction, assign its timestamp to the current time.
3685 * - If receiving a transaction outside a block, assign its timestamp to the
3686 * current time.
3687 * - If receiving a block with a future timestamp, assign all its (not already
3688 * known) transactions' timestamps to the current time.
3689 * - If receiving a block with a past timestamp, before the most recent known
3690 * transaction (that we care about), assign all its (not already known)
3691 * transactions' timestamps to the same timestamp as that most-recent-known
3692 * transaction.
3693 * - If receiving a block with a past timestamp, but after the most recent known
3694 * transaction, assign all its (not already known) transactions' timestamps to
3695 * the block time.
3697 * For more information see CWalletTx::nTimeSmart,
3698 * https://bitcointalk.org/?topic=54527, or
3699 * https://github.com/bitcoin/bitcoin/pull/1393.
3701 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3703 unsigned int nTimeSmart = wtx.nTimeReceived;
3704 if (!wtx.hashUnset()) {
3705 if (mapBlockIndex.count(wtx.hashBlock)) {
3706 int64_t latestNow = wtx.nTimeReceived;
3707 int64_t latestEntry = 0;
3709 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3710 int64_t latestTolerated = latestNow + 300;
3711 const TxItems& txOrdered = wtxOrdered;
3712 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3713 CWalletTx* const pwtx = it->second.first;
3714 if (pwtx == &wtx) {
3715 continue;
3717 CAccountingEntry* const pacentry = it->second.second;
3718 int64_t nSmartTime;
3719 if (pwtx) {
3720 nSmartTime = pwtx->nTimeSmart;
3721 if (!nSmartTime) {
3722 nSmartTime = pwtx->nTimeReceived;
3724 } else {
3725 nSmartTime = pacentry->nTime;
3727 if (nSmartTime <= latestTolerated) {
3728 latestEntry = nSmartTime;
3729 if (nSmartTime > latestNow) {
3730 latestNow = nSmartTime;
3732 break;
3736 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3737 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3738 } else {
3739 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3742 return nTimeSmart;
3745 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3747 if (boost::get<CNoDestination>(&dest))
3748 return false;
3750 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3751 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3754 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3756 if (!mapAddressBook[dest].destdata.erase(key))
3757 return false;
3758 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3761 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3763 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3764 return true;
3767 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3769 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3770 if(i != mapAddressBook.end())
3772 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3773 if(j != i->second.destdata.end())
3775 if(value)
3776 *value = j->second;
3777 return true;
3780 return false;
3783 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3785 LOCK(cs_wallet);
3786 std::vector<std::string> values;
3787 for (const auto& address : mapAddressBook) {
3788 for (const auto& data : address.second.destdata) {
3789 if (!data.first.compare(0, prefix.size(), prefix)) {
3790 values.emplace_back(data.second);
3794 return values;
3797 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3799 // needed to restore wallet transaction meta data after -zapwallettxes
3800 std::vector<CWalletTx> vWtx;
3802 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3803 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3805 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3806 std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
3807 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3808 if (nZapWalletRet != DB_LOAD_OK) {
3809 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3810 return nullptr;
3814 uiInterface.InitMessage(_("Loading wallet..."));
3816 int64_t nStart = GetTimeMillis();
3817 bool fFirstRun = true;
3818 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3819 CWallet *walletInstance = new CWallet(std::move(dbw));
3820 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3821 if (nLoadWalletRet != DB_LOAD_OK)
3823 if (nLoadWalletRet == DB_CORRUPT) {
3824 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3825 return nullptr;
3827 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3829 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3830 " or address book entries might be missing or incorrect."),
3831 walletFile));
3833 else if (nLoadWalletRet == DB_TOO_NEW) {
3834 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3835 return nullptr;
3837 else if (nLoadWalletRet == DB_NEED_REWRITE)
3839 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3840 return nullptr;
3842 else {
3843 InitError(strprintf(_("Error loading %s"), walletFile));
3844 return nullptr;
3848 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3850 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3851 if (nMaxVersion == 0) // the -upgradewallet without argument case
3853 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3854 nMaxVersion = CLIENT_VERSION;
3855 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3857 else
3858 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3859 if (nMaxVersion < walletInstance->GetVersion())
3861 InitError(_("Cannot downgrade wallet"));
3862 return nullptr;
3864 walletInstance->SetMaxVersion(nMaxVersion);
3867 if (fFirstRun)
3869 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3870 if (!gArgs.GetBoolArg("-usehd", true)) {
3871 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3872 return nullptr;
3874 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3876 // generate a new master key
3877 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3878 if (!walletInstance->SetHDMasterKey(masterPubKey))
3879 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3881 // Top up the keypool
3882 if (!walletInstance->TopUpKeyPool()) {
3883 InitError(_("Unable to generate initial keys") += "\n");
3884 return nullptr;
3887 walletInstance->SetBestChain(chainActive.GetLocator());
3889 else if (gArgs.IsArgSet("-usehd")) {
3890 bool useHD = gArgs.GetBoolArg("-usehd", true);
3891 if (walletInstance->IsHDEnabled() && !useHD) {
3892 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3893 return nullptr;
3895 if (!walletInstance->IsHDEnabled() && useHD) {
3896 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3897 return nullptr;
3901 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3903 RegisterValidationInterface(walletInstance);
3905 // Try to top up keypool. No-op if the wallet is locked.
3906 walletInstance->TopUpKeyPool();
3908 CBlockIndex *pindexRescan = chainActive.Genesis();
3909 if (!gArgs.GetBoolArg("-rescan", false))
3911 CWalletDB walletdb(*walletInstance->dbw);
3912 CBlockLocator locator;
3913 if (walletdb.ReadBestBlock(locator))
3914 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3916 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3918 //We can't rescan beyond non-pruned blocks, stop and throw an error
3919 //this might happen if a user uses an old wallet within a pruned node
3920 // or if he ran -disablewallet for a longer time, then decided to re-enable
3921 if (fPruneMode)
3923 CBlockIndex *block = chainActive.Tip();
3924 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3925 block = block->pprev;
3927 if (pindexRescan != block) {
3928 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3929 return nullptr;
3933 uiInterface.InitMessage(_("Rescanning..."));
3934 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3936 // No need to read and scan block if block was created before
3937 // our wallet birthday (as adjusted for block time variability)
3938 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3939 pindexRescan = chainActive.Next(pindexRescan);
3942 nStart = GetTimeMillis();
3943 walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
3944 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3945 walletInstance->SetBestChain(chainActive.GetLocator());
3946 walletInstance->dbw->IncrementUpdateCounter();
3948 // Restore wallet transaction metadata after -zapwallettxes=1
3949 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
3951 CWalletDB walletdb(*walletInstance->dbw);
3953 for (const CWalletTx& wtxOld : vWtx)
3955 uint256 hash = wtxOld.GetHash();
3956 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3957 if (mi != walletInstance->mapWallet.end())
3959 const CWalletTx* copyFrom = &wtxOld;
3960 CWalletTx* copyTo = &mi->second;
3961 copyTo->mapValue = copyFrom->mapValue;
3962 copyTo->vOrderForm = copyFrom->vOrderForm;
3963 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3964 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3965 copyTo->fFromMe = copyFrom->fFromMe;
3966 copyTo->strFromAccount = copyFrom->strFromAccount;
3967 copyTo->nOrderPos = copyFrom->nOrderPos;
3968 walletdb.WriteTx(*copyTo);
3973 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3976 LOCK(walletInstance->cs_wallet);
3977 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3978 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3979 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3982 return walletInstance;
3985 std::atomic<bool> CWallet::fFlushScheduled(false);
3987 void CWallet::postInitProcess(CScheduler& scheduler)
3989 // Add wallet transactions that aren't already in a block to mempool
3990 // Do this here as mempool requires genesis block to be loaded
3991 ReacceptWalletTransactions();
3993 // Run a thread to flush wallet periodically
3994 if (!CWallet::fFlushScheduled.exchange(true)) {
3995 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3999 bool CWallet::BackupWallet(const std::string& strDest)
4001 return dbw->Backup(strDest);
4004 CKeyPool::CKeyPool()
4006 nTime = GetTime();
4007 fInternal = false;
4010 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4012 nTime = GetTime();
4013 vchPubKey = vchPubKeyIn;
4014 fInternal = internalIn;
4017 CWalletKey::CWalletKey(int64_t nExpires)
4019 nTimeCreated = (nExpires ? GetTime() : 0);
4020 nTimeExpires = nExpires;
4023 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4025 // Update the tx's hashBlock
4026 hashBlock = pindex->GetBlockHash();
4028 // set the position of the transaction in the block
4029 nIndex = posInBlock;
4032 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4034 if (hashUnset())
4035 return 0;
4037 AssertLockHeld(cs_main);
4039 // Find the block it claims to be in
4040 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4041 if (mi == mapBlockIndex.end())
4042 return 0;
4043 CBlockIndex* pindex = (*mi).second;
4044 if (!pindex || !chainActive.Contains(pindex))
4045 return 0;
4047 pindexRet = pindex;
4048 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4051 int CMerkleTx::GetBlocksToMaturity() const
4053 if (!IsCoinBase())
4054 return 0;
4055 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4059 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4061 return ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
4062 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);