1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
9 #include "checkpoints.h"
10 #include "coincontrol.h"
12 #include "script/script.h"
13 #include "script/sign.h"
16 #include "utilmoneystr.h"
20 #include <boost/algorithm/string/replace.hpp>
21 #include <boost/thread.hpp>
28 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
29 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
30 unsigned int nTxConfirmTarget = 1;
31 bool bSpendZeroConfChange = true;
32 bool fSendFreeTransactions = false;
33 bool fPayAtLeastCustomFee = true;
36 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
37 * Override with -mintxfee
39 CFeeRate CWallet::minTxFee = CFeeRate(1000);
41 /** @defgroup mapWallet
46 struct CompareValueOnly
48 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
49 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
51 return t1.first < t2.first;
55 std::string COutput::ToString() const
57 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
60 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
63 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
64 if (it == mapWallet.end())
69 CPubKey CWallet::GenerateNewKey()
71 AssertLockHeld(cs_wallet); // mapKeyMetadata
72 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
76 secret.MakeNewKey(fCompressed);
78 // Compressed public keys were introduced in version 0.6.0
80 SetMinVersion(FEATURE_COMPRPUBKEY);
82 CPubKey pubkey = secret.GetPubKey();
83 assert(secret.VerifyPubKey(pubkey));
85 // Create new metadata
86 int64_t nCreationTime = GetTime();
87 mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
88 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
89 nTimeFirstKey = nCreationTime;
91 if (!AddKeyPubKey(secret, pubkey))
92 throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
96 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
98 AssertLockHeld(cs_wallet); // mapKeyMetadata
99 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
102 // check if we need to remove from watch-only
104 script = GetScriptForDestination(pubkey.GetID());
105 if (HaveWatchOnly(script))
106 RemoveWatchOnly(script);
111 return CWalletDB(strWalletFile).WriteKey(pubkey,
113 mapKeyMetadata[pubkey.GetID()]);
118 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
119 const vector<unsigned char> &vchCryptedSecret)
121 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
127 if (pwalletdbEncryption)
128 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
130 mapKeyMetadata[vchPubKey.GetID()]);
132 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
134 mapKeyMetadata[vchPubKey.GetID()]);
139 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
141 AssertLockHeld(cs_wallet); // mapKeyMetadata
142 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
143 nTimeFirstKey = meta.nCreateTime;
145 mapKeyMetadata[pubkey.GetID()] = meta;
149 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
151 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
154 bool CWallet::AddCScript(const CScript& redeemScript)
156 if (!CCryptoKeyStore::AddCScript(redeemScript))
160 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
163 bool CWallet::LoadCScript(const CScript& redeemScript)
165 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
166 * that never can be redeemed. However, old wallets may still contain
167 * these. Do not add them to the wallet and warn. */
168 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
170 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
171 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",
172 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
176 return CCryptoKeyStore::AddCScript(redeemScript);
179 bool CWallet::AddWatchOnly(const CScript &dest)
181 if (!CCryptoKeyStore::AddWatchOnly(dest))
183 nTimeFirstKey = 1; // No birthday information for watch-only keys.
184 NotifyWatchonlyChanged(true);
187 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
190 bool CWallet::RemoveWatchOnly(const CScript &dest)
192 AssertLockHeld(cs_wallet);
193 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
195 if (!HaveWatchOnly())
196 NotifyWatchonlyChanged(false);
198 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
204 bool CWallet::LoadWatchOnly(const CScript &dest)
206 return CCryptoKeyStore::AddWatchOnly(dest);
209 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
212 CKeyingMaterial vMasterKey;
216 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
218 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
220 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
221 continue; // try another master key
222 if (CCryptoKeyStore::Unlock(vMasterKey))
229 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
231 bool fWasLocked = IsLocked();
238 CKeyingMaterial vMasterKey;
239 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
241 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
243 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
245 if (CCryptoKeyStore::Unlock(vMasterKey))
247 int64_t nStartTime = GetTimeMillis();
248 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
249 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
251 nStartTime = GetTimeMillis();
252 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
253 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
255 if (pMasterKey.second.nDeriveIterations < 25000)
256 pMasterKey.second.nDeriveIterations = 25000;
258 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
260 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
262 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
264 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
275 void CWallet::SetBestChain(const CBlockLocator& loc)
277 CWalletDB walletdb(strWalletFile);
278 walletdb.WriteBestBlock(loc);
281 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
283 LOCK(cs_wallet); // nWalletVersion
284 if (nWalletVersion >= nVersion)
287 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
288 if (fExplicit && nVersion > nWalletMaxVersion)
289 nVersion = FEATURE_LATEST;
291 nWalletVersion = nVersion;
293 if (nVersion > nWalletMaxVersion)
294 nWalletMaxVersion = nVersion;
298 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
299 if (nWalletVersion > 40000)
300 pwalletdb->WriteMinVersion(nWalletVersion);
308 bool CWallet::SetMaxVersion(int nVersion)
310 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
311 // cannot downgrade below current version
312 if (nWalletVersion > nVersion)
315 nWalletMaxVersion = nVersion;
320 set<uint256> CWallet::GetConflicts(const uint256& txid) const
323 AssertLockHeld(cs_wallet);
325 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
326 if (it == mapWallet.end())
328 const CWalletTx& wtx = it->second;
330 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
332 BOOST_FOREACH(const CTxIn& txin, wtx.vin)
334 if (mapTxSpends.count(txin.prevout) <= 1)
335 continue; // No conflict if zero or one spends
336 range = mapTxSpends.equal_range(txin.prevout);
337 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
338 result.insert(it->second);
343 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
345 // We want all the wallet transactions in range to have the same metadata as
346 // the oldest (smallest nOrderPos).
347 // So: find smallest nOrderPos:
349 int nMinOrderPos = std::numeric_limits<int>::max();
350 const CWalletTx* copyFrom = NULL;
351 for (TxSpends::iterator it = range.first; it != range.second; ++it)
353 const uint256& hash = it->second;
354 int n = mapWallet[hash].nOrderPos;
355 if (n < nMinOrderPos)
358 copyFrom = &mapWallet[hash];
361 // Now copy data from copyFrom to rest:
362 for (TxSpends::iterator it = range.first; it != range.second; ++it)
364 const uint256& hash = it->second;
365 CWalletTx* copyTo = &mapWallet[hash];
366 if (copyFrom == copyTo) continue;
367 copyTo->mapValue = copyFrom->mapValue;
368 copyTo->vOrderForm = copyFrom->vOrderForm;
369 // fTimeReceivedIsTxTime not copied on purpose
370 // nTimeReceived not copied on purpose
371 copyTo->nTimeSmart = copyFrom->nTimeSmart;
372 copyTo->fFromMe = copyFrom->fFromMe;
373 copyTo->strFromAccount = copyFrom->strFromAccount;
374 // nOrderPos not copied on purpose
375 // cached members not copied on purpose
380 * Outpoint is spent if any non-conflicted transaction
383 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
385 const COutPoint outpoint(hash, n);
386 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
387 range = mapTxSpends.equal_range(outpoint);
389 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
391 const uint256& wtxid = it->second;
392 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
393 if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
394 return true; // Spent
399 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
401 mapTxSpends.insert(make_pair(outpoint, wtxid));
403 pair<TxSpends::iterator, TxSpends::iterator> range;
404 range = mapTxSpends.equal_range(outpoint);
409 void CWallet::AddToSpends(const uint256& wtxid)
411 assert(mapWallet.count(wtxid));
412 CWalletTx& thisTx = mapWallet[wtxid];
413 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
416 BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
417 AddToSpends(txin.prevout, wtxid);
420 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
425 CKeyingMaterial vMasterKey;
426 RandAddSeedPerfmon();
428 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
429 GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
431 CMasterKey kMasterKey;
432 RandAddSeedPerfmon();
434 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
435 GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
438 int64_t nStartTime = GetTimeMillis();
439 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
440 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
442 nStartTime = GetTimeMillis();
443 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
444 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
446 if (kMasterKey.nDeriveIterations < 25000)
447 kMasterKey.nDeriveIterations = 25000;
449 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
451 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
453 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
458 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
461 assert(!pwalletdbEncryption);
462 pwalletdbEncryption = new CWalletDB(strWalletFile);
463 if (!pwalletdbEncryption->TxnBegin()) {
464 delete pwalletdbEncryption;
465 pwalletdbEncryption = NULL;
468 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
471 if (!EncryptKeys(vMasterKey))
474 pwalletdbEncryption->TxnAbort();
475 delete pwalletdbEncryption;
477 // We now probably have half of our keys encrypted in memory, and half not...
478 // die and let the user reload their unencrypted wallet.
482 // Encryption was introduced in version 0.4.0
483 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
487 if (!pwalletdbEncryption->TxnCommit()) {
488 delete pwalletdbEncryption;
489 // We now have keys encrypted in memory, but not on disk...
490 // die to avoid confusion and let the user reload their unencrypted wallet.
494 delete pwalletdbEncryption;
495 pwalletdbEncryption = NULL;
499 Unlock(strWalletPassphrase);
503 // Need to completely rewrite the wallet file; if we don't, bdb might keep
504 // bits of the unencrypted private key in slack space in the database file.
505 CDB::Rewrite(strWalletFile);
508 NotifyStatusChanged(this);
513 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
515 AssertLockHeld(cs_wallet); // nOrderPosNext
516 int64_t nRet = nOrderPosNext++;
518 pwalletdb->WriteOrderPosNext(nOrderPosNext);
520 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
525 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
527 AssertLockHeld(cs_wallet); // mapWallet
528 CWalletDB walletdb(strWalletFile);
530 // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
533 // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
534 // would make this much faster for applications that do this a lot.
535 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
537 CWalletTx* wtx = &((*it).second);
538 txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
541 walletdb.ListAccountCreditDebit(strAccount, acentries);
542 BOOST_FOREACH(CAccountingEntry& entry, acentries)
544 txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
550 void CWallet::MarkDirty()
554 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
555 item.second.MarkDirty();
559 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
561 uint256 hash = wtxIn.GetHash();
565 mapWallet[hash] = wtxIn;
566 mapWallet[hash].BindWallet(this);
572 // Inserts only if not already there, returns tx inserted or tx found
573 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
574 CWalletTx& wtx = (*ret.first).second;
575 wtx.BindWallet(this);
576 bool fInsertedNew = ret.second;
579 wtx.nTimeReceived = GetAdjustedTime();
580 wtx.nOrderPos = IncOrderPosNext();
582 wtx.nTimeSmart = wtx.nTimeReceived;
583 if (wtxIn.hashBlock != 0)
585 if (mapBlockIndex.count(wtxIn.hashBlock))
587 int64_t latestNow = wtx.nTimeReceived;
588 int64_t latestEntry = 0;
590 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
591 int64_t latestTolerated = latestNow + 300;
592 std::list<CAccountingEntry> acentries;
593 TxItems txOrdered = OrderedTxItems(acentries);
594 for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
596 CWalletTx *const pwtx = (*it).second.first;
599 CAccountingEntry *const pacentry = (*it).second.second;
603 nSmartTime = pwtx->nTimeSmart;
605 nSmartTime = pwtx->nTimeReceived;
608 nSmartTime = pacentry->nTime;
609 if (nSmartTime <= latestTolerated)
611 latestEntry = nSmartTime;
612 if (nSmartTime > latestNow)
613 latestNow = nSmartTime;
619 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
620 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
623 LogPrintf("AddToWallet() : found %s in block %s not in index\n",
624 wtxIn.GetHash().ToString(),
625 wtxIn.hashBlock.ToString());
630 bool fUpdated = false;
634 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
636 wtx.hashBlock = wtxIn.hashBlock;
639 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
641 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
642 wtx.nIndex = wtxIn.nIndex;
645 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
647 wtx.fFromMe = wtxIn.fFromMe;
653 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
656 if (fInsertedNew || fUpdated)
657 if (!wtx.WriteToDisk())
660 // Break debit/credit balance caches:
663 // Notify UI of new or updated transaction
664 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
666 // notify an external script when a wallet transaction comes in or is updated
667 std::string strCmd = GetArg("-walletnotify", "");
669 if ( !strCmd.empty())
671 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
672 boost::thread t(runCommand, strCmd); // thread runs free
680 * Add a transaction to the wallet, or update it.
681 * pblock is optional, but should be provided if the transaction is known to be in a block.
682 * If fUpdate is true, existing transactions will be updated.
684 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
687 AssertLockHeld(cs_wallet);
688 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
689 if (fExisted && !fUpdate) return false;
690 if (fExisted || IsMine(tx) || IsFromMe(tx))
692 CWalletTx wtx(this,tx);
693 // Get merkle branch if transaction was found in a block
695 wtx.SetMerkleBranch(*pblock);
696 return AddToWallet(wtx);
702 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
704 LOCK2(cs_main, cs_wallet);
705 if (!AddToWalletIfInvolvingMe(tx, pblock, true))
706 return; // Not one of ours
708 // If a transaction changes 'conflicted' state, that changes the balance
709 // available of the outputs it spends. So force those to be
711 BOOST_FOREACH(const CTxIn& txin, tx.vin)
713 if (mapWallet.count(txin.prevout.hash))
714 mapWallet[txin.prevout.hash].MarkDirty();
718 void CWallet::EraseFromWallet(const uint256 &hash)
724 if (mapWallet.erase(hash))
725 CWalletDB(strWalletFile).EraseTx(hash);
731 isminetype CWallet::IsMine(const CTxIn &txin) const
735 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
736 if (mi != mapWallet.end())
738 const CWalletTx& prev = (*mi).second;
739 if (txin.prevout.n < prev.vout.size())
740 return IsMine(prev.vout[txin.prevout.n]);
746 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
750 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
751 if (mi != mapWallet.end())
753 const CWalletTx& prev = (*mi).second;
754 if (txin.prevout.n < prev.vout.size())
755 if (IsMine(prev.vout[txin.prevout.n]) & filter)
756 return prev.vout[txin.prevout.n].nValue;
762 bool CWallet::IsChange(const CTxOut& txout) const
764 // TODO: fix handling of 'change' outputs. The assumption is that any
765 // payment to a script that is ours, but is not in the address book
766 // is change. That assumption is likely to break when we implement multisignature
767 // wallets that return change back into a multi-signature-protected address;
768 // a better way of identifying which outputs are 'the send' and which are
769 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
770 // which output, if any, was change).
771 if (::IsMine(*this, txout.scriptPubKey))
773 CTxDestination address;
774 if (!ExtractDestination(txout.scriptPubKey, address))
778 if (!mapAddressBook.count(address))
784 int64_t CWalletTx::GetTxTime() const
786 int64_t n = nTimeSmart;
787 return n ? n : nTimeReceived;
790 int CWalletTx::GetRequestCount() const
792 // Returns -1 if it wasn't being tracked
795 LOCK(pwallet->cs_wallet);
801 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
802 if (mi != pwallet->mapRequestCount.end())
803 nRequests = (*mi).second;
808 // Did anyone request this transaction?
809 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
810 if (mi != pwallet->mapRequestCount.end())
812 nRequests = (*mi).second;
814 // How about the block it's in?
815 if (nRequests == 0 && hashBlock != 0)
817 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
818 if (mi != pwallet->mapRequestCount.end())
819 nRequests = (*mi).second;
821 nRequests = 1; // If it's in someone else's block it must have got out
829 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
830 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
833 listReceived.clear();
835 strSentAccount = strFromAccount;
838 CAmount nDebit = GetDebit(filter);
839 if (nDebit > 0) // debit>0 means we signed/sent this transaction
841 CAmount nValueOut = GetValueOut();
842 nFee = nDebit - nValueOut;
846 for (unsigned int i = 0; i < vout.size(); ++i)
848 const CTxOut& txout = vout[i];
849 isminetype fIsMine = pwallet->IsMine(txout);
850 // Only need to handle txouts if AT LEAST one of these is true:
851 // 1) they debit from us (sent)
852 // 2) the output is to us (received)
855 // Don't report 'change' txouts
856 if (pwallet->IsChange(txout))
859 else if (!(fIsMine & filter))
862 // In either case, we need to get the destination address
863 CTxDestination address;
864 if (!ExtractDestination(txout.scriptPubKey, address))
866 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
867 this->GetHash().ToString());
868 address = CNoDestination();
871 COutputEntry output = {address, txout.nValue, (int)i};
873 // If we are debited by the transaction, add the output as a "sent" entry
875 listSent.push_back(output);
877 // If we are receiving the output, add it as a "received" entry
878 if (fIsMine & filter)
879 listReceived.push_back(output);
884 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
885 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
887 nReceived = nSent = nFee = 0;
890 string strSentAccount;
891 list<COutputEntry> listReceived;
892 list<COutputEntry> listSent;
893 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
895 if (strAccount == strSentAccount)
897 BOOST_FOREACH(const COutputEntry& s, listSent)
902 LOCK(pwallet->cs_wallet);
903 BOOST_FOREACH(const COutputEntry& r, listReceived)
905 if (pwallet->mapAddressBook.count(r.destination))
907 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
908 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
909 nReceived += r.amount;
911 else if (strAccount.empty())
913 nReceived += r.amount;
920 bool CWalletTx::WriteToDisk()
922 return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
926 * Scan the block chain (starting in pindexStart) for transactions
927 * from or to us. If fUpdate is true, found transactions that already
928 * exist in the wallet will be updated.
930 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
933 int64_t nNow = GetTime();
935 CBlockIndex* pindex = pindexStart;
937 LOCK2(cs_main, cs_wallet);
939 // no need to read and scan block, if block was created before
940 // our wallet birthday (as adjusted for block time variability)
941 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
942 pindex = chainActive.Next(pindex);
944 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
945 double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
946 double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
949 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
950 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
953 ReadBlockFromDisk(block, pindex);
954 BOOST_FOREACH(CTransaction& tx, block.vtx)
956 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
959 pindex = chainActive.Next(pindex);
960 if (GetTime() >= nNow + 60) {
962 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
965 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
970 void CWallet::ReacceptWalletTransactions()
972 LOCK2(cs_main, cs_wallet);
973 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
975 const uint256& wtxid = item.first;
976 CWalletTx& wtx = item.second;
977 assert(wtx.GetHash() == wtxid);
979 int nDepth = wtx.GetDepthInMainChain();
981 if (!wtx.IsCoinBase() && nDepth < 0)
983 // Try to add to memory pool
985 wtx.AcceptToMemoryPool(false);
990 void CWalletTx::RelayWalletTransaction()
994 if (GetDepthInMainChain() == 0) {
995 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
996 RelayTransaction((CTransaction)*this);
1001 set<uint256> CWalletTx::GetConflicts() const
1003 set<uint256> result;
1004 if (pwallet != NULL)
1006 uint256 myHash = GetHash();
1007 result = pwallet->GetConflicts(myHash);
1008 result.erase(myHash);
1013 void CWallet::ResendWalletTransactions()
1015 // Do this infrequently and randomly to avoid giving away
1016 // that these are our transactions.
1017 if (GetTime() < nNextResend)
1019 bool fFirst = (nNextResend == 0);
1020 nNextResend = GetTime() + GetRand(30 * 60);
1024 // Only do it if there's been a new block since last time
1025 if (nTimeBestReceived < nLastResend)
1027 nLastResend = GetTime();
1029 // Rebroadcast any of our txes that aren't in a block yet
1030 LogPrintf("ResendWalletTransactions()\n");
1033 // Sort them in chronological order
1034 multimap<unsigned int, CWalletTx*> mapSorted;
1035 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1037 CWalletTx& wtx = item.second;
1038 // Don't rebroadcast until it's had plenty of time that
1039 // it should have gotten in already by now.
1040 if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1041 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1043 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1045 CWalletTx& wtx = *item.second;
1046 wtx.RelayWalletTransaction();
1051 /** @} */ // end of mapWallet
1056 /** @defgroup Actions
1062 CAmount CWallet::GetBalance() const
1066 LOCK2(cs_main, cs_wallet);
1067 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1069 const CWalletTx* pcoin = &(*it).second;
1070 if (pcoin->IsTrusted())
1071 nTotal += pcoin->GetAvailableCredit();
1078 CAmount CWallet::GetUnconfirmedBalance() const
1082 LOCK2(cs_main, cs_wallet);
1083 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1085 const CWalletTx* pcoin = &(*it).second;
1086 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1087 nTotal += pcoin->GetAvailableCredit();
1093 CAmount CWallet::GetImmatureBalance() const
1097 LOCK2(cs_main, cs_wallet);
1098 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1100 const CWalletTx* pcoin = &(*it).second;
1101 nTotal += pcoin->GetImmatureCredit();
1107 CAmount CWallet::GetWatchOnlyBalance() const
1111 LOCK2(cs_main, cs_wallet);
1112 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1114 const CWalletTx* pcoin = &(*it).second;
1115 if (pcoin->IsTrusted())
1116 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1123 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1127 LOCK2(cs_main, cs_wallet);
1128 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1130 const CWalletTx* pcoin = &(*it).second;
1131 if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1132 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1138 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1142 LOCK2(cs_main, cs_wallet);
1143 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1145 const CWalletTx* pcoin = &(*it).second;
1146 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1153 * populate vCoins with vector of available COutputs.
1155 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1160 LOCK2(cs_main, cs_wallet);
1161 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1163 const uint256& wtxid = it->first;
1164 const CWalletTx* pcoin = &(*it).second;
1166 if (!IsFinalTx(*pcoin))
1169 if (fOnlyConfirmed && !pcoin->IsTrusted())
1172 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1175 int nDepth = pcoin->GetDepthInMainChain();
1179 for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1180 isminetype mine = IsMine(pcoin->vout[i]);
1181 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1182 !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 &&
1183 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1184 vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
1190 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1191 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1193 vector<char> vfIncluded;
1195 vfBest.assign(vValue.size(), true);
1196 nBest = nTotalLower;
1198 seed_insecure_rand();
1200 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1202 vfIncluded.assign(vValue.size(), false);
1204 bool fReachedTarget = false;
1205 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1207 for (unsigned int i = 0; i < vValue.size(); i++)
1209 //The solver here uses a randomized algorithm,
1210 //the randomness serves no real security purpose but is just
1211 //needed to prevent degenerate behavior and it is important
1212 //that the rng is fast. We do not use a constant random sequence,
1213 //because there may be some privacy improvement by making
1214 //the selection random.
1215 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1217 nTotal += vValue[i].first;
1218 vfIncluded[i] = true;
1219 if (nTotal >= nTargetValue)
1221 fReachedTarget = true;
1225 vfBest = vfIncluded;
1227 nTotal -= vValue[i].first;
1228 vfIncluded[i] = false;
1236 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1237 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1239 setCoinsRet.clear();
1242 // List of values less than target
1243 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1244 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1245 coinLowestLarger.second.first = NULL;
1246 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1247 CAmount nTotalLower = 0;
1249 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1251 BOOST_FOREACH(const COutput &output, vCoins)
1253 if (!output.fSpendable)
1256 const CWalletTx *pcoin = output.tx;
1258 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1262 CAmount n = pcoin->vout[i].nValue;
1264 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1266 if (n == nTargetValue)
1268 setCoinsRet.insert(coin.second);
1269 nValueRet += coin.first;
1272 else if (n < nTargetValue + CENT)
1274 vValue.push_back(coin);
1277 else if (n < coinLowestLarger.first)
1279 coinLowestLarger = coin;
1283 if (nTotalLower == nTargetValue)
1285 for (unsigned int i = 0; i < vValue.size(); ++i)
1287 setCoinsRet.insert(vValue[i].second);
1288 nValueRet += vValue[i].first;
1293 if (nTotalLower < nTargetValue)
1295 if (coinLowestLarger.second.first == NULL)
1297 setCoinsRet.insert(coinLowestLarger.second);
1298 nValueRet += coinLowestLarger.first;
1302 // Solve subset sum by stochastic approximation
1303 sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1304 vector<char> vfBest;
1307 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1308 if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1309 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1311 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1312 // or the next bigger coin is closer), return the bigger coin
1313 if (coinLowestLarger.second.first &&
1314 ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1316 setCoinsRet.insert(coinLowestLarger.second);
1317 nValueRet += coinLowestLarger.first;
1320 for (unsigned int i = 0; i < vValue.size(); i++)
1323 setCoinsRet.insert(vValue[i].second);
1324 nValueRet += vValue[i].first;
1327 LogPrint("selectcoins", "SelectCoins() best subset: ");
1328 for (unsigned int i = 0; i < vValue.size(); i++)
1330 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1331 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
1337 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
1339 vector<COutput> vCoins;
1340 AvailableCoins(vCoins, true, coinControl);
1342 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1343 if (coinControl && coinControl->HasSelected())
1345 BOOST_FOREACH(const COutput& out, vCoins)
1349 nValueRet += out.tx->vout[out.i].nValue;
1350 setCoinsRet.insert(make_pair(out.tx, out.i));
1352 return (nValueRet >= nTargetValue);
1355 return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1356 SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1357 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
1363 bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
1364 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1367 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1371 strFailReason = _("Transaction amounts must be positive");
1376 if (vecSend.empty() || nValue < 0)
1378 strFailReason = _("Transaction amounts must be positive");
1382 wtxNew.fTimeReceivedIsTxTime = true;
1383 wtxNew.BindWallet(this);
1384 CMutableTransaction txNew;
1386 // Discourage fee sniping.
1388 // However because of a off-by-one-error in previous versions we need to
1389 // neuter it by setting nLockTime to at least one less than nBestHeight.
1390 // Secondly currently propagation of transactions created for block heights
1391 // corresponding to blocks that were just mined may be iffy - transactions
1392 // aren't re-accepted into the mempool - we additionally neuter the code by
1393 // going ten blocks back. Doesn't yet do anything for sniping, but does act
1394 // to shake out wallet bugs like not showing nLockTime'd transactions at
1396 txNew.nLockTime = std::max(0, chainActive.Height() - 10);
1398 // Secondly occasionally randomly pick a nLockTime even further back, so
1399 // that transactions that are delayed after signing for whatever reason,
1400 // e.g. high-latency mix networks and some CoinJoin implementations, have
1402 if (GetRandInt(10) == 0)
1403 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
1405 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
1406 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
1409 LOCK2(cs_main, cs_wallet);
1416 wtxNew.fFromMe = true;
1418 CAmount nTotalValue = nValue + nFeeRet;
1419 double dPriority = 0;
1420 // vouts to the payees
1421 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1423 CTxOut txout(s.second, s.first);
1424 if (txout.IsDust(::minRelayTxFee))
1426 strFailReason = _("Transaction amount too small");
1429 txNew.vout.push_back(txout);
1432 // Choose coins to use
1433 set<pair<const CWalletTx*,unsigned int> > setCoins;
1434 CAmount nValueIn = 0;
1435 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1437 strFailReason = _("Insufficient funds");
1440 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1442 CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
1443 //The priority after the next block (depth+1) is used instead of the current,
1444 //reflecting an assumption the user would accept a bit more delay for
1445 //a chance at a free transaction.
1446 dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);
1449 CAmount nChange = nValueIn - nValue - nFeeRet;
1453 // Fill a vout to ourself
1454 // TODO: pass in scriptChange instead of reservekey so
1455 // change transaction isn't always pay-to-bitcoin-address
1456 CScript scriptChange;
1458 // coin control: send change to custom address
1459 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1460 scriptChange = GetScriptForDestination(coinControl->destChange);
1462 // no coin control: send change to newly generated address
1465 // Note: We use a new key here to keep it from being obvious which side is the change.
1466 // The drawback is that by not reusing a previous key, the change may be lost if a
1467 // backup is restored, if the backup doesn't have the new private key for the change.
1468 // If we reused the old key, it would be possible to add code to look for and
1469 // rediscover unknown transactions that were written with keys of ours to recover
1470 // post-backup change.
1472 // Reserve a new key pair from key pool
1475 ret = reservekey.GetReservedKey(vchPubKey);
1476 assert(ret); // should never fail, as we just unlocked
1478 scriptChange = GetScriptForDestination(vchPubKey.GetID());
1481 CTxOut newTxOut(nChange, scriptChange);
1483 // Never create dust outputs; if we would, just
1484 // add the dust to the fee.
1485 if (newTxOut.IsDust(::minRelayTxFee))
1488 reservekey.ReturnKey();
1492 // Insert change txn at random position:
1493 vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1);
1494 txNew.vout.insert(position, newTxOut);
1498 reservekey.ReturnKey();
1502 // Note how the sequence number is set to max()-1 so that the
1503 // nLockTime set above actually works.
1504 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1505 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
1506 std::numeric_limits<unsigned int>::max()-1));
1510 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1511 if (!SignSignature(*this, *coin.first, txNew, nIn++))
1513 strFailReason = _("Signing transaction failed");
1517 // Embed the constructed transaction data in wtxNew.
1518 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
1521 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1522 if (nBytes >= MAX_STANDARD_TX_SIZE)
1524 strFailReason = _("Transaction too large");
1527 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
1529 // Can we complete this as a free transaction?
1530 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
1532 // Not enough fee: enough priority?
1533 double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1534 // Not enough mempool history to estimate: use hard-coded AllowFree.
1535 if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1538 // Small enough, and priority high enough, to send for free
1539 if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
1543 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
1545 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
1546 // because we must be at the maximum allowed fee.
1547 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
1549 strFailReason = _("Transaction too large for fee policy");
1553 if (nFeeRet >= nFeeNeeded)
1554 break; // Done, enough fee included.
1556 // Include more fee and try again.
1557 nFeeRet = nFeeNeeded;
1565 bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
1566 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1568 vector< pair<CScript, CAmount> > vecSend;
1569 vecSend.push_back(make_pair(scriptPubKey, nValue));
1570 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);
1574 * Call after CreateTransaction unless you want to abort
1576 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1579 LOCK2(cs_main, cs_wallet);
1580 LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
1582 // This is only to keep the database open to defeat the auto-flush for the
1583 // duration of this scope. This is the only place where this optimization
1584 // maybe makes sense; please don't do it anywhere else.
1585 CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1587 // Take key pair from key pool so it won't be used again
1588 reservekey.KeepKey();
1590 // Add tx to wallet, because if it has change it's also ours,
1591 // otherwise just for transaction history.
1592 AddToWallet(wtxNew);
1594 // Notify that old coins are spent
1595 set<CWalletTx*> setCoins;
1596 BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1598 CWalletTx &coin = mapWallet[txin.prevout.hash];
1599 coin.BindWallet(this);
1600 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1607 // Track how many getdata requests our transaction gets
1608 mapRequestCount[wtxNew.GetHash()] = 0;
1611 if (!wtxNew.AcceptToMemoryPool(false))
1613 // This must not fail. The transaction has already been signed and recorded.
1614 LogPrintf("CommitTransaction() : Error: Transaction not valid");
1617 wtxNew.RelayWalletTransaction();
1622 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
1624 // payTxFee is user-set "I want to pay this much"
1625 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
1626 // user selected total at least (default=true)
1627 if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
1628 nFeeNeeded = payTxFee.GetFeePerK();
1629 // User didn't set: use -txconfirmtarget to estimate...
1630 if (nFeeNeeded == 0)
1631 nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
1632 // ... unless we don't have enough mempool data, in which case fall
1633 // back to a hard-coded fee
1634 if (nFeeNeeded == 0)
1635 nFeeNeeded = minTxFee.GetFee(nTxBytes);
1636 // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
1637 if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
1638 nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
1639 // But always obey the maximum
1640 if (nFeeNeeded > maxTxFee)
1641 nFeeNeeded = maxTxFee;
1648 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1652 fFirstRunRet = false;
1653 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1654 if (nLoadWalletRet == DB_NEED_REWRITE)
1656 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1660 // Note: can't top-up keypool here, because wallet is locked.
1661 // User will be prompted to unlock wallet the next operation
1662 // the requires a new key.
1666 if (nLoadWalletRet != DB_LOAD_OK)
1667 return nLoadWalletRet;
1668 fFirstRunRet = !vchDefaultKey.IsValid();
1670 uiInterface.LoadWallet(this);
1676 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
1680 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
1681 if (nZapWalletTxRet == DB_NEED_REWRITE)
1683 if (CDB::Rewrite(strWalletFile, "\x04pool"))
1687 // Note: can't top-up keypool here, because wallet is locked.
1688 // User will be prompted to unlock wallet the next operation
1689 // that requires a new key.
1693 if (nZapWalletTxRet != DB_LOAD_OK)
1694 return nZapWalletTxRet;
1700 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
1702 bool fUpdated = false;
1704 LOCK(cs_wallet); // mapAddressBook
1705 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
1706 fUpdated = mi != mapAddressBook.end();
1707 mapAddressBook[address].name = strName;
1708 if (!strPurpose.empty()) /* update purpose only if requested */
1709 mapAddressBook[address].purpose = strPurpose;
1711 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
1712 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
1715 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
1717 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1720 bool CWallet::DelAddressBook(const CTxDestination& address)
1723 LOCK(cs_wallet); // mapAddressBook
1727 // Delete destdata tuples associated with address
1728 std::string strAddress = CBitcoinAddress(address).ToString();
1729 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
1731 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
1734 mapAddressBook.erase(address);
1737 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
1741 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
1742 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1745 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1749 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1752 vchDefaultKey = vchPubKey;
1757 * Mark old keypool keys as used,
1758 * and generate all new keys
1760 bool CWallet::NewKeyPool()
1764 CWalletDB walletdb(strWalletFile);
1765 BOOST_FOREACH(int64_t nIndex, setKeyPool)
1766 walletdb.ErasePool(nIndex);
1772 int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
1773 for (int i = 0; i < nKeys; i++)
1775 int64_t nIndex = i+1;
1776 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1777 setKeyPool.insert(nIndex);
1779 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
1784 bool CWallet::TopUpKeyPool(unsigned int kpSize)
1792 CWalletDB walletdb(strWalletFile);
1795 unsigned int nTargetSize;
1797 nTargetSize = kpSize;
1799 nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
1801 while (setKeyPool.size() < (nTargetSize + 1))
1804 if (!setKeyPool.empty())
1805 nEnd = *(--setKeyPool.end()) + 1;
1806 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1807 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1808 setKeyPool.insert(nEnd);
1809 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
1815 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
1818 keypool.vchPubKey = CPubKey();
1825 // Get the oldest key
1826 if(setKeyPool.empty())
1829 CWalletDB walletdb(strWalletFile);
1831 nIndex = *(setKeyPool.begin());
1832 setKeyPool.erase(setKeyPool.begin());
1833 if (!walletdb.ReadPool(nIndex, keypool))
1834 throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1835 if (!HaveKey(keypool.vchPubKey.GetID()))
1836 throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1837 assert(keypool.vchPubKey.IsValid());
1838 LogPrintf("keypool reserve %d\n", nIndex);
1842 void CWallet::KeepKey(int64_t nIndex)
1844 // Remove from key pool
1847 CWalletDB walletdb(strWalletFile);
1848 walletdb.ErasePool(nIndex);
1850 LogPrintf("keypool keep %d\n", nIndex);
1853 void CWallet::ReturnKey(int64_t nIndex)
1855 // Return to key pool
1858 setKeyPool.insert(nIndex);
1860 LogPrintf("keypool return %d\n", nIndex);
1863 bool CWallet::GetKeyFromPool(CPubKey& result)
1869 ReserveKeyFromKeyPool(nIndex, keypool);
1872 if (IsLocked()) return false;
1873 result = GenerateNewKey();
1877 result = keypool.vchPubKey;
1882 int64_t CWallet::GetOldestKeyPoolTime()
1886 ReserveKeyFromKeyPool(nIndex, keypool);
1890 return keypool.nTime;
1893 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
1895 map<CTxDestination, CAmount> balances;
1899 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1901 CWalletTx *pcoin = &walletEntry.second;
1903 if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
1906 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1909 int nDepth = pcoin->GetDepthInMainChain();
1910 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
1913 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1915 CTxDestination addr;
1916 if (!IsMine(pcoin->vout[i]))
1918 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1921 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
1923 if (!balances.count(addr))
1925 balances[addr] += n;
1933 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1935 AssertLockHeld(cs_wallet); // mapWallet
1936 set< set<CTxDestination> > groupings;
1937 set<CTxDestination> grouping;
1939 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1941 CWalletTx *pcoin = &walletEntry.second;
1943 if (pcoin->vin.size() > 0)
1945 bool any_mine = false;
1946 // group all input addresses with each other
1947 BOOST_FOREACH(CTxIn txin, pcoin->vin)
1949 CTxDestination address;
1950 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
1952 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1954 grouping.insert(address);
1958 // group change with input addresses
1961 BOOST_FOREACH(CTxOut txout, pcoin->vout)
1962 if (IsChange(txout))
1964 CTxDestination txoutAddr;
1965 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1967 grouping.insert(txoutAddr);
1970 if (grouping.size() > 0)
1972 groupings.insert(grouping);
1977 // group lone addrs by themselves
1978 for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1979 if (IsMine(pcoin->vout[i]))
1981 CTxDestination address;
1982 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1984 grouping.insert(address);
1985 groupings.insert(grouping);
1990 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1991 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
1992 BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1994 // make a set of all the groups hit by this new group
1995 set< set<CTxDestination>* > hits;
1996 map< CTxDestination, set<CTxDestination>* >::iterator it;
1997 BOOST_FOREACH(CTxDestination address, grouping)
1998 if ((it = setmap.find(address)) != setmap.end())
1999 hits.insert((*it).second);
2001 // merge all hit groups into a new single group and delete old groups
2002 set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2003 BOOST_FOREACH(set<CTxDestination>* hit, hits)
2005 merged->insert(hit->begin(), hit->end());
2006 uniqueGroupings.erase(hit);
2009 uniqueGroupings.insert(merged);
2012 BOOST_FOREACH(CTxDestination element, *merged)
2013 setmap[element] = merged;
2016 set< set<CTxDestination> > ret;
2017 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2019 ret.insert(*uniqueGrouping);
2020 delete uniqueGrouping;
2026 set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2029 set<CTxDestination> result;
2030 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2032 const CTxDestination& address = item.first;
2033 const string& strName = item.second.name;
2034 if (strName == strAccount)
2035 result.insert(address);
2040 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
2045 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2047 vchPubKey = keypool.vchPubKey;
2052 assert(vchPubKey.IsValid());
2057 void CReserveKey::KeepKey()
2060 pwallet->KeepKey(nIndex);
2062 vchPubKey = CPubKey();
2065 void CReserveKey::ReturnKey()
2068 pwallet->ReturnKey(nIndex);
2070 vchPubKey = CPubKey();
2073 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2077 CWalletDB walletdb(strWalletFile);
2079 LOCK2(cs_main, cs_wallet);
2080 BOOST_FOREACH(const int64_t& id, setKeyPool)
2083 if (!walletdb.ReadPool(id, keypool))
2084 throw runtime_error("GetAllReserveKeyHashes() : read failed");
2085 assert(keypool.vchPubKey.IsValid());
2086 CKeyID keyID = keypool.vchPubKey.GetID();
2087 if (!HaveKey(keyID))
2088 throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2089 setAddress.insert(keyID);
2093 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2097 // Only notify UI if this transaction is in this wallet
2098 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2099 if (mi != mapWallet.end())
2100 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2104 void CWallet::LockCoin(COutPoint& output)
2106 AssertLockHeld(cs_wallet); // setLockedCoins
2107 setLockedCoins.insert(output);
2110 void CWallet::UnlockCoin(COutPoint& output)
2112 AssertLockHeld(cs_wallet); // setLockedCoins
2113 setLockedCoins.erase(output);
2116 void CWallet::UnlockAllCoins()
2118 AssertLockHeld(cs_wallet); // setLockedCoins
2119 setLockedCoins.clear();
2122 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2124 AssertLockHeld(cs_wallet); // setLockedCoins
2125 COutPoint outpt(hash, n);
2127 return (setLockedCoins.count(outpt) > 0);
2130 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2132 AssertLockHeld(cs_wallet); // setLockedCoins
2133 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2134 it != setLockedCoins.end(); it++) {
2135 COutPoint outpt = (*it);
2136 vOutpts.push_back(outpt);
2140 /** @} */ // end of Actions
2142 class CAffectedKeysVisitor : public boost::static_visitor<void> {
2144 const CKeyStore &keystore;
2145 std::vector<CKeyID> &vKeys;
2148 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2150 void Process(const CScript &script) {
2152 std::vector<CTxDestination> vDest;
2154 if (ExtractDestinations(script, type, vDest, nRequired)) {
2155 BOOST_FOREACH(const CTxDestination &dest, vDest)
2156 boost::apply_visitor(*this, dest);
2160 void operator()(const CKeyID &keyId) {
2161 if (keystore.HaveKey(keyId))
2162 vKeys.push_back(keyId);
2165 void operator()(const CScriptID &scriptId) {
2167 if (keystore.GetCScript(scriptId, script))
2171 void operator()(const CNoDestination &none) {}
2174 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2175 AssertLockHeld(cs_wallet); // mapKeyMetadata
2176 mapKeyBirth.clear();
2178 // get birth times for keys with metadata
2179 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2180 if (it->second.nCreateTime)
2181 mapKeyBirth[it->first] = it->second.nCreateTime;
2183 // map in which we'll infer heights of other keys
2184 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
2185 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2186 std::set<CKeyID> setKeys;
2188 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2189 if (mapKeyBirth.count(keyid) == 0)
2190 mapKeyFirstBlock[keyid] = pindexMax;
2194 // if there are no such keys, we're done
2195 if (mapKeyFirstBlock.empty())
2198 // find first block that affects those keys, if there are any left
2199 std::vector<CKeyID> vAffected;
2200 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2201 // iterate over all wallet transactions...
2202 const CWalletTx &wtx = (*it).second;
2203 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2204 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
2205 // ... which are already in a block
2206 int nHeight = blit->second->nHeight;
2207 BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2208 // iterate over all their outputs
2209 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
2210 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2211 // ... and all their affected keys
2212 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2213 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2214 rit->second = blit->second;
2221 // Extract block timestamps for those keys
2222 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2223 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
2226 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2228 if (boost::get<CNoDestination>(&dest))
2231 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2234 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2237 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2239 if (!mapAddressBook[dest].destdata.erase(key))
2243 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2246 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2248 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2252 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2254 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2255 if(i != mapAddressBook.end())
2257 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2258 if(j != i->second.destdata.end())
2268 CKeyPool::CKeyPool()
2273 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2276 vchPubKey = vchPubKeyIn;
2279 CWalletKey::CWalletKey(int64_t nExpires)
2281 nTimeCreated = (nExpires ? GetTime() : 0);
2282 nTimeExpires = nExpires;
2285 int CMerkleTx::SetMerkleBranch(const CBlock& block)
2287 AssertLockHeld(cs_main);
2290 // Update the tx's hashBlock
2291 hashBlock = block.GetHash();
2293 // Locate the transaction
2294 for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2295 if (block.vtx[nIndex] == *(CTransaction*)this)
2297 if (nIndex == (int)block.vtx.size())
2299 vMerkleBranch.clear();
2301 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
2305 // Fill in merkle branch
2306 vMerkleBranch = block.GetMerkleBranch(nIndex);
2308 // Is the tx in a block that's in the main chain
2309 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2310 if (mi == mapBlockIndex.end())
2312 const CBlockIndex* pindex = (*mi).second;
2313 if (!pindex || !chainActive.Contains(pindex))
2316 return chainActive.Height() - pindex->nHeight + 1;
2319 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
2321 if (hashBlock == 0 || nIndex == -1)
2323 AssertLockHeld(cs_main);
2325 // Find the block it claims to be in
2326 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2327 if (mi == mapBlockIndex.end())
2329 CBlockIndex* pindex = (*mi).second;
2330 if (!pindex || !chainActive.Contains(pindex))
2333 // Make sure the merkle branch connects to this block
2334 if (!fMerkleVerified)
2336 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2338 fMerkleVerified = true;
2342 return chainActive.Height() - pindex->nHeight + 1;
2345 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
2347 AssertLockHeld(cs_main);
2348 int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2349 if (nResult == 0 && !mempool.exists(GetHash()))
2350 return -1; // Not in chain, not in mempool
2355 int CMerkleTx::GetBlocksToMaturity() const
2359 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2363 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee)
2365 CValidationState state;
2366 return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee);