wallet: Display non-HD error on first run
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobcbc045fa183e276863f3cf97f530108608fb94c1
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 CNoDestination &none) {}
117 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
119 LOCK(cs_wallet);
120 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
121 if (it == mapWallet.end())
122 return nullptr;
123 return &(it->second);
126 CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
128 AssertLockHeld(cs_wallet); // mapKeyMetadata
129 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
131 CKey secret;
133 // Create new metadata
134 int64_t nCreationTime = GetTime();
135 CKeyMetadata metadata(nCreationTime);
137 // use HD key derivation if HD was enabled during wallet creation
138 if (IsHDEnabled()) {
139 DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
140 } else {
141 secret.MakeNewKey(fCompressed);
144 // Compressed public keys were introduced in version 0.6.0
145 if (fCompressed) {
146 SetMinVersion(FEATURE_COMPRPUBKEY);
149 CPubKey pubkey = secret.GetPubKey();
150 assert(secret.VerifyPubKey(pubkey));
152 mapKeyMetadata[pubkey.GetID()] = metadata;
153 UpdateTimeFirstKey(nCreationTime);
155 if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
156 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
158 return pubkey;
161 void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
163 // for now we use a fixed keypath scheme of m/0'/0'/k
164 CKey key; //master key seed (256bit)
165 CExtKey masterKey; //hd master key
166 CExtKey accountKey; //key at m/0'
167 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
168 CExtKey childKey; //key at m/0'/0'/<n>'
170 // try to get the master key
171 if (!GetKey(hdChain.masterKeyID, key))
172 throw std::runtime_error(std::string(__func__) + ": Master key not found");
174 masterKey.SetMaster(key.begin(), key.size());
176 // derive m/0'
177 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
178 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
180 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
181 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
182 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
184 // derive child key at next index, skip keys already known to the wallet
185 do {
186 // always derive hardened keys
187 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
188 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
189 if (internal) {
190 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
191 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
192 hdChain.nInternalChainCounter++;
194 else {
195 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
196 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
197 hdChain.nExternalChainCounter++;
199 } while (HaveKey(childKey.key.GetPubKey().GetID()));
200 secret = childKey.key;
201 metadata.hdMasterKeyID = hdChain.masterKeyID;
202 // update the chain model in the database
203 if (!walletdb.WriteHDChain(hdChain))
204 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
207 bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
209 AssertLockHeld(cs_wallet); // mapKeyMetadata
211 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
212 // which is overridden below. To avoid flushes, the database handle is
213 // tunneled through to it.
214 bool needsDB = !pwalletdbEncryption;
215 if (needsDB) {
216 pwalletdbEncryption = &walletdb;
218 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
219 if (needsDB) pwalletdbEncryption = nullptr;
220 return false;
222 if (needsDB) pwalletdbEncryption = nullptr;
224 // check if we need to remove from watch-only
225 CScript script;
226 script = GetScriptForDestination(pubkey.GetID());
227 if (HaveWatchOnly(script)) {
228 RemoveWatchOnly(script);
230 script = GetScriptForRawPubKey(pubkey);
231 if (HaveWatchOnly(script)) {
232 RemoveWatchOnly(script);
235 if (!IsCrypted()) {
236 return walletdb.WriteKey(pubkey,
237 secret.GetPrivKey(),
238 mapKeyMetadata[pubkey.GetID()]);
240 return true;
243 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
245 CWalletDB walletdb(*dbw);
246 return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
249 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
250 const std::vector<unsigned char> &vchCryptedSecret)
252 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
253 return false;
255 LOCK(cs_wallet);
256 if (pwalletdbEncryption)
257 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
258 vchCryptedSecret,
259 mapKeyMetadata[vchPubKey.GetID()]);
260 else
261 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
262 vchCryptedSecret,
263 mapKeyMetadata[vchPubKey.GetID()]);
267 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
269 AssertLockHeld(cs_wallet); // mapKeyMetadata
270 UpdateTimeFirstKey(meta.nCreateTime);
271 mapKeyMetadata[keyID] = meta;
272 return true;
275 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
277 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
281 * Update wallet first key creation time. This should be called whenever keys
282 * are added to the wallet, with the oldest key creation time.
284 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
286 AssertLockHeld(cs_wallet);
287 if (nCreateTime <= 1) {
288 // Cannot determine birthday information, so set the wallet birthday to
289 // the beginning of time.
290 nTimeFirstKey = 1;
291 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
292 nTimeFirstKey = nCreateTime;
296 bool CWallet::AddCScript(const CScript& redeemScript)
298 if (!CCryptoKeyStore::AddCScript(redeemScript))
299 return false;
300 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
303 bool CWallet::LoadCScript(const CScript& redeemScript)
305 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
306 * that never can be redeemed. However, old wallets may still contain
307 * these. Do not add them to the wallet and warn. */
308 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
310 std::string strAddr = EncodeDestination(CScriptID(redeemScript));
311 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",
312 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
313 return true;
316 return CCryptoKeyStore::AddCScript(redeemScript);
319 bool CWallet::AddWatchOnly(const CScript& dest)
321 if (!CCryptoKeyStore::AddWatchOnly(dest))
322 return false;
323 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
324 UpdateTimeFirstKey(meta.nCreateTime);
325 NotifyWatchonlyChanged(true);
326 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
329 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
331 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
332 return AddWatchOnly(dest);
335 bool CWallet::RemoveWatchOnly(const CScript &dest)
337 AssertLockHeld(cs_wallet);
338 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
339 return false;
340 if (!HaveWatchOnly())
341 NotifyWatchonlyChanged(false);
342 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
343 return false;
345 return true;
348 bool CWallet::LoadWatchOnly(const CScript &dest)
350 return CCryptoKeyStore::AddWatchOnly(dest);
353 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
355 CCrypter crypter;
356 CKeyingMaterial _vMasterKey;
359 LOCK(cs_wallet);
360 for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
362 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
363 return false;
364 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
365 continue; // try another master key
366 if (CCryptoKeyStore::Unlock(_vMasterKey))
367 return true;
370 return false;
373 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
375 bool fWasLocked = IsLocked();
378 LOCK(cs_wallet);
379 Lock();
381 CCrypter crypter;
382 CKeyingMaterial _vMasterKey;
383 for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
385 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
386 return false;
387 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
388 return false;
389 if (CCryptoKeyStore::Unlock(_vMasterKey))
391 int64_t nStartTime = GetTimeMillis();
392 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
393 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
395 nStartTime = GetTimeMillis();
396 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
397 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
399 if (pMasterKey.second.nDeriveIterations < 25000)
400 pMasterKey.second.nDeriveIterations = 25000;
402 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
404 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
405 return false;
406 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
407 return false;
408 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
409 if (fWasLocked)
410 Lock();
411 return true;
416 return false;
419 void CWallet::SetBestChain(const CBlockLocator& loc)
421 CWalletDB walletdb(*dbw);
422 walletdb.WriteBestBlock(loc);
425 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
427 LOCK(cs_wallet); // nWalletVersion
428 if (nWalletVersion >= nVersion)
429 return true;
431 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
432 if (fExplicit && nVersion > nWalletMaxVersion)
433 nVersion = FEATURE_LATEST;
435 nWalletVersion = nVersion;
437 if (nVersion > nWalletMaxVersion)
438 nWalletMaxVersion = nVersion;
441 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
442 if (nWalletVersion > 40000)
443 pwalletdb->WriteMinVersion(nWalletVersion);
444 if (!pwalletdbIn)
445 delete pwalletdb;
448 return true;
451 bool CWallet::SetMaxVersion(int nVersion)
453 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
454 // cannot downgrade below current version
455 if (nWalletVersion > nVersion)
456 return false;
458 nWalletMaxVersion = nVersion;
460 return true;
463 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
465 std::set<uint256> result;
466 AssertLockHeld(cs_wallet);
468 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
469 if (it == mapWallet.end())
470 return result;
471 const CWalletTx& wtx = it->second;
473 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
475 for (const CTxIn& txin : wtx.tx->vin)
477 if (mapTxSpends.count(txin.prevout) <= 1)
478 continue; // No conflict if zero or one spends
479 range = mapTxSpends.equal_range(txin.prevout);
480 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
481 result.insert(_it->second);
483 return result;
486 bool CWallet::HasWalletSpend(const uint256& txid) const
488 AssertLockHeld(cs_wallet);
489 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
490 return (iter != mapTxSpends.end() && iter->first.hash == txid);
493 void CWallet::Flush(bool shutdown)
495 dbw->Flush(shutdown);
498 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
500 // We want all the wallet transactions in range to have the same metadata as
501 // the oldest (smallest nOrderPos).
502 // So: find smallest nOrderPos:
504 int nMinOrderPos = std::numeric_limits<int>::max();
505 const CWalletTx* copyFrom = nullptr;
506 for (TxSpends::iterator it = range.first; it != range.second; ++it)
508 const uint256& hash = it->second;
509 int n = mapWallet[hash].nOrderPos;
510 if (n < nMinOrderPos)
512 nMinOrderPos = n;
513 copyFrom = &mapWallet[hash];
516 // Now copy data from copyFrom to rest:
517 for (TxSpends::iterator it = range.first; it != range.second; ++it)
519 const uint256& hash = it->second;
520 CWalletTx* copyTo = &mapWallet[hash];
521 if (copyFrom == copyTo) continue;
522 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
523 copyTo->mapValue = copyFrom->mapValue;
524 copyTo->vOrderForm = copyFrom->vOrderForm;
525 // fTimeReceivedIsTxTime not copied on purpose
526 // nTimeReceived not copied on purpose
527 copyTo->nTimeSmart = copyFrom->nTimeSmart;
528 copyTo->fFromMe = copyFrom->fFromMe;
529 copyTo->strFromAccount = copyFrom->strFromAccount;
530 // nOrderPos not copied on purpose
531 // cached members not copied on purpose
536 * Outpoint is spent if any non-conflicted transaction
537 * spends it:
539 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
541 const COutPoint outpoint(hash, n);
542 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
543 range = mapTxSpends.equal_range(outpoint);
545 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
547 const uint256& wtxid = it->second;
548 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
549 if (mit != mapWallet.end()) {
550 int depth = mit->second.GetDepthInMainChain();
551 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
552 return true; // Spent
555 return false;
558 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
560 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
562 std::pair<TxSpends::iterator, TxSpends::iterator> range;
563 range = mapTxSpends.equal_range(outpoint);
564 SyncMetaData(range);
568 void CWallet::AddToSpends(const uint256& wtxid)
570 auto it = mapWallet.find(wtxid);
571 assert(it != mapWallet.end());
572 CWalletTx& thisTx = it->second;
573 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
574 return;
576 for (const CTxIn& txin : thisTx.tx->vin)
577 AddToSpends(txin.prevout, wtxid);
580 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
582 if (IsCrypted())
583 return false;
585 CKeyingMaterial _vMasterKey;
587 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
588 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
590 CMasterKey kMasterKey;
592 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
593 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
595 CCrypter crypter;
596 int64_t nStartTime = GetTimeMillis();
597 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
598 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
600 nStartTime = GetTimeMillis();
601 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
602 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
604 if (kMasterKey.nDeriveIterations < 25000)
605 kMasterKey.nDeriveIterations = 25000;
607 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
609 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
610 return false;
611 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
612 return false;
615 LOCK(cs_wallet);
616 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
617 assert(!pwalletdbEncryption);
618 pwalletdbEncryption = new CWalletDB(*dbw);
619 if (!pwalletdbEncryption->TxnBegin()) {
620 delete pwalletdbEncryption;
621 pwalletdbEncryption = nullptr;
622 return false;
624 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
626 if (!EncryptKeys(_vMasterKey))
628 pwalletdbEncryption->TxnAbort();
629 delete pwalletdbEncryption;
630 // We now probably have half of our keys encrypted in memory, and half not...
631 // die and let the user reload the unencrypted wallet.
632 assert(false);
635 // Encryption was introduced in version 0.4.0
636 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
638 if (!pwalletdbEncryption->TxnCommit()) {
639 delete pwalletdbEncryption;
640 // We now have keys encrypted in memory, but not on disk...
641 // die to avoid confusion and let the user reload the unencrypted wallet.
642 assert(false);
645 delete pwalletdbEncryption;
646 pwalletdbEncryption = nullptr;
648 Lock();
649 Unlock(strWalletPassphrase);
651 // if we are using HD, replace the HD master key (seed) with a new one
652 if (IsHDEnabled()) {
653 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
654 return false;
658 NewKeyPool();
659 Lock();
661 // Need to completely rewrite the wallet file; if we don't, bdb might keep
662 // bits of the unencrypted private key in slack space in the database file.
663 dbw->Rewrite();
666 NotifyStatusChanged(this);
668 return true;
671 DBErrors CWallet::ReorderTransactions()
673 LOCK(cs_wallet);
674 CWalletDB walletdb(*dbw);
676 // Old wallets didn't have any defined order for transactions
677 // Probably a bad idea to change the output of this
679 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
680 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
681 typedef std::multimap<int64_t, TxPair > TxItems;
682 TxItems txByTime;
684 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
686 CWalletTx* wtx = &((*it).second);
687 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
689 std::list<CAccountingEntry> acentries;
690 walletdb.ListAccountCreditDebit("", acentries);
691 for (CAccountingEntry& entry : acentries)
693 txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
696 nOrderPosNext = 0;
697 std::vector<int64_t> nOrderPosOffsets;
698 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
700 CWalletTx *const pwtx = (*it).second.first;
701 CAccountingEntry *const pacentry = (*it).second.second;
702 int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
704 if (nOrderPos == -1)
706 nOrderPos = nOrderPosNext++;
707 nOrderPosOffsets.push_back(nOrderPos);
709 if (pwtx)
711 if (!walletdb.WriteTx(*pwtx))
712 return DB_LOAD_FAIL;
714 else
715 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
716 return DB_LOAD_FAIL;
718 else
720 int64_t nOrderPosOff = 0;
721 for (const int64_t& nOffsetStart : nOrderPosOffsets)
723 if (nOrderPos >= nOffsetStart)
724 ++nOrderPosOff;
726 nOrderPos += nOrderPosOff;
727 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
729 if (!nOrderPosOff)
730 continue;
732 // Since we're changing the order, write it back
733 if (pwtx)
735 if (!walletdb.WriteTx(*pwtx))
736 return DB_LOAD_FAIL;
738 else
739 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
740 return DB_LOAD_FAIL;
743 walletdb.WriteOrderPosNext(nOrderPosNext);
745 return DB_LOAD_OK;
748 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
750 AssertLockHeld(cs_wallet); // nOrderPosNext
751 int64_t nRet = nOrderPosNext++;
752 if (pwalletdb) {
753 pwalletdb->WriteOrderPosNext(nOrderPosNext);
754 } else {
755 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
757 return nRet;
760 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
762 CWalletDB walletdb(*dbw);
763 if (!walletdb.TxnBegin())
764 return false;
766 int64_t nNow = GetAdjustedTime();
768 // Debit
769 CAccountingEntry debit;
770 debit.nOrderPos = IncOrderPosNext(&walletdb);
771 debit.strAccount = strFrom;
772 debit.nCreditDebit = -nAmount;
773 debit.nTime = nNow;
774 debit.strOtherAccount = strTo;
775 debit.strComment = strComment;
776 AddAccountingEntry(debit, &walletdb);
778 // Credit
779 CAccountingEntry credit;
780 credit.nOrderPos = IncOrderPosNext(&walletdb);
781 credit.strAccount = strTo;
782 credit.nCreditDebit = nAmount;
783 credit.nTime = nNow;
784 credit.strOtherAccount = strFrom;
785 credit.strComment = strComment;
786 AddAccountingEntry(credit, &walletdb);
788 if (!walletdb.TxnCommit())
789 return false;
791 return true;
794 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
796 CWalletDB walletdb(*dbw);
798 CAccount account;
799 walletdb.ReadAccount(strAccount, account);
801 if (!bForceNew) {
802 if (!account.vchPubKey.IsValid())
803 bForceNew = true;
804 else {
805 // Check if the current key has been used
806 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
807 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
808 it != mapWallet.end() && account.vchPubKey.IsValid();
809 ++it)
810 for (const CTxOut& txout : (*it).second.tx->vout)
811 if (txout.scriptPubKey == scriptPubKey) {
812 bForceNew = true;
813 break;
818 // Generate a new key
819 if (bForceNew) {
820 if (!GetKeyFromPool(account.vchPubKey, false))
821 return false;
823 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
824 walletdb.WriteAccount(strAccount, account);
827 pubKey = account.vchPubKey;
829 return true;
832 void CWallet::MarkDirty()
835 LOCK(cs_wallet);
836 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
837 item.second.MarkDirty();
841 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
843 LOCK(cs_wallet);
845 auto mi = mapWallet.find(originalHash);
847 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
848 assert(mi != mapWallet.end());
850 CWalletTx& wtx = (*mi).second;
852 // Ensure for now that we're not overwriting data
853 assert(wtx.mapValue.count("replaced_by_txid") == 0);
855 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
857 CWalletDB walletdb(*dbw, "r+");
859 bool success = true;
860 if (!walletdb.WriteTx(wtx)) {
861 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
862 success = false;
865 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
867 return success;
870 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
872 LOCK(cs_wallet);
874 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
876 uint256 hash = wtxIn.GetHash();
878 // Inserts only if not already there, returns tx inserted or tx found
879 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
880 CWalletTx& wtx = (*ret.first).second;
881 wtx.BindWallet(this);
882 bool fInsertedNew = ret.second;
883 if (fInsertedNew)
885 wtx.nTimeReceived = GetAdjustedTime();
886 wtx.nOrderPos = IncOrderPosNext(&walletdb);
887 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
888 wtx.nTimeSmart = ComputeTimeSmart(wtx);
889 AddToSpends(hash);
892 bool fUpdated = false;
893 if (!fInsertedNew)
895 // Merge
896 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
898 wtx.hashBlock = wtxIn.hashBlock;
899 fUpdated = true;
901 // If no longer abandoned, update
902 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
904 wtx.hashBlock = wtxIn.hashBlock;
905 fUpdated = true;
907 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
909 wtx.nIndex = wtxIn.nIndex;
910 fUpdated = true;
912 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
914 wtx.fFromMe = wtxIn.fFromMe;
915 fUpdated = true;
919 //// debug print
920 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
922 // Write to disk
923 if (fInsertedNew || fUpdated)
924 if (!walletdb.WriteTx(wtx))
925 return false;
927 // Break debit/credit balance caches:
928 wtx.MarkDirty();
930 // Notify UI of new or updated transaction
931 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
933 // notify an external script when a wallet transaction comes in or is updated
934 std::string strCmd = gArgs.GetArg("-walletnotify", "");
936 if ( !strCmd.empty())
938 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
939 boost::thread t(runCommand, strCmd); // thread runs free
942 return true;
945 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
947 uint256 hash = wtxIn.GetHash();
949 mapWallet[hash] = wtxIn;
950 CWalletTx& wtx = mapWallet[hash];
951 wtx.BindWallet(this);
952 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
953 AddToSpends(hash);
954 for (const CTxIn& txin : wtx.tx->vin) {
955 auto it = mapWallet.find(txin.prevout.hash);
956 if (it != mapWallet.end()) {
957 CWalletTx& prevtx = it->second;
958 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
959 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
964 return true;
968 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
969 * be set when the transaction was known to be included in a block. When
970 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
971 * notifications happen and cached balances are marked dirty.
973 * If fUpdate is true, existing transactions will be updated.
974 * TODO: One exception to this is that the abandoned state is cleared under the
975 * assumption that any further notification of a transaction that was considered
976 * abandoned is an indication that it is not safe to be considered abandoned.
977 * Abandoned state should probably be more carefully tracked via different
978 * posInBlock signals or by checking mempool presence when necessary.
980 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
982 const CTransaction& tx = *ptx;
984 AssertLockHeld(cs_wallet);
986 if (pIndex != nullptr) {
987 for (const CTxIn& txin : tx.vin) {
988 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
989 while (range.first != range.second) {
990 if (range.first->second != tx.GetHash()) {
991 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);
992 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
994 range.first++;
999 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
1000 if (fExisted && !fUpdate) return false;
1001 if (fExisted || IsMine(tx) || IsFromMe(tx))
1003 /* Check if any keys in the wallet keypool that were supposed to be unused
1004 * have appeared in a new transaction. If so, remove those keys from the keypool.
1005 * This can happen when restoring an old wallet backup that does not contain
1006 * the mostly recently created transactions from newer versions of the wallet.
1009 // loop though all outputs
1010 for (const CTxOut& txout: tx.vout) {
1011 // extract addresses and check if they match with an unused keypool key
1012 std::vector<CKeyID> vAffected;
1013 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
1014 for (const CKeyID &keyid : vAffected) {
1015 std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
1016 if (mi != m_pool_key_to_index.end()) {
1017 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
1018 MarkReserveKeysAsUsed(mi->second);
1020 if (!TopUpKeyPool()) {
1021 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
1027 CWalletTx wtx(this, ptx);
1029 // Get merkle branch if transaction was found in a block
1030 if (pIndex != nullptr)
1031 wtx.SetMerkleBranch(pIndex, posInBlock);
1033 return AddToWallet(wtx, false);
1036 return false;
1039 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
1041 LOCK2(cs_main, cs_wallet);
1042 const CWalletTx* wtx = GetWalletTx(hashTx);
1043 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1046 bool CWallet::AbandonTransaction(const uint256& hashTx)
1048 LOCK2(cs_main, cs_wallet);
1050 CWalletDB walletdb(*dbw, "r+");
1052 std::set<uint256> todo;
1053 std::set<uint256> done;
1055 // Can't mark abandoned if confirmed or in mempool
1056 auto it = mapWallet.find(hashTx);
1057 assert(it != mapWallet.end());
1058 CWalletTx& origtx = it->second;
1059 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1060 return false;
1063 todo.insert(hashTx);
1065 while (!todo.empty()) {
1066 uint256 now = *todo.begin();
1067 todo.erase(now);
1068 done.insert(now);
1069 auto it = mapWallet.find(now);
1070 assert(it != mapWallet.end());
1071 CWalletTx& wtx = it->second;
1072 int currentconfirm = wtx.GetDepthInMainChain();
1073 // If the orig tx was not in block, none of its spends can be
1074 assert(currentconfirm <= 0);
1075 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1076 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1077 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1078 assert(!wtx.InMempool());
1079 wtx.nIndex = -1;
1080 wtx.setAbandoned();
1081 wtx.MarkDirty();
1082 walletdb.WriteTx(wtx);
1083 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1084 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1085 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1086 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1087 if (!done.count(iter->second)) {
1088 todo.insert(iter->second);
1090 iter++;
1092 // If a transaction changes 'conflicted' state, that changes the balance
1093 // available of the outputs it spends. So force those to be recomputed
1094 for (const CTxIn& txin : wtx.tx->vin)
1096 auto it = mapWallet.find(txin.prevout.hash);
1097 if (it != mapWallet.end()) {
1098 it->second.MarkDirty();
1104 return true;
1107 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1109 LOCK2(cs_main, cs_wallet);
1111 int conflictconfirms = 0;
1112 if (mapBlockIndex.count(hashBlock)) {
1113 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1114 if (chainActive.Contains(pindex)) {
1115 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1118 // If number of conflict confirms cannot be determined, this means
1119 // that the block is still unknown or not yet part of the main chain,
1120 // for example when loading the wallet during a reindex. Do nothing in that
1121 // case.
1122 if (conflictconfirms >= 0)
1123 return;
1125 // Do not flush the wallet here for performance reasons
1126 CWalletDB walletdb(*dbw, "r+", false);
1128 std::set<uint256> todo;
1129 std::set<uint256> done;
1131 todo.insert(hashTx);
1133 while (!todo.empty()) {
1134 uint256 now = *todo.begin();
1135 todo.erase(now);
1136 done.insert(now);
1137 auto it = mapWallet.find(now);
1138 assert(it != mapWallet.end());
1139 CWalletTx& wtx = it->second;
1140 int currentconfirm = wtx.GetDepthInMainChain();
1141 if (conflictconfirms < currentconfirm) {
1142 // Block is 'more conflicted' than current confirm; update.
1143 // Mark transaction as conflicted with this block.
1144 wtx.nIndex = -1;
1145 wtx.hashBlock = hashBlock;
1146 wtx.MarkDirty();
1147 walletdb.WriteTx(wtx);
1148 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1149 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1150 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1151 if (!done.count(iter->second)) {
1152 todo.insert(iter->second);
1154 iter++;
1156 // If a transaction changes 'conflicted' state, that changes the balance
1157 // available of the outputs it spends. So force those to be recomputed
1158 for (const CTxIn& txin : wtx.tx->vin) {
1159 auto it = mapWallet.find(txin.prevout.hash);
1160 if (it != mapWallet.end()) {
1161 it->second.MarkDirty();
1168 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1169 const CTransaction& tx = *ptx;
1171 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1172 return; // Not one of ours
1174 // If a transaction changes 'conflicted' state, that changes the balance
1175 // available of the outputs it spends. So force those to be
1176 // recomputed, also:
1177 for (const CTxIn& txin : tx.vin) {
1178 auto it = mapWallet.find(txin.prevout.hash);
1179 if (it != mapWallet.end()) {
1180 it->second.MarkDirty();
1185 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1186 LOCK2(cs_main, cs_wallet);
1187 SyncTransaction(ptx);
1190 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1191 LOCK2(cs_main, cs_wallet);
1192 // TODO: Temporarily ensure that mempool removals are notified before
1193 // connected transactions. This shouldn't matter, but the abandoned
1194 // state of transactions in our wallet is currently cleared when we
1195 // receive another notification and there is a race condition where
1196 // notification of a connected conflict might cause an outside process
1197 // to abandon a transaction and then have it inadvertently cleared by
1198 // the notification that the conflicted transaction was evicted.
1200 for (const CTransactionRef& ptx : vtxConflicted) {
1201 SyncTransaction(ptx);
1203 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1204 SyncTransaction(pblock->vtx[i], pindex, i);
1208 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1209 LOCK2(cs_main, cs_wallet);
1211 for (const CTransactionRef& ptx : pblock->vtx) {
1212 SyncTransaction(ptx);
1218 isminetype CWallet::IsMine(const CTxIn &txin) const
1221 LOCK(cs_wallet);
1222 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1223 if (mi != mapWallet.end())
1225 const CWalletTx& prev = (*mi).second;
1226 if (txin.prevout.n < prev.tx->vout.size())
1227 return IsMine(prev.tx->vout[txin.prevout.n]);
1230 return ISMINE_NO;
1233 // Note that this function doesn't distinguish between a 0-valued input,
1234 // and a not-"is mine" (according to the filter) input.
1235 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1238 LOCK(cs_wallet);
1239 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1240 if (mi != mapWallet.end())
1242 const CWalletTx& prev = (*mi).second;
1243 if (txin.prevout.n < prev.tx->vout.size())
1244 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1245 return prev.tx->vout[txin.prevout.n].nValue;
1248 return 0;
1251 isminetype CWallet::IsMine(const CTxOut& txout) const
1253 return ::IsMine(*this, txout.scriptPubKey);
1256 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1258 if (!MoneyRange(txout.nValue))
1259 throw std::runtime_error(std::string(__func__) + ": value out of range");
1260 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1263 bool CWallet::IsChange(const CTxOut& txout) const
1265 // TODO: fix handling of 'change' outputs. The assumption is that any
1266 // payment to a script that is ours, but is not in the address book
1267 // is change. That assumption is likely to break when we implement multisignature
1268 // wallets that return change back into a multi-signature-protected address;
1269 // a better way of identifying which outputs are 'the send' and which are
1270 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1271 // which output, if any, was change).
1272 if (::IsMine(*this, txout.scriptPubKey))
1274 CTxDestination address;
1275 if (!ExtractDestination(txout.scriptPubKey, address))
1276 return true;
1278 LOCK(cs_wallet);
1279 if (!mapAddressBook.count(address))
1280 return true;
1282 return false;
1285 CAmount CWallet::GetChange(const CTxOut& txout) const
1287 if (!MoneyRange(txout.nValue))
1288 throw std::runtime_error(std::string(__func__) + ": value out of range");
1289 return (IsChange(txout) ? txout.nValue : 0);
1292 bool CWallet::IsMine(const CTransaction& tx) const
1294 for (const CTxOut& txout : tx.vout)
1295 if (IsMine(txout))
1296 return true;
1297 return false;
1300 bool CWallet::IsFromMe(const CTransaction& tx) const
1302 return (GetDebit(tx, ISMINE_ALL) > 0);
1305 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1307 CAmount nDebit = 0;
1308 for (const CTxIn& txin : tx.vin)
1310 nDebit += GetDebit(txin, filter);
1311 if (!MoneyRange(nDebit))
1312 throw std::runtime_error(std::string(__func__) + ": value out of range");
1314 return nDebit;
1317 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1319 LOCK(cs_wallet);
1321 for (const CTxIn& txin : tx.vin)
1323 auto mi = mapWallet.find(txin.prevout.hash);
1324 if (mi == mapWallet.end())
1325 return false; // any unknown inputs can't be from us
1327 const CWalletTx& prev = (*mi).second;
1329 if (txin.prevout.n >= prev.tx->vout.size())
1330 return false; // invalid input!
1332 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1333 return false;
1335 return true;
1338 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1340 CAmount nCredit = 0;
1341 for (const CTxOut& txout : tx.vout)
1343 nCredit += GetCredit(txout, filter);
1344 if (!MoneyRange(nCredit))
1345 throw std::runtime_error(std::string(__func__) + ": value out of range");
1347 return nCredit;
1350 CAmount CWallet::GetChange(const CTransaction& tx) const
1352 CAmount nChange = 0;
1353 for (const CTxOut& txout : tx.vout)
1355 nChange += GetChange(txout);
1356 if (!MoneyRange(nChange))
1357 throw std::runtime_error(std::string(__func__) + ": value out of range");
1359 return nChange;
1362 CPubKey CWallet::GenerateNewHDMasterKey()
1364 CKey key;
1365 key.MakeNewKey(true);
1367 int64_t nCreationTime = GetTime();
1368 CKeyMetadata metadata(nCreationTime);
1370 // calculate the pubkey
1371 CPubKey pubkey = key.GetPubKey();
1372 assert(key.VerifyPubKey(pubkey));
1374 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1375 metadata.hdKeypath = "m";
1376 metadata.hdMasterKeyID = pubkey.GetID();
1379 LOCK(cs_wallet);
1381 // mem store the metadata
1382 mapKeyMetadata[pubkey.GetID()] = metadata;
1384 // write the key&metadata to the database
1385 if (!AddKeyPubKey(key, pubkey))
1386 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1389 return pubkey;
1392 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1394 LOCK(cs_wallet);
1395 // store the keyid (hash160) together with
1396 // the child index counter in the database
1397 // as a hdchain object
1398 CHDChain newHdChain;
1399 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1400 newHdChain.masterKeyID = pubkey.GetID();
1401 SetHDChain(newHdChain, false);
1403 return true;
1406 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1408 LOCK(cs_wallet);
1409 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1410 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1412 hdChain = chain;
1413 return true;
1416 bool CWallet::IsHDEnabled() const
1418 return !hdChain.masterKeyID.IsNull();
1421 int64_t CWalletTx::GetTxTime() const
1423 int64_t n = nTimeSmart;
1424 return n ? n : nTimeReceived;
1427 int CWalletTx::GetRequestCount() const
1429 // Returns -1 if it wasn't being tracked
1430 int nRequests = -1;
1432 LOCK(pwallet->cs_wallet);
1433 if (IsCoinBase())
1435 // Generated block
1436 if (!hashUnset())
1438 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1439 if (mi != pwallet->mapRequestCount.end())
1440 nRequests = (*mi).second;
1443 else
1445 // Did anyone request this transaction?
1446 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1447 if (mi != pwallet->mapRequestCount.end())
1449 nRequests = (*mi).second;
1451 // How about the block it's in?
1452 if (nRequests == 0 && !hashUnset())
1454 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1455 if (_mi != pwallet->mapRequestCount.end())
1456 nRequests = (*_mi).second;
1457 else
1458 nRequests = 1; // If it's in someone else's block it must have got out
1463 return nRequests;
1466 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1467 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1469 nFee = 0;
1470 listReceived.clear();
1471 listSent.clear();
1472 strSentAccount = strFromAccount;
1474 // Compute fee:
1475 CAmount nDebit = GetDebit(filter);
1476 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1478 CAmount nValueOut = tx->GetValueOut();
1479 nFee = nDebit - nValueOut;
1482 // Sent/received.
1483 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1485 const CTxOut& txout = tx->vout[i];
1486 isminetype fIsMine = pwallet->IsMine(txout);
1487 // Only need to handle txouts if AT LEAST one of these is true:
1488 // 1) they debit from us (sent)
1489 // 2) the output is to us (received)
1490 if (nDebit > 0)
1492 // Don't report 'change' txouts
1493 if (pwallet->IsChange(txout))
1494 continue;
1496 else if (!(fIsMine & filter))
1497 continue;
1499 // In either case, we need to get the destination address
1500 CTxDestination address;
1502 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1504 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1505 this->GetHash().ToString());
1506 address = CNoDestination();
1509 COutputEntry output = {address, txout.nValue, (int)i};
1511 // If we are debited by the transaction, add the output as a "sent" entry
1512 if (nDebit > 0)
1513 listSent.push_back(output);
1515 // If we are receiving the output, add it as a "received" entry
1516 if (fIsMine & filter)
1517 listReceived.push_back(output);
1523 * Scan active chain for relevant transactions after importing keys. This should
1524 * be called whenever new keys are added to the wallet, with the oldest key
1525 * creation time.
1527 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1528 * returned will be higher than startTime if relevant blocks could not be read.
1530 int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
1532 AssertLockHeld(cs_main);
1533 AssertLockHeld(cs_wallet);
1535 // Find starting block. May be null if nCreateTime is greater than the
1536 // highest blockchain timestamp, in which case there is nothing that needs
1537 // to be scanned.
1538 CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
1539 LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
1541 if (startBlock) {
1542 const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, update);
1543 if (failedBlock) {
1544 return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
1547 return startTime;
1551 * Scan the block chain (starting in pindexStart) for transactions
1552 * from or to us. If fUpdate is true, found transactions that already
1553 * exist in the wallet will be updated.
1555 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1556 * possible (due to pruning or corruption), returns pointer to the most recent
1557 * block that could not be scanned.
1559 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1561 int64_t nNow = GetTime();
1562 const CChainParams& chainParams = Params();
1564 CBlockIndex* pindex = pindexStart;
1565 CBlockIndex* ret = nullptr;
1567 LOCK2(cs_main, cs_wallet);
1568 fAbortRescan = false;
1569 fScanningWallet = true;
1571 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1572 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1573 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1574 while (pindex && !fAbortRescan)
1576 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1577 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1578 if (GetTime() >= nNow + 60) {
1579 nNow = GetTime();
1580 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1583 CBlock block;
1584 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1585 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1586 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1588 } else {
1589 ret = pindex;
1591 pindex = chainActive.Next(pindex);
1593 if (pindex && fAbortRescan) {
1594 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1596 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1598 fScanningWallet = false;
1600 return ret;
1603 void CWallet::ReacceptWalletTransactions()
1605 // If transactions aren't being broadcasted, don't let them into local mempool either
1606 if (!fBroadcastTransactions)
1607 return;
1608 LOCK2(cs_main, cs_wallet);
1609 std::map<int64_t, CWalletTx*> mapSorted;
1611 // Sort pending wallet transactions based on their initial wallet insertion order
1612 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1614 const uint256& wtxid = item.first;
1615 CWalletTx& wtx = item.second;
1616 assert(wtx.GetHash() == wtxid);
1618 int nDepth = wtx.GetDepthInMainChain();
1620 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1621 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1625 // Try to add wallet transactions to memory pool
1626 for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
1628 CWalletTx& wtx = *(item.second);
1630 LOCK(mempool.cs);
1631 CValidationState state;
1632 wtx.AcceptToMemoryPool(maxTxFee, state);
1636 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1638 assert(pwallet->GetBroadcastTransactions());
1639 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1641 CValidationState state;
1642 /* GetDepthInMainChain already catches known conflicts. */
1643 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1644 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1645 if (connman) {
1646 CInv inv(MSG_TX, GetHash());
1647 connman->ForEachNode([&inv](CNode* pnode)
1649 pnode->PushInventory(inv);
1651 return true;
1655 return false;
1658 std::set<uint256> CWalletTx::GetConflicts() const
1660 std::set<uint256> result;
1661 if (pwallet != nullptr)
1663 uint256 myHash = GetHash();
1664 result = pwallet->GetConflicts(myHash);
1665 result.erase(myHash);
1667 return result;
1670 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1672 if (tx->vin.empty())
1673 return 0;
1675 CAmount debit = 0;
1676 if(filter & ISMINE_SPENDABLE)
1678 if (fDebitCached)
1679 debit += nDebitCached;
1680 else
1682 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1683 fDebitCached = true;
1684 debit += nDebitCached;
1687 if(filter & ISMINE_WATCH_ONLY)
1689 if(fWatchDebitCached)
1690 debit += nWatchDebitCached;
1691 else
1693 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1694 fWatchDebitCached = true;
1695 debit += nWatchDebitCached;
1698 return debit;
1701 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1703 // Must wait until coinbase is safely deep enough in the chain before valuing it
1704 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1705 return 0;
1707 CAmount credit = 0;
1708 if (filter & ISMINE_SPENDABLE)
1710 // GetBalance can assume transactions in mapWallet won't change
1711 if (fCreditCached)
1712 credit += nCreditCached;
1713 else
1715 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1716 fCreditCached = true;
1717 credit += nCreditCached;
1720 if (filter & ISMINE_WATCH_ONLY)
1722 if (fWatchCreditCached)
1723 credit += nWatchCreditCached;
1724 else
1726 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1727 fWatchCreditCached = true;
1728 credit += nWatchCreditCached;
1731 return credit;
1734 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1736 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1738 if (fUseCache && fImmatureCreditCached)
1739 return nImmatureCreditCached;
1740 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1741 fImmatureCreditCached = true;
1742 return nImmatureCreditCached;
1745 return 0;
1748 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1750 if (pwallet == nullptr)
1751 return 0;
1753 // Must wait until coinbase is safely deep enough in the chain before valuing it
1754 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1755 return 0;
1757 if (fUseCache && fAvailableCreditCached)
1758 return nAvailableCreditCached;
1760 CAmount nCredit = 0;
1761 uint256 hashTx = GetHash();
1762 for (unsigned int i = 0; i < tx->vout.size(); i++)
1764 if (!pwallet->IsSpent(hashTx, i))
1766 const CTxOut &txout = tx->vout[i];
1767 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1768 if (!MoneyRange(nCredit))
1769 throw std::runtime_error(std::string(__func__) + " : value out of range");
1773 nAvailableCreditCached = nCredit;
1774 fAvailableCreditCached = true;
1775 return nCredit;
1778 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1780 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1782 if (fUseCache && fImmatureWatchCreditCached)
1783 return nImmatureWatchCreditCached;
1784 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1785 fImmatureWatchCreditCached = true;
1786 return nImmatureWatchCreditCached;
1789 return 0;
1792 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1794 if (pwallet == nullptr)
1795 return 0;
1797 // Must wait until coinbase is safely deep enough in the chain before valuing it
1798 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1799 return 0;
1801 if (fUseCache && fAvailableWatchCreditCached)
1802 return nAvailableWatchCreditCached;
1804 CAmount nCredit = 0;
1805 for (unsigned int i = 0; i < tx->vout.size(); i++)
1807 if (!pwallet->IsSpent(GetHash(), i))
1809 const CTxOut &txout = tx->vout[i];
1810 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1811 if (!MoneyRange(nCredit))
1812 throw std::runtime_error(std::string(__func__) + ": value out of range");
1816 nAvailableWatchCreditCached = nCredit;
1817 fAvailableWatchCreditCached = true;
1818 return nCredit;
1821 CAmount CWalletTx::GetChange() const
1823 if (fChangeCached)
1824 return nChangeCached;
1825 nChangeCached = pwallet->GetChange(*this);
1826 fChangeCached = true;
1827 return nChangeCached;
1830 bool CWalletTx::InMempool() const
1832 LOCK(mempool.cs);
1833 return mempool.exists(GetHash());
1836 bool CWalletTx::IsTrusted() const
1838 // Quick answer in most cases
1839 if (!CheckFinalTx(*this))
1840 return false;
1841 int nDepth = GetDepthInMainChain();
1842 if (nDepth >= 1)
1843 return true;
1844 if (nDepth < 0)
1845 return false;
1846 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1847 return false;
1849 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1850 if (!InMempool())
1851 return false;
1853 // Trusted if all inputs are from us and are in the mempool:
1854 for (const CTxIn& txin : tx->vin)
1856 // Transactions not sent by us: not trusted
1857 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1858 if (parent == nullptr)
1859 return false;
1860 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1861 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1862 return false;
1864 return true;
1867 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1869 CMutableTransaction tx1 = *this->tx;
1870 CMutableTransaction tx2 = *_tx.tx;
1871 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1872 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1873 return CTransaction(tx1) == CTransaction(tx2);
1876 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1878 std::vector<uint256> result;
1880 LOCK(cs_wallet);
1882 // Sort them in chronological order
1883 std::multimap<unsigned int, CWalletTx*> mapSorted;
1884 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1886 CWalletTx& wtx = item.second;
1887 // Don't rebroadcast if newer than nTime:
1888 if (wtx.nTimeReceived > nTime)
1889 continue;
1890 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1892 for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1894 CWalletTx& wtx = *item.second;
1895 if (wtx.RelayWalletTransaction(connman))
1896 result.push_back(wtx.GetHash());
1898 return result;
1901 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1903 // Do this infrequently and randomly to avoid giving away
1904 // that these are our transactions.
1905 if (GetTime() < nNextResend || !fBroadcastTransactions)
1906 return;
1907 bool fFirst = (nNextResend == 0);
1908 nNextResend = GetTime() + GetRand(30 * 60);
1909 if (fFirst)
1910 return;
1912 // Only do it if there's been a new block since last time
1913 if (nBestBlockTime < nLastResend)
1914 return;
1915 nLastResend = GetTime();
1917 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1918 // block was found:
1919 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1920 if (!relayed.empty())
1921 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1924 /** @} */ // end of mapWallet
1929 /** @defgroup Actions
1931 * @{
1935 CAmount CWallet::GetBalance() const
1937 CAmount nTotal = 0;
1939 LOCK2(cs_main, cs_wallet);
1940 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1942 const CWalletTx* pcoin = &(*it).second;
1943 if (pcoin->IsTrusted())
1944 nTotal += pcoin->GetAvailableCredit();
1948 return nTotal;
1951 CAmount CWallet::GetUnconfirmedBalance() const
1953 CAmount nTotal = 0;
1955 LOCK2(cs_main, cs_wallet);
1956 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1958 const CWalletTx* pcoin = &(*it).second;
1959 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1960 nTotal += pcoin->GetAvailableCredit();
1963 return nTotal;
1966 CAmount CWallet::GetImmatureBalance() const
1968 CAmount nTotal = 0;
1970 LOCK2(cs_main, cs_wallet);
1971 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1973 const CWalletTx* pcoin = &(*it).second;
1974 nTotal += pcoin->GetImmatureCredit();
1977 return nTotal;
1980 CAmount CWallet::GetWatchOnlyBalance() const
1982 CAmount nTotal = 0;
1984 LOCK2(cs_main, cs_wallet);
1985 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1987 const CWalletTx* pcoin = &(*it).second;
1988 if (pcoin->IsTrusted())
1989 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1993 return nTotal;
1996 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1998 CAmount nTotal = 0;
2000 LOCK2(cs_main, cs_wallet);
2001 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2003 const CWalletTx* pcoin = &(*it).second;
2004 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
2005 nTotal += pcoin->GetAvailableWatchOnlyCredit();
2008 return nTotal;
2011 CAmount CWallet::GetImmatureWatchOnlyBalance() const
2013 CAmount nTotal = 0;
2015 LOCK2(cs_main, cs_wallet);
2016 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2018 const CWalletTx* pcoin = &(*it).second;
2019 nTotal += pcoin->GetImmatureWatchOnlyCredit();
2022 return nTotal;
2025 // Calculate total balance in a different way from GetBalance. The biggest
2026 // difference is that GetBalance sums up all unspent TxOuts paying to the
2027 // wallet, while this sums up both spent and unspent TxOuts paying to the
2028 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2029 // also has fewer restrictions on which unconfirmed transactions are considered
2030 // trusted.
2031 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
2033 LOCK2(cs_main, cs_wallet);
2035 CAmount balance = 0;
2036 for (const auto& entry : mapWallet) {
2037 const CWalletTx& wtx = entry.second;
2038 const int depth = wtx.GetDepthInMainChain();
2039 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
2040 continue;
2043 // Loop through tx outputs and add incoming payments. For outgoing txs,
2044 // treat change outputs specially, as part of the amount debited.
2045 CAmount debit = wtx.GetDebit(filter);
2046 const bool outgoing = debit > 0;
2047 for (const CTxOut& out : wtx.tx->vout) {
2048 if (outgoing && IsChange(out)) {
2049 debit -= out.nValue;
2050 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
2051 balance += out.nValue;
2055 // For outgoing txs, subtract amount debited.
2056 if (outgoing && (!account || *account == wtx.strFromAccount)) {
2057 balance -= debit;
2061 if (account) {
2062 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
2065 return balance;
2068 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
2070 LOCK2(cs_main, cs_wallet);
2072 CAmount balance = 0;
2073 std::vector<COutput> vCoins;
2074 AvailableCoins(vCoins, true, coinControl);
2075 for (const COutput& out : vCoins) {
2076 if (out.fSpendable) {
2077 balance += out.tx->tx->vout[out.i].nValue;
2080 return balance;
2083 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
2085 vCoins.clear();
2088 LOCK2(cs_main, cs_wallet);
2090 CAmount nTotal = 0;
2092 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2094 const uint256& wtxid = it->first;
2095 const CWalletTx* pcoin = &(*it).second;
2097 if (!CheckFinalTx(*pcoin))
2098 continue;
2100 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2101 continue;
2103 int nDepth = pcoin->GetDepthInMainChain();
2104 if (nDepth < 0)
2105 continue;
2107 // We should not consider coins which aren't at least in our mempool
2108 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2109 if (nDepth == 0 && !pcoin->InMempool())
2110 continue;
2112 bool safeTx = pcoin->IsTrusted();
2114 // We should not consider coins from transactions that are replacing
2115 // other transactions.
2117 // Example: There is a transaction A which is replaced by bumpfee
2118 // transaction B. In this case, we want to prevent creation of
2119 // a transaction B' which spends an output of B.
2121 // Reason: If transaction A were initially confirmed, transactions B
2122 // and B' would no longer be valid, so the user would have to create
2123 // a new transaction C to replace B'. However, in the case of a
2124 // one-block reorg, transactions B' and C might BOTH be accepted,
2125 // when the user only wanted one of them. Specifically, there could
2126 // be a 1-block reorg away from the chain where transactions A and C
2127 // were accepted to another chain where B, B', and C were all
2128 // accepted.
2129 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2130 safeTx = false;
2133 // Similarly, we should not consider coins from transactions that
2134 // have been replaced. In the example above, we would want to prevent
2135 // creation of a transaction A' spending an output of A, because if
2136 // transaction B were initially confirmed, conflicting with A and
2137 // A', we wouldn't want to the user to create a transaction D
2138 // intending to replace A', but potentially resulting in a scenario
2139 // where A, A', and D could all be accepted (instead of just B and
2140 // D, or just A and A' like the user would want).
2141 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2142 safeTx = false;
2145 if (fOnlySafe && !safeTx) {
2146 continue;
2149 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2150 continue;
2152 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2153 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2154 continue;
2156 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2157 continue;
2159 if (IsLockedCoin((*it).first, i))
2160 continue;
2162 if (IsSpent(wtxid, i))
2163 continue;
2165 isminetype mine = IsMine(pcoin->tx->vout[i]);
2167 if (mine == ISMINE_NO) {
2168 continue;
2171 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2172 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2174 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2176 // Checks the sum amount of all UTXO's.
2177 if (nMinimumSumAmount != MAX_MONEY) {
2178 nTotal += pcoin->tx->vout[i].nValue;
2180 if (nTotal >= nMinimumSumAmount) {
2181 return;
2185 // Checks the maximum number of UTXO's.
2186 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2187 return;
2194 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2196 // TODO: Add AssertLockHeld(cs_wallet) here.
2198 // Because the return value from this function contains pointers to
2199 // CWalletTx objects, callers to this function really should acquire the
2200 // cs_wallet lock before calling it. However, the current caller doesn't
2201 // acquire this lock yet. There was an attempt to add the missing lock in
2202 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2203 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2204 // avoid adding some extra complexity to the Qt code.
2206 std::map<CTxDestination, std::vector<COutput>> result;
2208 std::vector<COutput> availableCoins;
2209 AvailableCoins(availableCoins);
2211 LOCK2(cs_main, cs_wallet);
2212 for (auto& coin : availableCoins) {
2213 CTxDestination address;
2214 if (coin.fSpendable &&
2215 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2216 result[address].emplace_back(std::move(coin));
2220 std::vector<COutPoint> lockedCoins;
2221 ListLockedCoins(lockedCoins);
2222 for (const auto& output : lockedCoins) {
2223 auto it = mapWallet.find(output.hash);
2224 if (it != mapWallet.end()) {
2225 int depth = it->second.GetDepthInMainChain();
2226 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2227 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2228 CTxDestination address;
2229 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2230 result[address].emplace_back(
2231 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2237 return result;
2240 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2242 const CTransaction* ptx = &tx;
2243 int n = output;
2244 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2245 const COutPoint& prevout = ptx->vin[0].prevout;
2246 auto it = mapWallet.find(prevout.hash);
2247 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2248 !IsMine(it->second.tx->vout[prevout.n])) {
2249 break;
2251 ptx = it->second.tx.get();
2252 n = prevout.n;
2254 return ptx->vout[n];
2257 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2258 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2260 std::vector<char> vfIncluded;
2262 vfBest.assign(vValue.size(), true);
2263 nBest = nTotalLower;
2265 FastRandomContext insecure_rand;
2267 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2269 vfIncluded.assign(vValue.size(), false);
2270 CAmount nTotal = 0;
2271 bool fReachedTarget = false;
2272 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2274 for (unsigned int i = 0; i < vValue.size(); i++)
2276 //The solver here uses a randomized algorithm,
2277 //the randomness serves no real security purpose but is just
2278 //needed to prevent degenerate behavior and it is important
2279 //that the rng is fast. We do not use a constant random sequence,
2280 //because there may be some privacy improvement by making
2281 //the selection random.
2282 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2284 nTotal += vValue[i].txout.nValue;
2285 vfIncluded[i] = true;
2286 if (nTotal >= nTargetValue)
2288 fReachedTarget = true;
2289 if (nTotal < nBest)
2291 nBest = nTotal;
2292 vfBest = vfIncluded;
2294 nTotal -= vValue[i].txout.nValue;
2295 vfIncluded[i] = false;
2303 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2304 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2306 setCoinsRet.clear();
2307 nValueRet = 0;
2309 // List of values less than target
2310 boost::optional<CInputCoin> coinLowestLarger;
2311 std::vector<CInputCoin> vValue;
2312 CAmount nTotalLower = 0;
2314 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2316 for (const COutput &output : vCoins)
2318 if (!output.fSpendable)
2319 continue;
2321 const CWalletTx *pcoin = output.tx;
2323 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2324 continue;
2326 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2327 continue;
2329 int i = output.i;
2331 CInputCoin coin = CInputCoin(pcoin, i);
2333 if (coin.txout.nValue == nTargetValue)
2335 setCoinsRet.insert(coin);
2336 nValueRet += coin.txout.nValue;
2337 return true;
2339 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2341 vValue.push_back(coin);
2342 nTotalLower += coin.txout.nValue;
2344 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2346 coinLowestLarger = coin;
2350 if (nTotalLower == nTargetValue)
2352 for (const auto& input : vValue)
2354 setCoinsRet.insert(input);
2355 nValueRet += input.txout.nValue;
2357 return true;
2360 if (nTotalLower < nTargetValue)
2362 if (!coinLowestLarger)
2363 return false;
2364 setCoinsRet.insert(coinLowestLarger.get());
2365 nValueRet += coinLowestLarger->txout.nValue;
2366 return true;
2369 // Solve subset sum by stochastic approximation
2370 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2371 std::reverse(vValue.begin(), vValue.end());
2372 std::vector<char> vfBest;
2373 CAmount nBest;
2375 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2376 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2377 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2379 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2380 // or the next bigger coin is closer), return the bigger coin
2381 if (coinLowestLarger &&
2382 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2384 setCoinsRet.insert(coinLowestLarger.get());
2385 nValueRet += coinLowestLarger->txout.nValue;
2387 else {
2388 for (unsigned int i = 0; i < vValue.size(); i++)
2389 if (vfBest[i])
2391 setCoinsRet.insert(vValue[i]);
2392 nValueRet += vValue[i].txout.nValue;
2395 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2396 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2397 for (unsigned int i = 0; i < vValue.size(); i++) {
2398 if (vfBest[i]) {
2399 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2402 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2406 return true;
2409 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2411 std::vector<COutput> vCoins(vAvailableCoins);
2413 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2414 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2416 for (const COutput& out : vCoins)
2418 if (!out.fSpendable)
2419 continue;
2420 nValueRet += out.tx->tx->vout[out.i].nValue;
2421 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2423 return (nValueRet >= nTargetValue);
2426 // calculate value from preset inputs and store them
2427 std::set<CInputCoin> setPresetCoins;
2428 CAmount nValueFromPresetInputs = 0;
2430 std::vector<COutPoint> vPresetInputs;
2431 if (coinControl)
2432 coinControl->ListSelected(vPresetInputs);
2433 for (const COutPoint& outpoint : vPresetInputs)
2435 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2436 if (it != mapWallet.end())
2438 const CWalletTx* pcoin = &it->second;
2439 // Clearly invalid input, fail
2440 if (pcoin->tx->vout.size() <= outpoint.n)
2441 return false;
2442 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2443 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2444 } else
2445 return false; // TODO: Allow non-wallet inputs
2448 // remove preset inputs from vCoins
2449 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2451 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2452 it = vCoins.erase(it);
2453 else
2454 ++it;
2457 size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2458 bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2460 bool res = nTargetValue <= nValueFromPresetInputs ||
2461 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2462 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2463 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2464 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2465 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2466 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2467 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2469 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2470 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2472 // add preset inputs to the total value selected
2473 nValueRet += nValueFromPresetInputs;
2475 return res;
2478 bool CWallet::SignTransaction(CMutableTransaction &tx)
2480 AssertLockHeld(cs_wallet); // mapWallet
2482 // sign the new tx
2483 CTransaction txNewConst(tx);
2484 int nIn = 0;
2485 for (const auto& input : tx.vin) {
2486 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2487 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2488 return false;
2490 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2491 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2492 SignatureData sigdata;
2493 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2494 return false;
2496 UpdateTransaction(tx, nIn, sigdata);
2497 nIn++;
2499 return true;
2502 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
2504 std::vector<CRecipient> vecSend;
2506 // Turn the txout set into a CRecipient vector
2507 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2509 const CTxOut& txOut = tx.vout[idx];
2510 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2511 vecSend.push_back(recipient);
2514 coinControl.fAllowOtherInputs = true;
2516 for (const CTxIn& txin : tx.vin)
2517 coinControl.Select(txin.prevout);
2519 CReserveKey reservekey(this);
2520 CWalletTx wtx;
2521 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
2522 return false;
2525 if (nChangePosInOut != -1) {
2526 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2527 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2528 // so just remove the key from the keypool here.
2529 reservekey.KeepKey();
2532 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2533 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2534 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2536 // Add new txins (keeping original txin scriptSig/order)
2537 for (const CTxIn& txin : wtx.tx->vin)
2539 if (!coinControl.IsSelected(txin.prevout))
2541 tx.vin.push_back(txin);
2543 if (lockUnspents)
2545 LOCK2(cs_main, cs_wallet);
2546 LockCoin(txin.prevout);
2552 return true;
2555 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2556 int& nChangePosInOut, std::string& strFailReason, const CCoinControl& coin_control, bool sign)
2558 CAmount nValue = 0;
2559 int nChangePosRequest = nChangePosInOut;
2560 unsigned int nSubtractFeeFromAmount = 0;
2561 for (const auto& recipient : vecSend)
2563 if (nValue < 0 || recipient.nAmount < 0)
2565 strFailReason = _("Transaction amounts must not be negative");
2566 return false;
2568 nValue += recipient.nAmount;
2570 if (recipient.fSubtractFeeFromAmount)
2571 nSubtractFeeFromAmount++;
2573 if (vecSend.empty())
2575 strFailReason = _("Transaction must have at least one recipient");
2576 return false;
2579 wtxNew.fTimeReceivedIsTxTime = true;
2580 wtxNew.BindWallet(this);
2581 CMutableTransaction txNew;
2583 // Discourage fee sniping.
2585 // For a large miner the value of the transactions in the best block and
2586 // the mempool can exceed the cost of deliberately attempting to mine two
2587 // blocks to orphan the current best block. By setting nLockTime such that
2588 // only the next block can include the transaction, we discourage this
2589 // practice as the height restricted and limited blocksize gives miners
2590 // considering fee sniping fewer options for pulling off this attack.
2592 // A simple way to think about this is from the wallet's point of view we
2593 // always want the blockchain to move forward. By setting nLockTime this
2594 // way we're basically making the statement that we only want this
2595 // transaction to appear in the next block; we don't want to potentially
2596 // encourage reorgs by allowing transactions to appear at lower heights
2597 // than the next block in forks of the best chain.
2599 // Of course, the subsidy is high enough, and transaction volume low
2600 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2601 // now we ensure code won't be written that makes assumptions about
2602 // nLockTime that preclude a fix later.
2603 txNew.nLockTime = chainActive.Height();
2605 // Secondly occasionally randomly pick a nLockTime even further back, so
2606 // that transactions that are delayed after signing for whatever reason,
2607 // e.g. high-latency mix networks and some CoinJoin implementations, have
2608 // better privacy.
2609 if (GetRandInt(10) == 0)
2610 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2612 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2613 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2614 FeeCalculation feeCalc;
2615 CAmount nFeeNeeded;
2616 unsigned int nBytes;
2618 std::set<CInputCoin> setCoins;
2619 LOCK2(cs_main, cs_wallet);
2621 std::vector<COutput> vAvailableCoins;
2622 AvailableCoins(vAvailableCoins, true, &coin_control);
2624 // Create change script that will be used if we need change
2625 // TODO: pass in scriptChange instead of reservekey so
2626 // change transaction isn't always pay-to-bitcoin-address
2627 CScript scriptChange;
2629 // coin control: send change to custom address
2630 if (!boost::get<CNoDestination>(&coin_control.destChange)) {
2631 scriptChange = GetScriptForDestination(coin_control.destChange);
2632 } else { // no coin control: send change to newly generated address
2633 // Note: We use a new key here to keep it from being obvious which side is the change.
2634 // The drawback is that by not reusing a previous key, the change may be lost if a
2635 // backup is restored, if the backup doesn't have the new private key for the change.
2636 // If we reused the old key, it would be possible to add code to look for and
2637 // rediscover unknown transactions that were written with keys of ours to recover
2638 // post-backup change.
2640 // Reserve a new key pair from key pool
2641 CPubKey vchPubKey;
2642 bool ret;
2643 ret = reservekey.GetReservedKey(vchPubKey, true);
2644 if (!ret)
2646 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2647 return false;
2650 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2652 CTxOut change_prototype_txout(0, scriptChange);
2653 size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
2655 CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
2656 nFeeRet = 0;
2657 bool pick_new_inputs = true;
2658 CAmount nValueIn = 0;
2659 // Start with no fee and loop until there is enough fee
2660 while (true)
2662 nChangePosInOut = nChangePosRequest;
2663 txNew.vin.clear();
2664 txNew.vout.clear();
2665 wtxNew.fFromMe = true;
2666 bool fFirst = true;
2668 CAmount nValueToSelect = nValue;
2669 if (nSubtractFeeFromAmount == 0)
2670 nValueToSelect += nFeeRet;
2671 // vouts to the payees
2672 for (const auto& recipient : vecSend)
2674 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2676 if (recipient.fSubtractFeeFromAmount)
2678 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2680 if (fFirst) // first receiver pays the remainder not divisible by output count
2682 fFirst = false;
2683 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2687 if (IsDust(txout, ::dustRelayFee))
2689 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2691 if (txout.nValue < 0)
2692 strFailReason = _("The transaction amount is too small to pay the fee");
2693 else
2694 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2696 else
2697 strFailReason = _("Transaction amount too small");
2698 return false;
2700 txNew.vout.push_back(txout);
2703 // Choose coins to use
2704 if (pick_new_inputs) {
2705 nValueIn = 0;
2706 setCoins.clear();
2707 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
2709 strFailReason = _("Insufficient funds");
2710 return false;
2714 const CAmount nChange = nValueIn - nValueToSelect;
2716 if (nChange > 0)
2718 // Fill a vout to ourself
2719 CTxOut newTxOut(nChange, scriptChange);
2721 // Never create dust outputs; if we would, just
2722 // add the dust to the fee.
2723 if (IsDust(newTxOut, discard_rate))
2725 nChangePosInOut = -1;
2726 nFeeRet += nChange;
2728 else
2730 if (nChangePosInOut == -1)
2732 // Insert change txn at random position:
2733 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2735 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2737 strFailReason = _("Change index out of range");
2738 return false;
2741 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2742 txNew.vout.insert(position, newTxOut);
2744 } else {
2745 nChangePosInOut = -1;
2748 // Fill vin
2750 // Note how the sequence number is set to non-maxint so that
2751 // the nLockTime set above actually works.
2753 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2754 // we use the highest possible value in that range (maxint-2)
2755 // to avoid conflicting with other possible uses of nSequence,
2756 // and in the spirit of "smallest possible change from prior
2757 // behavior."
2758 const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
2759 for (const auto& coin : setCoins)
2760 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2761 nSequence));
2763 // Fill in dummy signatures for fee calculation.
2764 if (!DummySignTx(txNew, setCoins)) {
2765 strFailReason = _("Signing transaction failed");
2766 return false;
2769 nBytes = GetVirtualTransactionSize(txNew);
2771 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2772 for (auto& vin : txNew.vin) {
2773 vin.scriptSig = CScript();
2774 vin.scriptWitness.SetNull();
2777 nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
2779 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2780 // because we must be at the maximum allowed fee.
2781 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2783 strFailReason = _("Transaction too large for fee policy");
2784 return false;
2787 if (nFeeRet >= nFeeNeeded) {
2788 // Reduce fee to only the needed amount if possible. This
2789 // prevents potential overpayment in fees if the coins
2790 // selected to meet nFeeNeeded result in a transaction that
2791 // requires less fee than the prior iteration.
2793 // If we have no change and a big enough excess fee, then
2794 // try to construct transaction again only without picking
2795 // new inputs. We now know we only need the smaller fee
2796 // (because of reduced tx size) and so we should add a
2797 // change output. Only try this once.
2798 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2799 unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2800 CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
2801 CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
2802 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2803 pick_new_inputs = false;
2804 nFeeRet = fee_needed_with_change;
2805 continue;
2809 // If we have change output already, just increase it
2810 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2811 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2812 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2813 change_position->nValue += extraFeePaid;
2814 nFeeRet -= extraFeePaid;
2816 break; // Done, enough fee included.
2818 else if (!pick_new_inputs) {
2819 // This shouldn't happen, we should have had enough excess
2820 // fee to pay for the new output and still meet nFeeNeeded
2821 // Or we should have just subtracted fee from recipients and
2822 // nFeeNeeded should not have changed
2823 strFailReason = _("Transaction fee and change calculation failed");
2824 return false;
2827 // Try to reduce change to include necessary fee
2828 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2829 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2830 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2831 // Only reduce change if remaining amount is still a large enough output.
2832 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2833 change_position->nValue -= additionalFeeNeeded;
2834 nFeeRet += additionalFeeNeeded;
2835 break; // Done, able to increase fee from change
2839 // If subtracting fee from recipients, we now know what fee we
2840 // need to subtract, we have no reason to reselect inputs
2841 if (nSubtractFeeFromAmount > 0) {
2842 pick_new_inputs = false;
2845 // Include more fee and try again.
2846 nFeeRet = nFeeNeeded;
2847 continue;
2851 if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
2853 if (sign)
2855 CTransaction txNewConst(txNew);
2856 int nIn = 0;
2857 for (const auto& coin : setCoins)
2859 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2860 SignatureData sigdata;
2862 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2864 strFailReason = _("Signing transaction failed");
2865 return false;
2866 } else {
2867 UpdateTransaction(txNew, nIn, sigdata);
2870 nIn++;
2874 // Embed the constructed transaction data in wtxNew.
2875 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2877 // Limit size
2878 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2880 strFailReason = _("Transaction too large");
2881 return false;
2885 if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2886 // Lastly, ensure this tx will pass the mempool's chain limits
2887 LockPoints lp;
2888 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2889 CTxMemPool::setEntries setAncestors;
2890 size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2891 size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2892 size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2893 size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2894 std::string errString;
2895 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2896 strFailReason = _("Transaction has too long of a mempool chain");
2897 return false;
2901 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",
2902 nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
2903 feeCalc.est.pass.start, feeCalc.est.pass.end,
2904 100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
2905 feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
2906 feeCalc.est.fail.start, feeCalc.est.fail.end,
2907 100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
2908 feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
2909 return true;
2913 * Call after CreateTransaction unless you want to abort
2915 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2918 LOCK2(cs_main, cs_wallet);
2919 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2921 // Take key pair from key pool so it won't be used again
2922 reservekey.KeepKey();
2924 // Add tx to wallet, because if it has change it's also ours,
2925 // otherwise just for transaction history.
2926 AddToWallet(wtxNew);
2928 // Notify that old coins are spent
2929 for (const CTxIn& txin : wtxNew.tx->vin)
2931 CWalletTx &coin = mapWallet[txin.prevout.hash];
2932 coin.BindWallet(this);
2933 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2937 // Track how many getdata requests our transaction gets
2938 mapRequestCount[wtxNew.GetHash()] = 0;
2940 if (fBroadcastTransactions)
2942 // Broadcast
2943 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2944 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2945 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2946 } else {
2947 wtxNew.RelayWalletTransaction(connman);
2951 return true;
2954 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2955 CWalletDB walletdb(*dbw);
2956 return walletdb.ListAccountCreditDebit(strAccount, entries);
2959 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2961 CWalletDB walletdb(*dbw);
2963 return AddAccountingEntry(acentry, &walletdb);
2966 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2968 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
2969 return false;
2972 laccentries.push_back(acentry);
2973 CAccountingEntry & entry = laccentries.back();
2974 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
2976 return true;
2979 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2981 LOCK2(cs_main, cs_wallet);
2983 fFirstRunRet = false;
2984 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2985 if (nLoadWalletRet == DB_NEED_REWRITE)
2987 if (dbw->Rewrite("\x04pool"))
2989 setInternalKeyPool.clear();
2990 setExternalKeyPool.clear();
2991 m_pool_key_to_index.clear();
2992 // Note: can't top-up keypool here, because wallet is locked.
2993 // User will be prompted to unlock wallet the next operation
2994 // that requires a new key.
2998 // This wallet is in its first run if all of these are empty
2999 fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
3001 if (nLoadWalletRet != DB_LOAD_OK)
3002 return nLoadWalletRet;
3004 uiInterface.LoadWallet(this);
3006 return DB_LOAD_OK;
3009 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
3011 AssertLockHeld(cs_wallet); // mapWallet
3012 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
3013 for (uint256 hash : vHashOut)
3014 mapWallet.erase(hash);
3016 if (nZapSelectTxRet == DB_NEED_REWRITE)
3018 if (dbw->Rewrite("\x04pool"))
3020 setInternalKeyPool.clear();
3021 setExternalKeyPool.clear();
3022 m_pool_key_to_index.clear();
3023 // Note: can't top-up keypool here, because wallet is locked.
3024 // User will be prompted to unlock wallet the next operation
3025 // that requires a new key.
3029 if (nZapSelectTxRet != DB_LOAD_OK)
3030 return nZapSelectTxRet;
3032 MarkDirty();
3034 return DB_LOAD_OK;
3038 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
3040 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
3041 if (nZapWalletTxRet == DB_NEED_REWRITE)
3043 if (dbw->Rewrite("\x04pool"))
3045 LOCK(cs_wallet);
3046 setInternalKeyPool.clear();
3047 setExternalKeyPool.clear();
3048 m_pool_key_to_index.clear();
3049 // Note: can't top-up keypool here, because wallet is locked.
3050 // User will be prompted to unlock wallet the next operation
3051 // that requires a new key.
3055 if (nZapWalletTxRet != DB_LOAD_OK)
3056 return nZapWalletTxRet;
3058 return DB_LOAD_OK;
3062 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
3064 bool fUpdated = false;
3066 LOCK(cs_wallet); // mapAddressBook
3067 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3068 fUpdated = mi != mapAddressBook.end();
3069 mapAddressBook[address].name = strName;
3070 if (!strPurpose.empty()) /* update purpose only if requested */
3071 mapAddressBook[address].purpose = strPurpose;
3073 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3074 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3075 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
3076 return false;
3077 return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
3080 bool CWallet::DelAddressBook(const CTxDestination& address)
3083 LOCK(cs_wallet); // mapAddressBook
3085 // Delete destdata tuples associated with address
3086 std::string strAddress = EncodeDestination(address);
3087 for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
3089 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3091 mapAddressBook.erase(address);
3094 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3096 CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
3097 return CWalletDB(*dbw).EraseName(EncodeDestination(address));
3100 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3102 CTxDestination address;
3103 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3104 auto mi = mapAddressBook.find(address);
3105 if (mi != mapAddressBook.end()) {
3106 return mi->second.name;
3109 // A scriptPubKey that doesn't have an entry in the address book is
3110 // associated with the default account ("").
3111 const static std::string DEFAULT_ACCOUNT_NAME;
3112 return DEFAULT_ACCOUNT_NAME;
3116 * Mark old keypool keys as used,
3117 * and generate all new keys
3119 bool CWallet::NewKeyPool()
3122 LOCK(cs_wallet);
3123 CWalletDB walletdb(*dbw);
3125 for (int64_t nIndex : setInternalKeyPool) {
3126 walletdb.ErasePool(nIndex);
3128 setInternalKeyPool.clear();
3130 for (int64_t nIndex : setExternalKeyPool) {
3131 walletdb.ErasePool(nIndex);
3133 setExternalKeyPool.clear();
3135 m_pool_key_to_index.clear();
3137 if (!TopUpKeyPool()) {
3138 return false;
3140 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3142 return true;
3145 size_t CWallet::KeypoolCountExternalKeys()
3147 AssertLockHeld(cs_wallet); // setExternalKeyPool
3148 return setExternalKeyPool.size();
3151 void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
3153 AssertLockHeld(cs_wallet);
3154 if (keypool.fInternal) {
3155 setInternalKeyPool.insert(nIndex);
3156 } else {
3157 setExternalKeyPool.insert(nIndex);
3159 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3160 m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
3162 // If no metadata exists yet, create a default with the pool key's
3163 // creation time. Note that this may be overwritten by actually
3164 // stored metadata for that key later, which is fine.
3165 CKeyID keyid = keypool.vchPubKey.GetID();
3166 if (mapKeyMetadata.count(keyid) == 0)
3167 mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
3170 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3173 LOCK(cs_wallet);
3175 if (IsLocked())
3176 return false;
3178 // Top up key pool
3179 unsigned int nTargetSize;
3180 if (kpSize > 0)
3181 nTargetSize = kpSize;
3182 else
3183 nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3185 // count amount of available keys (internal, external)
3186 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3187 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3188 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
3190 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3192 // don't create extra internal keys
3193 missingInternal = 0;
3195 bool internal = false;
3196 CWalletDB walletdb(*dbw);
3197 for (int64_t i = missingInternal + missingExternal; i--;)
3199 if (i < missingInternal) {
3200 internal = true;
3203 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
3204 int64_t index = ++m_max_keypool_index;
3206 CPubKey pubkey(GenerateNewKey(walletdb, internal));
3207 if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
3208 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3211 if (internal) {
3212 setInternalKeyPool.insert(index);
3213 } else {
3214 setExternalKeyPool.insert(index);
3216 m_pool_key_to_index[pubkey.GetID()] = index;
3218 if (missingInternal + missingExternal > 0) {
3219 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
3222 return true;
3225 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
3227 nIndex = -1;
3228 keypool.vchPubKey = CPubKey();
3230 LOCK(cs_wallet);
3232 if (!IsLocked())
3233 TopUpKeyPool();
3235 bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
3236 std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
3238 // Get the oldest key
3239 if(setKeyPool.empty())
3240 return;
3242 CWalletDB walletdb(*dbw);
3244 auto it = setKeyPool.begin();
3245 nIndex = *it;
3246 setKeyPool.erase(it);
3247 if (!walletdb.ReadPool(nIndex, keypool)) {
3248 throw std::runtime_error(std::string(__func__) + ": read failed");
3250 if (!HaveKey(keypool.vchPubKey.GetID())) {
3251 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3253 if (keypool.fInternal != fReturningInternal) {
3254 throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
3257 assert(keypool.vchPubKey.IsValid());
3258 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3259 LogPrintf("keypool reserve %d\n", nIndex);
3263 void CWallet::KeepKey(int64_t nIndex)
3265 // Remove from key pool
3266 CWalletDB walletdb(*dbw);
3267 walletdb.ErasePool(nIndex);
3268 LogPrintf("keypool keep %d\n", nIndex);
3271 void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
3273 // Return to key pool
3275 LOCK(cs_wallet);
3276 if (fInternal) {
3277 setInternalKeyPool.insert(nIndex);
3278 } else {
3279 setExternalKeyPool.insert(nIndex);
3281 m_pool_key_to_index[pubkey.GetID()] = nIndex;
3283 LogPrintf("keypool return %d\n", nIndex);
3286 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3288 CKeyPool keypool;
3290 LOCK(cs_wallet);
3291 int64_t nIndex = 0;
3292 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3293 if (nIndex == -1)
3295 if (IsLocked()) return false;
3296 CWalletDB walletdb(*dbw);
3297 result = GenerateNewKey(walletdb, internal);
3298 return true;
3300 KeepKey(nIndex);
3301 result = keypool.vchPubKey;
3303 return true;
3306 static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
3307 if (setKeyPool.empty()) {
3308 return GetTime();
3311 CKeyPool keypool;
3312 int64_t nIndex = *(setKeyPool.begin());
3313 if (!walletdb.ReadPool(nIndex, keypool)) {
3314 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3316 assert(keypool.vchPubKey.IsValid());
3317 return keypool.nTime;
3320 int64_t CWallet::GetOldestKeyPoolTime()
3322 LOCK(cs_wallet);
3324 CWalletDB walletdb(*dbw);
3326 // load oldest key from keypool, get time and return
3327 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
3328 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
3329 oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
3332 return oldestKey;
3335 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3337 std::map<CTxDestination, CAmount> balances;
3340 LOCK(cs_wallet);
3341 for (const auto& walletEntry : mapWallet)
3343 const CWalletTx *pcoin = &walletEntry.second;
3345 if (!pcoin->IsTrusted())
3346 continue;
3348 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3349 continue;
3351 int nDepth = pcoin->GetDepthInMainChain();
3352 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3353 continue;
3355 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3357 CTxDestination addr;
3358 if (!IsMine(pcoin->tx->vout[i]))
3359 continue;
3360 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3361 continue;
3363 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3365 if (!balances.count(addr))
3366 balances[addr] = 0;
3367 balances[addr] += n;
3372 return balances;
3375 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3377 AssertLockHeld(cs_wallet); // mapWallet
3378 std::set< std::set<CTxDestination> > groupings;
3379 std::set<CTxDestination> grouping;
3381 for (const auto& walletEntry : mapWallet)
3383 const CWalletTx *pcoin = &walletEntry.second;
3385 if (pcoin->tx->vin.size() > 0)
3387 bool any_mine = false;
3388 // group all input addresses with each other
3389 for (CTxIn txin : pcoin->tx->vin)
3391 CTxDestination address;
3392 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3393 continue;
3394 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3395 continue;
3396 grouping.insert(address);
3397 any_mine = true;
3400 // group change with input addresses
3401 if (any_mine)
3403 for (CTxOut txout : pcoin->tx->vout)
3404 if (IsChange(txout))
3406 CTxDestination txoutAddr;
3407 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3408 continue;
3409 grouping.insert(txoutAddr);
3412 if (grouping.size() > 0)
3414 groupings.insert(grouping);
3415 grouping.clear();
3419 // group lone addrs by themselves
3420 for (const auto& txout : pcoin->tx->vout)
3421 if (IsMine(txout))
3423 CTxDestination address;
3424 if(!ExtractDestination(txout.scriptPubKey, address))
3425 continue;
3426 grouping.insert(address);
3427 groupings.insert(grouping);
3428 grouping.clear();
3432 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3433 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3434 for (std::set<CTxDestination> _grouping : groupings)
3436 // make a set of all the groups hit by this new group
3437 std::set< std::set<CTxDestination>* > hits;
3438 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3439 for (CTxDestination address : _grouping)
3440 if ((it = setmap.find(address)) != setmap.end())
3441 hits.insert((*it).second);
3443 // merge all hit groups into a new single group and delete old groups
3444 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3445 for (std::set<CTxDestination>* hit : hits)
3447 merged->insert(hit->begin(), hit->end());
3448 uniqueGroupings.erase(hit);
3449 delete hit;
3451 uniqueGroupings.insert(merged);
3453 // update setmap
3454 for (CTxDestination element : *merged)
3455 setmap[element] = merged;
3458 std::set< std::set<CTxDestination> > ret;
3459 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3461 ret.insert(*uniqueGrouping);
3462 delete uniqueGrouping;
3465 return ret;
3468 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3470 LOCK(cs_wallet);
3471 std::set<CTxDestination> result;
3472 for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
3474 const CTxDestination& address = item.first;
3475 const std::string& strName = item.second.name;
3476 if (strName == strAccount)
3477 result.insert(address);
3479 return result;
3482 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3484 if (nIndex == -1)
3486 CKeyPool keypool;
3487 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3488 if (nIndex != -1)
3489 vchPubKey = keypool.vchPubKey;
3490 else {
3491 return false;
3493 fInternal = keypool.fInternal;
3495 assert(vchPubKey.IsValid());
3496 pubkey = vchPubKey;
3497 return true;
3500 void CReserveKey::KeepKey()
3502 if (nIndex != -1)
3503 pwallet->KeepKey(nIndex);
3504 nIndex = -1;
3505 vchPubKey = CPubKey();
3508 void CReserveKey::ReturnKey()
3510 if (nIndex != -1) {
3511 pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
3513 nIndex = -1;
3514 vchPubKey = CPubKey();
3517 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
3519 AssertLockHeld(cs_wallet);
3520 bool internal = setInternalKeyPool.count(keypool_id);
3521 if (!internal) assert(setExternalKeyPool.count(keypool_id));
3522 std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
3523 auto it = setKeyPool->begin();
3525 CWalletDB walletdb(*dbw);
3526 while (it != std::end(*setKeyPool)) {
3527 const int64_t& index = *(it);
3528 if (index > keypool_id) break; // set*KeyPool is ordered
3530 CKeyPool keypool;
3531 if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
3532 m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
3534 walletdb.ErasePool(index);
3535 LogPrintf("keypool index %d removed\n", index);
3536 it = setKeyPool->erase(it);
3540 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3542 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3543 CPubKey pubkey;
3544 if (!rKey->GetReservedKey(pubkey))
3545 return;
3547 script = rKey;
3548 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3551 void CWallet::LockCoin(const COutPoint& output)
3553 AssertLockHeld(cs_wallet); // setLockedCoins
3554 setLockedCoins.insert(output);
3557 void CWallet::UnlockCoin(const COutPoint& output)
3559 AssertLockHeld(cs_wallet); // setLockedCoins
3560 setLockedCoins.erase(output);
3563 void CWallet::UnlockAllCoins()
3565 AssertLockHeld(cs_wallet); // setLockedCoins
3566 setLockedCoins.clear();
3569 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3571 AssertLockHeld(cs_wallet); // setLockedCoins
3572 COutPoint outpt(hash, n);
3574 return (setLockedCoins.count(outpt) > 0);
3577 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3579 AssertLockHeld(cs_wallet); // setLockedCoins
3580 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3581 it != setLockedCoins.end(); it++) {
3582 COutPoint outpt = (*it);
3583 vOutpts.push_back(outpt);
3587 /** @} */ // end of Actions
3589 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3590 AssertLockHeld(cs_wallet); // mapKeyMetadata
3591 mapKeyBirth.clear();
3593 // get birth times for keys with metadata
3594 for (const auto& entry : mapKeyMetadata) {
3595 if (entry.second.nCreateTime) {
3596 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3600 // map in which we'll infer heights of other keys
3601 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3602 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3603 for (const CKeyID &keyid : GetKeys()) {
3604 if (mapKeyBirth.count(keyid) == 0)
3605 mapKeyFirstBlock[keyid] = pindexMax;
3608 // if there are no such keys, we're done
3609 if (mapKeyFirstBlock.empty())
3610 return;
3612 // find first block that affects those keys, if there are any left
3613 std::vector<CKeyID> vAffected;
3614 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3615 // iterate over all wallet transactions...
3616 const CWalletTx &wtx = (*it).second;
3617 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3618 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3619 // ... which are already in a block
3620 int nHeight = blit->second->nHeight;
3621 for (const CTxOut &txout : wtx.tx->vout) {
3622 // iterate over all their outputs
3623 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3624 for (const CKeyID &keyid : vAffected) {
3625 // ... and all their affected keys
3626 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3627 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3628 rit->second = blit->second;
3630 vAffected.clear();
3635 // Extract block timestamps for those keys
3636 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3637 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3641 * Compute smart timestamp for a transaction being added to the wallet.
3643 * Logic:
3644 * - If sending a transaction, assign its timestamp to the current time.
3645 * - If receiving a transaction outside a block, assign its timestamp to the
3646 * current time.
3647 * - If receiving a block with a future timestamp, assign all its (not already
3648 * known) transactions' timestamps to the current time.
3649 * - If receiving a block with a past timestamp, before the most recent known
3650 * transaction (that we care about), assign all its (not already known)
3651 * transactions' timestamps to the same timestamp as that most-recent-known
3652 * transaction.
3653 * - If receiving a block with a past timestamp, but after the most recent known
3654 * transaction, assign all its (not already known) transactions' timestamps to
3655 * the block time.
3657 * For more information see CWalletTx::nTimeSmart,
3658 * https://bitcointalk.org/?topic=54527, or
3659 * https://github.com/bitcoin/bitcoin/pull/1393.
3661 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3663 unsigned int nTimeSmart = wtx.nTimeReceived;
3664 if (!wtx.hashUnset()) {
3665 if (mapBlockIndex.count(wtx.hashBlock)) {
3666 int64_t latestNow = wtx.nTimeReceived;
3667 int64_t latestEntry = 0;
3669 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3670 int64_t latestTolerated = latestNow + 300;
3671 const TxItems& txOrdered = wtxOrdered;
3672 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3673 CWalletTx* const pwtx = it->second.first;
3674 if (pwtx == &wtx) {
3675 continue;
3677 CAccountingEntry* const pacentry = it->second.second;
3678 int64_t nSmartTime;
3679 if (pwtx) {
3680 nSmartTime = pwtx->nTimeSmart;
3681 if (!nSmartTime) {
3682 nSmartTime = pwtx->nTimeReceived;
3684 } else {
3685 nSmartTime = pacentry->nTime;
3687 if (nSmartTime <= latestTolerated) {
3688 latestEntry = nSmartTime;
3689 if (nSmartTime > latestNow) {
3690 latestNow = nSmartTime;
3692 break;
3696 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3697 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3698 } else {
3699 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3702 return nTimeSmart;
3705 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3707 if (boost::get<CNoDestination>(&dest))
3708 return false;
3710 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3711 return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
3714 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3716 if (!mapAddressBook[dest].destdata.erase(key))
3717 return false;
3718 return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
3721 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3723 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3724 return true;
3727 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3729 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3730 if(i != mapAddressBook.end())
3732 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3733 if(j != i->second.destdata.end())
3735 if(value)
3736 *value = j->second;
3737 return true;
3740 return false;
3743 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3745 LOCK(cs_wallet);
3746 std::vector<std::string> values;
3747 for (const auto& address : mapAddressBook) {
3748 for (const auto& data : address.second.destdata) {
3749 if (!data.first.compare(0, prefix.size(), prefix)) {
3750 values.emplace_back(data.second);
3754 return values;
3757 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3759 // needed to restore wallet transaction meta data after -zapwallettxes
3760 std::vector<CWalletTx> vWtx;
3762 if (gArgs.GetBoolArg("-zapwallettxes", false)) {
3763 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3765 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3766 std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
3767 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3768 if (nZapWalletRet != DB_LOAD_OK) {
3769 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3770 return nullptr;
3774 uiInterface.InitMessage(_("Loading wallet..."));
3776 int64_t nStart = GetTimeMillis();
3777 bool fFirstRun = true;
3778 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3779 CWallet *walletInstance = new CWallet(std::move(dbw));
3780 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3781 if (nLoadWalletRet != DB_LOAD_OK)
3783 if (nLoadWalletRet == DB_CORRUPT) {
3784 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3785 return nullptr;
3787 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3789 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3790 " or address book entries might be missing or incorrect."),
3791 walletFile));
3793 else if (nLoadWalletRet == DB_TOO_NEW) {
3794 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3795 return nullptr;
3797 else if (nLoadWalletRet == DB_NEED_REWRITE)
3799 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3800 return nullptr;
3802 else {
3803 InitError(strprintf(_("Error loading %s"), walletFile));
3804 return nullptr;
3808 if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
3810 int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
3811 if (nMaxVersion == 0) // the -upgradewallet without argument case
3813 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3814 nMaxVersion = CLIENT_VERSION;
3815 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3817 else
3818 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3819 if (nMaxVersion < walletInstance->GetVersion())
3821 InitError(_("Cannot downgrade wallet"));
3822 return nullptr;
3824 walletInstance->SetMaxVersion(nMaxVersion);
3827 if (fFirstRun)
3829 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3830 if (!gArgs.GetBoolArg("-usehd", true)) {
3831 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
3832 return nullptr;
3834 walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
3836 // generate a new master key
3837 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3838 if (!walletInstance->SetHDMasterKey(masterPubKey))
3839 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3841 // Top up the keypool
3842 if (!walletInstance->TopUpKeyPool()) {
3843 InitError(_("Unable to generate initial keys") += "\n");
3844 return NULL;
3847 walletInstance->SetBestChain(chainActive.GetLocator());
3849 else if (gArgs.IsArgSet("-usehd")) {
3850 bool useHD = gArgs.GetBoolArg("-usehd", true);
3851 if (walletInstance->IsHDEnabled() && !useHD) {
3852 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
3853 return nullptr;
3855 if (!walletInstance->IsHDEnabled() && useHD) {
3856 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
3857 return nullptr;
3861 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3863 RegisterValidationInterface(walletInstance);
3865 // Try to top up keypool. No-op if the wallet is locked.
3866 walletInstance->TopUpKeyPool();
3868 CBlockIndex *pindexRescan = chainActive.Genesis();
3869 if (!gArgs.GetBoolArg("-rescan", false))
3871 CWalletDB walletdb(*walletInstance->dbw);
3872 CBlockLocator locator;
3873 if (walletdb.ReadBestBlock(locator))
3874 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3876 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3878 //We can't rescan beyond non-pruned blocks, stop and throw an error
3879 //this might happen if a user uses an old wallet within a pruned node
3880 // or if he ran -disablewallet for a longer time, then decided to re-enable
3881 if (fPruneMode)
3883 CBlockIndex *block = chainActive.Tip();
3884 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3885 block = block->pprev;
3887 if (pindexRescan != block) {
3888 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3889 return nullptr;
3893 uiInterface.InitMessage(_("Rescanning..."));
3894 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3896 // No need to read and scan block if block was created before
3897 // our wallet birthday (as adjusted for block time variability)
3898 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
3899 pindexRescan = chainActive.Next(pindexRescan);
3902 nStart = GetTimeMillis();
3903 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3904 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3905 walletInstance->SetBestChain(chainActive.GetLocator());
3906 walletInstance->dbw->IncrementUpdateCounter();
3908 // Restore wallet transaction metadata after -zapwallettxes=1
3909 if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
3911 CWalletDB walletdb(*walletInstance->dbw);
3913 for (const CWalletTx& wtxOld : vWtx)
3915 uint256 hash = wtxOld.GetHash();
3916 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3917 if (mi != walletInstance->mapWallet.end())
3919 const CWalletTx* copyFrom = &wtxOld;
3920 CWalletTx* copyTo = &mi->second;
3921 copyTo->mapValue = copyFrom->mapValue;
3922 copyTo->vOrderForm = copyFrom->vOrderForm;
3923 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3924 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3925 copyTo->fFromMe = copyFrom->fFromMe;
3926 copyTo->strFromAccount = copyFrom->strFromAccount;
3927 copyTo->nOrderPos = copyFrom->nOrderPos;
3928 walletdb.WriteTx(*copyTo);
3933 walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3936 LOCK(walletInstance->cs_wallet);
3937 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3938 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3939 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3942 return walletInstance;
3945 std::atomic<bool> CWallet::fFlushScheduled(false);
3947 void CWallet::postInitProcess(CScheduler& scheduler)
3949 // Add wallet transactions that aren't already in a block to mempool
3950 // Do this here as mempool requires genesis block to be loaded
3951 ReacceptWalletTransactions();
3953 // Run a thread to flush wallet periodically
3954 if (!CWallet::fFlushScheduled.exchange(true)) {
3955 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3959 bool CWallet::BackupWallet(const std::string& strDest)
3961 return dbw->Backup(strDest);
3964 CKeyPool::CKeyPool()
3966 nTime = GetTime();
3967 fInternal = false;
3970 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
3972 nTime = GetTime();
3973 vchPubKey = vchPubKeyIn;
3974 fInternal = internalIn;
3977 CWalletKey::CWalletKey(int64_t nExpires)
3979 nTimeCreated = (nExpires ? GetTime() : 0);
3980 nTimeExpires = nExpires;
3983 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
3985 // Update the tx's hashBlock
3986 hashBlock = pindex->GetBlockHash();
3988 // set the position of the transaction in the block
3989 nIndex = posInBlock;
3992 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3994 if (hashUnset())
3995 return 0;
3997 AssertLockHeld(cs_main);
3999 // Find the block it claims to be in
4000 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4001 if (mi == mapBlockIndex.end())
4002 return 0;
4003 CBlockIndex* pindex = (*mi).second;
4004 if (!pindex || !chainActive.Contains(pindex))
4005 return 0;
4007 pindexRet = pindex;
4008 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4011 int CMerkleTx::GetBlocksToMaturity() const
4013 if (!IsCoinBase())
4014 return 0;
4015 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4019 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4021 return ::AcceptToMemoryPool(mempool, state, tx, true, nullptr, nullptr, false, nAbsurdFee);