1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
12 #include "ui_interface.h"
13 #include "checkqueue.h"
14 #include "chainparams.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 nBestInvalidWork = 0;
37 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
38 int64 nTimeBestReceived = 0;
39 int nScriptCheckThreads = 0;
40 bool fImporting = false;
41 bool fReindex = false;
42 bool fBenchmark = false;
43 bool fTxIndex = false;
44 unsigned int nCoinCacheSize = 5000;
45 bool fHaveGUI = false;
47 /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
48 int64 CTransaction::nMinTxFee = 10000; // Override with -mintxfee
49 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
50 int64 CTransaction::nMinRelayTxFee = 10000;
52 CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
54 map<uint256, CBlock*> mapOrphanBlocks;
55 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
57 map<uint256, CTransaction> mapOrphanTransactions;
58 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
60 // Constant stuff for coinbase transactions we create:
61 CScript COINBASE_FLAGS;
63 const string strMessageMagic = "Bitcoin Signed Message:\n";
66 int64 nTransactionFee = 0;
70 //////////////////////////////////////////////////////////////////////////////
72 // dispatching functions
75 // These functions dispatch to one or all registered wallets
79 // Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found in.
80 boost::signals2::signal<void (const uint256 &, const CTransaction &, const CBlock *)> SyncTransaction;
81 // Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
82 boost::signals2::signal<void (const uint256 &)> EraseTransaction;
83 // Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
84 boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
85 // Notifies listeners of a new active block chain.
86 boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
87 // Notifies listeners about an inventory item being seen on the network.
88 boost::signals2::signal<void (const uint256 &)> Inventory;
89 // Tells listeners to broadcast their data.
90 boost::signals2::signal<void ()> Broadcast;
94 void RegisterWallet(CWalletInterface* pwalletIn) {
95 g_signals.SyncTransaction.connect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
96 g_signals.EraseTransaction.connect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
97 g_signals.UpdatedTransaction.connect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
98 g_signals.SetBestChain.connect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
99 g_signals.Inventory.connect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
100 g_signals.Broadcast.connect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
103 void UnregisterWallet(CWalletInterface* pwalletIn) {
104 g_signals.Broadcast.disconnect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
105 g_signals.Inventory.disconnect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
106 g_signals.SetBestChain.disconnect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
107 g_signals.UpdatedTransaction.disconnect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
108 g_signals.EraseTransaction.disconnect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
109 g_signals.SyncTransaction.disconnect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
112 void UnregisterAllWallets() {
113 g_signals.Broadcast.disconnect_all_slots();
114 g_signals.Inventory.disconnect_all_slots();
115 g_signals.SetBestChain.disconnect_all_slots();
116 g_signals.UpdatedTransaction.disconnect_all_slots();
117 g_signals.EraseTransaction.disconnect_all_slots();
118 g_signals.SyncTransaction.disconnect_all_slots();
121 void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) {
122 g_signals.SyncTransaction(hash, tx, pblock);
125 //////////////////////////////////////////////////////////////////////////////
127 // Registration of network node signals.
130 int static GetHeight()
133 return chainActive.Height();
136 void RegisterNodeSignals(CNodeSignals& nodeSignals)
138 nodeSignals.GetHeight.connect(&GetHeight);
139 nodeSignals.ProcessMessages.connect(&ProcessMessages);
140 nodeSignals.SendMessages.connect(&SendMessages);
143 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
145 nodeSignals.GetHeight.disconnect(&GetHeight);
146 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
147 nodeSignals.SendMessages.disconnect(&SendMessages);
150 //////////////////////////////////////////////////////////////////////////////
152 // CChain implementation
155 CBlockIndex *CChain::SetTip(CBlockIndex *pindex) {
156 if (pindex == NULL) {
160 vChain.resize(pindex->nHeight + 1);
161 while (pindex && vChain[pindex->nHeight] != pindex) {
162 vChain[pindex->nHeight] = pindex;
163 pindex = pindex->pprev;
168 CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
170 std::vector<uint256> vHave;
176 vHave.push_back(pindex->GetBlockHash());
177 // Stop when we have added the genesis block.
178 if (pindex->nHeight == 0)
180 // Exponentially larger steps back, plus the genesis block.
181 int nHeight = std::max(pindex->nHeight - nStep, 0);
182 // In case pindex is not in this chain, iterate pindex->pprev to find blocks.
183 while (pindex->nHeight > nHeight && !Contains(pindex))
184 pindex = pindex->pprev;
185 // If pindex is in this chain, use direct height-based access.
186 if (pindex->nHeight > nHeight)
187 pindex = (*this)[nHeight];
188 if (vHave.size() > 10)
192 return CBlockLocator(vHave);
195 CBlockIndex *CChain::FindFork(const CBlockLocator &locator) const {
196 // Find the first block the caller has in the main chain
197 BOOST_FOREACH(const uint256& hash, locator.vHave) {
198 std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
199 if (mi != mapBlockIndex.end())
201 CBlockIndex* pindex = (*mi).second;
202 if (Contains(pindex))
209 //////////////////////////////////////////////////////////////////////////////
211 // CCoinsView implementations
214 bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
215 bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
216 bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
217 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
218 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
219 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
220 bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
223 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
224 bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
225 bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
226 bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
227 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
228 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
229 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
230 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
231 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
233 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
235 bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
236 if (cacheCoins.count(txid)) {
237 coins = cacheCoins[txid];
240 if (base->GetCoins(txid, coins)) {
241 cacheCoins[txid] = coins;
247 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
248 std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
249 if (it != cacheCoins.end() && it->first == txid)
252 if (!base->GetCoins(txid,tmp))
253 return cacheCoins.end();
254 std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
255 tmp.swap(ret->second);
259 CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) {
260 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
261 assert(it != cacheCoins.end());
265 bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
266 cacheCoins[txid] = coins;
270 bool CCoinsViewCache::HaveCoins(const uint256 &txid) {
271 return FetchCoins(txid) != cacheCoins.end();
274 CBlockIndex *CCoinsViewCache::GetBestBlock() {
275 if (pindexTip == NULL)
276 pindexTip = base->GetBestBlock();
280 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
285 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
286 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
287 cacheCoins[it->first] = it->second;
292 bool CCoinsViewCache::Flush() {
293 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
299 unsigned int CCoinsViewCache::GetCacheSize() {
300 return cacheCoins.size();
303 /** CCoinsView that brings transactions from a memorypool into view.
304 It does not check for spendings by memory pool transactions. */
305 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
307 bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
308 if (base->GetCoins(txid, coins))
310 if (mempool.exists(txid)) {
311 const CTransaction &tx = mempool.lookup(txid);
312 coins = CCoins(tx, MEMPOOL_HEIGHT);
318 bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) {
319 return mempool.exists(txid) || base->HaveCoins(txid);
322 CCoinsViewCache *pcoinsTip = NULL;
323 CBlockTreeDB *pblocktree = NULL;
325 //////////////////////////////////////////////////////////////////////////////
327 // mapOrphanTransactions
330 bool AddOrphanTx(const CTransaction& tx)
332 uint256 hash = tx.GetHash();
333 if (mapOrphanTransactions.count(hash))
336 // Ignore big transactions, to avoid a
337 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
338 // large transaction with a missing parent then we assume
339 // it will rebroadcast it later, after the parent transaction(s)
340 // have been mined or received.
341 // 10,000 orphans, each of which is at most 5,000 bytes big is
342 // at most 500 megabytes of orphans:
343 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
346 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
350 mapOrphanTransactions[hash] = tx;
351 BOOST_FOREACH(const CTxIn& txin, tx.vin)
352 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
354 LogPrint("mempool", "stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
355 mapOrphanTransactions.size());
359 void static EraseOrphanTx(uint256 hash)
361 if (!mapOrphanTransactions.count(hash))
363 const CTransaction& tx = mapOrphanTransactions[hash];
364 BOOST_FOREACH(const CTxIn& txin, tx.vin)
366 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
367 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
368 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
370 mapOrphanTransactions.erase(hash);
373 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
375 unsigned int nEvicted = 0;
376 while (mapOrphanTransactions.size() > nMaxOrphans)
378 // Evict a random orphan:
379 uint256 randomhash = GetRandHash();
380 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
381 if (it == mapOrphanTransactions.end())
382 it = mapOrphanTransactions.begin();
383 EraseOrphanTx(it->first);
395 bool IsStandardTx(const CTransaction& tx, string& reason)
397 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
402 if (!IsFinalTx(tx)) {
403 reason = "non-final";
407 // Extremely large transactions with lots of inputs can cost the network
408 // almost as much to process as they cost the sender in fees, because
409 // computing signature hashes is O(ninputs*txsize). Limiting transactions
410 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
411 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
412 if (sz >= MAX_STANDARD_TX_SIZE) {
417 BOOST_FOREACH(const CTxIn& txin, tx.vin)
419 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
420 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
421 // ~65-byte public keys, plus a few script ops.
422 if (txin.scriptSig.size() > 500) {
423 reason = "scriptsig-size";
426 if (!txin.scriptSig.IsPushOnly()) {
427 reason = "scriptsig-not-pushonly";
432 unsigned int nDataOut = 0;
433 txnouttype whichType;
434 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
435 if (!::IsStandard(txout.scriptPubKey, whichType)) {
436 reason = "scriptpubkey";
439 if (whichType == TX_NULL_DATA)
441 else if (txout.IsDust(CTransaction::nMinRelayTxFee)) {
447 // only one OP_RETURN txout is permitted
449 reason = "mucho-data";
456 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64 nBlockTime)
458 // Time based nLockTime implemented in 0.1.6
459 if (tx.nLockTime == 0)
461 if (nBlockHeight == 0)
462 nBlockHeight = chainActive.Height();
464 nBlockTime = GetAdjustedTime();
465 if ((int64)tx.nLockTime < ((int64)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
467 BOOST_FOREACH(const CTxIn& txin, tx.vin)
473 /** Amount of bitcoins spent by the transaction.
474 @return sum of all outputs (note: does not include fees)
476 int64 GetValueOut(const CTransaction& tx)
479 BOOST_FOREACH(const CTxOut& txout, tx.vout)
481 nValueOut += txout.nValue;
482 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
483 throw std::runtime_error("GetValueOut() : value out of range");
489 // Check transaction inputs, and make sure any
490 // pay-to-script-hash transactions are evaluating IsStandard scripts
492 // Why bother? To avoid denial-of-service attacks; an attacker
493 // can submit a standard HASH... OP_EQUAL transaction,
494 // which will get accepted into blocks. The redemption
495 // script can be anything; an attacker could use a very
496 // expensive-to-check-upon-redemption script like:
497 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
499 bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs)
502 return true; // Coinbases don't use vin normally
504 for (unsigned int i = 0; i < tx.vin.size(); i++)
506 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
508 vector<vector<unsigned char> > vSolutions;
509 txnouttype whichType;
510 // get the scriptPubKey corresponding to this input:
511 const CScript& prevScript = prev.scriptPubKey;
512 if (!Solver(prevScript, whichType, vSolutions))
514 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
515 if (nArgsExpected < 0)
518 // Transactions with extra stuff in their scriptSigs are
519 // non-standard. Note that this EvalScript() call will
520 // be quick, because if there are any operations
521 // beside "push data" in the scriptSig the
522 // IsStandard() call returns false
523 vector<vector<unsigned char> > stack;
524 if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0))
527 if (whichType == TX_SCRIPTHASH)
531 CScript subscript(stack.back().begin(), stack.back().end());
532 vector<vector<unsigned char> > vSolutions2;
533 txnouttype whichType2;
534 if (!Solver(subscript, whichType2, vSolutions2))
536 if (whichType2 == TX_SCRIPTHASH)
540 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
543 nArgsExpected += tmpExpected;
546 if (stack.size() != (unsigned int)nArgsExpected)
553 unsigned int GetLegacySigOpCount(const CTransaction& tx)
555 unsigned int nSigOps = 0;
556 BOOST_FOREACH(const CTxIn& txin, tx.vin)
558 nSigOps += txin.scriptSig.GetSigOpCount(false);
560 BOOST_FOREACH(const CTxOut& txout, tx.vout)
562 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
567 unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& inputs)
572 unsigned int nSigOps = 0;
573 for (unsigned int i = 0; i < tx.vin.size(); i++)
575 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
576 if (prevout.scriptPubKey.IsPayToScriptHash())
577 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
582 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
586 if (pblock == NULL) {
588 if (pcoinsTip->GetCoins(GetHash(), coins)) {
589 CBlockIndex *pindex = chainActive[coins.nHeight];
591 if (!ReadBlockFromDisk(blockTmp, pindex))
599 // Update the tx's hashBlock
600 hashBlock = pblock->GetHash();
602 // Locate the transaction
603 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
604 if (pblock->vtx[nIndex] == *(CTransaction*)this)
606 if (nIndex == (int)pblock->vtx.size())
608 vMerkleBranch.clear();
610 LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
614 // Fill in merkle branch
615 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
618 // Is the tx in a block that's in the main chain
619 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
620 if (mi == mapBlockIndex.end())
622 CBlockIndex* pindex = (*mi).second;
623 if (!pindex || !chainActive.Contains(pindex))
626 return chainActive.Height() - pindex->nHeight + 1;
635 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
637 // Basic checks that don't depend on any context
639 return state.DoS(10, error("CheckTransaction() : vin empty"));
641 return state.DoS(10, error("CheckTransaction() : vout empty"));
643 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
644 return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
646 // Check for negative or overflow output values
648 BOOST_FOREACH(const CTxOut& txout, tx.vout)
650 if (txout.nValue < 0)
651 return state.DoS(100, error("CheckTransaction() : txout.nValue negative"));
652 if (txout.nValue > MAX_MONEY)
653 return state.DoS(100, error("CheckTransaction() : txout.nValue too high"));
654 nValueOut += txout.nValue;
655 if (!MoneyRange(nValueOut))
656 return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
659 // Check for duplicate inputs
660 set<COutPoint> vInOutPoints;
661 BOOST_FOREACH(const CTxIn& txin, tx.vin)
663 if (vInOutPoints.count(txin.prevout))
664 return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
665 vInOutPoints.insert(txin.prevout);
670 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
671 return state.DoS(100, error("CheckTransaction() : coinbase script size"));
675 BOOST_FOREACH(const CTxIn& txin, tx.vin)
676 if (txin.prevout.IsNull())
677 return state.DoS(10, error("CheckTransaction() : prevout is null"));
683 int64 GetMinFee(const CTransaction& tx, bool fAllowFree, enum GetMinFee_mode mode)
685 // Base fee is either nMinTxFee or nMinRelayTxFee
686 int64 nBaseFee = (mode == GMF_RELAY) ? tx.nMinRelayTxFee : tx.nMinTxFee;
688 unsigned int nBytes = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
689 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
693 // There is a free transaction area in blocks created by most miners,
694 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
695 // to be considered to fall into this category. We don't want to encourage sending
696 // multiple transactions instead of one big transaction to avoid fees.
697 // * If we are creating a transaction we allow transactions up to 1,000 bytes
698 // to be considered safe and assume they can likely make it into this section.
699 if (nBytes < (mode == GMF_SEND ? 1000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
703 // This code can be removed after enough miners have upgraded to version 0.9.
704 // Until then, be safe when sending and require a fee if any output
705 // is less than CENT:
706 if (nMinFee < nBaseFee && mode == GMF_SEND)
708 BOOST_FOREACH(const CTxOut& txout, tx.vout)
709 if (txout.nValue < CENT)
713 if (!MoneyRange(nMinFee))
718 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
722 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
724 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
725 while (it != mapNextTx.end() && it->first.hash == hashTx) {
726 coins.Spend(it->first.n); // and remove those outputs from coins
731 bool CTxMemPool::accept(CValidationState &state, const CTransaction &tx, bool fLimitFree,
732 bool* pfMissingInputs, bool fRejectInsaneFee)
735 *pfMissingInputs = false;
737 if (!CheckTransaction(tx, state))
738 return error("CTxMemPool::accept() : CheckTransaction failed");
740 // Coinbase is only valid in a block, not as a loose transaction
742 return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
744 // To help v0.1.5 clients who would see it as a negative number
745 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
746 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
748 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
750 if (Params().NetworkID() == CChainParams::MAIN && !IsStandardTx(tx, reason))
751 return error("CTxMemPool::accept() : nonstandard transaction: %s",
754 // is it already in the memory pool?
755 uint256 hash = tx.GetHash();
758 if (mapTx.count(hash))
762 // Check for conflicts with in-memory transactions
763 CTransaction* ptxOld = NULL;
764 for (unsigned int i = 0; i < tx.vin.size(); i++)
766 COutPoint outpoint = tx.vin[i].prevout;
767 if (mapNextTx.count(outpoint))
769 // Disable replacement feature for now
772 // Allow replacing with a newer version of the same transaction
775 ptxOld = mapNextTx[outpoint].ptx;
776 if (IsFinalTx(*ptxOld))
778 if (!tx.IsNewerThan(*ptxOld))
780 for (unsigned int i = 0; i < tx.vin.size(); i++)
782 COutPoint outpoint = tx.vin[i].prevout;
783 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
792 CCoinsViewCache view(dummy);
796 CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
797 view.SetBackend(viewMemPool);
799 // do we already have it?
800 if (view.HaveCoins(hash))
803 // do all inputs exist?
804 // Note that this does not check for the presence of actual outputs (see the next check for that),
805 // only helps filling in pfMissingInputs (to determine missing vs spent).
806 BOOST_FOREACH(const CTxIn txin, tx.vin) {
807 if (!view.HaveCoins(txin.prevout.hash)) {
809 *pfMissingInputs = true;
814 // are the actual inputs available?
815 if (!view.HaveInputs(tx))
816 return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
818 // Bring the best block into scope
821 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
822 view.SetBackend(dummy);
825 // Check for non-standard pay-to-script-hash in inputs
826 if (Params().NetworkID() == CChainParams::MAIN && !AreInputsStandard(tx, view))
827 return error("CTxMemPool::accept() : nonstandard transaction input");
829 // Note: if you modify this code to accept non-standard transactions, then
830 // you should add code here to check that the transaction does a
831 // reasonable number of ECDSA signature verifications.
833 int64 nFees = view.GetValueIn(tx)-GetValueOut(tx);
834 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
836 // Don't accept it if it can't get into a block
837 int64 txMinFee = GetMinFee(tx, true, GMF_RELAY);
838 if (fLimitFree && nFees < txMinFee)
839 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
840 hash.ToString().c_str(),
843 // Continuously rate-limit free transactions
844 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
845 // be annoying or make others' transactions take longer to confirm.
846 if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
848 static double dFreeCount;
849 static int64 nLastTime;
850 int64 nNow = GetTime();
854 // Use an exponentially decaying ~10-minute window:
855 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
857 // -limitfreerelay unit is thousand-bytes-per-minute
858 // At default rate it would take over a month to fill 1GB
859 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
860 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
862 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
866 if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 10000)
867 return error("CTxMemPool::accept() : insane fees %s, %"PRI64d" > %"PRI64d,
868 hash.ToString().c_str(),
869 nFees, CTransaction::nMinRelayTxFee * 10000);
871 // Check against previous transactions
872 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
873 if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
875 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str());
879 // Store transaction in memory
884 LogPrint("mempool", "CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
887 addUnchecked(hash, tx);
890 ///// are we sure this is ok when loading transactions or restoring block txes
891 // If updated, erase old tx from wallet
893 g_signals.EraseTransaction(ptxOld->GetHash());
894 g_signals.SyncTransaction(hash, tx, NULL);
896 LogPrint("mempool", "CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
897 hash.ToString().c_str(),
903 bool CTxMemPool::addUnchecked(const uint256& hash, const CTransaction &tx)
905 // Add to memory pool without checking anything. Don't call this directly,
906 // call CTxMemPool::accept to properly check the transaction first.
909 for (unsigned int i = 0; i < tx.vin.size(); i++)
910 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
911 nTransactionsUpdated++;
917 bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
919 // Remove transaction from memory pool
922 uint256 hash = tx.GetHash();
924 for (unsigned int i = 0; i < tx.vout.size(); i++) {
925 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
926 if (it != mapNextTx.end())
927 remove(*it->second.ptx, true);
930 if (mapTx.count(hash))
932 BOOST_FOREACH(const CTxIn& txin, tx.vin)
933 mapNextTx.erase(txin.prevout);
935 nTransactionsUpdated++;
941 bool CTxMemPool::removeConflicts(const CTransaction &tx)
943 // Remove transactions which depend on inputs of tx, recursively
945 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
946 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
947 if (it != mapNextTx.end()) {
948 const CTransaction &txConflict = *it->second.ptx;
949 if (txConflict != tx)
950 remove(txConflict, true);
956 void CTxMemPool::clear()
961 ++nTransactionsUpdated;
964 bool CTxMemPool::fChecks = false;
966 void CTxMemPool::check(CCoinsViewCache *pcoins) const
971 LogPrintf("Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
974 for (std::map<uint256, CTransaction>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
976 BOOST_FOREACH(const CTxIn &txin, it->second.vin) {
977 // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
978 std::map<uint256, CTransaction>::const_iterator it2 = mapTx.find(txin.prevout.hash);
979 if (it2 != mapTx.end()) {
980 assert(it2->second.vout.size() > txin.prevout.n && !it2->second.vout[txin.prevout.n].IsNull());
982 CCoins &coins = pcoins->GetCoins(txin.prevout.hash);
983 assert(coins.IsAvailable(txin.prevout.n));
985 // Check whether its inputs are marked in mapNextTx.
986 std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
987 assert(it3 != mapNextTx.end());
988 assert(it3->second.ptx == &it->second);
989 assert(it3->second.n == i);
993 for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
994 uint256 hash = it->second.ptx->GetHash();
995 std::map<uint256, CTransaction>::const_iterator it2 = mapTx.find(hash);
996 assert(it2 != mapTx.end());
997 assert(&it2->second == it->second.ptx);
998 assert(it2->second.vin.size() > it->second.n);
999 assert(it->first == it->second.ptx->vin[it->second.n].prevout);
1003 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
1008 vtxid.reserve(mapTx.size());
1009 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
1010 vtxid.push_back((*mi).first);
1016 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
1018 if (hashBlock == 0 || nIndex == -1)
1021 // Find the block it claims to be in
1022 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1023 if (mi == mapBlockIndex.end())
1025 CBlockIndex* pindex = (*mi).second;
1026 if (!pindex || !chainActive.Contains(pindex))
1029 // Make sure the merkle branch connects to this block
1030 if (!fMerkleVerified)
1032 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
1034 fMerkleVerified = true;
1038 return chainActive.Height() - pindex->nHeight + 1;
1042 int CMerkleTx::GetBlocksToMaturity() const
1046 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
1050 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree)
1052 CValidationState state;
1053 return mempool.accept(state, *this, fLimitFree, NULL);
1058 bool CWalletTx::AcceptWalletTransaction()
1062 // Add previous supporting transactions first
1063 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
1065 if (!tx.IsCoinBase())
1067 uint256 hash = tx.GetHash();
1068 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
1069 tx.AcceptToMemoryPool(false);
1072 return AcceptToMemoryPool(false);
1078 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
1079 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1081 CBlockIndex *pindexSlow = NULL;
1086 if (mempool.exists(hash))
1088 txOut = mempool.lookup(hash);
1095 if (pblocktree->ReadTxIndex(hash, postx)) {
1096 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1097 CBlockHeader header;
1100 fseek(file, postx.nTxOffset, SEEK_CUR);
1102 } catch (std::exception &e) {
1103 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1105 hashBlock = header.GetHash();
1106 if (txOut.GetHash() != hash)
1107 return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
1112 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1115 CCoinsViewCache &view = *pcoinsTip;
1117 if (view.GetCoins(hash, coins))
1118 nHeight = coins.nHeight;
1121 pindexSlow = chainActive[nHeight];
1127 if (ReadBlockFromDisk(block, pindexSlow)) {
1128 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1129 if (tx.GetHash() == hash) {
1131 hashBlock = pindexSlow->GetBlockHash();
1146 //////////////////////////////////////////////////////////////////////////////
1148 // CBlock and CBlockIndex
1151 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1153 // Open history file to append
1154 CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1156 return error("WriteBlockToDisk() : OpenBlockFile failed");
1158 // Write index header
1159 unsigned int nSize = fileout.GetSerializeSize(block);
1160 fileout << FLATDATA(Params().MessageStart()) << nSize;
1163 long fileOutPos = ftell(fileout);
1165 return error("WriteBlockToDisk() : ftell failed");
1166 pos.nPos = (unsigned int)fileOutPos;
1169 // Flush stdio buffers and commit to disk before returning
1171 if (!IsInitialBlockDownload())
1172 FileCommit(fileout);
1177 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1181 // Open history file to read
1182 CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1184 return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : OpenBlockFile failed");
1190 catch (std::exception &e) {
1191 return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1195 if (!CheckProofOfWork(block.GetHash(), block.nBits))
1196 return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : errors in block header");
1201 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1203 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1205 if (block.GetHash() != pindex->GetBlockHash())
1206 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1210 uint256 static GetOrphanRoot(const CBlockHeader* pblock)
1212 // Work back to the first block in the orphan chain
1213 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1214 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1215 return pblock->GetHash();
1218 int64 GetBlockValue(int nHeight, int64 nFees)
1220 int64 nSubsidy = 50 * COIN;
1222 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1223 nSubsidy >>= (nHeight / Params().SubsidyHalvingInterval());
1225 return nSubsidy + nFees;
1228 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
1229 static const int64 nTargetSpacing = 10 * 60;
1230 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
1233 // minimum amount of work that could possibly be required nTime after
1234 // minimum work required was nBase
1236 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1238 const CBigNum &bnLimit = Params().ProofOfWorkLimit();
1239 // Testnet has min-difficulty blocks
1240 // after nTargetSpacing*2 time between blocks:
1241 if (TestNet() && nTime > nTargetSpacing*2)
1242 return bnLimit.GetCompact();
1245 bnResult.SetCompact(nBase);
1246 while (nTime > 0 && bnResult < bnLimit)
1248 // Maximum 400% adjustment...
1250 // ... in best-case exactly 4-times-normal target time
1251 nTime -= nTargetTimespan*4;
1253 if (bnResult > bnLimit)
1255 return bnResult.GetCompact();
1258 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
1260 unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
1263 if (pindexLast == NULL)
1264 return nProofOfWorkLimit;
1266 // Only change once per interval
1267 if ((pindexLast->nHeight+1) % nInterval != 0)
1271 // Special difficulty rule for testnet:
1272 // If the new block's timestamp is more than 2* 10 minutes
1273 // then allow mining of a min-difficulty block.
1274 if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
1275 return nProofOfWorkLimit;
1278 // Return the last non-special-min-difficulty-rules-block
1279 const CBlockIndex* pindex = pindexLast;
1280 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
1281 pindex = pindex->pprev;
1282 return pindex->nBits;
1285 return pindexLast->nBits;
1288 // Go back by what we want to be 14 days worth of blocks
1289 const CBlockIndex* pindexFirst = pindexLast;
1290 for (int i = 0; pindexFirst && i < nInterval-1; i++)
1291 pindexFirst = pindexFirst->pprev;
1292 assert(pindexFirst);
1294 // Limit adjustment step
1295 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
1296 LogPrintf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
1297 if (nActualTimespan < nTargetTimespan/4)
1298 nActualTimespan = nTargetTimespan/4;
1299 if (nActualTimespan > nTargetTimespan*4)
1300 nActualTimespan = nTargetTimespan*4;
1304 bnNew.SetCompact(pindexLast->nBits);
1305 bnNew *= nActualTimespan;
1306 bnNew /= nTargetTimespan;
1308 if (bnNew > Params().ProofOfWorkLimit())
1309 bnNew = Params().ProofOfWorkLimit();
1312 LogPrintf("GetNextWorkRequired RETARGET\n");
1313 LogPrintf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
1314 LogPrintf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
1315 LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
1317 return bnNew.GetCompact();
1320 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1323 bnTarget.SetCompact(nBits);
1326 if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit())
1327 return error("CheckProofOfWork() : nBits below minimum work");
1329 // Check proof of work matches claimed amount
1330 if (hash > bnTarget.getuint256())
1331 return error("CheckProofOfWork() : hash doesn't match nBits");
1336 // Return maximum amount of blocks that other nodes claim to have
1337 int GetNumBlocksOfPeers()
1339 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1342 bool IsInitialBlockDownload()
1344 if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1346 static int64 nLastUpdate;
1347 static CBlockIndex* pindexLastBest;
1348 if (chainActive.Tip() != pindexLastBest)
1350 pindexLastBest = chainActive.Tip();
1351 nLastUpdate = GetTime();
1353 return (GetTime() - nLastUpdate < 10 &&
1354 chainActive.Tip()->GetBlockTime() < GetTime() - 24 * 60 * 60);
1357 bool fLargeWorkForkFound = false;
1358 bool fLargeWorkInvalidChainFound = false;
1359 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1361 void CheckForkWarningConditions()
1363 // Before we get past initial download, we cannot reliably alert about forks
1364 // (we assume we don't get stuck on a fork before the last checkpoint)
1365 if (IsInitialBlockDownload())
1368 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1369 // of our head, drop it
1370 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1371 pindexBestForkTip = NULL;
1373 if (pindexBestForkTip || nBestInvalidWork > chainActive.Tip()->nChainWork + (chainActive.Tip()->GetBlockWork() * 6).getuint256())
1375 if (!fLargeWorkForkFound)
1377 std::string strCmd = GetArg("-alertnotify", "");
1378 if (!strCmd.empty())
1380 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1381 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1382 boost::replace_all(strCmd, "%s", warning);
1383 boost::thread t(runCommand, strCmd); // thread runs free
1386 if (pindexBestForkTip)
1388 LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
1389 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString().c_str(),
1390 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString().c_str());
1391 fLargeWorkForkFound = true;
1395 LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1396 fLargeWorkInvalidChainFound = true;
1401 fLargeWorkForkFound = false;
1402 fLargeWorkInvalidChainFound = false;
1406 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1408 // If we are on a fork that is sufficiently large, set a warning flag
1409 CBlockIndex* pfork = pindexNewForkTip;
1410 CBlockIndex* plonger = chainActive.Tip();
1411 while (pfork && pfork != plonger)
1413 while (plonger && plonger->nHeight > pfork->nHeight)
1414 plonger = plonger->pprev;
1415 if (pfork == plonger)
1417 pfork = pfork->pprev;
1420 // We define a condition which we should warn the user about as a fork of at least 7 blocks
1421 // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1422 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1423 // hash rate operating on the fork.
1424 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1425 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1426 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1427 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1428 pindexNewForkTip->nChainWork - pfork->nChainWork > (pfork->GetBlockWork() * 7).getuint256() &&
1429 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1431 pindexBestForkTip = pindexNewForkTip;
1432 pindexBestForkBase = pfork;
1435 CheckForkWarningConditions();
1438 void static InvalidChainFound(CBlockIndex* pindexNew)
1440 if (pindexNew->nChainWork > nBestInvalidWork)
1442 nBestInvalidWork = pindexNew->nChainWork;
1443 pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork));
1444 uiInterface.NotifyBlocksChanged();
1446 LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1447 pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
1448 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1449 pindexNew->GetBlockTime()).c_str());
1450 LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1451 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1452 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
1453 CheckForkWarningConditions();
1456 void static InvalidBlockFound(CBlockIndex *pindex) {
1457 pindex->nStatus |= BLOCK_FAILED_VALID;
1458 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
1459 setBlockIndexValid.erase(pindex);
1460 InvalidChainFound(pindex);
1461 if (chainActive.Next(pindex)) {
1462 CValidationState stateDummy;
1463 ConnectBestBlock(stateDummy); // reorganise away from the failed block
1467 bool ConnectBestBlock(CValidationState &state) {
1469 CBlockIndex *pindexNewBest;
1472 std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
1473 if (it == setBlockIndexValid.rend())
1475 pindexNewBest = *it;
1478 if (pindexNewBest == chainActive.Tip() || (chainActive.Tip() && pindexNewBest->nChainWork == chainActive.Tip()->nChainWork))
1479 return true; // nothing to do
1482 CBlockIndex *pindexTest = pindexNewBest;
1483 std::vector<CBlockIndex*> vAttach;
1485 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
1486 // mark descendants failed
1487 CBlockIndex *pindexFailed = pindexNewBest;
1488 while (pindexTest != pindexFailed) {
1489 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
1490 setBlockIndexValid.erase(pindexFailed);
1491 pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
1492 pindexFailed = pindexFailed->pprev;
1494 InvalidChainFound(pindexNewBest);
1498 if (chainActive.Tip() == NULL || pindexTest->nChainWork > chainActive.Tip()->nChainWork)
1499 vAttach.push_back(pindexTest);
1501 if (pindexTest->pprev == NULL || chainActive.Next(pindexTest)) {
1502 reverse(vAttach.begin(), vAttach.end());
1503 BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
1504 boost::this_thread::interruption_point();
1506 if (!SetBestChain(state, pindexSwitch))
1508 } catch(std::runtime_error &e) {
1509 return state.Abort(_("System error: ") + e.what());
1514 pindexTest = pindexTest->pprev;
1519 void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev)
1521 block.nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
1523 // Updating time can change work required on testnet:
1525 block.nBits = GetNextWorkRequired(pindexPrev, &block);
1538 const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input)
1540 const CCoins &coins = GetCoins(input.prevout.hash);
1541 assert(coins.IsAvailable(input.prevout.n));
1542 return coins.vout[input.prevout.n];
1545 int64 CCoinsViewCache::GetValueIn(const CTransaction& tx)
1547 if (tx.IsCoinBase())
1551 for (unsigned int i = 0; i < tx.vin.size(); i++)
1552 nResult += GetOutputFor(tx.vin[i]).nValue;
1557 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
1559 // mark inputs spent
1560 if (!tx.IsCoinBase()) {
1561 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1562 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1564 assert(coins.Spend(txin.prevout, undo));
1565 txundo.vprevout.push_back(undo);
1570 assert(inputs.SetCoins(txhash, CCoins(tx, nHeight)));
1573 bool CCoinsViewCache::HaveInputs(const CTransaction& tx)
1575 if (!tx.IsCoinBase()) {
1576 // first check whether information about the prevout hash is available
1577 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1578 const COutPoint &prevout = tx.vin[i].prevout;
1579 if (!HaveCoins(prevout.hash))
1583 // then check whether the actual outputs are available
1584 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1585 const COutPoint &prevout = tx.vin[i].prevout;
1586 const CCoins &coins = GetCoins(prevout.hash);
1587 if (!coins.IsAvailable(prevout.n))
1594 bool CScriptCheck::operator()() const {
1595 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1596 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1597 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
1601 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1603 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1606 bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1608 if (!tx.IsCoinBase())
1611 pvChecks->reserve(tx.vin.size());
1613 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1614 // for an attacker to attempt to split the network.
1615 if (!inputs.HaveInputs(tx))
1616 return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString().c_str()));
1618 // While checking, GetBestBlock() refers to the parent block.
1619 // This is also true for mempool checks.
1620 int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
1623 for (unsigned int i = 0; i < tx.vin.size(); i++)
1625 const COutPoint &prevout = tx.vin[i].prevout;
1626 const CCoins &coins = inputs.GetCoins(prevout.hash);
1628 // If prev is coinbase, check that it's matured
1629 if (coins.IsCoinBase()) {
1630 if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
1631 return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
1634 // Check for negative or overflow input values
1635 nValueIn += coins.vout[prevout.n].nValue;
1636 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1637 return state.DoS(100, error("CheckInputs() : txin values out of range"));
1641 if (nValueIn < GetValueOut(tx))
1642 return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString().c_str()));
1644 // Tally transaction fees
1645 int64 nTxFee = nValueIn - GetValueOut(tx);
1647 return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString().c_str()));
1649 if (!MoneyRange(nFees))
1650 return state.DoS(100, error("CheckInputs() : nFees out of range"));
1652 // The first loop above does all the inexpensive checks.
1653 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1654 // Helps prevent CPU exhaustion attacks.
1656 // Skip ECDSA signature verification when connecting blocks
1657 // before the last block chain checkpoint. This is safe because block merkle hashes are
1658 // still computed and checked, and any change will be caught at the next checkpoint.
1659 if (fScriptChecks) {
1660 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1661 const COutPoint &prevout = tx.vin[i].prevout;
1662 const CCoins &coins = inputs.GetCoins(prevout.hash);
1665 CScriptCheck check(coins, tx, i, flags, 0);
1667 pvChecks->push_back(CScriptCheck());
1668 check.swap(pvChecks->back());
1669 } else if (!check()) {
1670 if (flags & SCRIPT_VERIFY_STRICTENC) {
1671 // For now, check whether the failure was caused by non-canonical
1672 // encodings or not; if so, don't trigger DoS protection.
1673 CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
1675 return state.Invalid();
1677 return state.DoS(100,false);
1688 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1690 assert(pindex == view.GetBestBlock());
1697 CBlockUndo blockUndo;
1698 CDiskBlockPos pos = pindex->GetUndoPos();
1700 return error("DisconnectBlock() : no undo data available");
1701 if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1702 return error("DisconnectBlock() : failure reading undo data");
1704 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1705 return error("DisconnectBlock() : block and undo data inconsistent");
1707 // undo transactions in reverse order
1708 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1709 const CTransaction &tx = block.vtx[i];
1710 uint256 hash = tx.GetHash();
1712 // check that all outputs are available
1713 if (!view.HaveCoins(hash)) {
1714 fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
1715 view.SetCoins(hash, CCoins());
1717 CCoins &outs = view.GetCoins(hash);
1718 outs.ClearUnspendable();
1720 CCoins outsBlock = CCoins(tx, pindex->nHeight);
1721 // The CCoins serialization does not serialize negative numbers.
1722 // No network rules currently depend on the version here, so an inconsistency is harmless
1723 // but it must be corrected before txout nversion ever influences a network rule.
1724 if (outsBlock.nVersion < 0)
1725 outs.nVersion = outsBlock.nVersion;
1726 if (outs != outsBlock)
1727 fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1733 if (i > 0) { // not coinbases
1734 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1735 if (txundo.vprevout.size() != tx.vin.size())
1736 return error("DisconnectBlock() : transaction and undo data inconsistent");
1737 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1738 const COutPoint &out = tx.vin[j].prevout;
1739 const CTxInUndo &undo = txundo.vprevout[j];
1741 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1742 if (undo.nHeight != 0) {
1743 // undo data contains height: this is the last output of the prevout tx being spent
1744 if (!coins.IsPruned())
1745 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1747 coins.fCoinBase = undo.fCoinBase;
1748 coins.nHeight = undo.nHeight;
1749 coins.nVersion = undo.nVersion;
1751 if (coins.IsPruned())
1752 fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1754 if (coins.IsAvailable(out.n))
1755 fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1756 if (coins.vout.size() < out.n+1)
1757 coins.vout.resize(out.n+1);
1758 coins.vout[out.n] = undo.txout;
1759 if (!view.SetCoins(out.hash, coins))
1760 return error("DisconnectBlock() : cannot restore coin inputs");
1765 // move best block pointer to prevout block
1766 view.SetBestBlock(pindex->pprev);
1776 void static FlushBlockFile(bool fFinalize = false)
1778 LOCK(cs_LastBlockFile);
1780 CDiskBlockPos posOld(nLastBlockFile, 0);
1782 FILE *fileOld = OpenBlockFile(posOld);
1785 TruncateFile(fileOld, infoLastBlockFile.nSize);
1786 FileCommit(fileOld);
1790 fileOld = OpenUndoFile(posOld);
1793 TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
1794 FileCommit(fileOld);
1799 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1801 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1803 void ThreadScriptCheck() {
1804 RenameThread("bitcoin-scriptch");
1805 scriptcheckqueue.Thread();
1808 bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1810 // Check it again in case a previous version let a bad block in
1811 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1814 // verify that the view's current state corresponds to the previous block
1815 assert(pindex->pprev == view.GetBestBlock());
1817 // Special case for the genesis block, skipping connection of its transactions
1818 // (its coinbase is unspendable)
1819 if (block.GetHash() == Params().HashGenesisBlock()) {
1820 view.SetBestBlock(pindex);
1824 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1826 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1827 // unless those are already completely spent.
1828 // If such overwrites are allowed, coinbases and transactions depending upon those
1829 // can be duplicated to remove the ability to spend the first instance -- even after
1830 // being sent to another address.
1831 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1832 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1833 // already refuses previously-known transaction ids entirely.
1834 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1835 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1836 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1837 // initial block download.
1838 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1839 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1840 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1841 if (fEnforceBIP30) {
1842 for (unsigned int i = 0; i < block.vtx.size(); i++) {
1843 uint256 hash = block.GetTxHash(i);
1844 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1845 return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
1849 // BIP16 didn't become active until Apr 1 2012
1850 int64 nBIP16SwitchTime = 1333238400;
1851 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1853 unsigned int flags = SCRIPT_VERIFY_NOCACHE |
1854 (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
1856 CBlockUndo blockundo;
1858 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1860 int64 nStart = GetTimeMicros();
1863 unsigned int nSigOps = 0;
1864 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1865 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1866 vPos.reserve(block.vtx.size());
1867 for (unsigned int i = 0; i < block.vtx.size(); i++)
1869 const CTransaction &tx = block.vtx[i];
1871 nInputs += tx.vin.size();
1872 nSigOps += GetLegacySigOpCount(tx);
1873 if (nSigOps > MAX_BLOCK_SIGOPS)
1874 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1876 if (!tx.IsCoinBase())
1878 if (!view.HaveInputs(tx))
1879 return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
1881 if (fStrictPayToScriptHash)
1883 // Add in sigops done by pay-to-script-hash inputs;
1884 // this is to prevent a "rogue miner" from creating
1885 // an incredibly-expensive-to-validate block.
1886 nSigOps += GetP2SHSigOpCount(tx, view);
1887 if (nSigOps > MAX_BLOCK_SIGOPS)
1888 return state.DoS(100, error("ConnectBlock() : too many sigops"));
1891 nFees += view.GetValueIn(tx)-GetValueOut(tx);
1893 std::vector<CScriptCheck> vChecks;
1894 if (!CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
1896 control.Add(vChecks);
1900 UpdateCoins(tx, state, view, txundo, pindex->nHeight, block.GetTxHash(i));
1901 if (!tx.IsCoinBase())
1902 blockundo.vtxundo.push_back(txundo);
1904 vPos.push_back(std::make_pair(block.GetTxHash(i), pos));
1905 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1907 int64 nTime = GetTimeMicros() - nStart;
1909 LogPrintf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)block.vtx.size(), 0.001 * nTime, 0.001 * nTime / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
1911 if (GetValueOut(block.vtx[0]) > GetBlockValue(pindex->nHeight, nFees))
1912 return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", GetValueOut(block.vtx[0]), GetBlockValue(pindex->nHeight, nFees)));
1914 if (!control.Wait())
1915 return state.DoS(100, false);
1916 int64 nTime2 = GetTimeMicros() - nStart;
1918 LogPrintf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
1923 // Write undo information to disk
1924 if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
1926 if (pindex->GetUndoPos().IsNull()) {
1928 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1929 return error("ConnectBlock() : FindUndoPos failed");
1930 if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1931 return state.Abort(_("Failed to write undo data"));
1933 // update nUndoPos in block index
1934 pindex->nUndoPos = pos.nPos;
1935 pindex->nStatus |= BLOCK_HAVE_UNDO;
1938 pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
1940 CDiskBlockIndex blockindex(pindex);
1941 if (!pblocktree->WriteBlockIndex(blockindex))
1942 return state.Abort(_("Failed to write block index"));
1946 if (!pblocktree->WriteTxIndex(vPos))
1947 return state.Abort(_("Failed to write transaction index"));
1949 // add this block to the view's block chain
1950 assert(view.SetBestBlock(pindex));
1952 // Watch for transactions paying to me
1953 for (unsigned int i = 0; i < block.vtx.size(); i++)
1954 g_signals.SyncTransaction(block.GetTxHash(i), block.vtx[i], &block);
1959 bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
1961 mempool.check(pcoinsTip);
1963 // All modifications to the coin state will be done in this cache.
1964 // Only when all have succeeded, we push it to pcoinsTip.
1965 CCoinsViewCache view(*pcoinsTip, true);
1967 // Find the fork (typically, there is none)
1968 CBlockIndex* pfork = view.GetBestBlock();
1969 CBlockIndex* plonger = pindexNew;
1970 while (pfork && pfork != plonger)
1972 while (plonger->nHeight > pfork->nHeight) {
1973 plonger = plonger->pprev;
1974 assert(plonger != NULL);
1976 if (pfork == plonger)
1978 pfork = pfork->pprev;
1979 assert(pfork != NULL);
1982 // List of what to disconnect (typically nothing)
1983 vector<CBlockIndex*> vDisconnect;
1984 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1985 vDisconnect.push_back(pindex);
1987 // List of what to connect (typically only pindexNew)
1988 vector<CBlockIndex*> vConnect;
1989 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1990 vConnect.push_back(pindex);
1991 reverse(vConnect.begin(), vConnect.end());
1993 if (vDisconnect.size() > 0) {
1994 LogPrintf("REORGANIZE: Disconnect %"PRIszu" blocks; %s...\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
1995 LogPrintf("REORGANIZE: Connect %"PRIszu" blocks; ...%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
1998 // Disconnect shorter branch
1999 list<CTransaction> vResurrect;
2000 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
2002 if (!ReadBlockFromDisk(block, pindex))
2003 return state.Abort(_("Failed to read block"));
2004 int64 nStart = GetTimeMicros();
2005 if (!DisconnectBlock(block, state, pindex, view))
2006 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
2008 LogPrintf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2010 // Queue memory transactions to resurrect.
2011 // We only do this for blocks after the last checkpoint (reorganisation before that
2012 // point should only happen with -reindex/-loadblock, or a misbehaving peer.
2013 BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
2014 if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
2015 vResurrect.push_front(tx);
2018 // Connect longer branch
2019 vector<CTransaction> vDelete;
2020 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
2022 if (!ReadBlockFromDisk(block, pindex))
2023 return state.Abort(_("Failed to read block"));
2024 int64 nStart = GetTimeMicros();
2025 if (!ConnectBlock(block, state, pindex, view)) {
2026 if (state.IsInvalid()) {
2027 InvalidChainFound(pindexNew);
2028 InvalidBlockFound(pindex);
2030 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
2033 LogPrintf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2035 // Queue memory transactions to delete
2036 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2037 vDelete.push_back(tx);
2040 // Flush changes to global coin state
2041 int64 nStart = GetTimeMicros();
2042 int nModified = view.GetCacheSize();
2043 assert(view.Flush());
2044 int64 nTime = GetTimeMicros() - nStart;
2046 LogPrintf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
2048 // Make sure it's successfully written to disk before changing memory structure
2049 bool fIsInitialDownload = IsInitialBlockDownload();
2050 if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
2051 // Typical CCoins structures on disk are around 100 bytes in size.
2052 // Pushing a new one to the database can cause it to be written
2053 // twice (once in the log, and once in the tables). This is already
2054 // an overestimation, as most will delete an existing entry or
2055 // overwrite one. Still, use a conservative safety factor of 2.
2056 if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
2057 return state.Error();
2060 if (!pcoinsTip->Flush())
2061 return state.Abort(_("Failed to write to coin database"));
2064 // At this point, all changes have been done to the database.
2065 // Proceed by updating the memory structures.
2067 // Register new best chain
2068 chainActive.SetTip(pindexNew);
2070 // Resurrect memory transactions that were in the disconnected branch
2071 BOOST_FOREACH(CTransaction& tx, vResurrect) {
2072 // ignore validation errors in resurrected transactions
2073 CValidationState stateDummy;
2074 if (!mempool.accept(stateDummy, tx, false, NULL))
2075 mempool.remove(tx, true);
2078 // Delete redundant memory transactions that are in the connected branch
2079 BOOST_FOREACH(CTransaction& tx, vDelete) {
2081 mempool.removeConflicts(tx);
2084 mempool.check(pcoinsTip);
2086 // Update best block in wallet (so we can detect restored wallets)
2087 if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
2088 g_signals.SetBestChain(chainActive.GetLocator(pindexNew));
2091 nTimeBestReceived = GetTime();
2092 nTransactionsUpdated++;
2093 LogPrintf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
2094 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
2095 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str(),
2096 Checkpoints::GuessVerificationProgress(chainActive.Tip()));
2098 // Check the version of the last 100 blocks to see if we need to upgrade:
2099 if (!fIsInitialDownload)
2102 const CBlockIndex* pindex = chainActive.Tip();
2103 for (int i = 0; i < 100 && pindex != NULL; i++)
2105 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2107 pindex = pindex->pprev;
2110 LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2111 if (nUpgraded > 100/2)
2112 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2113 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2116 std::string strCmd = GetArg("-blocknotify", "");
2118 if (!fIsInitialDownload && !strCmd.empty())
2120 boost::replace_all(strCmd, "%s", chainActive.Tip()->GetBlockHash().GetHex());
2121 boost::thread t(runCommand, strCmd); // thread runs free
2128 bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos)
2130 // Check for duplicate
2131 uint256 hash = block.GetHash();
2132 if (mapBlockIndex.count(hash))
2133 return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
2135 // Construct new block index object
2136 CBlockIndex* pindexNew = new CBlockIndex(block);
2138 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2139 pindexNew->phashBlock = &((*mi).first);
2140 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2141 if (miPrev != mapBlockIndex.end())
2143 pindexNew->pprev = (*miPrev).second;
2144 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2146 pindexNew->nTx = block.vtx.size();
2147 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
2148 pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
2149 pindexNew->nFile = pos.nFile;
2150 pindexNew->nDataPos = pos.nPos;
2151 pindexNew->nUndoPos = 0;
2152 pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
2153 setBlockIndexValid.insert(pindexNew);
2155 if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
2156 return state.Abort(_("Failed to write block index"));
2159 if (!ConnectBestBlock(state))
2162 if (pindexNew == chainActive.Tip())
2164 // Clear fork warning if its no longer applicable
2165 CheckForkWarningConditions();
2166 // Notify UI to display prev block's coinbase if it was ours
2167 static uint256 hashPrevBestCoinBase;
2168 g_signals.UpdatedTransaction(hashPrevBestCoinBase);
2169 hashPrevBestCoinBase = block.GetTxHash(0);
2171 CheckForkWarningConditionsOnNewFork(pindexNew);
2173 if (!pblocktree->Flush())
2174 return state.Abort(_("Failed to sync block index"));
2176 uiInterface.NotifyBlocksChanged();
2181 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
2183 bool fUpdatedLast = false;
2185 LOCK(cs_LastBlockFile);
2188 if (nLastBlockFile != pos.nFile) {
2189 nLastBlockFile = pos.nFile;
2190 infoLastBlockFile.SetNull();
2191 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
2192 fUpdatedLast = true;
2195 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2196 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2197 FlushBlockFile(true);
2199 infoLastBlockFile.SetNull();
2200 pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2201 fUpdatedLast = true;
2203 pos.nFile = nLastBlockFile;
2204 pos.nPos = infoLastBlockFile.nSize;
2207 infoLastBlockFile.nSize += nAddSize;
2208 infoLastBlockFile.AddBlock(nHeight, nTime);
2211 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2212 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2213 if (nNewChunks > nOldChunks) {
2214 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2215 FILE *file = OpenBlockFile(pos);
2217 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2218 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2223 return state.Error();
2227 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2228 return state.Abort(_("Failed to write file info"));
2230 pblocktree->WriteLastBlockFile(nLastBlockFile);
2235 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2239 LOCK(cs_LastBlockFile);
2241 unsigned int nNewSize;
2242 if (nFile == nLastBlockFile) {
2243 pos.nPos = infoLastBlockFile.nUndoSize;
2244 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2245 if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2246 return state.Abort(_("Failed to write block info"));
2248 CBlockFileInfo info;
2249 if (!pblocktree->ReadBlockFileInfo(nFile, info))
2250 return state.Abort(_("Failed to read block info"));
2251 pos.nPos = info.nUndoSize;
2252 nNewSize = (info.nUndoSize += nAddSize);
2253 if (!pblocktree->WriteBlockFileInfo(nFile, info))
2254 return state.Abort(_("Failed to write block info"));
2257 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2258 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2259 if (nNewChunks > nOldChunks) {
2260 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2261 FILE *file = OpenUndoFile(pos);
2263 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2264 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2269 return state.Error();
2276 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2278 // These are checks that are independent of context
2279 // that can be verified before saving an orphan block.
2282 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2283 return state.DoS(100, error("CheckBlock() : size limits failed"));
2285 // Check proof of work matches claimed amount
2286 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2287 return state.DoS(50, error("CheckBlock() : proof of work failed"));
2290 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2291 return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
2293 // First transaction must be coinbase, the rest must not be
2294 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2295 return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
2296 for (unsigned int i = 1; i < block.vtx.size(); i++)
2297 if (block.vtx[i].IsCoinBase())
2298 return state.DoS(100, error("CheckBlock() : more than one coinbase"));
2300 // Check transactions
2301 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2302 if (!CheckTransaction(tx, state))
2303 return error("CheckBlock() : CheckTransaction failed");
2305 // Build the merkle tree already. We need it anyway later, and it makes the
2306 // block cache the transaction hashes, which means they don't need to be
2307 // recalculated many times during this block's validation.
2308 block.BuildMerkleTree();
2310 // Check for duplicate txids. This is caught by ConnectInputs(),
2311 // but catching it earlier avoids a potential DoS attack:
2312 set<uint256> uniqueTx;
2313 for (unsigned int i = 0; i < block.vtx.size(); i++) {
2314 uniqueTx.insert(block.GetTxHash(i));
2316 if (uniqueTx.size() != block.vtx.size())
2317 return state.DoS(100, error("CheckBlock() : duplicate transaction"));
2319 unsigned int nSigOps = 0;
2320 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2322 nSigOps += GetLegacySigOpCount(tx);
2324 if (nSigOps > MAX_BLOCK_SIGOPS)
2325 return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2327 // Check merkle root
2328 if (fCheckMerkleRoot && block.hashMerkleRoot != block.vMerkleTree.back())
2329 return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2334 bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp)
2336 // Check for duplicate
2337 uint256 hash = block.GetHash();
2338 if (mapBlockIndex.count(hash))
2339 return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
2341 // Get prev block index
2342 CBlockIndex* pindexPrev = NULL;
2344 if (hash != Params().HashGenesisBlock()) {
2345 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2346 if (mi == mapBlockIndex.end())
2347 return state.DoS(10, error("AcceptBlock() : prev block not found"));
2348 pindexPrev = (*mi).second;
2349 nHeight = pindexPrev->nHeight+1;
2351 // Check proof of work
2352 if (block.nBits != GetNextWorkRequired(pindexPrev, &block))
2353 return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
2355 // Check timestamp against prev
2356 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2357 return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
2359 // Check that all transactions are finalized
2360 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2361 if (!IsFinalTx(tx, nHeight, block.GetBlockTime()))
2362 return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2364 // Check that the block chain matches the known block chain up to a checkpoint
2365 if (!Checkpoints::CheckBlock(nHeight, hash))
2366 return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
2368 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2369 if (block.nVersion < 2)
2371 if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
2372 (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
2374 return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
2377 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2378 if (block.nVersion >= 2)
2380 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2381 if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
2382 (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
2384 CScript expect = CScript() << nHeight;
2385 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2386 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin()))
2387 return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2392 // Write block to history file
2394 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2395 CDiskBlockPos blockPos;
2398 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.nTime, dbp != NULL))
2399 return error("AcceptBlock() : FindBlockPos failed");
2401 if (!WriteBlockToDisk(block, blockPos))
2402 return state.Abort(_("Failed to write block"));
2403 if (!AddToBlockIndex(block, state, blockPos))
2404 return error("AcceptBlock() : AddToBlockIndex failed");
2405 } catch(std::runtime_error &e) {
2406 return state.Abort(_("System error: ") + e.what());
2409 // Relay inventory, but don't relay old inventory during initial block download
2410 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2411 if (chainActive.Tip()->GetBlockHash() == hash)
2414 BOOST_FOREACH(CNode* pnode, vNodes)
2415 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2416 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2422 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2424 unsigned int nFound = 0;
2425 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2427 if (pstart->nVersion >= minVersion)
2429 pstart = pstart->pprev;
2431 return (nFound >= nRequired);
2434 int64 CBlockIndex::GetMedianTime() const
2436 const CBlockIndex* pindex = this;
2437 for (int i = 0; i < nMedianTimeSpan/2; i++)
2439 if (!chainActive.Next(pindex))
2440 return GetBlockTime();
2441 pindex = chainActive.Next(pindex);
2443 return pindex->GetMedianTimePast();
2446 void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
2448 // Filter out duplicate requests
2449 if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
2451 pnode->pindexLastGetBlocksBegin = pindexBegin;
2452 pnode->hashLastGetBlocksEnd = hashEnd;
2454 pnode->PushMessage("getblocks", chainActive.GetLocator(pindexBegin), hashEnd);
2457 bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2459 // Check for duplicate
2460 uint256 hash = pblock->GetHash();
2461 if (mapBlockIndex.count(hash))
2462 return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
2463 if (mapOrphanBlocks.count(hash))
2464 return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
2466 // Preliminary checks
2467 if (!CheckBlock(*pblock, state))
2468 return error("ProcessBlock() : CheckBlock FAILED");
2470 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
2471 if (pcheckpoint && pblock->hashPrevBlock != (chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(0)))
2473 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2474 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2477 return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
2480 bnNewBlock.SetCompact(pblock->nBits);
2482 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
2483 if (bnNewBlock > bnRequired)
2485 return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
2490 // If we don't already have its previous block, shunt it off to holding area until we get it
2491 if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
2493 LogPrintf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
2495 // Accept orphans as long as there is a node to request its parents from
2497 CBlock* pblock2 = new CBlock(*pblock);
2498 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2499 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2501 // Ask this guy to fill in what we're missing
2502 PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(pblock2));
2508 if (!AcceptBlock(*pblock, state, dbp))
2509 return error("ProcessBlock() : AcceptBlock FAILED");
2511 // Recursively process any orphan blocks that depended on this one
2512 vector<uint256> vWorkQueue;
2513 vWorkQueue.push_back(hash);
2514 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2516 uint256 hashPrev = vWorkQueue[i];
2517 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2518 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2521 CBlock* pblockOrphan = (*mi).second;
2522 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
2523 CValidationState stateDummy;
2524 if (AcceptBlock(*pblockOrphan, stateDummy))
2525 vWorkQueue.push_back(pblockOrphan->GetHash());
2526 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2527 delete pblockOrphan;
2529 mapOrphanBlocksByPrev.erase(hashPrev);
2532 LogPrintf("ProcessBlock: ACCEPTED\n");
2543 CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
2545 header = block.GetBlockHeader();
2547 vector<bool> vMatch;
2548 vector<uint256> vHashes;
2550 vMatch.reserve(block.vtx.size());
2551 vHashes.reserve(block.vtx.size());
2553 for (unsigned int i = 0; i < block.vtx.size(); i++)
2555 uint256 hash = block.vtx[i].GetHash();
2556 if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
2558 vMatch.push_back(true);
2559 vMatchedTxn.push_back(make_pair(i, hash));
2562 vMatch.push_back(false);
2563 vHashes.push_back(hash);
2566 txn = CPartialMerkleTree(vHashes, vMatch);
2576 uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
2578 // hash at height 0 is the txids themself
2581 // calculate left hash
2582 uint256 left = CalcHash(height-1, pos*2, vTxid), right;
2583 // calculate right hash if not beyong the end of the array - copy left hash otherwise1
2584 if (pos*2+1 < CalcTreeWidth(height-1))
2585 right = CalcHash(height-1, pos*2+1, vTxid);
2588 // combine subhashes
2589 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2593 void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
2594 // determine whether this node is the parent of at least one matched txid
2595 bool fParentOfMatch = false;
2596 for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
2597 fParentOfMatch |= vMatch[p];
2598 // store as flag bit
2599 vBits.push_back(fParentOfMatch);
2600 if (height==0 || !fParentOfMatch) {
2601 // if at height 0, or nothing interesting below, store hash and stop
2602 vHash.push_back(CalcHash(height, pos, vTxid));
2604 // otherwise, don't store any hash, but descend into the subtrees
2605 TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
2606 if (pos*2+1 < CalcTreeWidth(height-1))
2607 TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
2611 uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
2612 if (nBitsUsed >= vBits.size()) {
2613 // overflowed the bits array - failure
2617 bool fParentOfMatch = vBits[nBitsUsed++];
2618 if (height==0 || !fParentOfMatch) {
2619 // if at height 0, or nothing interesting below, use stored hash and do not descend
2620 if (nHashUsed >= vHash.size()) {
2621 // overflowed the hash array - failure
2625 const uint256 &hash = vHash[nHashUsed++];
2626 if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
2627 vMatch.push_back(hash);
2630 // otherwise, descend into the subtrees to extract matched txids and hashes
2631 uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
2632 if (pos*2+1 < CalcTreeWidth(height-1))
2633 right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
2636 // and combine them before returning
2637 return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
2641 CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
2646 // calculate height of tree
2648 while (CalcTreeWidth(nHeight) > 1)
2651 // traverse the partial tree
2652 TraverseAndBuild(nHeight, 0, vTxid, vMatch);
2655 CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
2657 uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
2659 // An empty set will not work
2660 if (nTransactions == 0)
2662 // check for excessively high numbers of transactions
2663 if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
2665 // there can never be more hashes provided than one for every txid
2666 if (vHash.size() > nTransactions)
2668 // there must be at least one bit per node in the partial tree, and at least one node per hash
2669 if (vBits.size() < vHash.size())
2671 // calculate height of tree
2673 while (CalcTreeWidth(nHeight) > 1)
2675 // traverse the partial tree
2676 unsigned int nBitsUsed = 0, nHashUsed = 0;
2677 uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
2678 // verify that no problems occured during the tree traversal
2681 // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
2682 if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
2684 // verify that all hashes were consumed
2685 if (nHashUsed != vHash.size())
2687 return hashMerkleRoot;
2696 bool AbortNode(const std::string &strMessage) {
2697 strMiscWarning = strMessage;
2698 LogPrintf("*** %s\n", strMessage.c_str());
2699 uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
2704 bool CheckDiskSpace(uint64 nAdditionalBytes)
2706 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2708 // Check for nMinDiskSpace bytes (currently 50MB)
2709 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2710 return AbortNode(_("Error: Disk space is low!"));
2715 CCriticalSection cs_LastBlockFile;
2716 CBlockFileInfo infoLastBlockFile;
2717 int nLastBlockFile = 0;
2719 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2723 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2724 boost::filesystem::create_directories(path.parent_path());
2725 FILE* file = fopen(path.string().c_str(), "rb+");
2726 if (!file && !fReadOnly)
2727 file = fopen(path.string().c_str(), "wb+");
2729 LogPrintf("Unable to open file %s\n", path.string().c_str());
2733 if (fseek(file, pos.nPos, SEEK_SET)) {
2734 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2742 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2743 return OpenDiskFile(pos, "blk", fReadOnly);
2746 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2747 return OpenDiskFile(pos, "rev", fReadOnly);
2750 CBlockIndex * InsertBlockIndex(uint256 hash)
2756 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2757 if (mi != mapBlockIndex.end())
2758 return (*mi).second;
2761 CBlockIndex* pindexNew = new CBlockIndex();
2763 throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2764 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2765 pindexNew->phashBlock = &((*mi).first);
2770 bool static LoadBlockIndexDB()
2772 if (!pblocktree->LoadBlockIndexGuts())
2775 boost::this_thread::interruption_point();
2777 // Calculate nChainWork
2778 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2779 vSortedByHeight.reserve(mapBlockIndex.size());
2780 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2782 CBlockIndex* pindex = item.second;
2783 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2785 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2786 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2788 CBlockIndex* pindex = item.second;
2789 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
2790 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2791 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
2792 setBlockIndexValid.insert(pindex);
2795 // Load block file info
2796 pblocktree->ReadLastBlockFile(nLastBlockFile);
2797 LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
2798 if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2799 LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
2801 // Load nBestInvalidWork, OK if it doesn't exist
2802 CBigNum bnBestInvalidWork;
2803 pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
2804 nBestInvalidWork = bnBestInvalidWork.getuint256();
2806 // Check whether we need to continue reindexing
2807 bool fReindexing = false;
2808 pblocktree->ReadReindexing(fReindexing);
2809 fReindex |= fReindexing;
2811 // Check whether we have a transaction index
2812 pblocktree->ReadFlag("txindex", fTxIndex);
2813 LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2815 // Load hashBestChain pointer to end of best chain
2816 chainActive.SetTip(pcoinsTip->GetBestBlock());
2817 if (chainActive.Tip() == NULL)
2820 // register best chain
2821 LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
2822 chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(),
2823 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
2828 bool VerifyDB(int nCheckLevel, int nCheckDepth)
2830 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
2833 // Verify blocks in the best chain
2834 if (nCheckDepth <= 0)
2835 nCheckDepth = 1000000000; // suffices until the year 19000
2836 if (nCheckDepth > chainActive.Height())
2837 nCheckDepth = chainActive.Height();
2838 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2839 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2840 CCoinsViewCache coins(*pcoinsTip, true);
2841 CBlockIndex* pindexState = chainActive.Tip();
2842 CBlockIndex* pindexFailure = NULL;
2843 int nGoodTransactions = 0;
2844 CValidationState state;
2845 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2847 boost::this_thread::interruption_point();
2848 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2851 // check level 0: read from disk
2852 if (!ReadBlockFromDisk(block, pindex))
2853 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2854 // check level 1: verify block validity
2855 if (nCheckLevel >= 1 && !CheckBlock(block, state))
2856 return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2857 // check level 2: verify undo validity
2858 if (nCheckLevel >= 2 && pindex) {
2860 CDiskBlockPos pos = pindex->GetUndoPos();
2861 if (!pos.IsNull()) {
2862 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
2863 return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2866 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
2867 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
2869 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
2870 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2871 pindexState = pindex->pprev;
2873 nGoodTransactions = 0;
2874 pindexFailure = pindex;
2876 nGoodTransactions += block.vtx.size();
2880 return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
2882 // check level 4: try reconnecting blocks
2883 if (nCheckLevel >= 4) {
2884 CBlockIndex *pindex = pindexState;
2885 while (pindex != chainActive.Tip()) {
2886 boost::this_thread::interruption_point();
2887 pindex = chainActive.Next(pindex);
2889 if (!ReadBlockFromDisk(block, pindex))
2890 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2891 if (!ConnectBlock(block, state, pindex, coins))
2892 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
2896 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
2901 void UnloadBlockIndex()
2903 mapBlockIndex.clear();
2904 setBlockIndexValid.clear();
2905 chainActive.SetTip(NULL);
2906 nBestInvalidWork = 0;
2909 bool LoadBlockIndex()
2911 // Load block index from databases
2912 if (!fReindex && !LoadBlockIndexDB())
2918 bool InitBlockIndex() {
2919 // Check whether we're already initialized
2920 if (chainActive.Genesis() != NULL)
2923 // Use the provided setting for -txindex in the new database
2924 fTxIndex = GetBoolArg("-txindex", false);
2925 pblocktree->WriteFlag("txindex", fTxIndex);
2926 LogPrintf("Initializing databases...\n");
2928 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
2931 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
2932 // Start new block file
2933 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2934 CDiskBlockPos blockPos;
2935 CValidationState state;
2936 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
2937 return error("LoadBlockIndex() : FindBlockPos failed");
2938 if (!WriteBlockToDisk(block, blockPos))
2939 return error("LoadBlockIndex() : writing genesis block to disk failed");
2940 if (!AddToBlockIndex(block, state, blockPos))
2941 return error("LoadBlockIndex() : genesis block not accepted");
2942 } catch(std::runtime_error &e) {
2943 return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
2952 void PrintBlockTree()
2954 // pre-compute tree structure
2955 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2956 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2958 CBlockIndex* pindex = (*mi).second;
2959 mapNext[pindex->pprev].push_back(pindex);
2961 //while (rand() % 3 == 0)
2962 // mapNext[pindex->pprev].push_back(pindex);
2965 vector<pair<int, CBlockIndex*> > vStack;
2966 vStack.push_back(make_pair(0, chainActive.Genesis()));
2969 while (!vStack.empty())
2971 int nCol = vStack.back().first;
2972 CBlockIndex* pindex = vStack.back().second;
2975 // print split or gap
2976 if (nCol > nPrevCol)
2978 for (int i = 0; i < nCol-1; i++)
2982 else if (nCol < nPrevCol)
2984 for (int i = 0; i < nCol; i++)
2991 for (int i = 0; i < nCol; i++)
2996 ReadBlockFromDisk(block, pindex);
2997 LogPrintf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2999 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
3000 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
3003 // put the main time-chain first
3004 vector<CBlockIndex*>& vNext = mapNext[pindex];
3005 for (unsigned int i = 0; i < vNext.size(); i++)
3007 if (chainActive.Next(vNext[i]))
3009 swap(vNext[0], vNext[i]);
3015 for (unsigned int i = 0; i < vNext.size(); i++)
3016 vStack.push_back(make_pair(nCol+i, vNext[i]));
3020 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3022 int64 nStart = GetTimeMillis();
3026 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3027 uint64 nStartByte = 0;
3029 // (try to) skip already indexed part
3030 CBlockFileInfo info;
3031 if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
3032 nStartByte = info.nSize;
3033 blkdat.Seek(info.nSize);
3036 uint64 nRewind = blkdat.GetPos();
3037 while (blkdat.good() && !blkdat.eof()) {
3038 boost::this_thread::interruption_point();
3040 blkdat.SetPos(nRewind);
3041 nRewind++; // start one byte further next time, in case of failure
3042 blkdat.SetLimit(); // remove former limit
3043 unsigned int nSize = 0;
3046 unsigned char buf[4];
3047 blkdat.FindByte(Params().MessageStart()[0]);
3048 nRewind = blkdat.GetPos()+1;
3049 blkdat >> FLATDATA(buf);
3050 if (memcmp(buf, Params().MessageStart(), 4))
3054 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3056 } catch (std::exception &e) {
3057 // no valid block header found; don't complain
3062 uint64 nBlockPos = blkdat.GetPos();
3063 blkdat.SetLimit(nBlockPos + nSize);
3066 nRewind = blkdat.GetPos();
3069 if (nBlockPos >= nStartByte) {
3072 dbp->nPos = nBlockPos;
3073 CValidationState state;
3074 if (ProcessBlock(state, NULL, &block, dbp))
3076 if (state.IsError())
3079 } catch (std::exception &e) {
3080 LogPrintf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
3084 } catch(std::runtime_error &e) {
3085 AbortNode(_("Error: system error: ") + e.what());
3088 LogPrintf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3101 //////////////////////////////////////////////////////////////////////////////
3106 extern map<uint256, CAlert> mapAlerts;
3107 extern CCriticalSection cs_mapAlerts;
3109 string GetWarnings(string strFor)
3112 string strStatusBar;
3115 if (GetBoolArg("-testsafemode", false))
3118 if (!CLIENT_VERSION_IS_RELEASE)
3119 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3121 // Misc warnings like out of disk space and clock is wrong
3122 if (strMiscWarning != "")
3125 strStatusBar = strMiscWarning;
3128 if (fLargeWorkForkFound)
3131 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3133 else if (fLargeWorkInvalidChainFound)
3136 strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
3142 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3144 const CAlert& alert = item.second;
3145 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3147 nPriority = alert.nPriority;
3148 strStatusBar = alert.strStatusBar;
3153 if (strFor == "statusbar")
3154 return strStatusBar;
3155 else if (strFor == "rpc")
3157 assert(!"GetWarnings() : invalid parameter");
3168 //////////////////////////////////////////////////////////////////////////////
3174 bool static AlreadyHave(const CInv& inv)
3180 bool txInMap = false;
3183 txInMap = mempool.exists(inv.hash);
3185 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3186 pcoinsTip->HaveCoins(inv.hash);
3189 return mapBlockIndex.count(inv.hash) ||
3190 mapOrphanBlocks.count(inv.hash);
3192 // Don't know what it is, just say we already got one
3199 void static ProcessGetData(CNode* pfrom)
3201 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3203 vector<CInv> vNotFound;
3207 while (it != pfrom->vRecvGetData.end()) {
3208 // Don't bother if send buffer is too full to respond anyway
3209 if (pfrom->nSendSize >= SendBufferSize())
3212 const CInv &inv = *it;
3214 boost::this_thread::interruption_point();
3217 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3219 // Send block from disk
3220 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3221 if (mi != mapBlockIndex.end())
3224 ReadBlockFromDisk(block, (*mi).second);
3225 if (inv.type == MSG_BLOCK)
3226 pfrom->PushMessage("block", block);
3227 else // MSG_FILTERED_BLOCK)
3229 LOCK(pfrom->cs_filter);
3232 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3233 pfrom->PushMessage("merkleblock", merkleBlock);
3234 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3235 // This avoids hurting performance by pointlessly requiring a round-trip
3236 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3237 // they must either disconnect and retry or request the full block.
3238 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3239 // however we MUST always provide at least what the remote peer needs
3240 typedef std::pair<unsigned int, uint256> PairType;
3241 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3242 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3243 pfrom->PushMessage("tx", block.vtx[pair.first]);
3249 // Trigger them to send a getblocks request for the next batch of inventory
3250 if (inv.hash == pfrom->hashContinue)
3252 // Bypass PushInventory, this must send even if redundant,
3253 // and we want it right after the last block so they don't
3254 // wait for other stuff first.
3256 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3257 pfrom->PushMessage("inv", vInv);
3258 pfrom->hashContinue = 0;
3262 else if (inv.IsKnownType())
3264 // Send stream from relay memory
3265 bool pushed = false;
3268 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3269 if (mi != mapRelay.end()) {
3270 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3274 if (!pushed && inv.type == MSG_TX) {
3276 if (mempool.exists(inv.hash)) {
3277 CTransaction tx = mempool.lookup(inv.hash);
3278 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3281 pfrom->PushMessage("tx", ss);
3286 vNotFound.push_back(inv);
3290 // Track requests for our stuff.
3291 g_signals.Inventory(inv.hash);
3295 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3297 if (!vNotFound.empty()) {
3298 // Let the peer know that we didn't find what it asked for, so it doesn't
3299 // have to wait around forever. Currently only SPV clients actually care
3300 // about this message: it's needed when they are recursively walking the
3301 // dependencies of relevant unconfirmed transactions. SPV clients want to
3302 // do that because they want to know about (and store and rebroadcast and
3303 // risk analyze) the dependencies of transactions relevant to them, without
3304 // having to download the entire memory pool.
3305 pfrom->PushMessage("notfound", vNotFound);
3309 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3311 RandAddSeedPerfmon();
3312 LogPrint("net", "received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3313 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3315 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3323 if (strCommand == "version")
3325 // Each connection can only send one version message
3326 if (pfrom->nVersion != 0)
3328 pfrom->Misbehaving(1);
3336 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3337 if (pfrom->nVersion < MIN_PROTO_VERSION)
3339 // Since February 20, 2012, the protocol is initiated at version 209,
3340 // and earlier versions are no longer supported
3341 LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3342 pfrom->fDisconnect = true;
3346 if (pfrom->nVersion == 10300)
3347 pfrom->nVersion = 300;
3349 vRecv >> addrFrom >> nNonce;
3351 vRecv >> pfrom->strSubVer;
3353 vRecv >> pfrom->nStartingHeight;
3355 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3357 pfrom->fRelayTxes = true;
3359 if (pfrom->fInbound && addrMe.IsRoutable())
3361 pfrom->addrLocal = addrMe;
3365 // Disconnect if we connected to ourself
3366 if (nNonce == nLocalHostNonce && nNonce > 1)
3368 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3369 pfrom->fDisconnect = true;
3373 // Be shy and don't send version until we hear
3374 if (pfrom->fInbound)
3375 pfrom->PushVersion();
3377 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3381 pfrom->PushMessage("verack");
3382 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3384 if (!pfrom->fInbound)
3386 // Advertise our address
3387 if (!fNoListen && !IsInitialBlockDownload())
3389 CAddress addr = GetLocalAddress(&pfrom->addr);
3390 if (addr.IsRoutable())
3391 pfrom->PushAddress(addr);
3394 // Get recent addresses
3395 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3397 pfrom->PushMessage("getaddr");
3398 pfrom->fGetAddr = true;
3400 addrman.Good(pfrom->addr);
3402 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3404 addrman.Add(addrFrom, addrFrom);
3405 addrman.Good(addrFrom);
3412 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3413 item.second.RelayTo(pfrom);
3416 pfrom->fSuccessfullyConnected = true;
3418 LogPrintf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3421 AddTimeData(pfrom->addr, nTime);
3422 cPeerBlockCounts.input(pfrom->nStartingHeight);
3426 else if (pfrom->nVersion == 0)
3428 // Must have a version message before anything else
3429 pfrom->Misbehaving(1);
3434 else if (strCommand == "verack")
3436 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3440 else if (strCommand == "addr")
3442 vector<CAddress> vAddr;
3445 // Don't want addr from older versions unless seeding
3446 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3448 if (vAddr.size() > 1000)
3450 pfrom->Misbehaving(20);
3451 return error("message addr size() = %"PRIszu"", vAddr.size());
3454 // Store the new addresses
3455 vector<CAddress> vAddrOk;
3456 int64 nNow = GetAdjustedTime();
3457 int64 nSince = nNow - 10 * 60;
3458 BOOST_FOREACH(CAddress& addr, vAddr)
3460 boost::this_thread::interruption_point();
3462 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3463 addr.nTime = nNow - 5 * 24 * 60 * 60;
3464 pfrom->AddAddressKnown(addr);
3465 bool fReachable = IsReachable(addr);
3466 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3468 // Relay to a limited number of other nodes
3471 // Use deterministic randomness to send to the same nodes for 24 hours
3472 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3473 static uint256 hashSalt;
3475 hashSalt = GetRandHash();
3476 uint64 hashAddr = addr.GetHash();
3477 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3478 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3479 multimap<uint256, CNode*> mapMix;
3480 BOOST_FOREACH(CNode* pnode, vNodes)
3482 if (pnode->nVersion < CADDR_TIME_VERSION)
3484 unsigned int nPointer;
3485 memcpy(&nPointer, &pnode, sizeof(nPointer));
3486 uint256 hashKey = hashRand ^ nPointer;
3487 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3488 mapMix.insert(make_pair(hashKey, pnode));
3490 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3491 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3492 ((*mi).second)->PushAddress(addr);
3495 // Do not store addresses outside our network
3497 vAddrOk.push_back(addr);
3499 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3500 if (vAddr.size() < 1000)
3501 pfrom->fGetAddr = false;
3502 if (pfrom->fOneShot)
3503 pfrom->fDisconnect = true;
3507 else if (strCommand == "inv")
3511 if (vInv.size() > MAX_INV_SZ)
3513 pfrom->Misbehaving(20);
3514 return error("message inv size() = %"PRIszu"", vInv.size());
3517 // find last block in inv vector
3518 unsigned int nLastBlock = (unsigned int)(-1);
3519 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3520 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3521 nLastBlock = vInv.size() - 1 - nInv;
3528 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3530 const CInv &inv = vInv[nInv];
3532 boost::this_thread::interruption_point();
3533 pfrom->AddInventoryKnown(inv);
3535 bool fAlreadyHave = AlreadyHave(inv);
3536 LogPrint("net", " got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3538 if (!fAlreadyHave) {
3539 if (!fImporting && !fReindex)
3541 } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3542 PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3543 } else if (nInv == nLastBlock) {
3544 // In case we are on a very long side-chain, it is possible that we already have
3545 // the last block in an inv bundle sent in response to getblocks. Try to detect
3546 // this situation and push another getblocks to continue.
3547 PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
3549 LogPrintf("force request: %s\n", inv.ToString().c_str());
3552 // Track requests for our stuff
3553 g_signals.Inventory(inv.hash);
3558 else if (strCommand == "getdata")
3562 if (vInv.size() > MAX_INV_SZ)
3564 pfrom->Misbehaving(20);
3565 return error("message getdata size() = %"PRIszu"", vInv.size());
3568 if (fDebugNet || (vInv.size() != 1))
3569 LogPrint("net", "received getdata (%"PRIszu" invsz)\n", vInv.size());
3571 if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
3572 LogPrint("net", "received getdata for: %s\n", vInv[0].ToString().c_str());
3574 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3575 ProcessGetData(pfrom);
3579 else if (strCommand == "getblocks")
3581 CBlockLocator locator;
3583 vRecv >> locator >> hashStop;
3587 // Find the last block the caller has in the main chain
3588 CBlockIndex* pindex = chainActive.FindFork(locator);
3590 // Send the rest of the chain
3592 pindex = chainActive.Next(pindex);
3594 LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
3595 for (; pindex; pindex = chainActive.Next(pindex))
3597 if (pindex->GetBlockHash() == hashStop)
3599 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3602 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3605 // When this block is requested, we'll send an inv that'll make them
3606 // getblocks the next batch of inventory.
3607 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
3608 pfrom->hashContinue = pindex->GetBlockHash();
3615 else if (strCommand == "getheaders")
3617 CBlockLocator locator;
3619 vRecv >> locator >> hashStop;
3623 CBlockIndex* pindex = NULL;
3624 if (locator.IsNull())
3626 // If locator is null, return the hashStop block
3627 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3628 if (mi == mapBlockIndex.end())
3630 pindex = (*mi).second;
3634 // Find the last block the caller has in the main chain
3635 pindex = chainActive.FindFork(locator);
3637 pindex = chainActive.Next(pindex);
3640 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3641 vector<CBlock> vHeaders;
3643 LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
3644 for (; pindex; pindex = chainActive.Next(pindex))
3646 vHeaders.push_back(pindex->GetBlockHeader());
3647 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3650 pfrom->PushMessage("headers", vHeaders);
3654 else if (strCommand == "tx")
3656 vector<uint256> vWorkQueue;
3657 vector<uint256> vEraseQueue;
3661 CInv inv(MSG_TX, tx.GetHash());
3662 pfrom->AddInventoryKnown(inv);
3666 bool fMissingInputs = false;
3667 CValidationState state;
3668 if (mempool.accept(state, tx, true, &fMissingInputs))
3670 mempool.check(pcoinsTip);
3671 RelayTransaction(tx, inv.hash);
3672 mapAlreadyAskedFor.erase(inv);
3673 vWorkQueue.push_back(inv.hash);
3674 vEraseQueue.push_back(inv.hash);
3676 // Recursively process any orphan transactions that depended on this one
3677 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3679 uint256 hashPrev = vWorkQueue[i];
3680 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3681 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3684 const uint256& orphanHash = *mi;
3685 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
3686 bool fMissingInputs2 = false;
3687 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3688 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3689 // anyone relaying LegitTxX banned)
3690 CValidationState stateDummy;
3692 if (mempool.accept(stateDummy, orphanTx, true, &fMissingInputs2))
3694 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString().c_str());
3695 RelayTransaction(orphanTx, orphanHash);
3696 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
3697 vWorkQueue.push_back(orphanHash);
3698 vEraseQueue.push_back(orphanHash);
3700 else if (!fMissingInputs2)
3702 // invalid or too-little-fee orphan
3703 vEraseQueue.push_back(orphanHash);
3704 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString().c_str());
3706 mempool.check(pcoinsTip);
3710 BOOST_FOREACH(uint256 hash, vEraseQueue)
3711 EraseOrphanTx(hash);
3713 else if (fMissingInputs)
3717 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3718 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3720 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3723 if (state.IsInvalid(nDoS))
3725 pfrom->Misbehaving(nDoS);
3729 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3734 LogPrint("net", "received block %s\n", block.GetHash().ToString().c_str());
3737 CInv inv(MSG_BLOCK, block.GetHash());
3738 pfrom->AddInventoryKnown(inv);
3742 CValidationState state;
3743 if (ProcessBlock(state, pfrom, &block))
3744 mapAlreadyAskedFor.erase(inv);
3746 if (state.IsInvalid(nDoS))
3748 pfrom->Misbehaving(nDoS);
3752 else if (strCommand == "getaddr")
3754 pfrom->vAddrToSend.clear();
3755 vector<CAddress> vAddr = addrman.GetAddr();
3756 BOOST_FOREACH(const CAddress &addr, vAddr)
3757 pfrom->PushAddress(addr);
3761 else if (strCommand == "mempool")
3765 std::vector<uint256> vtxid;
3766 LOCK2(mempool.cs, pfrom->cs_filter);
3767 mempool.queryHashes(vtxid);
3769 BOOST_FOREACH(uint256& hash, vtxid) {
3770 CInv inv(MSG_TX, hash);
3771 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
3773 vInv.push_back(inv);
3774 if (vInv.size() == MAX_INV_SZ)
3777 if (vInv.size() > 0)
3778 pfrom->PushMessage("inv", vInv);
3782 else if (strCommand == "ping")
3784 if (pfrom->nVersion > BIP0031_VERSION)
3788 // Echo the message back with the nonce. This allows for two useful features:
3790 // 1) A remote node can quickly check if the connection is operational
3791 // 2) Remote nodes can measure the latency of the network thread. If this node
3792 // is overloaded it won't respond to pings quickly and the remote node can
3793 // avoid sending us more work, like chain download requests.
3795 // The nonce stops the remote getting confused between different pings: without
3796 // it, if the remote node sends a ping once per second and this node takes 5
3797 // seconds to respond to each, the 5th ping the remote sends would appear to
3798 // return very quickly.
3799 pfrom->PushMessage("pong", nonce);
3804 else if (strCommand == "pong")
3806 int64 pingUsecEnd = GetTimeMicros();
3808 size_t nAvail = vRecv.in_avail();
3809 bool bPingFinished = false;
3810 std::string sProblem;
3812 if (nAvail >= sizeof(nonce)) {
3815 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
3816 if (pfrom->nPingNonceSent != 0) {
3817 if (nonce == pfrom->nPingNonceSent) {
3818 // Matching pong received, this ping is no longer outstanding
3819 bPingFinished = true;
3820 int64 pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
3821 if (pingUsecTime > 0) {
3822 // Successful ping time measurement, replace previous
3823 pfrom->nPingUsecTime = pingUsecTime;
3825 // This should never happen
3826 sProblem = "Timing mishap";
3829 // Nonce mismatches are normal when pings are overlapping
3830 sProblem = "Nonce mismatch";
3832 // This is most likely a bug in another implementation somewhere, cancel this ping
3833 bPingFinished = true;
3834 sProblem = "Nonce zero";
3838 sProblem = "Unsolicited pong without ping";
3841 // This is most likely a bug in another implementation somewhere, cancel this ping
3842 bPingFinished = true;
3843 sProblem = "Short payload";
3846 if (!(sProblem.empty())) {
3847 LogPrint("net", "pong %s %s: %s, %"PRI64x" expected, %"PRI64x" received, %"PRIszu" bytes\n",
3848 pfrom->addr.ToString().c_str(),
3849 pfrom->strSubVer.c_str(),
3851 pfrom->nPingNonceSent,
3855 if (bPingFinished) {
3856 pfrom->nPingNonceSent = 0;
3861 else if (strCommand == "alert")
3866 uint256 alertHash = alert.GetHash();
3867 if (pfrom->setKnown.count(alertHash) == 0)
3869 if (alert.ProcessAlert())
3872 pfrom->setKnown.insert(alertHash);
3875 BOOST_FOREACH(CNode* pnode, vNodes)
3876 alert.RelayTo(pnode);
3880 // Small DoS penalty so peers that send us lots of
3881 // duplicate/expired/invalid-signature/whatever alerts
3882 // eventually get banned.
3883 // This isn't a Misbehaving(100) (immediate ban) because the
3884 // peer might be an older or different implementation with
3885 // a different signature key, etc.
3886 pfrom->Misbehaving(10);
3892 else if (strCommand == "filterload")
3894 CBloomFilter filter;
3897 if (!filter.IsWithinSizeConstraints())
3898 // There is no excuse for sending a too-large filter
3899 pfrom->Misbehaving(100);
3902 LOCK(pfrom->cs_filter);
3903 delete pfrom->pfilter;
3904 pfrom->pfilter = new CBloomFilter(filter);
3905 pfrom->pfilter->UpdateEmptyFull();
3907 pfrom->fRelayTxes = true;
3911 else if (strCommand == "filteradd")
3913 vector<unsigned char> vData;
3916 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
3917 // and thus, the maximum size any matched object can have) in a filteradd message
3918 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
3920 pfrom->Misbehaving(100);
3922 LOCK(pfrom->cs_filter);
3924 pfrom->pfilter->insert(vData);
3926 pfrom->Misbehaving(100);
3931 else if (strCommand == "filterclear")
3933 LOCK(pfrom->cs_filter);
3934 delete pfrom->pfilter;
3935 pfrom->pfilter = new CBloomFilter();
3936 pfrom->fRelayTxes = true;
3942 // Ignore unknown commands for extensibility
3946 // Update the last seen time for this node's address
3947 if (pfrom->fNetworkNode)
3948 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3949 AddressCurrentlyConnected(pfrom->addr);
3955 // requires LOCK(cs_vRecvMsg)
3956 bool ProcessMessages(CNode* pfrom)
3959 // LogPrintf("ProcessMessages(%"PRIszu" messages)\n", pfrom->vRecvMsg.size());
3963 // (4) message start
3971 if (!pfrom->vRecvGetData.empty())
3972 ProcessGetData(pfrom);
3974 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
3975 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
3976 // Don't bother if send buffer is too full to respond anyway
3977 if (pfrom->nSendSize >= SendBufferSize())
3981 CNetMessage& msg = *it;
3984 // LogPrintf("ProcessMessages(message %u msgsz, %"PRIszu" bytes, complete:%s)\n",
3985 // msg.hdr.nMessageSize, msg.vRecv.size(),
3986 // msg.complete() ? "Y" : "N");
3988 // end, if an incomplete message is found
3989 if (!msg.complete())
3992 // at this point, any failure means we can delete the current message
3995 // Scan for message start
3996 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
3997 LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
4003 CMessageHeader& hdr = msg.hdr;
4006 LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
4009 string strCommand = hdr.GetCommand();
4012 unsigned int nMessageSize = hdr.nMessageSize;
4015 CDataStream& vRecv = msg.vRecv;
4016 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4017 unsigned int nChecksum = 0;
4018 memcpy(&nChecksum, &hash, sizeof(nChecksum));
4019 if (nChecksum != hdr.nChecksum)
4021 LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4022 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
4030 fRet = ProcessMessage(pfrom, strCommand, vRecv);
4031 boost::this_thread::interruption_point();
4033 catch (std::ios_base::failure& e)
4035 if (strstr(e.what(), "end of data"))
4037 // Allow exceptions from under-length message on vRecv
4038 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
4040 else if (strstr(e.what(), "size too large"))
4042 // Allow exceptions from over-long size
4043 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4047 PrintExceptionContinue(&e, "ProcessMessages()");
4050 catch (boost::thread_interrupted) {
4053 catch (std::exception& e) {
4054 PrintExceptionContinue(&e, "ProcessMessages()");
4056 PrintExceptionContinue(NULL, "ProcessMessages()");
4060 LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4063 // In case the connection got shut down, its receive buffer was wiped
4064 if (!pfrom->fDisconnect)
4065 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4071 bool SendMessages(CNode* pto, bool fSendTrickle)
4074 // Don't send anything until we get their version message
4075 if (pto->nVersion == 0)
4081 bool pingSend = false;
4082 if (pto->fPingQueued) {
4083 // RPC ping request by user
4086 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
4087 // Ping automatically sent as a keepalive
4092 while (nonce == 0) {
4093 RAND_bytes((unsigned char*)&nonce, sizeof(nonce));
4095 pto->nPingNonceSent = nonce;
4096 pto->fPingQueued = false;
4097 if (pto->nVersion > BIP0031_VERSION) {
4098 // Take timestamp as close as possible before transmitting ping
4099 pto->nPingUsecStart = GetTimeMicros();
4100 pto->PushMessage("ping", nonce);
4102 // Peer is too old to support ping command with nonce, pong will never arrive, disable timing
4103 pto->nPingUsecStart = 0;
4104 pto->PushMessage("ping");
4108 // Address refresh broadcast
4109 static int64 nLastRebroadcast;
4110 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4114 BOOST_FOREACH(CNode* pnode, vNodes)
4116 // Periodically clear setAddrKnown to allow refresh broadcasts
4117 if (nLastRebroadcast)
4118 pnode->setAddrKnown.clear();
4120 // Rebroadcast our address
4123 CAddress addr = GetLocalAddress(&pnode->addr);
4124 if (addr.IsRoutable())
4125 pnode->PushAddress(addr);
4129 nLastRebroadcast = GetTime();
4137 vector<CAddress> vAddr;
4138 vAddr.reserve(pto->vAddrToSend.size());
4139 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4141 // returns true if wasn't already contained in the set
4142 if (pto->setAddrKnown.insert(addr).second)
4144 vAddr.push_back(addr);
4145 // receiver rejects addr messages larger than 1000
4146 if (vAddr.size() >= 1000)
4148 pto->PushMessage("addr", vAddr);
4153 pto->vAddrToSend.clear();
4155 pto->PushMessage("addr", vAddr);
4158 TRY_LOCK(cs_main, lockMain);
4163 if (pto->fStartSync && !fImporting && !fReindex) {
4164 pto->fStartSync = false;
4165 PushGetBlocks(pto, chainActive.Tip(), uint256(0));
4168 // Resend wallet transactions that haven't gotten in a block yet
4169 // Except during reindex, importing and IBD, when old wallet
4170 // transactions become unconfirmed and spams other nodes.
4171 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4173 g_signals.Broadcast();
4177 // Message: inventory
4180 vector<CInv> vInvWait;
4182 LOCK(pto->cs_inventory);
4183 vInv.reserve(pto->vInventoryToSend.size());
4184 vInvWait.reserve(pto->vInventoryToSend.size());
4185 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4187 if (pto->setInventoryKnown.count(inv))
4190 // trickle out tx inv to protect privacy
4191 if (inv.type == MSG_TX && !fSendTrickle)
4193 // 1/4 of tx invs blast to all immediately
4194 static uint256 hashSalt;
4196 hashSalt = GetRandHash();
4197 uint256 hashRand = inv.hash ^ hashSalt;
4198 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4199 bool fTrickleWait = ((hashRand & 3) != 0);
4203 vInvWait.push_back(inv);
4208 // returns true if wasn't already contained in the set
4209 if (pto->setInventoryKnown.insert(inv).second)
4211 vInv.push_back(inv);
4212 if (vInv.size() >= 1000)
4214 pto->PushMessage("inv", vInv);
4219 pto->vInventoryToSend = vInvWait;
4222 pto->PushMessage("inv", vInv);
4228 vector<CInv> vGetData;
4229 int64 nNow = GetTime() * 1000000;
4230 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4232 const CInv& inv = (*pto->mapAskFor.begin()).second;
4233 if (!AlreadyHave(inv))
4236 LogPrint("net", "sending getdata: %s\n", inv.ToString().c_str());
4237 vGetData.push_back(inv);
4238 if (vGetData.size() >= 1000)
4240 pto->PushMessage("getdata", vGetData);
4244 pto->mapAskFor.erase(pto->mapAskFor.begin());
4246 if (!vGetData.empty())
4247 pto->PushMessage("getdata", vGetData);
4264 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4265 for (; it1 != mapBlockIndex.end(); it1++)
4266 delete (*it1).second;
4267 mapBlockIndex.clear();
4270 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4271 for (; it2 != mapOrphanBlocks.end(); it2++)
4272 delete (*it2).second;
4273 mapOrphanBlocks.clear();
4275 // orphan transactions
4276 mapOrphanTransactions.clear();
4278 } instance_of_cmaincleanup;