Merge #10521: Limit variable scope
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobb3fed1c4dca8b56f9a90298a8788201805214d06
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "wallet/wallet.h"
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "chain.h"
11 #include "wallet/coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.h"
14 #include "fs.h"
15 #include "key.h"
16 #include "keystore.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/fees.h"
20 #include "policy/policy.h"
21 #include "policy/rbf.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "script/script.h"
25 #include "script/sign.h"
26 #include "scheduler.h"
27 #include "timedata.h"
28 #include "txmempool.h"
29 #include "util.h"
30 #include "ui_interface.h"
31 #include "utilmoneystr.h"
33 #include <assert.h>
35 #include <boost/algorithm/string/replace.hpp>
36 #include <boost/thread.hpp>
38 CWallet* pwalletMain = NULL;
39 /** Transaction fee set by the user */
40 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
41 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 bool fWalletRbf = DEFAULT_WALLET_RBF;
45 const char * DEFAULT_WALLET_DAT = "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
48 /**
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
53 /**
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
60 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
62 /** @defgroup mapWallet
64 * @{
67 struct CompareValueOnly
69 bool operator()(const CInputCoin& t1,
70 const CInputCoin& t2) const
72 return t1.txout.nValue < t2.txout.nValue;
76 std::string COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
81 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
83 LOCK(cs_wallet);
84 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
85 if (it == mapWallet.end())
86 return NULL;
87 return &(it->second);
90 CPubKey CWallet::GenerateNewKey(bool internal)
92 AssertLockHeld(cs_wallet); // mapKeyMetadata
93 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
95 CKey secret;
97 // Create new metadata
98 int64_t nCreationTime = GetTime();
99 CKeyMetadata metadata(nCreationTime);
101 // use HD key derivation if HD was enabled during wallet creation
102 if (IsHDEnabled()) {
103 DeriveNewChildKey(metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
104 } else {
105 secret.MakeNewKey(fCompressed);
108 // Compressed public keys were introduced in version 0.6.0
109 if (fCompressed)
110 SetMinVersion(FEATURE_COMPRPUBKEY);
112 CPubKey pubkey = secret.GetPubKey();
113 assert(secret.VerifyPubKey(pubkey));
115 mapKeyMetadata[pubkey.GetID()] = metadata;
116 UpdateTimeFirstKey(nCreationTime);
118 if (!AddKeyPubKey(secret, pubkey))
119 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
120 return pubkey;
123 void CWallet::DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret, bool internal)
125 // for now we use a fixed keypath scheme of m/0'/0'/k
126 CKey key; //master key seed (256bit)
127 CExtKey masterKey; //hd master key
128 CExtKey accountKey; //key at m/0'
129 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
130 CExtKey childKey; //key at m/0'/0'/<n>'
132 // try to get the master key
133 if (!GetKey(hdChain.masterKeyID, key))
134 throw std::runtime_error(std::string(__func__) + ": Master key not found");
136 masterKey.SetMaster(key.begin(), key.size());
138 // derive m/0'
139 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
140 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
142 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
143 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
144 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
146 // derive child key at next index, skip keys already known to the wallet
147 do {
148 // always derive hardened keys
149 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
150 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
151 if (internal) {
152 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
153 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
154 hdChain.nInternalChainCounter++;
156 else {
157 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
158 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
159 hdChain.nExternalChainCounter++;
161 } while (HaveKey(childKey.key.GetPubKey().GetID()));
162 secret = childKey.key;
163 metadata.hdMasterKeyID = hdChain.masterKeyID;
164 // update the chain model in the database
165 if (!CWalletDB(*dbw).WriteHDChain(hdChain))
166 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
169 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
171 AssertLockHeld(cs_wallet); // mapKeyMetadata
172 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
173 return false;
175 // check if we need to remove from watch-only
176 CScript script;
177 script = GetScriptForDestination(pubkey.GetID());
178 if (HaveWatchOnly(script))
179 RemoveWatchOnly(script);
180 script = GetScriptForRawPubKey(pubkey);
181 if (HaveWatchOnly(script))
182 RemoveWatchOnly(script);
184 if (!IsCrypted()) {
185 return CWalletDB(*dbw).WriteKey(pubkey,
186 secret.GetPrivKey(),
187 mapKeyMetadata[pubkey.GetID()]);
189 return true;
192 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
193 const std::vector<unsigned char> &vchCryptedSecret)
195 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
196 return false;
198 LOCK(cs_wallet);
199 if (pwalletdbEncryption)
200 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
201 vchCryptedSecret,
202 mapKeyMetadata[vchPubKey.GetID()]);
203 else
204 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
205 vchCryptedSecret,
206 mapKeyMetadata[vchPubKey.GetID()]);
208 return false;
211 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
213 AssertLockHeld(cs_wallet); // mapKeyMetadata
214 UpdateTimeFirstKey(meta.nCreateTime);
215 mapKeyMetadata[keyID] = meta;
216 return true;
219 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
221 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
224 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
226 AssertLockHeld(cs_wallet);
227 if (nCreateTime <= 1) {
228 // Cannot determine birthday information, so set the wallet birthday to
229 // the beginning of time.
230 nTimeFirstKey = 1;
231 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
232 nTimeFirstKey = nCreateTime;
236 bool CWallet::AddCScript(const CScript& redeemScript)
238 if (!CCryptoKeyStore::AddCScript(redeemScript))
239 return false;
240 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
243 bool CWallet::LoadCScript(const CScript& redeemScript)
245 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
246 * that never can be redeemed. However, old wallets may still contain
247 * these. Do not add them to the wallet and warn. */
248 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
250 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
251 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",
252 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
253 return true;
256 return CCryptoKeyStore::AddCScript(redeemScript);
259 bool CWallet::AddWatchOnly(const CScript& dest)
261 if (!CCryptoKeyStore::AddWatchOnly(dest))
262 return false;
263 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
264 UpdateTimeFirstKey(meta.nCreateTime);
265 NotifyWatchonlyChanged(true);
266 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
269 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
271 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
272 return AddWatchOnly(dest);
275 bool CWallet::RemoveWatchOnly(const CScript &dest)
277 AssertLockHeld(cs_wallet);
278 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
279 return false;
280 if (!HaveWatchOnly())
281 NotifyWatchonlyChanged(false);
282 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
283 return false;
285 return true;
288 bool CWallet::LoadWatchOnly(const CScript &dest)
290 return CCryptoKeyStore::AddWatchOnly(dest);
293 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
295 CCrypter crypter;
296 CKeyingMaterial _vMasterKey;
299 LOCK(cs_wallet);
300 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
302 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
303 return false;
304 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
305 continue; // try another master key
306 if (CCryptoKeyStore::Unlock(_vMasterKey))
307 return true;
310 return false;
313 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
315 bool fWasLocked = IsLocked();
318 LOCK(cs_wallet);
319 Lock();
321 CCrypter crypter;
322 CKeyingMaterial _vMasterKey;
323 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
325 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
326 return false;
327 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
328 return false;
329 if (CCryptoKeyStore::Unlock(_vMasterKey))
331 int64_t nStartTime = GetTimeMillis();
332 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
333 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
335 nStartTime = GetTimeMillis();
336 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
337 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
339 if (pMasterKey.second.nDeriveIterations < 25000)
340 pMasterKey.second.nDeriveIterations = 25000;
342 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
344 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
345 return false;
346 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
347 return false;
348 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
349 if (fWasLocked)
350 Lock();
351 return true;
356 return false;
359 void CWallet::SetBestChain(const CBlockLocator& loc)
361 CWalletDB walletdb(*dbw);
362 walletdb.WriteBestBlock(loc);
365 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
367 LOCK(cs_wallet); // nWalletVersion
368 if (nWalletVersion >= nVersion)
369 return true;
371 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
372 if (fExplicit && nVersion > nWalletMaxVersion)
373 nVersion = FEATURE_LATEST;
375 nWalletVersion = nVersion;
377 if (nVersion > nWalletMaxVersion)
378 nWalletMaxVersion = nVersion;
381 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
382 if (nWalletVersion > 40000)
383 pwalletdb->WriteMinVersion(nWalletVersion);
384 if (!pwalletdbIn)
385 delete pwalletdb;
388 return true;
391 bool CWallet::SetMaxVersion(int nVersion)
393 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
394 // cannot downgrade below current version
395 if (nWalletVersion > nVersion)
396 return false;
398 nWalletMaxVersion = nVersion;
400 return true;
403 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
405 std::set<uint256> result;
406 AssertLockHeld(cs_wallet);
408 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
409 if (it == mapWallet.end())
410 return result;
411 const CWalletTx& wtx = it->second;
413 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
415 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
417 if (mapTxSpends.count(txin.prevout) <= 1)
418 continue; // No conflict if zero or one spends
419 range = mapTxSpends.equal_range(txin.prevout);
420 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
421 result.insert(_it->second);
423 return result;
426 bool CWallet::HasWalletSpend(const uint256& txid) const
428 AssertLockHeld(cs_wallet);
429 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
430 return (iter != mapTxSpends.end() && iter->first.hash == txid);
433 void CWallet::Flush(bool shutdown)
435 dbw->Flush(shutdown);
438 bool CWallet::Verify()
440 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
441 return true;
443 uiInterface.InitMessage(_("Verifying wallet..."));
444 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
446 std::string strError;
447 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError))
448 return InitError(strError);
450 if (GetBoolArg("-salvagewallet", false))
452 // Recover readable keypairs:
453 CWallet dummyWallet;
454 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter))
455 return false;
458 std::string strWarning;
459 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
460 if (!strWarning.empty())
461 InitWarning(strWarning);
462 if (!dbV)
464 InitError(strError);
465 return false;
467 return true;
470 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
472 // We want all the wallet transactions in range to have the same metadata as
473 // the oldest (smallest nOrderPos).
474 // So: find smallest nOrderPos:
476 int nMinOrderPos = std::numeric_limits<int>::max();
477 const CWalletTx* copyFrom = NULL;
478 for (TxSpends::iterator it = range.first; it != range.second; ++it)
480 const uint256& hash = it->second;
481 int n = mapWallet[hash].nOrderPos;
482 if (n < nMinOrderPos)
484 nMinOrderPos = n;
485 copyFrom = &mapWallet[hash];
488 // Now copy data from copyFrom to rest:
489 for (TxSpends::iterator it = range.first; it != range.second; ++it)
491 const uint256& hash = it->second;
492 CWalletTx* copyTo = &mapWallet[hash];
493 if (copyFrom == copyTo) continue;
494 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
495 copyTo->mapValue = copyFrom->mapValue;
496 copyTo->vOrderForm = copyFrom->vOrderForm;
497 // fTimeReceivedIsTxTime not copied on purpose
498 // nTimeReceived not copied on purpose
499 copyTo->nTimeSmart = copyFrom->nTimeSmart;
500 copyTo->fFromMe = copyFrom->fFromMe;
501 copyTo->strFromAccount = copyFrom->strFromAccount;
502 // nOrderPos not copied on purpose
503 // cached members not copied on purpose
508 * Outpoint is spent if any non-conflicted transaction
509 * spends it:
511 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
513 const COutPoint outpoint(hash, n);
514 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
515 range = mapTxSpends.equal_range(outpoint);
517 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
519 const uint256& wtxid = it->second;
520 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
521 if (mit != mapWallet.end()) {
522 int depth = mit->second.GetDepthInMainChain();
523 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
524 return true; // Spent
527 return false;
530 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
532 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
534 std::pair<TxSpends::iterator, TxSpends::iterator> range;
535 range = mapTxSpends.equal_range(outpoint);
536 SyncMetaData(range);
540 void CWallet::AddToSpends(const uint256& wtxid)
542 assert(mapWallet.count(wtxid));
543 CWalletTx& thisTx = mapWallet[wtxid];
544 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
545 return;
547 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
548 AddToSpends(txin.prevout, wtxid);
551 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
553 if (IsCrypted())
554 return false;
556 CKeyingMaterial _vMasterKey;
558 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
559 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
561 CMasterKey kMasterKey;
563 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
564 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
566 CCrypter crypter;
567 int64_t nStartTime = GetTimeMillis();
568 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
569 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
571 nStartTime = GetTimeMillis();
572 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
573 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
575 if (kMasterKey.nDeriveIterations < 25000)
576 kMasterKey.nDeriveIterations = 25000;
578 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
580 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
581 return false;
582 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
583 return false;
586 LOCK(cs_wallet);
587 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
588 assert(!pwalletdbEncryption);
589 pwalletdbEncryption = new CWalletDB(*dbw);
590 if (!pwalletdbEncryption->TxnBegin()) {
591 delete pwalletdbEncryption;
592 pwalletdbEncryption = NULL;
593 return false;
595 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
597 if (!EncryptKeys(_vMasterKey))
599 pwalletdbEncryption->TxnAbort();
600 delete pwalletdbEncryption;
601 // We now probably have half of our keys encrypted in memory, and half not...
602 // die and let the user reload the unencrypted wallet.
603 assert(false);
606 // Encryption was introduced in version 0.4.0
607 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
609 if (!pwalletdbEncryption->TxnCommit()) {
610 delete pwalletdbEncryption;
611 // We now have keys encrypted in memory, but not on disk...
612 // die to avoid confusion and let the user reload the unencrypted wallet.
613 assert(false);
616 delete pwalletdbEncryption;
617 pwalletdbEncryption = NULL;
619 Lock();
620 Unlock(strWalletPassphrase);
622 // if we are using HD, replace the HD master key (seed) with a new one
623 if (IsHDEnabled()) {
624 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
625 return false;
629 NewKeyPool();
630 Lock();
632 // Need to completely rewrite the wallet file; if we don't, bdb might keep
633 // bits of the unencrypted private key in slack space in the database file.
634 dbw->Rewrite();
637 NotifyStatusChanged(this);
639 return true;
642 DBErrors CWallet::ReorderTransactions()
644 LOCK(cs_wallet);
645 CWalletDB walletdb(*dbw);
647 // Old wallets didn't have any defined order for transactions
648 // Probably a bad idea to change the output of this
650 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
651 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
652 typedef std::multimap<int64_t, TxPair > TxItems;
653 TxItems txByTime;
655 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
657 CWalletTx* wtx = &((*it).second);
658 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
660 std::list<CAccountingEntry> acentries;
661 walletdb.ListAccountCreditDebit("", acentries);
662 BOOST_FOREACH(CAccountingEntry& entry, acentries)
664 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
667 nOrderPosNext = 0;
668 std::vector<int64_t> nOrderPosOffsets;
669 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
671 CWalletTx *const pwtx = (*it).second.first;
672 CAccountingEntry *const pacentry = (*it).second.second;
673 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
675 if (nOrderPos == -1)
677 nOrderPos = nOrderPosNext++;
678 nOrderPosOffsets.push_back(nOrderPos);
680 if (pwtx)
682 if (!walletdb.WriteTx(*pwtx))
683 return DB_LOAD_FAIL;
685 else
686 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
687 return DB_LOAD_FAIL;
689 else
691 int64_t nOrderPosOff = 0;
692 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
694 if (nOrderPos >= nOffsetStart)
695 ++nOrderPosOff;
697 nOrderPos += nOrderPosOff;
698 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
700 if (!nOrderPosOff)
701 continue;
703 // Since we're changing the order, write it back
704 if (pwtx)
706 if (!walletdb.WriteTx(*pwtx))
707 return DB_LOAD_FAIL;
709 else
710 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
711 return DB_LOAD_FAIL;
714 walletdb.WriteOrderPosNext(nOrderPosNext);
716 return DB_LOAD_OK;
719 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
721 AssertLockHeld(cs_wallet); // nOrderPosNext
722 int64_t nRet = nOrderPosNext++;
723 if (pwalletdb) {
724 pwalletdb->WriteOrderPosNext(nOrderPosNext);
725 } else {
726 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
728 return nRet;
731 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
733 CWalletDB walletdb(*dbw);
734 if (!walletdb.TxnBegin())
735 return false;
737 int64_t nNow = GetAdjustedTime();
739 // Debit
740 CAccountingEntry debit;
741 debit.nOrderPos = IncOrderPosNext(&walletdb);
742 debit.strAccount = strFrom;
743 debit.nCreditDebit = -nAmount;
744 debit.nTime = nNow;
745 debit.strOtherAccount = strTo;
746 debit.strComment = strComment;
747 AddAccountingEntry(debit, &walletdb);
749 // Credit
750 CAccountingEntry credit;
751 credit.nOrderPos = IncOrderPosNext(&walletdb);
752 credit.strAccount = strTo;
753 credit.nCreditDebit = nAmount;
754 credit.nTime = nNow;
755 credit.strOtherAccount = strFrom;
756 credit.strComment = strComment;
757 AddAccountingEntry(credit, &walletdb);
759 if (!walletdb.TxnCommit())
760 return false;
762 return true;
765 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
767 CWalletDB walletdb(*dbw);
769 CAccount account;
770 walletdb.ReadAccount(strAccount, account);
772 if (!bForceNew) {
773 if (!account.vchPubKey.IsValid())
774 bForceNew = true;
775 else {
776 // Check if the current key has been used
777 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
778 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
779 it != mapWallet.end() && account.vchPubKey.IsValid();
780 ++it)
781 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
782 if (txout.scriptPubKey == scriptPubKey) {
783 bForceNew = true;
784 break;
789 // Generate a new key
790 if (bForceNew) {
791 if (!GetKeyFromPool(account.vchPubKey, false))
792 return false;
794 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
795 walletdb.WriteAccount(strAccount, account);
798 pubKey = account.vchPubKey;
800 return true;
803 void CWallet::MarkDirty()
806 LOCK(cs_wallet);
807 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
808 item.second.MarkDirty();
812 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
814 LOCK(cs_wallet);
816 auto mi = mapWallet.find(originalHash);
818 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
819 assert(mi != mapWallet.end());
821 CWalletTx& wtx = (*mi).second;
823 // Ensure for now that we're not overwriting data
824 assert(wtx.mapValue.count("replaced_by_txid") == 0);
826 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
828 CWalletDB walletdb(*dbw, "r+");
830 bool success = true;
831 if (!walletdb.WriteTx(wtx)) {
832 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
833 success = false;
836 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
838 return success;
841 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
843 LOCK(cs_wallet);
845 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
847 uint256 hash = wtxIn.GetHash();
849 // Inserts only if not already there, returns tx inserted or tx found
850 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
851 CWalletTx& wtx = (*ret.first).second;
852 wtx.BindWallet(this);
853 bool fInsertedNew = ret.second;
854 if (fInsertedNew)
856 wtx.nTimeReceived = GetAdjustedTime();
857 wtx.nOrderPos = IncOrderPosNext(&walletdb);
858 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
859 wtx.nTimeSmart = ComputeTimeSmart(wtx);
860 AddToSpends(hash);
863 bool fUpdated = false;
864 if (!fInsertedNew)
866 // Merge
867 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
869 wtx.hashBlock = wtxIn.hashBlock;
870 fUpdated = true;
872 // If no longer abandoned, update
873 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
875 wtx.hashBlock = wtxIn.hashBlock;
876 fUpdated = true;
878 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
880 wtx.nIndex = wtxIn.nIndex;
881 fUpdated = true;
883 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
885 wtx.fFromMe = wtxIn.fFromMe;
886 fUpdated = true;
890 //// debug print
891 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
893 // Write to disk
894 if (fInsertedNew || fUpdated)
895 if (!walletdb.WriteTx(wtx))
896 return false;
898 // Break debit/credit balance caches:
899 wtx.MarkDirty();
901 // Notify UI of new or updated transaction
902 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
904 // notify an external script when a wallet transaction comes in or is updated
905 std::string strCmd = GetArg("-walletnotify", "");
907 if ( !strCmd.empty())
909 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
910 boost::thread t(runCommand, strCmd); // thread runs free
913 return true;
916 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
918 uint256 hash = wtxIn.GetHash();
920 mapWallet[hash] = wtxIn;
921 CWalletTx& wtx = mapWallet[hash];
922 wtx.BindWallet(this);
923 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
924 AddToSpends(hash);
925 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
926 if (mapWallet.count(txin.prevout.hash)) {
927 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
928 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
929 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
934 return true;
938 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
939 * be set when the transaction was known to be included in a block. When
940 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
941 * notifications happen and cached balances are marked dirty.
943 * If fUpdate is true, existing transactions will be updated.
944 * TODO: One exception to this is that the abandoned state is cleared under the
945 * assumption that any further notification of a transaction that was considered
946 * abandoned is an indication that it is not safe to be considered abandoned.
947 * Abandoned state should probably be more carefully tracked via different
948 * posInBlock signals or by checking mempool presence when necessary.
950 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
952 const CTransaction& tx = *ptx;
954 AssertLockHeld(cs_wallet);
956 if (pIndex != NULL) {
957 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
958 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
959 while (range.first != range.second) {
960 if (range.first->second != tx.GetHash()) {
961 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);
962 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
964 range.first++;
969 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
970 if (fExisted && !fUpdate) return false;
971 if (fExisted || IsMine(tx) || IsFromMe(tx))
973 CWalletTx wtx(this, ptx);
975 // Get merkle branch if transaction was found in a block
976 if (pIndex != NULL)
977 wtx.SetMerkleBranch(pIndex, posInBlock);
979 return AddToWallet(wtx, false);
982 return false;
985 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
987 LOCK2(cs_main, cs_wallet);
988 const CWalletTx* wtx = GetWalletTx(hashTx);
989 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
992 bool CWallet::AbandonTransaction(const uint256& hashTx)
994 LOCK2(cs_main, cs_wallet);
996 CWalletDB walletdb(*dbw, "r+");
998 std::set<uint256> todo;
999 std::set<uint256> done;
1001 // Can't mark abandoned if confirmed or in mempool
1002 assert(mapWallet.count(hashTx));
1003 CWalletTx& origtx = mapWallet[hashTx];
1004 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1005 return false;
1008 todo.insert(hashTx);
1010 while (!todo.empty()) {
1011 uint256 now = *todo.begin();
1012 todo.erase(now);
1013 done.insert(now);
1014 assert(mapWallet.count(now));
1015 CWalletTx& wtx = mapWallet[now];
1016 int currentconfirm = wtx.GetDepthInMainChain();
1017 // If the orig tx was not in block, none of its spends can be
1018 assert(currentconfirm <= 0);
1019 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1020 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1021 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1022 assert(!wtx.InMempool());
1023 wtx.nIndex = -1;
1024 wtx.setAbandoned();
1025 wtx.MarkDirty();
1026 walletdb.WriteTx(wtx);
1027 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1028 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1029 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1030 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1031 if (!done.count(iter->second)) {
1032 todo.insert(iter->second);
1034 iter++;
1036 // If a transaction changes 'conflicted' state, that changes the balance
1037 // available of the outputs it spends. So force those to be recomputed
1038 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1040 if (mapWallet.count(txin.prevout.hash))
1041 mapWallet[txin.prevout.hash].MarkDirty();
1046 return true;
1049 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1051 LOCK2(cs_main, cs_wallet);
1053 int conflictconfirms = 0;
1054 if (mapBlockIndex.count(hashBlock)) {
1055 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1056 if (chainActive.Contains(pindex)) {
1057 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1060 // If number of conflict confirms cannot be determined, this means
1061 // that the block is still unknown or not yet part of the main chain,
1062 // for example when loading the wallet during a reindex. Do nothing in that
1063 // case.
1064 if (conflictconfirms >= 0)
1065 return;
1067 // Do not flush the wallet here for performance reasons
1068 CWalletDB walletdb(*dbw, "r+", false);
1070 std::set<uint256> todo;
1071 std::set<uint256> done;
1073 todo.insert(hashTx);
1075 while (!todo.empty()) {
1076 uint256 now = *todo.begin();
1077 todo.erase(now);
1078 done.insert(now);
1079 assert(mapWallet.count(now));
1080 CWalletTx& wtx = mapWallet[now];
1081 int currentconfirm = wtx.GetDepthInMainChain();
1082 if (conflictconfirms < currentconfirm) {
1083 // Block is 'more conflicted' than current confirm; update.
1084 // Mark transaction as conflicted with this block.
1085 wtx.nIndex = -1;
1086 wtx.hashBlock = hashBlock;
1087 wtx.MarkDirty();
1088 walletdb.WriteTx(wtx);
1089 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1090 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1091 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1092 if (!done.count(iter->second)) {
1093 todo.insert(iter->second);
1095 iter++;
1097 // If a transaction changes 'conflicted' state, that changes the balance
1098 // available of the outputs it spends. So force those to be recomputed
1099 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1101 if (mapWallet.count(txin.prevout.hash))
1102 mapWallet[txin.prevout.hash].MarkDirty();
1108 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1109 const CTransaction& tx = *ptx;
1111 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1112 return; // Not one of ours
1114 // If a transaction changes 'conflicted' state, that changes the balance
1115 // available of the outputs it spends. So force those to be
1116 // recomputed, also:
1117 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1119 if (mapWallet.count(txin.prevout.hash))
1120 mapWallet[txin.prevout.hash].MarkDirty();
1124 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1125 LOCK2(cs_main, cs_wallet);
1126 SyncTransaction(ptx);
1129 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1130 LOCK2(cs_main, cs_wallet);
1131 // TODO: Temporarily ensure that mempool removals are notified before
1132 // connected transactions. This shouldn't matter, but the abandoned
1133 // state of transactions in our wallet is currently cleared when we
1134 // receive another notification and there is a race condition where
1135 // notification of a connected conflict might cause an outside process
1136 // to abandon a transaction and then have it inadvertently cleared by
1137 // the notification that the conflicted transaction was evicted.
1139 for (const CTransactionRef& ptx : vtxConflicted) {
1140 SyncTransaction(ptx);
1142 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1143 SyncTransaction(pblock->vtx[i], pindex, i);
1147 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1148 LOCK2(cs_main, cs_wallet);
1150 for (const CTransactionRef& ptx : pblock->vtx) {
1151 SyncTransaction(ptx);
1157 isminetype CWallet::IsMine(const CTxIn &txin) const
1160 LOCK(cs_wallet);
1161 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1162 if (mi != mapWallet.end())
1164 const CWalletTx& prev = (*mi).second;
1165 if (txin.prevout.n < prev.tx->vout.size())
1166 return IsMine(prev.tx->vout[txin.prevout.n]);
1169 return ISMINE_NO;
1172 // Note that this function doesn't distinguish between a 0-valued input,
1173 // and a not-"is mine" (according to the filter) input.
1174 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1177 LOCK(cs_wallet);
1178 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1179 if (mi != mapWallet.end())
1181 const CWalletTx& prev = (*mi).second;
1182 if (txin.prevout.n < prev.tx->vout.size())
1183 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1184 return prev.tx->vout[txin.prevout.n].nValue;
1187 return 0;
1190 isminetype CWallet::IsMine(const CTxOut& txout) const
1192 return ::IsMine(*this, txout.scriptPubKey);
1195 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1197 if (!MoneyRange(txout.nValue))
1198 throw std::runtime_error(std::string(__func__) + ": value out of range");
1199 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1202 bool CWallet::IsChange(const CTxOut& txout) const
1204 // TODO: fix handling of 'change' outputs. The assumption is that any
1205 // payment to a script that is ours, but is not in the address book
1206 // is change. That assumption is likely to break when we implement multisignature
1207 // wallets that return change back into a multi-signature-protected address;
1208 // a better way of identifying which outputs are 'the send' and which are
1209 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1210 // which output, if any, was change).
1211 if (::IsMine(*this, txout.scriptPubKey))
1213 CTxDestination address;
1214 if (!ExtractDestination(txout.scriptPubKey, address))
1215 return true;
1217 LOCK(cs_wallet);
1218 if (!mapAddressBook.count(address))
1219 return true;
1221 return false;
1224 CAmount CWallet::GetChange(const CTxOut& txout) const
1226 if (!MoneyRange(txout.nValue))
1227 throw std::runtime_error(std::string(__func__) + ": value out of range");
1228 return (IsChange(txout) ? txout.nValue : 0);
1231 bool CWallet::IsMine(const CTransaction& tx) const
1233 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1234 if (IsMine(txout))
1235 return true;
1236 return false;
1239 bool CWallet::IsFromMe(const CTransaction& tx) const
1241 return (GetDebit(tx, ISMINE_ALL) > 0);
1244 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1246 CAmount nDebit = 0;
1247 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1249 nDebit += GetDebit(txin, filter);
1250 if (!MoneyRange(nDebit))
1251 throw std::runtime_error(std::string(__func__) + ": value out of range");
1253 return nDebit;
1256 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1258 LOCK(cs_wallet);
1260 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1262 auto mi = mapWallet.find(txin.prevout.hash);
1263 if (mi == mapWallet.end())
1264 return false; // any unknown inputs can't be from us
1266 const CWalletTx& prev = (*mi).second;
1268 if (txin.prevout.n >= prev.tx->vout.size())
1269 return false; // invalid input!
1271 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1272 return false;
1274 return true;
1277 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1279 CAmount nCredit = 0;
1280 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1282 nCredit += GetCredit(txout, filter);
1283 if (!MoneyRange(nCredit))
1284 throw std::runtime_error(std::string(__func__) + ": value out of range");
1286 return nCredit;
1289 CAmount CWallet::GetChange(const CTransaction& tx) const
1291 CAmount nChange = 0;
1292 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1294 nChange += GetChange(txout);
1295 if (!MoneyRange(nChange))
1296 throw std::runtime_error(std::string(__func__) + ": value out of range");
1298 return nChange;
1301 CPubKey CWallet::GenerateNewHDMasterKey()
1303 CKey key;
1304 key.MakeNewKey(true);
1306 int64_t nCreationTime = GetTime();
1307 CKeyMetadata metadata(nCreationTime);
1309 // calculate the pubkey
1310 CPubKey pubkey = key.GetPubKey();
1311 assert(key.VerifyPubKey(pubkey));
1313 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1314 metadata.hdKeypath = "m";
1315 metadata.hdMasterKeyID = pubkey.GetID();
1318 LOCK(cs_wallet);
1320 // mem store the metadata
1321 mapKeyMetadata[pubkey.GetID()] = metadata;
1323 // write the key&metadata to the database
1324 if (!AddKeyPubKey(key, pubkey))
1325 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1328 return pubkey;
1331 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1333 LOCK(cs_wallet);
1334 // store the keyid (hash160) together with
1335 // the child index counter in the database
1336 // as a hdchain object
1337 CHDChain newHdChain;
1338 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1339 newHdChain.masterKeyID = pubkey.GetID();
1340 SetHDChain(newHdChain, false);
1342 return true;
1345 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1347 LOCK(cs_wallet);
1348 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1349 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1351 hdChain = chain;
1352 return true;
1355 bool CWallet::IsHDEnabled() const
1357 return !hdChain.masterKeyID.IsNull();
1360 int64_t CWalletTx::GetTxTime() const
1362 int64_t n = nTimeSmart;
1363 return n ? n : nTimeReceived;
1366 int CWalletTx::GetRequestCount() const
1368 // Returns -1 if it wasn't being tracked
1369 int nRequests = -1;
1371 LOCK(pwallet->cs_wallet);
1372 if (IsCoinBase())
1374 // Generated block
1375 if (!hashUnset())
1377 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1378 if (mi != pwallet->mapRequestCount.end())
1379 nRequests = (*mi).second;
1382 else
1384 // Did anyone request this transaction?
1385 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1386 if (mi != pwallet->mapRequestCount.end())
1388 nRequests = (*mi).second;
1390 // How about the block it's in?
1391 if (nRequests == 0 && !hashUnset())
1393 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1394 if (_mi != pwallet->mapRequestCount.end())
1395 nRequests = (*_mi).second;
1396 else
1397 nRequests = 1; // If it's in someone else's block it must have got out
1402 return nRequests;
1405 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1406 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1408 nFee = 0;
1409 listReceived.clear();
1410 listSent.clear();
1411 strSentAccount = strFromAccount;
1413 // Compute fee:
1414 CAmount nDebit = GetDebit(filter);
1415 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1417 CAmount nValueOut = tx->GetValueOut();
1418 nFee = nDebit - nValueOut;
1421 // Sent/received.
1422 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1424 const CTxOut& txout = tx->vout[i];
1425 isminetype fIsMine = pwallet->IsMine(txout);
1426 // Only need to handle txouts if AT LEAST one of these is true:
1427 // 1) they debit from us (sent)
1428 // 2) the output is to us (received)
1429 if (nDebit > 0)
1431 // Don't report 'change' txouts
1432 if (pwallet->IsChange(txout))
1433 continue;
1435 else if (!(fIsMine & filter))
1436 continue;
1438 // In either case, we need to get the destination address
1439 CTxDestination address;
1441 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1443 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1444 this->GetHash().ToString());
1445 address = CNoDestination();
1448 COutputEntry output = {address, txout.nValue, (int)i};
1450 // If we are debited by the transaction, add the output as a "sent" entry
1451 if (nDebit > 0)
1452 listSent.push_back(output);
1454 // If we are receiving the output, add it as a "received" entry
1455 if (fIsMine & filter)
1456 listReceived.push_back(output);
1462 * Scan the block chain (starting in pindexStart) for transactions
1463 * from or to us. If fUpdate is true, found transactions that already
1464 * exist in the wallet will be updated.
1466 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1467 * possible (due to pruning or corruption), returns pointer to the most recent
1468 * block that could not be scanned.
1470 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1472 int64_t nNow = GetTime();
1473 const CChainParams& chainParams = Params();
1475 CBlockIndex* pindex = pindexStart;
1476 CBlockIndex* ret = nullptr;
1478 LOCK2(cs_main, cs_wallet);
1479 fAbortRescan = false;
1480 fScanningWallet = true;
1482 // no need to read and scan block, if block was created before
1483 // our wallet birthday (as adjusted for block time variability)
1484 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1485 pindex = chainActive.Next(pindex);
1487 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1488 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1489 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1490 while (pindex && !fAbortRescan)
1492 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1493 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1494 if (GetTime() >= nNow + 60) {
1495 nNow = GetTime();
1496 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1499 CBlock block;
1500 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1501 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1502 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1504 } else {
1505 ret = pindex;
1507 pindex = chainActive.Next(pindex);
1509 if (pindex && fAbortRescan) {
1510 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1512 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1514 fScanningWallet = false;
1516 return ret;
1519 void CWallet::ReacceptWalletTransactions()
1521 // If transactions aren't being broadcasted, don't let them into local mempool either
1522 if (!fBroadcastTransactions)
1523 return;
1524 LOCK2(cs_main, cs_wallet);
1525 std::map<int64_t, CWalletTx*> mapSorted;
1527 // Sort pending wallet transactions based on their initial wallet insertion order
1528 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1530 const uint256& wtxid = item.first;
1531 CWalletTx& wtx = item.second;
1532 assert(wtx.GetHash() == wtxid);
1534 int nDepth = wtx.GetDepthInMainChain();
1536 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1537 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1541 // Try to add wallet transactions to memory pool
1542 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1544 CWalletTx& wtx = *(item.second);
1546 LOCK(mempool.cs);
1547 CValidationState state;
1548 wtx.AcceptToMemoryPool(maxTxFee, state);
1552 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1554 assert(pwallet->GetBroadcastTransactions());
1555 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1557 CValidationState state;
1558 /* GetDepthInMainChain already catches known conflicts. */
1559 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1560 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1561 if (connman) {
1562 CInv inv(MSG_TX, GetHash());
1563 connman->ForEachNode([&inv](CNode* pnode)
1565 pnode->PushInventory(inv);
1567 return true;
1571 return false;
1574 std::set<uint256> CWalletTx::GetConflicts() const
1576 std::set<uint256> result;
1577 if (pwallet != NULL)
1579 uint256 myHash = GetHash();
1580 result = pwallet->GetConflicts(myHash);
1581 result.erase(myHash);
1583 return result;
1586 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1588 if (tx->vin.empty())
1589 return 0;
1591 CAmount debit = 0;
1592 if(filter & ISMINE_SPENDABLE)
1594 if (fDebitCached)
1595 debit += nDebitCached;
1596 else
1598 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1599 fDebitCached = true;
1600 debit += nDebitCached;
1603 if(filter & ISMINE_WATCH_ONLY)
1605 if(fWatchDebitCached)
1606 debit += nWatchDebitCached;
1607 else
1609 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1610 fWatchDebitCached = true;
1611 debit += nWatchDebitCached;
1614 return debit;
1617 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1619 // Must wait until coinbase is safely deep enough in the chain before valuing it
1620 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1621 return 0;
1623 CAmount credit = 0;
1624 if (filter & ISMINE_SPENDABLE)
1626 // GetBalance can assume transactions in mapWallet won't change
1627 if (fCreditCached)
1628 credit += nCreditCached;
1629 else
1631 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1632 fCreditCached = true;
1633 credit += nCreditCached;
1636 if (filter & ISMINE_WATCH_ONLY)
1638 if (fWatchCreditCached)
1639 credit += nWatchCreditCached;
1640 else
1642 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1643 fWatchCreditCached = true;
1644 credit += nWatchCreditCached;
1647 return credit;
1650 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1652 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1654 if (fUseCache && fImmatureCreditCached)
1655 return nImmatureCreditCached;
1656 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1657 fImmatureCreditCached = true;
1658 return nImmatureCreditCached;
1661 return 0;
1664 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1666 if (pwallet == 0)
1667 return 0;
1669 // Must wait until coinbase is safely deep enough in the chain before valuing it
1670 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1671 return 0;
1673 if (fUseCache && fAvailableCreditCached)
1674 return nAvailableCreditCached;
1676 CAmount nCredit = 0;
1677 uint256 hashTx = GetHash();
1678 for (unsigned int i = 0; i < tx->vout.size(); i++)
1680 if (!pwallet->IsSpent(hashTx, i))
1682 const CTxOut &txout = tx->vout[i];
1683 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1684 if (!MoneyRange(nCredit))
1685 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1689 nAvailableCreditCached = nCredit;
1690 fAvailableCreditCached = true;
1691 return nCredit;
1694 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1696 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1698 if (fUseCache && fImmatureWatchCreditCached)
1699 return nImmatureWatchCreditCached;
1700 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1701 fImmatureWatchCreditCached = true;
1702 return nImmatureWatchCreditCached;
1705 return 0;
1708 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1710 if (pwallet == 0)
1711 return 0;
1713 // Must wait until coinbase is safely deep enough in the chain before valuing it
1714 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1715 return 0;
1717 if (fUseCache && fAvailableWatchCreditCached)
1718 return nAvailableWatchCreditCached;
1720 CAmount nCredit = 0;
1721 for (unsigned int i = 0; i < tx->vout.size(); i++)
1723 if (!pwallet->IsSpent(GetHash(), i))
1725 const CTxOut &txout = tx->vout[i];
1726 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1727 if (!MoneyRange(nCredit))
1728 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1732 nAvailableWatchCreditCached = nCredit;
1733 fAvailableWatchCreditCached = true;
1734 return nCredit;
1737 CAmount CWalletTx::GetChange() const
1739 if (fChangeCached)
1740 return nChangeCached;
1741 nChangeCached = pwallet->GetChange(*this);
1742 fChangeCached = true;
1743 return nChangeCached;
1746 bool CWalletTx::InMempool() const
1748 LOCK(mempool.cs);
1749 return mempool.exists(GetHash());
1752 bool CWalletTx::IsTrusted() const
1754 // Quick answer in most cases
1755 if (!CheckFinalTx(*this))
1756 return false;
1757 int nDepth = GetDepthInMainChain();
1758 if (nDepth >= 1)
1759 return true;
1760 if (nDepth < 0)
1761 return false;
1762 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1763 return false;
1765 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1766 if (!InMempool())
1767 return false;
1769 // Trusted if all inputs are from us and are in the mempool:
1770 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1772 // Transactions not sent by us: not trusted
1773 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1774 if (parent == NULL)
1775 return false;
1776 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1777 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1778 return false;
1780 return true;
1783 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1785 CMutableTransaction tx1 = *this->tx;
1786 CMutableTransaction tx2 = *_tx.tx;
1787 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1788 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1789 return CTransaction(tx1) == CTransaction(tx2);
1792 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1794 std::vector<uint256> result;
1796 LOCK(cs_wallet);
1797 // Sort them in chronological order
1798 std::multimap<unsigned int, CWalletTx*> mapSorted;
1799 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1801 CWalletTx& wtx = item.second;
1802 // Don't rebroadcast if newer than nTime:
1803 if (wtx.nTimeReceived > nTime)
1804 continue;
1805 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1807 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1809 CWalletTx& wtx = *item.second;
1810 if (wtx.RelayWalletTransaction(connman))
1811 result.push_back(wtx.GetHash());
1813 return result;
1816 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1818 // Do this infrequently and randomly to avoid giving away
1819 // that these are our transactions.
1820 if (GetTime() < nNextResend || !fBroadcastTransactions)
1821 return;
1822 bool fFirst = (nNextResend == 0);
1823 nNextResend = GetTime() + GetRand(30 * 60);
1824 if (fFirst)
1825 return;
1827 // Only do it if there's been a new block since last time
1828 if (nBestBlockTime < nLastResend)
1829 return;
1830 nLastResend = GetTime();
1832 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1833 // block was found:
1834 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1835 if (!relayed.empty())
1836 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1839 /** @} */ // end of mapWallet
1844 /** @defgroup Actions
1846 * @{
1850 CAmount CWallet::GetBalance() const
1852 CAmount nTotal = 0;
1854 LOCK2(cs_main, cs_wallet);
1855 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1857 const CWalletTx* pcoin = &(*it).second;
1858 if (pcoin->IsTrusted())
1859 nTotal += pcoin->GetAvailableCredit();
1863 return nTotal;
1866 CAmount CWallet::GetUnconfirmedBalance() const
1868 CAmount nTotal = 0;
1870 LOCK2(cs_main, cs_wallet);
1871 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1873 const CWalletTx* pcoin = &(*it).second;
1874 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1875 nTotal += pcoin->GetAvailableCredit();
1878 return nTotal;
1881 CAmount CWallet::GetImmatureBalance() const
1883 CAmount nTotal = 0;
1885 LOCK2(cs_main, cs_wallet);
1886 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1888 const CWalletTx* pcoin = &(*it).second;
1889 nTotal += pcoin->GetImmatureCredit();
1892 return nTotal;
1895 CAmount CWallet::GetWatchOnlyBalance() const
1897 CAmount nTotal = 0;
1899 LOCK2(cs_main, cs_wallet);
1900 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1902 const CWalletTx* pcoin = &(*it).second;
1903 if (pcoin->IsTrusted())
1904 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1908 return nTotal;
1911 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1913 CAmount nTotal = 0;
1915 LOCK2(cs_main, cs_wallet);
1916 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1918 const CWalletTx* pcoin = &(*it).second;
1919 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1920 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1923 return nTotal;
1926 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1928 CAmount nTotal = 0;
1930 LOCK2(cs_main, cs_wallet);
1931 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1933 const CWalletTx* pcoin = &(*it).second;
1934 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1937 return nTotal;
1940 // Calculate total balance in a different way from GetBalance. The biggest
1941 // difference is that GetBalance sums up all unspent TxOuts paying to the
1942 // wallet, while this sums up both spent and unspent TxOuts paying to the
1943 // wallet, and then subtracts the values of TxIns spending from the wallet. This
1944 // also has fewer restrictions on which unconfirmed transactions are considered
1945 // trusted.
1946 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
1948 LOCK2(cs_main, cs_wallet);
1950 CAmount balance = 0;
1951 for (const auto& entry : mapWallet) {
1952 const CWalletTx& wtx = entry.second;
1953 const int depth = wtx.GetDepthInMainChain();
1954 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
1955 continue;
1958 // Loop through tx outputs and add incoming payments. For outgoing txs,
1959 // treat change outputs specially, as part of the amount debited.
1960 CAmount debit = wtx.GetDebit(filter);
1961 const bool outgoing = debit > 0;
1962 for (const CTxOut& out : wtx.tx->vout) {
1963 if (outgoing && IsChange(out)) {
1964 debit -= out.nValue;
1965 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
1966 balance += out.nValue;
1970 // For outgoing txs, subtract amount debited.
1971 if (outgoing && (!account || *account == wtx.strFromAccount)) {
1972 balance -= debit;
1976 if (account) {
1977 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
1980 return balance;
1983 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
1985 LOCK2(cs_main, cs_wallet);
1987 CAmount balance = 0;
1988 std::vector<COutput> vCoins;
1989 AvailableCoins(vCoins, true, coinControl);
1990 for (const COutput& out : vCoins) {
1991 if (out.fSpendable) {
1992 balance += out.tx->tx->vout[out.i].nValue;
1995 return balance;
1998 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
2000 vCoins.clear();
2003 LOCK2(cs_main, cs_wallet);
2005 CAmount nTotal = 0;
2007 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2009 const uint256& wtxid = it->first;
2010 const CWalletTx* pcoin = &(*it).second;
2012 if (!CheckFinalTx(*pcoin))
2013 continue;
2015 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2016 continue;
2018 int nDepth = pcoin->GetDepthInMainChain();
2019 if (nDepth < 0)
2020 continue;
2022 // We should not consider coins which aren't at least in our mempool
2023 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2024 if (nDepth == 0 && !pcoin->InMempool())
2025 continue;
2027 bool safeTx = pcoin->IsTrusted();
2029 // We should not consider coins from transactions that are replacing
2030 // other transactions.
2032 // Example: There is a transaction A which is replaced by bumpfee
2033 // transaction B. In this case, we want to prevent creation of
2034 // a transaction B' which spends an output of B.
2036 // Reason: If transaction A were initially confirmed, transactions B
2037 // and B' would no longer be valid, so the user would have to create
2038 // a new transaction C to replace B'. However, in the case of a
2039 // one-block reorg, transactions B' and C might BOTH be accepted,
2040 // when the user only wanted one of them. Specifically, there could
2041 // be a 1-block reorg away from the chain where transactions A and C
2042 // were accepted to another chain where B, B', and C were all
2043 // accepted.
2044 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2045 safeTx = false;
2048 // Similarly, we should not consider coins from transactions that
2049 // have been replaced. In the example above, we would want to prevent
2050 // creation of a transaction A' spending an output of A, because if
2051 // transaction B were initially confirmed, conflicting with A and
2052 // A', we wouldn't want to the user to create a transaction D
2053 // intending to replace A', but potentially resulting in a scenario
2054 // where A, A', and D could all be accepted (instead of just B and
2055 // D, or just A and A' like the user would want).
2056 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2057 safeTx = false;
2060 if (fOnlySafe && !safeTx) {
2061 continue;
2064 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2065 continue;
2067 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2068 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2069 continue;
2071 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2072 continue;
2074 if (IsLockedCoin((*it).first, i))
2075 continue;
2077 if (IsSpent(wtxid, i))
2078 continue;
2080 isminetype mine = IsMine(pcoin->tx->vout[i]);
2082 if (mine == ISMINE_NO) {
2083 continue;
2086 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2087 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2089 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2091 // Checks the sum amount of all UTXO's.
2092 if (nMinimumSumAmount != MAX_MONEY) {
2093 nTotal += pcoin->tx->vout[i].nValue;
2095 if (nTotal >= nMinimumSumAmount) {
2096 return;
2100 // Checks the maximum number of UTXO's.
2101 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2102 return;
2109 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2111 // TODO: Add AssertLockHeld(cs_wallet) here.
2113 // Because the return value from this function contains pointers to
2114 // CWalletTx objects, callers to this function really should acquire the
2115 // cs_wallet lock before calling it. However, the current caller doesn't
2116 // acquire this lock yet. There was an attempt to add the missing lock in
2117 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2118 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2119 // avoid adding some extra complexity to the Qt code.
2121 std::map<CTxDestination, std::vector<COutput>> result;
2123 std::vector<COutput> availableCoins;
2124 AvailableCoins(availableCoins);
2126 LOCK2(cs_main, cs_wallet);
2127 for (auto& coin : availableCoins) {
2128 CTxDestination address;
2129 if (coin.fSpendable &&
2130 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2131 result[address].emplace_back(std::move(coin));
2135 std::vector<COutPoint> lockedCoins;
2136 ListLockedCoins(lockedCoins);
2137 for (const auto& output : lockedCoins) {
2138 auto it = mapWallet.find(output.hash);
2139 if (it != mapWallet.end()) {
2140 int depth = it->second.GetDepthInMainChain();
2141 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2142 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2143 CTxDestination address;
2144 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2145 result[address].emplace_back(
2146 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2152 return result;
2155 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2157 const CTransaction* ptx = &tx;
2158 int n = output;
2159 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2160 const COutPoint& prevout = ptx->vin[0].prevout;
2161 auto it = mapWallet.find(prevout.hash);
2162 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2163 !IsMine(it->second.tx->vout[prevout.n])) {
2164 break;
2166 ptx = it->second.tx.get();
2167 n = prevout.n;
2169 return ptx->vout[n];
2172 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2173 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2175 std::vector<char> vfIncluded;
2177 vfBest.assign(vValue.size(), true);
2178 nBest = nTotalLower;
2180 FastRandomContext insecure_rand;
2182 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2184 vfIncluded.assign(vValue.size(), false);
2185 CAmount nTotal = 0;
2186 bool fReachedTarget = false;
2187 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2189 for (unsigned int i = 0; i < vValue.size(); i++)
2191 //The solver here uses a randomized algorithm,
2192 //the randomness serves no real security purpose but is just
2193 //needed to prevent degenerate behavior and it is important
2194 //that the rng is fast. We do not use a constant random sequence,
2195 //because there may be some privacy improvement by making
2196 //the selection random.
2197 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2199 nTotal += vValue[i].txout.nValue;
2200 vfIncluded[i] = true;
2201 if (nTotal >= nTargetValue)
2203 fReachedTarget = true;
2204 if (nTotal < nBest)
2206 nBest = nTotal;
2207 vfBest = vfIncluded;
2209 nTotal -= vValue[i].txout.nValue;
2210 vfIncluded[i] = false;
2218 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2219 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2221 setCoinsRet.clear();
2222 nValueRet = 0;
2224 // List of values less than target
2225 boost::optional<CInputCoin> coinLowestLarger;
2226 std::vector<CInputCoin> vValue;
2227 CAmount nTotalLower = 0;
2229 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2231 BOOST_FOREACH(const COutput &output, vCoins)
2233 if (!output.fSpendable)
2234 continue;
2236 const CWalletTx *pcoin = output.tx;
2238 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2239 continue;
2241 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2242 continue;
2244 int i = output.i;
2246 CInputCoin coin = CInputCoin(pcoin, i);
2248 if (coin.txout.nValue == nTargetValue)
2250 setCoinsRet.insert(coin);
2251 nValueRet += coin.txout.nValue;
2252 return true;
2254 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2256 vValue.push_back(coin);
2257 nTotalLower += coin.txout.nValue;
2259 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2261 coinLowestLarger = coin;
2265 if (nTotalLower == nTargetValue)
2267 for (const auto& input : vValue)
2269 setCoinsRet.insert(input);
2270 nValueRet += input.txout.nValue;
2272 return true;
2275 if (nTotalLower < nTargetValue)
2277 if (!coinLowestLarger)
2278 return false;
2279 setCoinsRet.insert(coinLowestLarger.get());
2280 nValueRet += coinLowestLarger->txout.nValue;
2281 return true;
2284 // Solve subset sum by stochastic approximation
2285 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2286 std::reverse(vValue.begin(), vValue.end());
2287 std::vector<char> vfBest;
2288 CAmount nBest;
2290 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2291 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2292 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2294 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2295 // or the next bigger coin is closer), return the bigger coin
2296 if (coinLowestLarger &&
2297 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2299 setCoinsRet.insert(coinLowestLarger.get());
2300 nValueRet += coinLowestLarger->txout.nValue;
2302 else {
2303 for (unsigned int i = 0; i < vValue.size(); i++)
2304 if (vfBest[i])
2306 setCoinsRet.insert(vValue[i]);
2307 nValueRet += vValue[i].txout.nValue;
2310 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2311 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2312 for (unsigned int i = 0; i < vValue.size(); i++) {
2313 if (vfBest[i]) {
2314 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2317 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2321 return true;
2324 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2326 std::vector<COutput> vCoins(vAvailableCoins);
2328 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2329 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2331 BOOST_FOREACH(const COutput& out, vCoins)
2333 if (!out.fSpendable)
2334 continue;
2335 nValueRet += out.tx->tx->vout[out.i].nValue;
2336 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2338 return (nValueRet >= nTargetValue);
2341 // calculate value from preset inputs and store them
2342 std::set<CInputCoin> setPresetCoins;
2343 CAmount nValueFromPresetInputs = 0;
2345 std::vector<COutPoint> vPresetInputs;
2346 if (coinControl)
2347 coinControl->ListSelected(vPresetInputs);
2348 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2350 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2351 if (it != mapWallet.end())
2353 const CWalletTx* pcoin = &it->second;
2354 // Clearly invalid input, fail
2355 if (pcoin->tx->vout.size() <= outpoint.n)
2356 return false;
2357 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2358 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2359 } else
2360 return false; // TODO: Allow non-wallet inputs
2363 // remove preset inputs from vCoins
2364 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2366 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2367 it = vCoins.erase(it);
2368 else
2369 ++it;
2372 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2373 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2375 bool res = nTargetValue <= nValueFromPresetInputs ||
2376 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2377 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2378 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2379 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2380 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2381 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2382 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2384 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2385 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2387 // add preset inputs to the total value selected
2388 nValueRet += nValueFromPresetInputs;
2390 return res;
2393 bool CWallet::SignTransaction(CMutableTransaction &tx)
2395 AssertLockHeld(cs_wallet); // mapWallet
2397 // sign the new tx
2398 CTransaction txNewConst(tx);
2399 int nIn = 0;
2400 for (const auto& input : tx.vin) {
2401 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2402 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2403 return false;
2405 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2406 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2407 SignatureData sigdata;
2408 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2409 return false;
2411 UpdateTransaction(tx, nIn, sigdata);
2412 nIn++;
2414 return true;
2417 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl, bool keepReserveKey)
2419 std::vector<CRecipient> vecSend;
2421 // Turn the txout set into a CRecipient vector
2422 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2424 const CTxOut& txOut = tx.vout[idx];
2425 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2426 vecSend.push_back(recipient);
2429 coinControl.fAllowOtherInputs = true;
2431 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2432 coinControl.Select(txin.prevout);
2434 CReserveKey reservekey(this);
2435 CWalletTx wtx;
2436 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2437 return false;
2439 if (nChangePosInOut != -1)
2440 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2442 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2443 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2444 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2446 // Add new txins (keeping original txin scriptSig/order)
2447 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2449 if (!coinControl.IsSelected(txin.prevout))
2451 tx.vin.push_back(txin);
2453 if (lockUnspents)
2455 LOCK2(cs_main, cs_wallet);
2456 LockCoin(txin.prevout);
2461 // optionally keep the change output key
2462 if (keepReserveKey)
2463 reservekey.KeepKey();
2465 return true;
2468 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2469 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2471 CAmount nValue = 0;
2472 int nChangePosRequest = nChangePosInOut;
2473 unsigned int nSubtractFeeFromAmount = 0;
2474 for (const auto& recipient : vecSend)
2476 if (nValue < 0 || recipient.nAmount < 0)
2478 strFailReason = _("Transaction amounts must not be negative");
2479 return false;
2481 nValue += recipient.nAmount;
2483 if (recipient.fSubtractFeeFromAmount)
2484 nSubtractFeeFromAmount++;
2486 if (vecSend.empty())
2488 strFailReason = _("Transaction must have at least one recipient");
2489 return false;
2492 wtxNew.fTimeReceivedIsTxTime = true;
2493 wtxNew.BindWallet(this);
2494 CMutableTransaction txNew;
2496 // Discourage fee sniping.
2498 // For a large miner the value of the transactions in the best block and
2499 // the mempool can exceed the cost of deliberately attempting to mine two
2500 // blocks to orphan the current best block. By setting nLockTime such that
2501 // only the next block can include the transaction, we discourage this
2502 // practice as the height restricted and limited blocksize gives miners
2503 // considering fee sniping fewer options for pulling off this attack.
2505 // A simple way to think about this is from the wallet's point of view we
2506 // always want the blockchain to move forward. By setting nLockTime this
2507 // way we're basically making the statement that we only want this
2508 // transaction to appear in the next block; we don't want to potentially
2509 // encourage reorgs by allowing transactions to appear at lower heights
2510 // than the next block in forks of the best chain.
2512 // Of course, the subsidy is high enough, and transaction volume low
2513 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2514 // now we ensure code won't be written that makes assumptions about
2515 // nLockTime that preclude a fix later.
2516 txNew.nLockTime = chainActive.Height();
2518 // Secondly occasionally randomly pick a nLockTime even further back, so
2519 // that transactions that are delayed after signing for whatever reason,
2520 // e.g. high-latency mix networks and some CoinJoin implementations, have
2521 // better privacy.
2522 if (GetRandInt(10) == 0)
2523 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2525 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2526 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2529 std::set<CInputCoin> setCoins;
2530 LOCK2(cs_main, cs_wallet);
2532 std::vector<COutput> vAvailableCoins;
2533 AvailableCoins(vAvailableCoins, true, coinControl);
2535 nFeeRet = 0;
2536 // Start with no fee and loop until there is enough fee
2537 while (true)
2539 nChangePosInOut = nChangePosRequest;
2540 txNew.vin.clear();
2541 txNew.vout.clear();
2542 wtxNew.fFromMe = true;
2543 bool fFirst = true;
2545 CAmount nValueToSelect = nValue;
2546 if (nSubtractFeeFromAmount == 0)
2547 nValueToSelect += nFeeRet;
2548 // vouts to the payees
2549 for (const auto& recipient : vecSend)
2551 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2553 if (recipient.fSubtractFeeFromAmount)
2555 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2557 if (fFirst) // first receiver pays the remainder not divisible by output count
2559 fFirst = false;
2560 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2564 if (IsDust(txout, ::dustRelayFee))
2566 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2568 if (txout.nValue < 0)
2569 strFailReason = _("The transaction amount is too small to pay the fee");
2570 else
2571 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2573 else
2574 strFailReason = _("Transaction amount too small");
2575 return false;
2577 txNew.vout.push_back(txout);
2580 // Choose coins to use
2581 CAmount nValueIn = 0;
2582 setCoins.clear();
2583 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2585 strFailReason = _("Insufficient funds");
2586 return false;
2589 const CAmount nChange = nValueIn - nValueToSelect;
2590 if (nChange > 0)
2592 // Fill a vout to ourself
2593 // TODO: pass in scriptChange instead of reservekey so
2594 // change transaction isn't always pay-to-bitcoin-address
2595 CScript scriptChange;
2597 // coin control: send change to custom address
2598 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2599 scriptChange = GetScriptForDestination(coinControl->destChange);
2601 // no coin control: send change to newly generated address
2602 else
2604 // Note: We use a new key here to keep it from being obvious which side is the change.
2605 // The drawback is that by not reusing a previous key, the change may be lost if a
2606 // backup is restored, if the backup doesn't have the new private key for the change.
2607 // If we reused the old key, it would be possible to add code to look for and
2608 // rediscover unknown transactions that were written with keys of ours to recover
2609 // post-backup change.
2611 // Reserve a new key pair from key pool
2612 CPubKey vchPubKey;
2613 bool ret;
2614 ret = reservekey.GetReservedKey(vchPubKey, true);
2615 if (!ret)
2617 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2618 return false;
2621 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2624 CTxOut newTxOut(nChange, scriptChange);
2626 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2627 // This would be against the purpose of the all-inclusive feature.
2628 // So instead we raise the change and deduct from the recipient.
2629 if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
2631 CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
2632 newTxOut.nValue += nDust; // raise change until no more dust
2633 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2635 if (vecSend[i].fSubtractFeeFromAmount)
2637 txNew.vout[i].nValue -= nDust;
2638 if (IsDust(txNew.vout[i], ::dustRelayFee))
2640 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2641 return false;
2643 break;
2648 // Never create dust outputs; if we would, just
2649 // add the dust to the fee.
2650 if (IsDust(newTxOut, ::dustRelayFee))
2652 nChangePosInOut = -1;
2653 nFeeRet += nChange;
2654 reservekey.ReturnKey();
2656 else
2658 if (nChangePosInOut == -1)
2660 // Insert change txn at random position:
2661 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2663 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2665 strFailReason = _("Change index out of range");
2666 return false;
2669 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2670 txNew.vout.insert(position, newTxOut);
2672 } else {
2673 reservekey.ReturnKey();
2674 nChangePosInOut = -1;
2677 // Fill vin
2679 // Note how the sequence number is set to non-maxint so that
2680 // the nLockTime set above actually works.
2682 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2683 // we use the highest possible value in that range (maxint-2)
2684 // to avoid conflicting with other possible uses of nSequence,
2685 // and in the spirit of "smallest possible change from prior
2686 // behavior."
2687 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2688 const uint32_t nSequence = rbf ? MAX_BIP125_RBF_SEQUENCE : (std::numeric_limits<unsigned int>::max() - 1);
2689 for (const auto& coin : setCoins)
2690 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2691 nSequence));
2693 // Fill in dummy signatures for fee calculation.
2694 if (!DummySignTx(txNew, setCoins)) {
2695 strFailReason = _("Signing transaction failed");
2696 return false;
2699 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2701 CTransaction txNewConst(txNew);
2703 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2704 for (auto& vin : txNew.vin) {
2705 vin.scriptSig = CScript();
2706 vin.scriptWitness.SetNull();
2709 // Allow to override the default confirmation target over the CoinControl instance
2710 int currentConfirmationTarget = nTxConfirmTarget;
2711 if (coinControl && coinControl->nConfirmTarget > 0)
2712 currentConfirmationTarget = coinControl->nConfirmTarget;
2714 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
2715 if (coinControl && coinControl->fOverrideFeeRate)
2716 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2718 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2719 // because we must be at the maximum allowed fee.
2720 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2722 strFailReason = _("Transaction too large for fee policy");
2723 return false;
2726 if (nFeeRet >= nFeeNeeded) {
2727 // Reduce fee to only the needed amount if we have change
2728 // output to increase. This prevents potential overpayment
2729 // in fees if the coins selected to meet nFeeNeeded result
2730 // in a transaction that requires less fee than the prior
2731 // iteration.
2732 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2733 // to be addressed because it requires returning the fee to
2734 // the payees and not the change output.
2735 // TODO: The case where there is no change output remains
2736 // to be addressed so we avoid creating too small an output.
2737 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2738 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2739 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2740 change_position->nValue += extraFeePaid;
2741 nFeeRet -= extraFeePaid;
2743 break; // Done, enough fee included.
2746 // Try to reduce change to include necessary fee
2747 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2748 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2749 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2750 // Only reduce change if remaining amount is still a large enough output.
2751 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2752 change_position->nValue -= additionalFeeNeeded;
2753 nFeeRet += additionalFeeNeeded;
2754 break; // Done, able to increase fee from change
2758 // Include more fee and try again.
2759 nFeeRet = nFeeNeeded;
2760 continue;
2764 if (sign)
2766 CTransaction txNewConst(txNew);
2767 int nIn = 0;
2768 for (const auto& coin : setCoins)
2770 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2771 SignatureData sigdata;
2773 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2775 strFailReason = _("Signing transaction failed");
2776 return false;
2777 } else {
2778 UpdateTransaction(txNew, nIn, sigdata);
2781 nIn++;
2785 // Embed the constructed transaction data in wtxNew.
2786 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2788 // Limit size
2789 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2791 strFailReason = _("Transaction too large");
2792 return false;
2796 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2797 // Lastly, ensure this tx will pass the mempool's chain limits
2798 LockPoints lp;
2799 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2800 CTxMemPool::setEntries setAncestors;
2801 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2802 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2803 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2804 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2805 std::string errString;
2806 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2807 strFailReason = _("Transaction has too long of a mempool chain");
2808 return false;
2811 return true;
2815 * Call after CreateTransaction unless you want to abort
2817 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2820 LOCK2(cs_main, cs_wallet);
2821 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2823 // Take key pair from key pool so it won't be used again
2824 reservekey.KeepKey();
2826 // Add tx to wallet, because if it has change it's also ours,
2827 // otherwise just for transaction history.
2828 AddToWallet(wtxNew);
2830 // Notify that old coins are spent
2831 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2833 CWalletTx &coin = mapWallet[txin.prevout.hash];
2834 coin.BindWallet(this);
2835 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2839 // Track how many getdata requests our transaction gets
2840 mapRequestCount[wtxNew.GetHash()] = 0;
2842 if (fBroadcastTransactions)
2844 // Broadcast
2845 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2846 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2847 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2848 } else {
2849 wtxNew.RelayWalletTransaction(connman);
2853 return true;
2856 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2857 CWalletDB walletdb(*dbw);
2858 return walletdb.ListAccountCreditDebit(strAccount, entries);
2861 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2863 CWalletDB walletdb(*dbw);
2865 return AddAccountingEntry(acentry, &walletdb);
2868 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2870 if (!pwalletdb->WriteAccountingEntry_Backend(acentry))
2871 return false;
2873 laccentries.push_back(acentry);
2874 CAccountingEntry & entry = laccentries.back();
2875 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2877 return true;
2880 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2882 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2885 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee)
2887 // payTxFee is the user-set global for desired feerate
2888 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2889 // User didn't set: use -txconfirmtarget to estimate...
2890 if (nFeeNeeded == 0 || ignoreGlobalPayTxFee) {
2891 int estimateFoundTarget = nConfirmTarget;
2892 nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
2893 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2894 if (nFeeNeeded == 0)
2895 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2897 // prevent user from paying a fee below minRelayTxFee or minTxFee
2898 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2899 // But always obey the maximum
2900 if (nFeeNeeded > maxTxFee)
2901 nFeeNeeded = maxTxFee;
2902 return nFeeNeeded;
2908 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2910 fFirstRunRet = false;
2911 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2912 if (nLoadWalletRet == DB_NEED_REWRITE)
2914 if (dbw->Rewrite("\x04pool"))
2916 LOCK(cs_wallet);
2917 setKeyPool.clear();
2918 // Note: can't top-up keypool here, because wallet is locked.
2919 // User will be prompted to unlock wallet the next operation
2920 // that requires a new key.
2924 if (nLoadWalletRet != DB_LOAD_OK)
2925 return nLoadWalletRet;
2926 fFirstRunRet = !vchDefaultKey.IsValid();
2928 uiInterface.LoadWallet(this);
2930 return DB_LOAD_OK;
2933 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2935 AssertLockHeld(cs_wallet); // mapWallet
2936 vchDefaultKey = CPubKey();
2937 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
2938 for (uint256 hash : vHashOut)
2939 mapWallet.erase(hash);
2941 if (nZapSelectTxRet == DB_NEED_REWRITE)
2943 if (dbw->Rewrite("\x04pool"))
2945 setKeyPool.clear();
2946 // Note: can't top-up keypool here, because wallet is locked.
2947 // User will be prompted to unlock wallet the next operation
2948 // that requires a new key.
2952 if (nZapSelectTxRet != DB_LOAD_OK)
2953 return nZapSelectTxRet;
2955 MarkDirty();
2957 return DB_LOAD_OK;
2961 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2963 vchDefaultKey = CPubKey();
2964 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
2965 if (nZapWalletTxRet == DB_NEED_REWRITE)
2967 if (dbw->Rewrite("\x04pool"))
2969 LOCK(cs_wallet);
2970 setKeyPool.clear();
2971 // Note: can't top-up keypool here, because wallet is locked.
2972 // User will be prompted to unlock wallet the next operation
2973 // that requires a new key.
2977 if (nZapWalletTxRet != DB_LOAD_OK)
2978 return nZapWalletTxRet;
2980 return DB_LOAD_OK;
2984 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2986 bool fUpdated = false;
2988 LOCK(cs_wallet); // mapAddressBook
2989 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2990 fUpdated = mi != mapAddressBook.end();
2991 mapAddressBook[address].name = strName;
2992 if (!strPurpose.empty()) /* update purpose only if requested */
2993 mapAddressBook[address].purpose = strPurpose;
2995 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2996 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2997 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2998 return false;
2999 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3002 bool CWallet::DelAddressBook(const CTxDestination& address)
3005 LOCK(cs_wallet); // mapAddressBook
3007 // Delete destdata tuples associated with address
3008 std::string strAddress = CBitcoinAddress(address).ToString();
3009 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
3011 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3013 mapAddressBook.erase(address);
3016 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3018 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3019 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3022 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3024 CTxDestination address;
3025 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3026 auto mi = mapAddressBook.find(address);
3027 if (mi != mapAddressBook.end()) {
3028 return mi->second.name;
3031 // A scriptPubKey that doesn't have an entry in the address book is
3032 // associated with the default account ("").
3033 const static std::string DEFAULT_ACCOUNT_NAME;
3034 return DEFAULT_ACCOUNT_NAME;
3037 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3039 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3040 return false;
3041 vchDefaultKey = vchPubKey;
3042 return true;
3046 * Mark old keypool keys as used,
3047 * and generate all new keys
3049 bool CWallet::NewKeyPool()
3052 LOCK(cs_wallet);
3053 CWalletDB walletdb(*dbw);
3054 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3055 walletdb.ErasePool(nIndex);
3056 setKeyPool.clear();
3058 if (!TopUpKeyPool()) {
3059 return false;
3061 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3063 return true;
3066 size_t CWallet::KeypoolCountExternalKeys()
3068 AssertLockHeld(cs_wallet); // setKeyPool
3070 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
3071 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3072 return setKeyPool.size();
3074 CWalletDB walletdb(*dbw);
3076 // count amount of external keys
3077 size_t amountE = 0;
3078 for(const int64_t& id : setKeyPool)
3080 CKeyPool tmpKeypool;
3081 if (!walletdb.ReadPool(id, tmpKeypool))
3082 throw std::runtime_error(std::string(__func__) + ": read failed");
3083 amountE += !tmpKeypool.fInternal;
3086 return amountE;
3089 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3092 LOCK(cs_wallet);
3094 if (IsLocked())
3095 return false;
3097 // Top up key pool
3098 unsigned int nTargetSize;
3099 if (kpSize > 0)
3100 nTargetSize = kpSize;
3101 else
3102 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3104 // count amount of available keys (internal, external)
3105 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3106 int64_t amountExternal = KeypoolCountExternalKeys();
3107 int64_t amountInternal = setKeyPool.size() - amountExternal;
3108 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3109 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3111 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3113 // don't create extra internal keys
3114 missingInternal = 0;
3116 bool internal = false;
3117 CWalletDB walletdb(*dbw);
3118 for (int64_t i = missingInternal + missingExternal; i--;)
3120 int64_t nEnd = 1;
3121 if (i < missingInternal)
3122 internal = true;
3123 if (!setKeyPool.empty())
3124 nEnd = *(--setKeyPool.end()) + 1;
3125 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3126 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3127 setKeyPool.insert(nEnd);
3128 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3131 return true;
3134 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3136 nIndex = -1;
3137 keypool.vchPubKey = CPubKey();
3139 LOCK(cs_wallet);
3141 if (!IsLocked())
3142 TopUpKeyPool();
3144 // Get the oldest key
3145 if(setKeyPool.empty())
3146 return;
3148 CWalletDB walletdb(*dbw);
3150 // try to find a key that matches the internal/external filter
3151 for(const int64_t& id : setKeyPool)
3153 CKeyPool tmpKeypool;
3154 if (!walletdb.ReadPool(id, tmpKeypool))
3155 throw std::runtime_error(std::string(__func__) + ": read failed");
3156 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3157 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3158 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3160 nIndex = id;
3161 keypool = tmpKeypool;
3162 setKeyPool.erase(id);
3163 assert(keypool.vchPubKey.IsValid());
3164 LogPrintf("keypool reserve %d\n", nIndex);
3165 return;
3171 void CWallet::KeepKey(int64_t nIndex)
3173 // Remove from key pool
3174 CWalletDB walletdb(*dbw);
3175 walletdb.ErasePool(nIndex);
3176 LogPrintf("keypool keep %d\n", nIndex);
3179 void CWallet::ReturnKey(int64_t nIndex)
3181 // Return to key pool
3183 LOCK(cs_wallet);
3184 setKeyPool.insert(nIndex);
3186 LogPrintf("keypool return %d\n", nIndex);
3189 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3191 CKeyPool keypool;
3193 LOCK(cs_wallet);
3194 int64_t nIndex = 0;
3195 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3196 if (nIndex == -1)
3198 if (IsLocked()) return false;
3199 result = GenerateNewKey(internal);
3200 return true;
3202 KeepKey(nIndex);
3203 result = keypool.vchPubKey;
3205 return true;
3208 int64_t CWallet::GetOldestKeyPoolTime()
3210 LOCK(cs_wallet);
3212 // if the keypool is empty, return <NOW>
3213 if (setKeyPool.empty())
3214 return GetTime();
3216 CKeyPool keypool;
3217 CWalletDB walletdb(*dbw);
3219 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3221 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3222 int64_t now = GetTime();
3223 int64_t oldest_external = now, oldest_internal = now;
3225 for(const int64_t& id : setKeyPool)
3227 if (!walletdb.ReadPool(id, keypool)) {
3228 throw std::runtime_error(std::string(__func__) + ": read failed");
3230 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3231 oldest_internal = keypool.nTime;
3233 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3234 oldest_external = keypool.nTime;
3236 if (oldest_internal != now && oldest_external != now) {
3237 break;
3240 return std::max(oldest_internal, oldest_external);
3242 // load oldest key from keypool, get time and return
3243 int64_t nIndex = *(setKeyPool.begin());
3244 if (!walletdb.ReadPool(nIndex, keypool))
3245 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3246 assert(keypool.vchPubKey.IsValid());
3247 return keypool.nTime;
3250 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3252 std::map<CTxDestination, CAmount> balances;
3255 LOCK(cs_wallet);
3256 for (const auto& walletEntry : mapWallet)
3258 const CWalletTx *pcoin = &walletEntry.second;
3260 if (!pcoin->IsTrusted())
3261 continue;
3263 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3264 continue;
3266 int nDepth = pcoin->GetDepthInMainChain();
3267 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3268 continue;
3270 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3272 CTxDestination addr;
3273 if (!IsMine(pcoin->tx->vout[i]))
3274 continue;
3275 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3276 continue;
3278 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3280 if (!balances.count(addr))
3281 balances[addr] = 0;
3282 balances[addr] += n;
3287 return balances;
3290 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3292 AssertLockHeld(cs_wallet); // mapWallet
3293 std::set< std::set<CTxDestination> > groupings;
3294 std::set<CTxDestination> grouping;
3296 for (const auto& walletEntry : mapWallet)
3298 const CWalletTx *pcoin = &walletEntry.second;
3300 if (pcoin->tx->vin.size() > 0)
3302 bool any_mine = false;
3303 // group all input addresses with each other
3304 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3306 CTxDestination address;
3307 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3308 continue;
3309 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3310 continue;
3311 grouping.insert(address);
3312 any_mine = true;
3315 // group change with input addresses
3316 if (any_mine)
3318 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3319 if (IsChange(txout))
3321 CTxDestination txoutAddr;
3322 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3323 continue;
3324 grouping.insert(txoutAddr);
3327 if (grouping.size() > 0)
3329 groupings.insert(grouping);
3330 grouping.clear();
3334 // group lone addrs by themselves
3335 for (const auto& txout : pcoin->tx->vout)
3336 if (IsMine(txout))
3338 CTxDestination address;
3339 if(!ExtractDestination(txout.scriptPubKey, address))
3340 continue;
3341 grouping.insert(address);
3342 groupings.insert(grouping);
3343 grouping.clear();
3347 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3348 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3349 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3351 // make a set of all the groups hit by this new group
3352 std::set< std::set<CTxDestination>* > hits;
3353 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3354 BOOST_FOREACH(CTxDestination address, _grouping)
3355 if ((it = setmap.find(address)) != setmap.end())
3356 hits.insert((*it).second);
3358 // merge all hit groups into a new single group and delete old groups
3359 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3360 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3362 merged->insert(hit->begin(), hit->end());
3363 uniqueGroupings.erase(hit);
3364 delete hit;
3366 uniqueGroupings.insert(merged);
3368 // update setmap
3369 BOOST_FOREACH(CTxDestination element, *merged)
3370 setmap[element] = merged;
3373 std::set< std::set<CTxDestination> > ret;
3374 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3376 ret.insert(*uniqueGrouping);
3377 delete uniqueGrouping;
3380 return ret;
3383 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3385 LOCK(cs_wallet);
3386 std::set<CTxDestination> result;
3387 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3389 const CTxDestination& address = item.first;
3390 const std::string& strName = item.second.name;
3391 if (strName == strAccount)
3392 result.insert(address);
3394 return result;
3397 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3399 if (nIndex == -1)
3401 CKeyPool keypool;
3402 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3403 if (nIndex != -1)
3404 vchPubKey = keypool.vchPubKey;
3405 else {
3406 return false;
3409 assert(vchPubKey.IsValid());
3410 pubkey = vchPubKey;
3411 return true;
3414 void CReserveKey::KeepKey()
3416 if (nIndex != -1)
3417 pwallet->KeepKey(nIndex);
3418 nIndex = -1;
3419 vchPubKey = CPubKey();
3422 void CReserveKey::ReturnKey()
3424 if (nIndex != -1)
3425 pwallet->ReturnKey(nIndex);
3426 nIndex = -1;
3427 vchPubKey = CPubKey();
3430 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3432 setAddress.clear();
3434 CWalletDB walletdb(*dbw);
3436 LOCK2(cs_main, cs_wallet);
3437 BOOST_FOREACH(const int64_t& id, setKeyPool)
3439 CKeyPool keypool;
3440 if (!walletdb.ReadPool(id, keypool))
3441 throw std::runtime_error(std::string(__func__) + ": read failed");
3442 assert(keypool.vchPubKey.IsValid());
3443 CKeyID keyID = keypool.vchPubKey.GetID();
3444 if (!HaveKey(keyID))
3445 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3446 setAddress.insert(keyID);
3450 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3452 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3453 CPubKey pubkey;
3454 if (!rKey->GetReservedKey(pubkey))
3455 return;
3457 script = rKey;
3458 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3461 void CWallet::LockCoin(const COutPoint& output)
3463 AssertLockHeld(cs_wallet); // setLockedCoins
3464 setLockedCoins.insert(output);
3467 void CWallet::UnlockCoin(const COutPoint& output)
3469 AssertLockHeld(cs_wallet); // setLockedCoins
3470 setLockedCoins.erase(output);
3473 void CWallet::UnlockAllCoins()
3475 AssertLockHeld(cs_wallet); // setLockedCoins
3476 setLockedCoins.clear();
3479 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3481 AssertLockHeld(cs_wallet); // setLockedCoins
3482 COutPoint outpt(hash, n);
3484 return (setLockedCoins.count(outpt) > 0);
3487 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3489 AssertLockHeld(cs_wallet); // setLockedCoins
3490 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3491 it != setLockedCoins.end(); it++) {
3492 COutPoint outpt = (*it);
3493 vOutpts.push_back(outpt);
3497 /** @} */ // end of Actions
3499 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3500 private:
3501 const CKeyStore &keystore;
3502 std::vector<CKeyID> &vKeys;
3504 public:
3505 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3507 void Process(const CScript &script) {
3508 txnouttype type;
3509 std::vector<CTxDestination> vDest;
3510 int nRequired;
3511 if (ExtractDestinations(script, type, vDest, nRequired)) {
3512 BOOST_FOREACH(const CTxDestination &dest, vDest)
3513 boost::apply_visitor(*this, dest);
3517 void operator()(const CKeyID &keyId) {
3518 if (keystore.HaveKey(keyId))
3519 vKeys.push_back(keyId);
3522 void operator()(const CScriptID &scriptId) {
3523 CScript script;
3524 if (keystore.GetCScript(scriptId, script))
3525 Process(script);
3528 void operator()(const CNoDestination &none) {}
3531 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3532 AssertLockHeld(cs_wallet); // mapKeyMetadata
3533 mapKeyBirth.clear();
3535 // get birth times for keys with metadata
3536 for (const auto& entry : mapKeyMetadata) {
3537 if (entry.second.nCreateTime) {
3538 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3542 // map in which we'll infer heights of other keys
3543 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3544 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3545 std::set<CKeyID> setKeys;
3546 GetKeys(setKeys);
3547 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3548 if (mapKeyBirth.count(keyid) == 0)
3549 mapKeyFirstBlock[keyid] = pindexMax;
3551 setKeys.clear();
3553 // if there are no such keys, we're done
3554 if (mapKeyFirstBlock.empty())
3555 return;
3557 // find first block that affects those keys, if there are any left
3558 std::vector<CKeyID> vAffected;
3559 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3560 // iterate over all wallet transactions...
3561 const CWalletTx &wtx = (*it).second;
3562 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3563 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3564 // ... which are already in a block
3565 int nHeight = blit->second->nHeight;
3566 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3567 // iterate over all their outputs
3568 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3569 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3570 // ... and all their affected keys
3571 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3572 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3573 rit->second = blit->second;
3575 vAffected.clear();
3580 // Extract block timestamps for those keys
3581 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3582 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3586 * Compute smart timestamp for a transaction being added to the wallet.
3588 * Logic:
3589 * - If sending a transaction, assign its timestamp to the current time.
3590 * - If receiving a transaction outside a block, assign its timestamp to the
3591 * current time.
3592 * - If receiving a block with a future timestamp, assign all its (not already
3593 * known) transactions' timestamps to the current time.
3594 * - If receiving a block with a past timestamp, before the most recent known
3595 * transaction (that we care about), assign all its (not already known)
3596 * transactions' timestamps to the same timestamp as that most-recent-known
3597 * transaction.
3598 * - If receiving a block with a past timestamp, but after the most recent known
3599 * transaction, assign all its (not already known) transactions' timestamps to
3600 * the block time.
3602 * For more information see CWalletTx::nTimeSmart,
3603 * https://bitcointalk.org/?topic=54527, or
3604 * https://github.com/bitcoin/bitcoin/pull/1393.
3606 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3608 unsigned int nTimeSmart = wtx.nTimeReceived;
3609 if (!wtx.hashUnset()) {
3610 if (mapBlockIndex.count(wtx.hashBlock)) {
3611 int64_t latestNow = wtx.nTimeReceived;
3612 int64_t latestEntry = 0;
3614 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3615 int64_t latestTolerated = latestNow + 300;
3616 const TxItems& txOrdered = wtxOrdered;
3617 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3618 CWalletTx* const pwtx = it->second.first;
3619 if (pwtx == &wtx) {
3620 continue;
3622 CAccountingEntry* const pacentry = it->second.second;
3623 int64_t nSmartTime;
3624 if (pwtx) {
3625 nSmartTime = pwtx->nTimeSmart;
3626 if (!nSmartTime) {
3627 nSmartTime = pwtx->nTimeReceived;
3629 } else {
3630 nSmartTime = pacentry->nTime;
3632 if (nSmartTime <= latestTolerated) {
3633 latestEntry = nSmartTime;
3634 if (nSmartTime > latestNow) {
3635 latestNow = nSmartTime;
3637 break;
3641 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3642 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3643 } else {
3644 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3647 return nTimeSmart;
3650 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3652 if (boost::get<CNoDestination>(&dest))
3653 return false;
3655 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3656 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3659 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3661 if (!mapAddressBook[dest].destdata.erase(key))
3662 return false;
3663 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3666 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3668 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3669 return true;
3672 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3674 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3675 if(i != mapAddressBook.end())
3677 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3678 if(j != i->second.destdata.end())
3680 if(value)
3681 *value = j->second;
3682 return true;
3685 return false;
3688 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3690 LOCK(cs_wallet);
3691 std::vector<std::string> values;
3692 for (const auto& address : mapAddressBook) {
3693 for (const auto& data : address.second.destdata) {
3694 if (!data.first.compare(0, prefix.size(), prefix)) {
3695 values.emplace_back(data.second);
3699 return values;
3702 std::string CWallet::GetWalletHelpString(bool showDebug)
3704 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3705 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3706 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3707 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3708 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3709 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3710 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3711 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3712 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3713 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3714 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3715 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3716 strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
3717 strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
3718 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3719 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3720 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3721 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3722 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3723 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3724 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3726 if (showDebug)
3728 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3730 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3731 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3732 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3733 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3736 return strUsage;
3739 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3741 // needed to restore wallet transaction meta data after -zapwallettxes
3742 std::vector<CWalletTx> vWtx;
3744 if (GetBoolArg("-zapwallettxes", false)) {
3745 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3747 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3748 CWallet *tempWallet = new CWallet(std::move(dbw));
3749 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3750 if (nZapWalletRet != DB_LOAD_OK) {
3751 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3752 return NULL;
3755 delete tempWallet;
3756 tempWallet = NULL;
3759 uiInterface.InitMessage(_("Loading wallet..."));
3761 int64_t nStart = GetTimeMillis();
3762 bool fFirstRun = true;
3763 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3764 CWallet *walletInstance = new CWallet(std::move(dbw));
3765 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3766 if (nLoadWalletRet != DB_LOAD_OK)
3768 if (nLoadWalletRet == DB_CORRUPT) {
3769 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3770 return NULL;
3772 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3774 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3775 " or address book entries might be missing or incorrect."),
3776 walletFile));
3778 else if (nLoadWalletRet == DB_TOO_NEW) {
3779 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3780 return NULL;
3782 else if (nLoadWalletRet == DB_NEED_REWRITE)
3784 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3785 return NULL;
3787 else {
3788 InitError(strprintf(_("Error loading %s"), walletFile));
3789 return NULL;
3793 if (GetBoolArg("-upgradewallet", fFirstRun))
3795 int nMaxVersion = GetArg("-upgradewallet", 0);
3796 if (nMaxVersion == 0) // the -upgradewallet without argument case
3798 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3799 nMaxVersion = CLIENT_VERSION;
3800 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3802 else
3803 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3804 if (nMaxVersion < walletInstance->GetVersion())
3806 InitError(_("Cannot downgrade wallet"));
3807 return NULL;
3809 walletInstance->SetMaxVersion(nMaxVersion);
3812 if (fFirstRun)
3814 // Create new keyUser and set as default key
3815 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3817 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3818 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3820 // generate a new master key
3821 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3822 if (!walletInstance->SetHDMasterKey(masterPubKey))
3823 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3825 CPubKey newDefaultKey;
3826 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3827 walletInstance->SetDefaultKey(newDefaultKey);
3828 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3829 InitError(_("Cannot write default address") += "\n");
3830 return NULL;
3834 walletInstance->SetBestChain(chainActive.GetLocator());
3836 else if (IsArgSet("-usehd")) {
3837 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3838 if (walletInstance->IsHDEnabled() && !useHD) {
3839 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3840 return NULL;
3842 if (!walletInstance->IsHDEnabled() && useHD) {
3843 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3844 return NULL;
3848 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3850 RegisterValidationInterface(walletInstance);
3852 CBlockIndex *pindexRescan = chainActive.Genesis();
3853 if (!GetBoolArg("-rescan", false))
3855 CWalletDB walletdb(*walletInstance->dbw);
3856 CBlockLocator locator;
3857 if (walletdb.ReadBestBlock(locator))
3858 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3860 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3862 //We can't rescan beyond non-pruned blocks, stop and throw an error
3863 //this might happen if a user uses a old wallet within a pruned node
3864 // or if he ran -disablewallet for a longer time, then decided to re-enable
3865 if (fPruneMode)
3867 CBlockIndex *block = chainActive.Tip();
3868 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3869 block = block->pprev;
3871 if (pindexRescan != block) {
3872 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3873 return NULL;
3877 uiInterface.InitMessage(_("Rescanning..."));
3878 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3879 nStart = GetTimeMillis();
3880 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3881 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3882 walletInstance->SetBestChain(chainActive.GetLocator());
3883 CWalletDB::IncrementUpdateCounter();
3885 // Restore wallet transaction metadata after -zapwallettxes=1
3886 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3888 CWalletDB walletdb(*walletInstance->dbw);
3890 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3892 uint256 hash = wtxOld.GetHash();
3893 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3894 if (mi != walletInstance->mapWallet.end())
3896 const CWalletTx* copyFrom = &wtxOld;
3897 CWalletTx* copyTo = &mi->second;
3898 copyTo->mapValue = copyFrom->mapValue;
3899 copyTo->vOrderForm = copyFrom->vOrderForm;
3900 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3901 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3902 copyTo->fFromMe = copyFrom->fFromMe;
3903 copyTo->strFromAccount = copyFrom->strFromAccount;
3904 copyTo->nOrderPos = copyFrom->nOrderPos;
3905 walletdb.WriteTx(*copyTo);
3910 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3913 LOCK(walletInstance->cs_wallet);
3914 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3915 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3916 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3919 return walletInstance;
3922 bool CWallet::InitLoadWallet()
3924 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3925 pwalletMain = NULL;
3926 LogPrintf("Wallet disabled!\n");
3927 return true;
3930 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3932 if (boost::filesystem::path(walletFile).filename() != walletFile) {
3933 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
3934 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
3935 return InitError(_("Invalid characters in -wallet filename"));
3938 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3939 if (!pwallet) {
3940 return false;
3942 pwalletMain = pwallet;
3944 return true;
3947 std::atomic<bool> CWallet::fFlushScheduled(false);
3949 void CWallet::postInitProcess(CScheduler& scheduler)
3951 // Add wallet transactions that aren't already in a block to mempool
3952 // Do this here as mempool requires genesis block to be loaded
3953 ReacceptWalletTransactions();
3955 // Run a thread to flush wallet periodically
3956 if (!CWallet::fFlushScheduled.exchange(true)) {
3957 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3961 bool CWallet::ParameterInteraction()
3963 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3964 return true;
3966 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3967 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3970 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3971 // Rewrite just private keys: rescan to find transactions
3972 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3975 // -zapwallettx implies a rescan
3976 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3977 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3980 if (GetBoolArg("-sysperms", false))
3981 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3982 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3983 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3985 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
3986 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3987 _("The wallet will avoid paying less than the minimum relay fee."));
3989 if (IsArgSet("-mintxfee"))
3991 CAmount n = 0;
3992 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
3993 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3994 if (n > HIGH_TX_FEE_PER_KB)
3995 InitWarning(AmountHighWarn("-mintxfee") + " " +
3996 _("This is the minimum transaction fee you pay on every transaction."));
3997 CWallet::minTxFee = CFeeRate(n);
3999 if (IsArgSet("-fallbackfee"))
4001 CAmount nFeePerK = 0;
4002 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4003 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4004 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4005 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4006 _("This is the transaction fee you may pay when fee estimates are not available."));
4007 CWallet::fallbackFee = CFeeRate(nFeePerK);
4009 if (IsArgSet("-paytxfee"))
4011 CAmount nFeePerK = 0;
4012 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4013 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4014 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4015 InitWarning(AmountHighWarn("-paytxfee") + " " +
4016 _("This is the transaction fee you will pay if you send a transaction."));
4018 payTxFee = CFeeRate(nFeePerK, 1000);
4019 if (payTxFee < ::minRelayTxFee)
4021 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4022 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4025 if (IsArgSet("-maxtxfee"))
4027 CAmount nMaxFee = 0;
4028 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4029 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4030 if (nMaxFee > HIGH_MAX_TX_FEE)
4031 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4032 maxTxFee = nMaxFee;
4033 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4035 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4036 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4039 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4040 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4041 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4043 return true;
4046 bool CWallet::BackupWallet(const std::string& strDest)
4048 return dbw->Backup(strDest);
4051 CKeyPool::CKeyPool()
4053 nTime = GetTime();
4054 fInternal = false;
4057 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4059 nTime = GetTime();
4060 vchPubKey = vchPubKeyIn;
4061 fInternal = internalIn;
4064 CWalletKey::CWalletKey(int64_t nExpires)
4066 nTimeCreated = (nExpires ? GetTime() : 0);
4067 nTimeExpires = nExpires;
4070 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4072 // Update the tx's hashBlock
4073 hashBlock = pindex->GetBlockHash();
4075 // set the position of the transaction in the block
4076 nIndex = posInBlock;
4079 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4081 if (hashUnset())
4082 return 0;
4084 AssertLockHeld(cs_main);
4086 // Find the block it claims to be in
4087 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4088 if (mi == mapBlockIndex.end())
4089 return 0;
4090 CBlockIndex* pindex = (*mi).second;
4091 if (!pindex || !chainActive.Contains(pindex))
4092 return 0;
4094 pindexRet = pindex;
4095 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4098 int CMerkleTx::GetBlocksToMaturity() const
4100 if (!IsCoinBase())
4101 return 0;
4102 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4106 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4108 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);