[depends] native ccache 3.2.4
[bitcoinplatinum.git] / src / main.cpp
blob9016fe42a0c90dd1f20e86082274d7610f1b250b
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "main.h"
8 #include "addrman.h"
9 #include "alert.h"
10 #include "arith_uint256.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "consensus/consensus.h"
15 #include "consensus/validation.h"
16 #include "hash.h"
17 #include "init.h"
18 #include "merkleblock.h"
19 #include "net.h"
20 #include "policy/policy.h"
21 #include "pow.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "script/script.h"
25 #include "script/sigcache.h"
26 #include "script/standard.h"
27 #include "tinyformat.h"
28 #include "txdb.h"
29 #include "txmempool.h"
30 #include "ui_interface.h"
31 #include "undo.h"
32 #include "util.h"
33 #include "utilmoneystr.h"
34 #include "utilstrencodings.h"
35 #include "validationinterface.h"
37 #include <sstream>
39 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/filesystem.hpp>
41 #include <boost/filesystem/fstream.hpp>
42 #include <boost/math/distributions/poisson.hpp>
43 #include <boost/thread.hpp>
45 using namespace std;
47 #if defined(NDEBUG)
48 # error "Bitcoin cannot be compiled without assertions."
49 #endif
51 /**
52 * Global state
55 CCriticalSection cs_main;
57 BlockMap mapBlockIndex;
58 CChain chainActive;
59 CBlockIndex *pindexBestHeader = NULL;
60 int64_t nTimeBestReceived = 0;
61 CWaitableCriticalSection csBestBlock;
62 CConditionVariable cvBlockChange;
63 int nScriptCheckThreads = 0;
64 bool fImporting = false;
65 bool fReindex = false;
66 bool fTxIndex = false;
67 bool fHavePruned = false;
68 bool fPruneMode = false;
69 bool fIsBareMultisigStd = true;
70 bool fRequireStandard = true;
71 bool fCheckBlockIndex = false;
72 bool fCheckpointsEnabled = true;
73 size_t nCoinCacheUsage = 5000 * 300;
74 uint64_t nPruneTarget = 0;
75 bool fAlerts = DEFAULT_ALERTS;
77 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying, mining and transaction creation) */
78 CFeeRate minRelayTxFee = CFeeRate(1000);
80 CTxMemPool mempool(::minRelayTxFee);
82 struct COrphanTx {
83 CTransaction tx;
84 NodeId fromPeer;
86 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
87 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
88 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
90 /**
91 * Returns true if there are nRequired or more blocks of minVersion or above
92 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
94 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
95 static void CheckBlockIndex();
97 /** Constant stuff for coinbase transactions we create: */
98 CScript COINBASE_FLAGS;
100 const string strMessageMagic = "Bitcoin Signed Message:\n";
102 // Internal stuff
103 namespace {
105 struct CBlockIndexWorkComparator
107 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
108 // First sort by most total work, ...
109 if (pa->nChainWork > pb->nChainWork) return false;
110 if (pa->nChainWork < pb->nChainWork) return true;
112 // ... then by earliest time received, ...
113 if (pa->nSequenceId < pb->nSequenceId) return false;
114 if (pa->nSequenceId > pb->nSequenceId) return true;
116 // Use pointer address as tie breaker (should only happen with blocks
117 // loaded from disk, as those all have id 0).
118 if (pa < pb) return false;
119 if (pa > pb) return true;
121 // Identical blocks.
122 return false;
126 CBlockIndex *pindexBestInvalid;
129 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
130 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
131 * missing the data for the block.
133 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
134 /** Number of nodes with fSyncStarted. */
135 int nSyncStarted = 0;
136 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
137 * Pruned nodes may have entries where B is missing data.
139 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
141 CCriticalSection cs_LastBlockFile;
142 std::vector<CBlockFileInfo> vinfoBlockFile;
143 int nLastBlockFile = 0;
144 /** Global flag to indicate we should check to see if there are
145 * block/undo files that should be deleted. Set on startup
146 * or if we allocate more file space when we're in prune mode
148 bool fCheckForPruning = false;
151 * Every received block is assigned a unique and increasing identifier, so we
152 * know which one to give priority in case of a fork.
154 CCriticalSection cs_nBlockSequenceId;
155 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
156 uint32_t nBlockSequenceId = 1;
159 * Sources of received blocks, saved to be able to send them reject
160 * messages or ban them when processing happens afterwards. Protected by
161 * cs_main.
163 map<uint256, NodeId> mapBlockSource;
166 * Filter for transactions that were recently rejected by
167 * AcceptToMemoryPool. These are not rerequested until the chain tip
168 * changes, at which point the entire filter is reset. Protected by
169 * cs_main.
171 * Without this filter we'd be re-requesting txs from each of our peers,
172 * increasing bandwidth consumption considerably. For instance, with 100
173 * peers, half of which relay a tx we don't accept, that might be a 50x
174 * bandwidth increase. A flooding attacker attempting to roll-over the
175 * filter using minimum-sized, 60byte, transactions might manage to send
176 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
177 * two minute window to send invs to us.
179 * Decreasing the false positive rate is fairly cheap, so we pick one in a
180 * million to make it highly unlikely for users to have issues with this
181 * filter.
183 * Memory used: 1.7MB
185 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
186 uint256 hashRecentRejectsChainTip;
188 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
189 struct QueuedBlock {
190 uint256 hash;
191 CBlockIndex *pindex; //! Optional.
192 int64_t nTime; //! Time of "getdata" request in microseconds.
193 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
194 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
196 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
198 /** Number of blocks in flight with validated headers. */
199 int nQueuedValidatedHeaders = 0;
201 /** Number of preferable block download peers. */
202 int nPreferredDownload = 0;
204 /** Dirty block index entries. */
205 set<CBlockIndex*> setDirtyBlockIndex;
207 /** Dirty block file entries. */
208 set<int> setDirtyFileInfo;
209 } // anon namespace
211 //////////////////////////////////////////////////////////////////////////////
213 // Registration of network node signals.
216 namespace {
218 struct CBlockReject {
219 unsigned char chRejectCode;
220 string strRejectReason;
221 uint256 hashBlock;
225 * Maintain validation-specific state about nodes, protected by cs_main, instead
226 * by CNode's own locks. This simplifies asynchronous operation, where
227 * processing of incoming data is done after the ProcessMessage call returns,
228 * and we're no longer holding the node's locks.
230 struct CNodeState {
231 //! The peer's address
232 CService address;
233 //! Whether we have a fully established connection.
234 bool fCurrentlyConnected;
235 //! Accumulated misbehaviour score for this peer.
236 int nMisbehavior;
237 //! Whether this peer should be disconnected and banned (unless whitelisted).
238 bool fShouldBan;
239 //! String name of this peer (debugging/logging purposes).
240 std::string name;
241 //! List of asynchronously-determined block rejections to notify this peer about.
242 std::vector<CBlockReject> rejects;
243 //! The best known block we know this peer has announced.
244 CBlockIndex *pindexBestKnownBlock;
245 //! The hash of the last unknown block this peer has announced.
246 uint256 hashLastUnknownBlock;
247 //! The last full block we both have.
248 CBlockIndex *pindexLastCommonBlock;
249 //! Whether we've started headers synchronization with this peer.
250 bool fSyncStarted;
251 //! Since when we're stalling block download progress (in microseconds), or 0.
252 int64_t nStallingSince;
253 list<QueuedBlock> vBlocksInFlight;
254 int nBlocksInFlight;
255 int nBlocksInFlightValidHeaders;
256 //! Whether we consider this a preferred download peer.
257 bool fPreferredDownload;
259 CNodeState() {
260 fCurrentlyConnected = false;
261 nMisbehavior = 0;
262 fShouldBan = false;
263 pindexBestKnownBlock = NULL;
264 hashLastUnknownBlock.SetNull();
265 pindexLastCommonBlock = NULL;
266 fSyncStarted = false;
267 nStallingSince = 0;
268 nBlocksInFlight = 0;
269 nBlocksInFlightValidHeaders = 0;
270 fPreferredDownload = false;
274 /** Map maintaining per-node state. Requires cs_main. */
275 map<NodeId, CNodeState> mapNodeState;
277 // Requires cs_main.
278 CNodeState *State(NodeId pnode) {
279 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
280 if (it == mapNodeState.end())
281 return NULL;
282 return &it->second;
285 int GetHeight()
287 LOCK(cs_main);
288 return chainActive.Height();
291 void UpdatePreferredDownload(CNode* node, CNodeState* state)
293 nPreferredDownload -= state->fPreferredDownload;
295 // Whether this node should be marked as a preferred download node.
296 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
298 nPreferredDownload += state->fPreferredDownload;
301 // Returns time at which to timeout block request (nTime in microseconds)
302 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
304 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
307 void InitializeNode(NodeId nodeid, const CNode *pnode) {
308 LOCK(cs_main);
309 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
310 state.name = pnode->addrName;
311 state.address = pnode->addr;
314 void FinalizeNode(NodeId nodeid) {
315 LOCK(cs_main);
316 CNodeState *state = State(nodeid);
318 if (state->fSyncStarted)
319 nSyncStarted--;
321 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
322 AddressCurrentlyConnected(state->address);
325 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
326 mapBlocksInFlight.erase(entry.hash);
327 EraseOrphansFor(nodeid);
328 nPreferredDownload -= state->fPreferredDownload;
330 mapNodeState.erase(nodeid);
333 // Requires cs_main.
334 // Returns a bool indicating whether we requested this block.
335 bool MarkBlockAsReceived(const uint256& hash) {
336 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
337 if (itInFlight != mapBlocksInFlight.end()) {
338 CNodeState *state = State(itInFlight->second.first);
339 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
340 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
341 state->vBlocksInFlight.erase(itInFlight->second.second);
342 state->nBlocksInFlight--;
343 state->nStallingSince = 0;
344 mapBlocksInFlight.erase(itInFlight);
345 return true;
347 return false;
350 // Requires cs_main.
351 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
352 CNodeState *state = State(nodeid);
353 assert(state != NULL);
355 // Make sure it's not listed somewhere already.
356 MarkBlockAsReceived(hash);
358 int64_t nNow = GetTimeMicros();
359 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
360 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
361 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
362 state->nBlocksInFlight++;
363 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
364 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
367 /** Check whether the last unknown block a peer advertized is not yet known. */
368 void ProcessBlockAvailability(NodeId nodeid) {
369 CNodeState *state = State(nodeid);
370 assert(state != NULL);
372 if (!state->hashLastUnknownBlock.IsNull()) {
373 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
374 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
375 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
376 state->pindexBestKnownBlock = itOld->second;
377 state->hashLastUnknownBlock.SetNull();
382 /** Update tracking information about which blocks a peer is assumed to have. */
383 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
384 CNodeState *state = State(nodeid);
385 assert(state != NULL);
387 ProcessBlockAvailability(nodeid);
389 BlockMap::iterator it = mapBlockIndex.find(hash);
390 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
391 // An actually better block was announced.
392 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
393 state->pindexBestKnownBlock = it->second;
394 } else {
395 // An unknown block was announced; just assume that the latest one is the best one.
396 state->hashLastUnknownBlock = hash;
400 /** Find the last common ancestor two blocks have.
401 * Both pa and pb must be non-NULL. */
402 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
403 if (pa->nHeight > pb->nHeight) {
404 pa = pa->GetAncestor(pb->nHeight);
405 } else if (pb->nHeight > pa->nHeight) {
406 pb = pb->GetAncestor(pa->nHeight);
409 while (pa != pb && pa && pb) {
410 pa = pa->pprev;
411 pb = pb->pprev;
414 // Eventually all chain branches meet at the genesis block.
415 assert(pa == pb);
416 return pa;
419 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
420 * at most count entries. */
421 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
422 if (count == 0)
423 return;
425 vBlocks.reserve(vBlocks.size() + count);
426 CNodeState *state = State(nodeid);
427 assert(state != NULL);
429 // Make sure pindexBestKnownBlock is up to date, we'll need it.
430 ProcessBlockAvailability(nodeid);
432 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
433 // This peer has nothing interesting.
434 return;
437 if (state->pindexLastCommonBlock == NULL) {
438 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
439 // Guessing wrong in either direction is not a problem.
440 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
443 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
444 // of its current tip anymore. Go back enough to fix that.
445 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
446 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
447 return;
449 std::vector<CBlockIndex*> vToFetch;
450 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
451 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
452 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
453 // download that next block if the window were 1 larger.
454 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
455 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
456 NodeId waitingfor = -1;
457 while (pindexWalk->nHeight < nMaxHeight) {
458 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
459 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
460 // as iterating over ~100 CBlockIndex* entries anyway.
461 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
462 vToFetch.resize(nToFetch);
463 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
464 vToFetch[nToFetch - 1] = pindexWalk;
465 for (unsigned int i = nToFetch - 1; i > 0; i--) {
466 vToFetch[i - 1] = vToFetch[i]->pprev;
469 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
470 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
471 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
472 // already part of our chain (and therefore don't need it even if pruned).
473 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
474 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
475 // We consider the chain that this peer is on invalid.
476 return;
478 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
479 if (pindex->nChainTx)
480 state->pindexLastCommonBlock = pindex;
481 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
482 // The block is not already downloaded, and not yet in flight.
483 if (pindex->nHeight > nWindowEnd) {
484 // We reached the end of the window.
485 if (vBlocks.size() == 0 && waitingfor != nodeid) {
486 // We aren't able to fetch anything, but we would be if the download window was one larger.
487 nodeStaller = waitingfor;
489 return;
491 vBlocks.push_back(pindex);
492 if (vBlocks.size() == count) {
493 return;
495 } else if (waitingfor == -1) {
496 // This is the first already-in-flight block.
497 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
503 } // anon namespace
505 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
506 LOCK(cs_main);
507 CNodeState *state = State(nodeid);
508 if (state == NULL)
509 return false;
510 stats.nMisbehavior = state->nMisbehavior;
511 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
512 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
513 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
514 if (queue.pindex)
515 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
517 return true;
520 void RegisterNodeSignals(CNodeSignals& nodeSignals)
522 nodeSignals.GetHeight.connect(&GetHeight);
523 nodeSignals.ProcessMessages.connect(&ProcessMessages);
524 nodeSignals.SendMessages.connect(&SendMessages);
525 nodeSignals.InitializeNode.connect(&InitializeNode);
526 nodeSignals.FinalizeNode.connect(&FinalizeNode);
529 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
531 nodeSignals.GetHeight.disconnect(&GetHeight);
532 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
533 nodeSignals.SendMessages.disconnect(&SendMessages);
534 nodeSignals.InitializeNode.disconnect(&InitializeNode);
535 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
538 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
540 // Find the first block the caller has in the main chain
541 BOOST_FOREACH(const uint256& hash, locator.vHave) {
542 BlockMap::iterator mi = mapBlockIndex.find(hash);
543 if (mi != mapBlockIndex.end())
545 CBlockIndex* pindex = (*mi).second;
546 if (chain.Contains(pindex))
547 return pindex;
550 return chain.Genesis();
553 CCoinsViewCache *pcoinsTip = NULL;
554 CBlockTreeDB *pblocktree = NULL;
556 //////////////////////////////////////////////////////////////////////////////
558 // mapOrphanTransactions
561 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
563 uint256 hash = tx.GetHash();
564 if (mapOrphanTransactions.count(hash))
565 return false;
567 // Ignore big transactions, to avoid a
568 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
569 // large transaction with a missing parent then we assume
570 // it will rebroadcast it later, after the parent transaction(s)
571 // have been mined or received.
572 // 10,000 orphans, each of which is at most 5,000 bytes big is
573 // at most 500 megabytes of orphans:
574 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
575 if (sz > 5000)
577 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
578 return false;
581 mapOrphanTransactions[hash].tx = tx;
582 mapOrphanTransactions[hash].fromPeer = peer;
583 BOOST_FOREACH(const CTxIn& txin, tx.vin)
584 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
586 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
587 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
588 return true;
591 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
593 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
594 if (it == mapOrphanTransactions.end())
595 return;
596 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
598 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
599 if (itPrev == mapOrphanTransactionsByPrev.end())
600 continue;
601 itPrev->second.erase(hash);
602 if (itPrev->second.empty())
603 mapOrphanTransactionsByPrev.erase(itPrev);
605 mapOrphanTransactions.erase(it);
608 void EraseOrphansFor(NodeId peer)
610 int nErased = 0;
611 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
612 while (iter != mapOrphanTransactions.end())
614 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
615 if (maybeErase->second.fromPeer == peer)
617 EraseOrphanTx(maybeErase->second.tx.GetHash());
618 ++nErased;
621 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
625 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
627 unsigned int nEvicted = 0;
628 while (mapOrphanTransactions.size() > nMaxOrphans)
630 // Evict a random orphan:
631 uint256 randomhash = GetRandHash();
632 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
633 if (it == mapOrphanTransactions.end())
634 it = mapOrphanTransactions.begin();
635 EraseOrphanTx(it->first);
636 ++nEvicted;
638 return nEvicted;
641 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
643 if (tx.nLockTime == 0)
644 return true;
645 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
646 return true;
647 BOOST_FOREACH(const CTxIn& txin, tx.vin)
648 if (!txin.IsFinal())
649 return false;
650 return true;
653 bool CheckFinalTx(const CTransaction &tx, int flags)
655 AssertLockHeld(cs_main);
657 // By convention a negative value for flags indicates that the
658 // current network-enforced consensus rules should be used. In
659 // a future soft-fork scenario that would mean checking which
660 // rules would be enforced for the next block and setting the
661 // appropriate flags. At the present time no soft-forks are
662 // scheduled, so no flags are set.
663 flags = std::max(flags, 0);
665 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
666 // nLockTime because when IsFinalTx() is called within
667 // CBlock::AcceptBlock(), the height of the block *being*
668 // evaluated is what is used. Thus if we want to know if a
669 // transaction can be part of the *next* block, we need to call
670 // IsFinalTx() with one more than chainActive.Height().
671 const int nBlockHeight = chainActive.Height() + 1;
673 // Timestamps on the other hand don't get any special treatment,
674 // because we can't know what timestamp the next block will have,
675 // and there aren't timestamp applications where it matters.
676 // However this changes once median past time-locks are enforced:
677 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
678 ? chainActive.Tip()->GetMedianTimePast()
679 : GetAdjustedTime();
681 return IsFinalTx(tx, nBlockHeight, nBlockTime);
684 unsigned int GetLegacySigOpCount(const CTransaction& tx)
686 unsigned int nSigOps = 0;
687 BOOST_FOREACH(const CTxIn& txin, tx.vin)
689 nSigOps += txin.scriptSig.GetSigOpCount(false);
691 BOOST_FOREACH(const CTxOut& txout, tx.vout)
693 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
695 return nSigOps;
698 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
700 if (tx.IsCoinBase())
701 return 0;
703 unsigned int nSigOps = 0;
704 for (unsigned int i = 0; i < tx.vin.size(); i++)
706 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
707 if (prevout.scriptPubKey.IsPayToScriptHash())
708 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
710 return nSigOps;
720 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
722 // Basic checks that don't depend on any context
723 if (tx.vin.empty())
724 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
725 if (tx.vout.empty())
726 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
727 // Size limits
728 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
729 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
731 // Check for negative or overflow output values
732 CAmount nValueOut = 0;
733 BOOST_FOREACH(const CTxOut& txout, tx.vout)
735 if (txout.nValue < 0)
736 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
737 if (txout.nValue > MAX_MONEY)
738 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
739 nValueOut += txout.nValue;
740 if (!MoneyRange(nValueOut))
741 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
744 // Check for duplicate inputs
745 set<COutPoint> vInOutPoints;
746 BOOST_FOREACH(const CTxIn& txin, tx.vin)
748 if (vInOutPoints.count(txin.prevout))
749 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
750 vInOutPoints.insert(txin.prevout);
753 if (tx.IsCoinBase())
755 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
756 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
758 else
760 BOOST_FOREACH(const CTxIn& txin, tx.vin)
761 if (txin.prevout.IsNull())
762 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
765 return true;
768 CAmount GetMinRelayFee(const CTransaction& tx, const CTxMemPool& pool, unsigned int nBytes, bool fAllowFree)
770 uint256 hash = tx.GetHash();
771 double dPriorityDelta = 0;
772 CAmount nFeeDelta = 0;
773 pool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
774 if (dPriorityDelta > 0 || nFeeDelta > 0)
775 return 0;
777 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
779 if (fAllowFree)
781 // There is a free transaction area in blocks created by most miners,
782 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
783 // to be considered to fall into this category. We don't want to encourage sending
784 // multiple transactions instead of one big transaction to avoid fees.
785 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
786 nMinFee = 0;
789 if (!MoneyRange(nMinFee))
790 nMinFee = MAX_MONEY;
791 return nMinFee;
794 /** Convert CValidationState to a human-readable message for logging */
795 static std::string FormatStateMessage(const CValidationState &state)
797 return strprintf("%s%s (code %i)",
798 state.GetRejectReason(),
799 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
800 state.GetRejectCode());
803 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
804 bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee)
806 AssertLockHeld(cs_main);
807 if (pfMissingInputs)
808 *pfMissingInputs = false;
810 if (!CheckTransaction(tx, state))
811 return false;
813 // Coinbase is only valid in a block, not as a loose transaction
814 if (tx.IsCoinBase())
815 return state.DoS(100, false, REJECT_INVALID, "coinbase");
817 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
818 string reason;
819 if (fRequireStandard && !IsStandardTx(tx, reason))
820 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
822 // Only accept nLockTime-using transactions that can be mined in the next
823 // block; we don't want our mempool filled up with transactions that can't
824 // be mined yet.
825 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
826 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
828 // is it already in the memory pool?
829 uint256 hash = tx.GetHash();
830 if (pool.exists(hash))
831 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
833 // Check for conflicts with in-memory transactions
835 LOCK(pool.cs); // protect pool.mapNextTx
836 for (unsigned int i = 0; i < tx.vin.size(); i++)
838 COutPoint outpoint = tx.vin[i].prevout;
839 if (pool.mapNextTx.count(outpoint))
841 // Disable replacement feature for now
842 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
848 CCoinsView dummy;
849 CCoinsViewCache view(&dummy);
851 CAmount nValueIn = 0;
853 LOCK(pool.cs);
854 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
855 view.SetBackend(viewMemPool);
857 // do we already have it?
858 if (view.HaveCoins(hash))
859 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
861 // do all inputs exist?
862 // Note that this does not check for the presence of actual outputs (see the next check for that),
863 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
864 BOOST_FOREACH(const CTxIn txin, tx.vin) {
865 if (!view.HaveCoins(txin.prevout.hash)) {
866 if (pfMissingInputs)
867 *pfMissingInputs = true;
868 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
872 // are the actual inputs available?
873 if (!view.HaveInputs(tx))
874 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
876 // Bring the best block into scope
877 view.GetBestBlock();
879 nValueIn = view.GetValueIn(tx);
881 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
882 view.SetBackend(dummy);
885 // Check for non-standard pay-to-script-hash in inputs
886 if (fRequireStandard && !AreInputsStandard(tx, view))
887 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
889 // Check that the transaction doesn't have an excessive number of
890 // sigops, making it impossible to mine. Since the coinbase transaction
891 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
892 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
893 // merely non-standard transaction.
894 unsigned int nSigOps = GetLegacySigOpCount(tx);
895 nSigOps += GetP2SHSigOpCount(tx, view);
896 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
897 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
898 strprintf("%d > %d", nSigOps, MAX_STANDARD_TX_SIGOPS));
900 CAmount nValueOut = tx.GetValueOut();
901 CAmount nFees = nValueIn-nValueOut;
902 double dPriority = view.GetPriority(tx, chainActive.Height());
904 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), pool.HasNoInputsOf(tx));
905 unsigned int nSize = entry.GetTxSize();
907 // Don't accept it if it can't get into a block
908 CAmount txMinFee = GetMinRelayFee(tx, pool, nSize, true);
909 if (fLimitFree && nFees < txMinFee)
910 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false,
911 strprintf("%d < %d", nFees, txMinFee));
913 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
914 if (mempoolRejectFee > 0 && nFees < mempoolRejectFee) {
915 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
916 } else if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
917 // Require that free transactions have sufficient priority to be mined in the next block.
918 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
921 // Continuously rate-limit free (really, very-low-fee) transactions
922 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
923 // be annoying or make others' transactions take longer to confirm.
924 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
926 static CCriticalSection csFreeLimiter;
927 static double dFreeCount;
928 static int64_t nLastTime;
929 int64_t nNow = GetTime();
931 LOCK(csFreeLimiter);
933 // Use an exponentially decaying ~10-minute window:
934 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
935 nLastTime = nNow;
936 // -limitfreerelay unit is thousand-bytes-per-minute
937 // At default rate it would take over a month to fill 1GB
938 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
939 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
940 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
941 dFreeCount += nSize;
944 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
945 return state.Invalid(false,
946 REJECT_HIGHFEE, "absurdly-high-fee",
947 strprintf("%d > %d", nFees, ::minRelayTxFee.GetFee(nSize) * 10000));
949 // Calculate in-mempool ancestors, up to a limit.
950 CTxMemPool::setEntries setAncestors;
951 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
952 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
953 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
954 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
955 std::string errString;
956 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
957 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
960 // Check against previous transactions
961 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
962 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
963 return false;
965 // Check again against just the consensus-critical mandatory script
966 // verification flags, in case of bugs in the standard flags that cause
967 // transactions to pass as valid when they're actually invalid. For
968 // instance the STRICTENC flag was incorrectly allowing certain
969 // CHECKSIG NOT scripts to pass, even though they were invalid.
971 // There is a similar check in CreateNewBlock() to prevent creating
972 // invalid blocks, however allowing such transactions into the mempool
973 // can be exploited as a DoS attack.
974 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
976 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
977 __func__, hash.ToString(), FormatStateMessage(state));
980 // Store transaction in memory
981 pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload());
983 // trim mempool and check if tx was trimmed
984 if (!fOverrideMempoolLimit) {
985 int expired = pool.Expire(GetTime() - GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
986 if (expired != 0)
987 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
989 pool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
990 if (!pool.exists(tx.GetHash()))
991 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
995 SyncWithWallets(tx, NULL);
997 return true;
1000 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1001 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1003 CBlockIndex *pindexSlow = NULL;
1005 LOCK(cs_main);
1007 if (mempool.lookup(hash, txOut))
1009 return true;
1012 if (fTxIndex) {
1013 CDiskTxPos postx;
1014 if (pblocktree->ReadTxIndex(hash, postx)) {
1015 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1016 if (file.IsNull())
1017 return error("%s: OpenBlockFile failed", __func__);
1018 CBlockHeader header;
1019 try {
1020 file >> header;
1021 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1022 file >> txOut;
1023 } catch (const std::exception& e) {
1024 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1026 hashBlock = header.GetHash();
1027 if (txOut.GetHash() != hash)
1028 return error("%s: txid mismatch", __func__);
1029 return true;
1033 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1034 int nHeight = -1;
1036 CCoinsViewCache &view = *pcoinsTip;
1037 const CCoins* coins = view.AccessCoins(hash);
1038 if (coins)
1039 nHeight = coins->nHeight;
1041 if (nHeight > 0)
1042 pindexSlow = chainActive[nHeight];
1045 if (pindexSlow) {
1046 CBlock block;
1047 if (ReadBlockFromDisk(block, pindexSlow)) {
1048 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1049 if (tx.GetHash() == hash) {
1050 txOut = tx;
1051 hashBlock = pindexSlow->GetBlockHash();
1052 return true;
1058 return false;
1066 //////////////////////////////////////////////////////////////////////////////
1068 // CBlock and CBlockIndex
1071 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1073 // Open history file to append
1074 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1075 if (fileout.IsNull())
1076 return error("WriteBlockToDisk: OpenBlockFile failed");
1078 // Write index header
1079 unsigned int nSize = fileout.GetSerializeSize(block);
1080 fileout << FLATDATA(messageStart) << nSize;
1082 // Write block
1083 long fileOutPos = ftell(fileout.Get());
1084 if (fileOutPos < 0)
1085 return error("WriteBlockToDisk: ftell failed");
1086 pos.nPos = (unsigned int)fileOutPos;
1087 fileout << block;
1089 return true;
1092 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1094 block.SetNull();
1096 // Open history file to read
1097 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1098 if (filein.IsNull())
1099 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1101 // Read block
1102 try {
1103 filein >> block;
1105 catch (const std::exception& e) {
1106 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1109 // Check the header
1110 if (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
1111 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1113 return true;
1116 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1118 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1119 return false;
1120 if (block.GetHash() != pindex->GetBlockHash())
1121 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1122 pindex->ToString(), pindex->GetBlockPos().ToString());
1123 return true;
1126 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1128 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1129 // Force block reward to zero when right shift is undefined.
1130 if (halvings >= 64)
1131 return 0;
1133 CAmount nSubsidy = 50 * COIN;
1134 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1135 nSubsidy >>= halvings;
1136 return nSubsidy;
1139 bool IsInitialBlockDownload()
1141 const CChainParams& chainParams = Params();
1142 LOCK(cs_main);
1143 if (fImporting || fReindex)
1144 return true;
1145 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1146 return true;
1147 static bool lockIBDState = false;
1148 if (lockIBDState)
1149 return false;
1150 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1151 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1152 if (!state)
1153 lockIBDState = true;
1154 return state;
1157 bool fLargeWorkForkFound = false;
1158 bool fLargeWorkInvalidChainFound = false;
1159 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1161 void CheckForkWarningConditions()
1163 AssertLockHeld(cs_main);
1164 // Before we get past initial download, we cannot reliably alert about forks
1165 // (we assume we don't get stuck on a fork before the last checkpoint)
1166 if (IsInitialBlockDownload())
1167 return;
1169 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1170 // of our head, drop it
1171 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1172 pindexBestForkTip = NULL;
1174 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1176 if (!fLargeWorkForkFound && pindexBestForkBase)
1178 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1179 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1180 CAlert::Notify(warning, true);
1182 if (pindexBestForkTip && pindexBestForkBase)
1184 LogPrintf("%s: 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", __func__,
1185 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1186 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1187 fLargeWorkForkFound = true;
1189 else
1191 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1192 fLargeWorkInvalidChainFound = true;
1195 else
1197 fLargeWorkForkFound = false;
1198 fLargeWorkInvalidChainFound = false;
1202 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1204 AssertLockHeld(cs_main);
1205 // If we are on a fork that is sufficiently large, set a warning flag
1206 CBlockIndex* pfork = pindexNewForkTip;
1207 CBlockIndex* plonger = chainActive.Tip();
1208 while (pfork && pfork != plonger)
1210 while (plonger && plonger->nHeight > pfork->nHeight)
1211 plonger = plonger->pprev;
1212 if (pfork == plonger)
1213 break;
1214 pfork = pfork->pprev;
1217 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1218 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1219 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1220 // hash rate operating on the fork.
1221 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1222 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1223 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1224 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1225 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1226 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1228 pindexBestForkTip = pindexNewForkTip;
1229 pindexBestForkBase = pfork;
1232 CheckForkWarningConditions();
1235 // Requires cs_main.
1236 void Misbehaving(NodeId pnode, int howmuch)
1238 if (howmuch == 0)
1239 return;
1241 CNodeState *state = State(pnode);
1242 if (state == NULL)
1243 return;
1245 state->nMisbehavior += howmuch;
1246 int banscore = GetArg("-banscore", 100);
1247 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1249 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1250 state->fShouldBan = true;
1251 } else
1252 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1255 void static InvalidChainFound(CBlockIndex* pindexNew)
1257 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1258 pindexBestInvalid = pindexNew;
1260 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1261 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1262 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1263 pindexNew->GetBlockTime()));
1264 CBlockIndex *tip = chainActive.Tip();
1265 assert (tip);
1266 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1267 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1268 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1269 CheckForkWarningConditions();
1272 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1273 int nDoS = 0;
1274 if (state.IsInvalid(nDoS)) {
1275 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1276 if (it != mapBlockSource.end() && State(it->second)) {
1277 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
1278 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1279 State(it->second)->rejects.push_back(reject);
1280 if (nDoS > 0)
1281 Misbehaving(it->second, nDoS);
1284 if (!state.CorruptionPossible()) {
1285 pindex->nStatus |= BLOCK_FAILED_VALID;
1286 setDirtyBlockIndex.insert(pindex);
1287 setBlockIndexCandidates.erase(pindex);
1288 InvalidChainFound(pindex);
1292 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1294 // mark inputs spent
1295 if (!tx.IsCoinBase()) {
1296 txundo.vprevout.reserve(tx.vin.size());
1297 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1298 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1299 unsigned nPos = txin.prevout.n;
1301 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1302 assert(false);
1303 // mark an outpoint spent, and construct undo information
1304 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1305 coins->Spend(nPos);
1306 if (coins->vout.size() == 0) {
1307 CTxInUndo& undo = txundo.vprevout.back();
1308 undo.nHeight = coins->nHeight;
1309 undo.fCoinBase = coins->fCoinBase;
1310 undo.nVersion = coins->nVersion;
1315 // add outputs
1316 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1319 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1321 CTxUndo txundo;
1322 UpdateCoins(tx, state, inputs, txundo, nHeight);
1325 bool CScriptCheck::operator()() {
1326 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1327 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1328 return false;
1330 return true;
1333 int GetSpendHeight(const CCoinsViewCache& inputs)
1335 LOCK(cs_main);
1336 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1337 return pindexPrev->nHeight + 1;
1340 namespace Consensus {
1341 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1343 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1344 // for an attacker to attempt to split the network.
1345 if (!inputs.HaveInputs(tx))
1346 return state.Invalid(false, 0, "", "Inputs unavailable");
1348 CAmount nValueIn = 0;
1349 CAmount nFees = 0;
1350 for (unsigned int i = 0; i < tx.vin.size(); i++)
1352 const COutPoint &prevout = tx.vin[i].prevout;
1353 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1354 assert(coins);
1356 // If prev is coinbase, check that it's matured
1357 if (coins->IsCoinBase()) {
1358 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1359 return state.Invalid(false,
1360 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1361 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1364 // Check for negative or overflow input values
1365 nValueIn += coins->vout[prevout.n].nValue;
1366 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1367 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1371 if (nValueIn < tx.GetValueOut())
1372 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1373 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1375 // Tally transaction fees
1376 CAmount nTxFee = nValueIn - tx.GetValueOut();
1377 if (nTxFee < 0)
1378 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1379 nFees += nTxFee;
1380 if (!MoneyRange(nFees))
1381 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1382 return true;
1384 }// namespace Consensus
1386 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1388 if (!tx.IsCoinBase())
1390 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1391 return false;
1393 if (pvChecks)
1394 pvChecks->reserve(tx.vin.size());
1396 // The first loop above does all the inexpensive checks.
1397 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1398 // Helps prevent CPU exhaustion attacks.
1400 // Skip ECDSA signature verification when connecting blocks
1401 // before the last block chain checkpoint. This is safe because block merkle hashes are
1402 // still computed and checked, and any change will be caught at the next checkpoint.
1403 if (fScriptChecks) {
1404 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1405 const COutPoint &prevout = tx.vin[i].prevout;
1406 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1407 assert(coins);
1409 // Verify signature
1410 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1411 if (pvChecks) {
1412 pvChecks->push_back(CScriptCheck());
1413 check.swap(pvChecks->back());
1414 } else if (!check()) {
1415 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1416 // Check whether the failure was caused by a
1417 // non-mandatory script verification check, such as
1418 // non-standard DER encodings or non-null dummy
1419 // arguments; if so, don't trigger DoS protection to
1420 // avoid splitting the network between upgraded and
1421 // non-upgraded nodes.
1422 CScriptCheck check(*coins, tx, i,
1423 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1424 if (check())
1425 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1427 // Failures of other flags indicate a transaction that is
1428 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1429 // such nodes as they are not following the protocol. That
1430 // said during an upgrade careful thought should be taken
1431 // as to the correct behavior - we may want to continue
1432 // peering with non-upgraded nodes even after a soft-fork
1433 // super-majority vote has passed.
1434 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1440 return true;
1443 namespace {
1445 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1447 // Open history file to append
1448 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1449 if (fileout.IsNull())
1450 return error("%s: OpenUndoFile failed", __func__);
1452 // Write index header
1453 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1454 fileout << FLATDATA(messageStart) << nSize;
1456 // Write undo data
1457 long fileOutPos = ftell(fileout.Get());
1458 if (fileOutPos < 0)
1459 return error("%s: ftell failed", __func__);
1460 pos.nPos = (unsigned int)fileOutPos;
1461 fileout << blockundo;
1463 // calculate & write checksum
1464 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1465 hasher << hashBlock;
1466 hasher << blockundo;
1467 fileout << hasher.GetHash();
1469 return true;
1472 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1474 // Open history file to read
1475 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1476 if (filein.IsNull())
1477 return error("%s: OpenBlockFile failed", __func__);
1479 // Read block
1480 uint256 hashChecksum;
1481 try {
1482 filein >> blockundo;
1483 filein >> hashChecksum;
1485 catch (const std::exception& e) {
1486 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1489 // Verify checksum
1490 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1491 hasher << hashBlock;
1492 hasher << blockundo;
1493 if (hashChecksum != hasher.GetHash())
1494 return error("%s: Checksum mismatch", __func__);
1496 return true;
1499 /** Abort with a message */
1500 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1502 strMiscWarning = strMessage;
1503 LogPrintf("*** %s\n", strMessage);
1504 uiInterface.ThreadSafeMessageBox(
1505 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1506 "", CClientUIInterface::MSG_ERROR);
1507 StartShutdown();
1508 return false;
1511 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1513 AbortNode(strMessage, userMessage);
1514 return state.Error(strMessage);
1517 } // anon namespace
1520 * Apply the undo operation of a CTxInUndo to the given chain state.
1521 * @param undo The undo object.
1522 * @param view The coins view to which to apply the changes.
1523 * @param out The out point that corresponds to the tx input.
1524 * @return True on success.
1526 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1528 bool fClean = true;
1530 CCoinsModifier coins = view.ModifyCoins(out.hash);
1531 if (undo.nHeight != 0) {
1532 // undo data contains height: this is the last output of the prevout tx being spent
1533 if (!coins->IsPruned())
1534 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1535 coins->Clear();
1536 coins->fCoinBase = undo.fCoinBase;
1537 coins->nHeight = undo.nHeight;
1538 coins->nVersion = undo.nVersion;
1539 } else {
1540 if (coins->IsPruned())
1541 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1543 if (coins->IsAvailable(out.n))
1544 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1545 if (coins->vout.size() < out.n+1)
1546 coins->vout.resize(out.n+1);
1547 coins->vout[out.n] = undo.txout;
1549 return fClean;
1552 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1554 assert(pindex->GetBlockHash() == view.GetBestBlock());
1556 if (pfClean)
1557 *pfClean = false;
1559 bool fClean = true;
1561 CBlockUndo blockUndo;
1562 CDiskBlockPos pos = pindex->GetUndoPos();
1563 if (pos.IsNull())
1564 return error("DisconnectBlock(): no undo data available");
1565 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1566 return error("DisconnectBlock(): failure reading undo data");
1568 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1569 return error("DisconnectBlock(): block and undo data inconsistent");
1571 // undo transactions in reverse order
1572 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1573 const CTransaction &tx = block.vtx[i];
1574 uint256 hash = tx.GetHash();
1576 // Check that all outputs are available and match the outputs in the block itself
1577 // exactly.
1579 CCoinsModifier outs = view.ModifyCoins(hash);
1580 outs->ClearUnspendable();
1582 CCoins outsBlock(tx, pindex->nHeight);
1583 // The CCoins serialization does not serialize negative numbers.
1584 // No network rules currently depend on the version here, so an inconsistency is harmless
1585 // but it must be corrected before txout nversion ever influences a network rule.
1586 if (outsBlock.nVersion < 0)
1587 outs->nVersion = outsBlock.nVersion;
1588 if (*outs != outsBlock)
1589 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1591 // remove outputs
1592 outs->Clear();
1595 // restore inputs
1596 if (i > 0) { // not coinbases
1597 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1598 if (txundo.vprevout.size() != tx.vin.size())
1599 return error("DisconnectBlock(): transaction and undo data inconsistent");
1600 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1601 const COutPoint &out = tx.vin[j].prevout;
1602 const CTxInUndo &undo = txundo.vprevout[j];
1603 if (!ApplyTxInUndo(undo, view, out))
1604 fClean = false;
1609 // move best block pointer to prevout block
1610 view.SetBestBlock(pindex->pprev->GetBlockHash());
1612 if (pfClean) {
1613 *pfClean = fClean;
1614 return true;
1617 return fClean;
1620 void static FlushBlockFile(bool fFinalize = false)
1622 LOCK(cs_LastBlockFile);
1624 CDiskBlockPos posOld(nLastBlockFile, 0);
1626 FILE *fileOld = OpenBlockFile(posOld);
1627 if (fileOld) {
1628 if (fFinalize)
1629 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1630 FileCommit(fileOld);
1631 fclose(fileOld);
1634 fileOld = OpenUndoFile(posOld);
1635 if (fileOld) {
1636 if (fFinalize)
1637 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1638 FileCommit(fileOld);
1639 fclose(fileOld);
1643 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1645 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1647 void ThreadScriptCheck() {
1648 RenameThread("bitcoin-scriptch");
1649 scriptcheckqueue.Thread();
1653 // Called periodically asynchronously; alerts if it smells like
1654 // we're being fed a bad chain (blocks being generated much
1655 // too slowly or too quickly).
1657 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1658 int64_t nPowTargetSpacing)
1660 if (bestHeader == NULL || initialDownloadCheck()) return;
1662 static int64_t lastAlertTime = 0;
1663 int64_t now = GetAdjustedTime();
1664 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1666 const int SPAN_HOURS=4;
1667 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1668 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1670 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1672 std::string strWarning;
1673 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1675 LOCK(cs);
1676 const CBlockIndex* i = bestHeader;
1677 int nBlocks = 0;
1678 while (i->GetBlockTime() >= startTime) {
1679 ++nBlocks;
1680 i = i->pprev;
1681 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
1684 // How likely is it to find that many by chance?
1685 double p = boost::math::pdf(poisson, nBlocks);
1687 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1688 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
1690 // Aim for one false-positive about every fifty years of normal running:
1691 const int FIFTY_YEARS = 50*365*24*60*60;
1692 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
1694 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
1696 // Many fewer blocks than expected: alert!
1697 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
1698 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1700 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
1702 // Many more blocks than expected: alert!
1703 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
1704 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1706 if (!strWarning.empty())
1708 strMiscWarning = strWarning;
1709 CAlert::Notify(strWarning, true);
1710 lastAlertTime = now;
1714 static int64_t nTimeVerify = 0;
1715 static int64_t nTimeConnect = 0;
1716 static int64_t nTimeIndex = 0;
1717 static int64_t nTimeCallbacks = 0;
1718 static int64_t nTimeTotal = 0;
1720 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1722 const CChainParams& chainparams = Params();
1723 AssertLockHeld(cs_main);
1724 // Check it again in case a previous version let a bad block in
1725 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1726 return false;
1728 // verify that the view's current state corresponds to the previous block
1729 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1730 assert(hashPrevBlock == view.GetBestBlock());
1732 // Special case for the genesis block, skipping connection of its transactions
1733 // (its coinbase is unspendable)
1734 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1735 if (!fJustCheck)
1736 view.SetBestBlock(pindex->GetBlockHash());
1737 return true;
1740 bool fScriptChecks = true;
1741 if (fCheckpointsEnabled) {
1742 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
1743 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
1744 // This block is an ancestor of a checkpoint: disable script checks
1745 fScriptChecks = false;
1749 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1750 // unless those are already completely spent.
1751 // If such overwrites are allowed, coinbases and transactions depending upon those
1752 // can be duplicated to remove the ability to spend the first instance -- even after
1753 // being sent to another address.
1754 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1755 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1756 // already refuses previously-known transaction ids entirely.
1757 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1758 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1759 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1760 // initial block download.
1761 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1762 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1763 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1764 if (fEnforceBIP30) {
1765 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1766 const CCoins* coins = view.AccessCoins(tx.GetHash());
1767 if (coins && !coins->IsPruned())
1768 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1769 REJECT_INVALID, "bad-txns-BIP30");
1773 // BIP16 didn't become active until Apr 1 2012
1774 int64_t nBIP16SwitchTime = 1333238400;
1775 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1777 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1779 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
1780 // when 75% of the network has upgraded:
1781 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1782 flags |= SCRIPT_VERIFY_DERSIG;
1785 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
1786 // blocks, when 75% of the network has upgraded:
1787 if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1788 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1791 CBlockUndo blockundo;
1793 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1795 int64_t nTimeStart = GetTimeMicros();
1796 CAmount nFees = 0;
1797 int nInputs = 0;
1798 unsigned int nSigOps = 0;
1799 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1800 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1801 vPos.reserve(block.vtx.size());
1802 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1803 for (unsigned int i = 0; i < block.vtx.size(); i++)
1805 const CTransaction &tx = block.vtx[i];
1807 nInputs += tx.vin.size();
1808 nSigOps += GetLegacySigOpCount(tx);
1809 if (nSigOps > MAX_BLOCK_SIGOPS)
1810 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1811 REJECT_INVALID, "bad-blk-sigops");
1813 if (!tx.IsCoinBase())
1815 if (!view.HaveInputs(tx))
1816 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1817 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1819 if (fStrictPayToScriptHash)
1821 // Add in sigops done by pay-to-script-hash inputs;
1822 // this is to prevent a "rogue miner" from creating
1823 // an incredibly-expensive-to-validate block.
1824 nSigOps += GetP2SHSigOpCount(tx, view);
1825 if (nSigOps > MAX_BLOCK_SIGOPS)
1826 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1827 REJECT_INVALID, "bad-blk-sigops");
1830 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1832 std::vector<CScriptCheck> vChecks;
1833 if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1834 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1835 tx.GetHash().ToString(), FormatStateMessage(state));
1836 control.Add(vChecks);
1839 CTxUndo undoDummy;
1840 if (i > 0) {
1841 blockundo.vtxundo.push_back(CTxUndo());
1843 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1845 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1846 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1848 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1849 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
1851 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1852 if (block.vtx[0].GetValueOut() > blockReward)
1853 return state.DoS(100,
1854 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1855 block.vtx[0].GetValueOut(), blockReward),
1856 REJECT_INVALID, "bad-cb-amount");
1858 if (!control.Wait())
1859 return state.DoS(100, false);
1860 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1861 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
1863 if (fJustCheck)
1864 return true;
1866 // Write undo information to disk
1867 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1869 if (pindex->GetUndoPos().IsNull()) {
1870 CDiskBlockPos pos;
1871 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1872 return error("ConnectBlock(): FindUndoPos failed");
1873 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1874 return AbortNode(state, "Failed to write undo data");
1876 // update nUndoPos in block index
1877 pindex->nUndoPos = pos.nPos;
1878 pindex->nStatus |= BLOCK_HAVE_UNDO;
1881 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1882 setDirtyBlockIndex.insert(pindex);
1885 if (fTxIndex)
1886 if (!pblocktree->WriteTxIndex(vPos))
1887 return AbortNode(state, "Failed to write transaction index");
1889 // add this block to the view's block chain
1890 view.SetBestBlock(pindex->GetBlockHash());
1892 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1893 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1895 // Watch for changes to the previous coinbase transaction.
1896 static uint256 hashPrevBestCoinBase;
1897 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1898 hashPrevBestCoinBase = block.vtx[0].GetHash();
1900 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1901 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1903 return true;
1906 enum FlushStateMode {
1907 FLUSH_STATE_NONE,
1908 FLUSH_STATE_IF_NEEDED,
1909 FLUSH_STATE_PERIODIC,
1910 FLUSH_STATE_ALWAYS
1914 * Update the on-disk chain state.
1915 * The caches and indexes are flushed depending on the mode we're called with
1916 * if they're too large, if it's been a while since the last write,
1917 * or always and in all cases if we're in prune mode and are deleting files.
1919 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1920 LOCK2(cs_main, cs_LastBlockFile);
1921 static int64_t nLastWrite = 0;
1922 static int64_t nLastFlush = 0;
1923 static int64_t nLastSetChain = 0;
1924 std::set<int> setFilesToPrune;
1925 bool fFlushForPrune = false;
1926 try {
1927 if (fPruneMode && fCheckForPruning && !fReindex) {
1928 FindFilesToPrune(setFilesToPrune);
1929 fCheckForPruning = false;
1930 if (!setFilesToPrune.empty()) {
1931 fFlushForPrune = true;
1932 if (!fHavePruned) {
1933 pblocktree->WriteFlag("prunedblockfiles", true);
1934 fHavePruned = true;
1938 int64_t nNow = GetTimeMicros();
1939 // Avoid writing/flushing immediately after startup.
1940 if (nLastWrite == 0) {
1941 nLastWrite = nNow;
1943 if (nLastFlush == 0) {
1944 nLastFlush = nNow;
1946 if (nLastSetChain == 0) {
1947 nLastSetChain = nNow;
1949 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1950 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1951 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
1952 // The cache is over the limit, we have to write now.
1953 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
1954 // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
1955 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1956 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1957 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1958 // Combine all conditions that result in a full cache flush.
1959 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1960 // Write blocks and block index to disk.
1961 if (fDoFullFlush || fPeriodicWrite) {
1962 // Depend on nMinDiskSpace to ensure we can write block index
1963 if (!CheckDiskSpace(0))
1964 return state.Error("out of disk space");
1965 // First make sure all block and undo data is flushed to disk.
1966 FlushBlockFile();
1967 // Then update all block file information (which may refer to block and undo files).
1969 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1970 vFiles.reserve(setDirtyFileInfo.size());
1971 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1972 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
1973 setDirtyFileInfo.erase(it++);
1975 std::vector<const CBlockIndex*> vBlocks;
1976 vBlocks.reserve(setDirtyBlockIndex.size());
1977 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1978 vBlocks.push_back(*it);
1979 setDirtyBlockIndex.erase(it++);
1981 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1982 return AbortNode(state, "Files to write to block index database");
1985 // Finally remove any pruned files
1986 if (fFlushForPrune)
1987 UnlinkPrunedFiles(setFilesToPrune);
1988 nLastWrite = nNow;
1990 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1991 if (fDoFullFlush) {
1992 // Typical CCoins structures on disk are around 128 bytes in size.
1993 // Pushing a new one to the database can cause it to be written
1994 // twice (once in the log, and once in the tables). This is already
1995 // an overestimation, as most will delete an existing entry or
1996 // overwrite one. Still, use a conservative safety factor of 2.
1997 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
1998 return state.Error("out of disk space");
1999 // Flush the chainstate (which may refer to block index entries).
2000 if (!pcoinsTip->Flush())
2001 return AbortNode(state, "Failed to write to coin database");
2002 nLastFlush = nNow;
2004 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2005 // Update best block in wallet (so we can detect restored wallets).
2006 GetMainSignals().SetBestChain(chainActive.GetLocator());
2007 nLastSetChain = nNow;
2009 } catch (const std::runtime_error& e) {
2010 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2012 return true;
2015 void FlushStateToDisk() {
2016 CValidationState state;
2017 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2020 void PruneAndFlush() {
2021 CValidationState state;
2022 fCheckForPruning = true;
2023 FlushStateToDisk(state, FLUSH_STATE_NONE);
2026 /** Update chainActive and related internal data structures. */
2027 void static UpdateTip(CBlockIndex *pindexNew) {
2028 const CChainParams& chainParams = Params();
2029 chainActive.SetTip(pindexNew);
2031 // New best block
2032 nTimeBestReceived = GetTime();
2033 mempool.AddTransactionsUpdated(1);
2035 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2036 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2037 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2038 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2040 cvBlockChange.notify_all();
2042 // Check the version of the last 100 blocks to see if we need to upgrade:
2043 static bool fWarned = false;
2044 if (!IsInitialBlockDownload() && !fWarned)
2046 int nUpgraded = 0;
2047 const CBlockIndex* pindex = chainActive.Tip();
2048 for (int i = 0; i < 100 && pindex != NULL; i++)
2050 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2051 ++nUpgraded;
2052 pindex = pindex->pprev;
2054 if (nUpgraded > 0)
2055 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2056 if (nUpgraded > 100/2)
2058 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2059 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2060 CAlert::Notify(strMiscWarning, true);
2061 fWarned = true;
2066 /** Disconnect chainActive's tip. You want to manually re-limit mempool size after this */
2067 bool static DisconnectTip(CValidationState &state) {
2068 CBlockIndex *pindexDelete = chainActive.Tip();
2069 assert(pindexDelete);
2070 mempool.check(pcoinsTip);
2071 // Read block from disk.
2072 CBlock block;
2073 if (!ReadBlockFromDisk(block, pindexDelete))
2074 return AbortNode(state, "Failed to read block");
2075 // Apply the block atomically to the chain state.
2076 int64_t nStart = GetTimeMicros();
2078 CCoinsViewCache view(pcoinsTip);
2079 if (!DisconnectBlock(block, state, pindexDelete, view))
2080 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2081 assert(view.Flush());
2083 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2084 // Write the chain state to disk, if necessary.
2085 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2086 return false;
2087 // Resurrect mempool transactions from the disconnected block.
2088 std::vector<uint256> vHashUpdate;
2089 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2090 // ignore validation errors in resurrected transactions
2091 list<CTransaction> removed;
2092 CValidationState stateDummy;
2093 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) {
2094 mempool.remove(tx, removed, true);
2095 } else if (mempool.exists(tx.GetHash())) {
2096 vHashUpdate.push_back(tx.GetHash());
2099 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2100 // no in-mempool children, which is generally not true when adding
2101 // previously-confirmed transactions back to the mempool.
2102 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2103 // block that were added back and cleans up the mempool state.
2104 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2105 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2106 mempool.check(pcoinsTip);
2107 // Update chainActive and related variables.
2108 UpdateTip(pindexDelete->pprev);
2109 // Let wallets know transactions went from 1-confirmed to
2110 // 0-confirmed or conflicted:
2111 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2112 SyncWithWallets(tx, NULL);
2114 return true;
2117 static int64_t nTimeReadFromDisk = 0;
2118 static int64_t nTimeConnectTotal = 0;
2119 static int64_t nTimeFlush = 0;
2120 static int64_t nTimeChainState = 0;
2121 static int64_t nTimePostConnect = 0;
2124 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2125 * corresponding to pindexNew, to bypass loading it again from disk.
2127 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, const CBlock *pblock) {
2128 assert(pindexNew->pprev == chainActive.Tip());
2129 mempool.check(pcoinsTip);
2130 // Read block from disk.
2131 int64_t nTime1 = GetTimeMicros();
2132 CBlock block;
2133 if (!pblock) {
2134 if (!ReadBlockFromDisk(block, pindexNew))
2135 return AbortNode(state, "Failed to read block");
2136 pblock = &block;
2138 // Apply the block atomically to the chain state.
2139 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2140 int64_t nTime3;
2141 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2143 CCoinsViewCache view(pcoinsTip);
2144 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2145 GetMainSignals().BlockChecked(*pblock, state);
2146 if (!rv) {
2147 if (state.IsInvalid())
2148 InvalidBlockFound(pindexNew, state);
2149 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2151 mapBlockSource.erase(pindexNew->GetBlockHash());
2152 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2153 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2154 assert(view.Flush());
2156 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2157 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2158 // Write the chain state to disk, if necessary.
2159 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2160 return false;
2161 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2162 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2163 // Remove conflicting transactions from the mempool.
2164 list<CTransaction> txConflicted;
2165 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2166 mempool.check(pcoinsTip);
2167 // Update chainActive & related variables.
2168 UpdateTip(pindexNew);
2169 // Tell wallet about transactions that went from mempool
2170 // to conflicted:
2171 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2172 SyncWithWallets(tx, NULL);
2174 // ... and about transactions that got confirmed:
2175 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2176 SyncWithWallets(tx, pblock);
2179 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2180 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2181 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2182 return true;
2186 * Return the tip of the chain with the most work in it, that isn't
2187 * known to be invalid (it's however far from certain to be valid).
2189 static CBlockIndex* FindMostWorkChain() {
2190 do {
2191 CBlockIndex *pindexNew = NULL;
2193 // Find the best candidate header.
2195 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2196 if (it == setBlockIndexCandidates.rend())
2197 return NULL;
2198 pindexNew = *it;
2201 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2202 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2203 CBlockIndex *pindexTest = pindexNew;
2204 bool fInvalidAncestor = false;
2205 while (pindexTest && !chainActive.Contains(pindexTest)) {
2206 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2208 // Pruned nodes may have entries in setBlockIndexCandidates for
2209 // which block files have been deleted. Remove those as candidates
2210 // for the most work chain if we come across them; we can't switch
2211 // to a chain unless we have all the non-active-chain parent blocks.
2212 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2213 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2214 if (fFailedChain || fMissingData) {
2215 // Candidate chain is not usable (either invalid or missing data)
2216 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2217 pindexBestInvalid = pindexNew;
2218 CBlockIndex *pindexFailed = pindexNew;
2219 // Remove the entire chain from the set.
2220 while (pindexTest != pindexFailed) {
2221 if (fFailedChain) {
2222 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2223 } else if (fMissingData) {
2224 // If we're missing data, then add back to mapBlocksUnlinked,
2225 // so that if the block arrives in the future we can try adding
2226 // to setBlockIndexCandidates again.
2227 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2229 setBlockIndexCandidates.erase(pindexFailed);
2230 pindexFailed = pindexFailed->pprev;
2232 setBlockIndexCandidates.erase(pindexTest);
2233 fInvalidAncestor = true;
2234 break;
2236 pindexTest = pindexTest->pprev;
2238 if (!fInvalidAncestor)
2239 return pindexNew;
2240 } while(true);
2243 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2244 static void PruneBlockIndexCandidates() {
2245 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2246 // reorganization to a better block fails.
2247 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2248 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2249 setBlockIndexCandidates.erase(it++);
2251 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2252 assert(!setBlockIndexCandidates.empty());
2256 * Try to make some progress towards making pindexMostWork the active block.
2257 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2259 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, const CBlock *pblock) {
2260 AssertLockHeld(cs_main);
2261 bool fInvalidFound = false;
2262 const CBlockIndex *pindexOldTip = chainActive.Tip();
2263 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2265 // Disconnect active blocks which are no longer in the best chain.
2266 bool fBlocksDisconnected = false;
2267 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2268 if (!DisconnectTip(state))
2269 return false;
2270 fBlocksDisconnected = true;
2273 // Build list of new blocks to connect.
2274 std::vector<CBlockIndex*> vpindexToConnect;
2275 bool fContinue = true;
2276 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2277 while (fContinue && nHeight != pindexMostWork->nHeight) {
2278 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2279 // a few blocks along the way.
2280 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2281 vpindexToConnect.clear();
2282 vpindexToConnect.reserve(nTargetHeight - nHeight);
2283 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2284 while (pindexIter && pindexIter->nHeight != nHeight) {
2285 vpindexToConnect.push_back(pindexIter);
2286 pindexIter = pindexIter->pprev;
2288 nHeight = nTargetHeight;
2290 // Connect new blocks.
2291 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2292 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2293 if (state.IsInvalid()) {
2294 // The block violates a consensus rule.
2295 if (!state.CorruptionPossible())
2296 InvalidChainFound(vpindexToConnect.back());
2297 state = CValidationState();
2298 fInvalidFound = true;
2299 fContinue = false;
2300 break;
2301 } else {
2302 // A system error occurred (disk space, database error, ...).
2303 return false;
2305 } else {
2306 PruneBlockIndexCandidates();
2307 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2308 // We're in a better position than we were. Return temporarily to release the lock.
2309 fContinue = false;
2310 break;
2316 if (fBlocksDisconnected)
2317 mempool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2319 // Callbacks/notifications for a new best chain.
2320 if (fInvalidFound)
2321 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2322 else
2323 CheckForkWarningConditions();
2325 return true;
2329 * Make the best chain active, in multiple steps. The result is either failure
2330 * or an activated best chain. pblock is either NULL or a pointer to a block
2331 * that is already loaded (to avoid loading it again from disk).
2333 bool ActivateBestChain(CValidationState &state, const CBlock *pblock) {
2334 CBlockIndex *pindexNewTip = NULL;
2335 CBlockIndex *pindexMostWork = NULL;
2336 const CChainParams& chainParams = Params();
2337 do {
2338 boost::this_thread::interruption_point();
2340 bool fInitialDownload;
2342 LOCK(cs_main);
2343 pindexMostWork = FindMostWorkChain();
2345 // Whether we have anything to do at all.
2346 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2347 return true;
2349 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2350 return false;
2352 pindexNewTip = chainActive.Tip();
2353 fInitialDownload = IsInitialBlockDownload();
2355 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2357 // Notifications/callbacks that can run without cs_main
2358 if (!fInitialDownload) {
2359 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2360 // Relay inventory, but don't relay old inventory during initial block download.
2361 int nBlockEstimate = 0;
2362 if (fCheckpointsEnabled)
2363 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2365 LOCK(cs_vNodes);
2366 BOOST_FOREACH(CNode* pnode, vNodes)
2367 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2368 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2370 // Notify external listeners about the new tip.
2371 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2372 uiInterface.NotifyBlockTip(hashNewTip);
2374 } while(pindexMostWork != chainActive.Tip());
2375 CheckBlockIndex();
2377 // Write changes periodically to disk, after relay.
2378 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2379 return false;
2382 return true;
2385 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2386 AssertLockHeld(cs_main);
2388 // Mark the block itself as invalid.
2389 pindex->nStatus |= BLOCK_FAILED_VALID;
2390 setDirtyBlockIndex.insert(pindex);
2391 setBlockIndexCandidates.erase(pindex);
2393 while (chainActive.Contains(pindex)) {
2394 CBlockIndex *pindexWalk = chainActive.Tip();
2395 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2396 setDirtyBlockIndex.insert(pindexWalk);
2397 setBlockIndexCandidates.erase(pindexWalk);
2398 // ActivateBestChain considers blocks already in chainActive
2399 // unconditionally valid already, so force disconnect away from it.
2400 if (!DisconnectTip(state)) {
2401 return false;
2405 mempool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2407 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2408 // add it again.
2409 BlockMap::iterator it = mapBlockIndex.begin();
2410 while (it != mapBlockIndex.end()) {
2411 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2412 setBlockIndexCandidates.insert(it->second);
2414 it++;
2417 InvalidChainFound(pindex);
2418 return true;
2421 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2422 AssertLockHeld(cs_main);
2424 int nHeight = pindex->nHeight;
2426 // Remove the invalidity flag from this block and all its descendants.
2427 BlockMap::iterator it = mapBlockIndex.begin();
2428 while (it != mapBlockIndex.end()) {
2429 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2430 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2431 setDirtyBlockIndex.insert(it->second);
2432 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2433 setBlockIndexCandidates.insert(it->second);
2435 if (it->second == pindexBestInvalid) {
2436 // Reset invalid block marker if it was pointing to one of those.
2437 pindexBestInvalid = NULL;
2440 it++;
2443 // Remove the invalidity flag from all ancestors too.
2444 while (pindex != NULL) {
2445 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2446 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2447 setDirtyBlockIndex.insert(pindex);
2449 pindex = pindex->pprev;
2451 return true;
2454 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2456 // Check for duplicate
2457 uint256 hash = block.GetHash();
2458 BlockMap::iterator it = mapBlockIndex.find(hash);
2459 if (it != mapBlockIndex.end())
2460 return it->second;
2462 // Construct new block index object
2463 CBlockIndex* pindexNew = new CBlockIndex(block);
2464 assert(pindexNew);
2465 // We assign the sequence id to blocks only when the full data is available,
2466 // to avoid miners withholding blocks but broadcasting headers, to get a
2467 // competitive advantage.
2468 pindexNew->nSequenceId = 0;
2469 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2470 pindexNew->phashBlock = &((*mi).first);
2471 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2472 if (miPrev != mapBlockIndex.end())
2474 pindexNew->pprev = (*miPrev).second;
2475 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2476 pindexNew->BuildSkip();
2478 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2479 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2480 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2481 pindexBestHeader = pindexNew;
2483 setDirtyBlockIndex.insert(pindexNew);
2485 return pindexNew;
2488 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2489 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2491 pindexNew->nTx = block.vtx.size();
2492 pindexNew->nChainTx = 0;
2493 pindexNew->nFile = pos.nFile;
2494 pindexNew->nDataPos = pos.nPos;
2495 pindexNew->nUndoPos = 0;
2496 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2497 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2498 setDirtyBlockIndex.insert(pindexNew);
2500 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2501 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2502 deque<CBlockIndex*> queue;
2503 queue.push_back(pindexNew);
2505 // Recursively process any descendant blocks that now may be eligible to be connected.
2506 while (!queue.empty()) {
2507 CBlockIndex *pindex = queue.front();
2508 queue.pop_front();
2509 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2511 LOCK(cs_nBlockSequenceId);
2512 pindex->nSequenceId = nBlockSequenceId++;
2514 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2515 setBlockIndexCandidates.insert(pindex);
2517 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2518 while (range.first != range.second) {
2519 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2520 queue.push_back(it->second);
2521 range.first++;
2522 mapBlocksUnlinked.erase(it);
2525 } else {
2526 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2527 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2531 return true;
2534 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2536 LOCK(cs_LastBlockFile);
2538 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2539 if (vinfoBlockFile.size() <= nFile) {
2540 vinfoBlockFile.resize(nFile + 1);
2543 if (!fKnown) {
2544 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2545 nFile++;
2546 if (vinfoBlockFile.size() <= nFile) {
2547 vinfoBlockFile.resize(nFile + 1);
2550 pos.nFile = nFile;
2551 pos.nPos = vinfoBlockFile[nFile].nSize;
2554 if (nFile != nLastBlockFile) {
2555 if (!fKnown) {
2556 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2558 FlushBlockFile(!fKnown);
2559 nLastBlockFile = nFile;
2562 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2563 if (fKnown)
2564 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2565 else
2566 vinfoBlockFile[nFile].nSize += nAddSize;
2568 if (!fKnown) {
2569 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2570 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2571 if (nNewChunks > nOldChunks) {
2572 if (fPruneMode)
2573 fCheckForPruning = true;
2574 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2575 FILE *file = OpenBlockFile(pos);
2576 if (file) {
2577 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2578 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2579 fclose(file);
2582 else
2583 return state.Error("out of disk space");
2587 setDirtyFileInfo.insert(nFile);
2588 return true;
2591 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2593 pos.nFile = nFile;
2595 LOCK(cs_LastBlockFile);
2597 unsigned int nNewSize;
2598 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2599 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2600 setDirtyFileInfo.insert(nFile);
2602 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2603 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2604 if (nNewChunks > nOldChunks) {
2605 if (fPruneMode)
2606 fCheckForPruning = true;
2607 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2608 FILE *file = OpenUndoFile(pos);
2609 if (file) {
2610 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2611 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2612 fclose(file);
2615 else
2616 return state.Error("out of disk space");
2619 return true;
2622 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2624 // Check proof of work matches claimed amount
2625 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2626 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2627 REJECT_INVALID, "high-hash");
2629 // Check timestamp
2630 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2631 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2632 REJECT_INVALID, "time-too-new");
2634 return true;
2637 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2639 // These are checks that are independent of context.
2641 if (block.fChecked)
2642 return true;
2644 // Check that the header is valid (particularly PoW). This is mostly
2645 // redundant with the call in AcceptBlockHeader.
2646 if (!CheckBlockHeader(block, state, fCheckPOW))
2647 return false;
2649 // Check the merkle root.
2650 if (fCheckMerkleRoot) {
2651 bool mutated;
2652 uint256 hashMerkleRoot2 = block.ComputeMerkleRoot(&mutated);
2653 if (block.hashMerkleRoot != hashMerkleRoot2)
2654 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2655 REJECT_INVALID, "bad-txnmrklroot", true);
2657 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2658 // of transactions in a block without affecting the merkle root of a block,
2659 // while still invalidating it.
2660 if (mutated)
2661 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2662 REJECT_INVALID, "bad-txns-duplicate", true);
2665 // All potential-corruption validation must be done before we do any
2666 // transaction validation, as otherwise we may mark the header as invalid
2667 // because we receive the wrong transactions for it.
2669 // Size limits
2670 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2671 return state.DoS(100, error("CheckBlock(): size limits failed"),
2672 REJECT_INVALID, "bad-blk-length");
2674 // First transaction must be coinbase, the rest must not be
2675 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2676 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2677 REJECT_INVALID, "bad-cb-missing");
2678 for (unsigned int i = 1; i < block.vtx.size(); i++)
2679 if (block.vtx[i].IsCoinBase())
2680 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2681 REJECT_INVALID, "bad-cb-multiple");
2683 // Check transactions
2684 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2685 if (!CheckTransaction(tx, state))
2686 return error("CheckBlock(): CheckTransaction of %s failed with %s",
2687 tx.GetHash().ToString(),
2688 FormatStateMessage(state));
2690 unsigned int nSigOps = 0;
2691 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2693 nSigOps += GetLegacySigOpCount(tx);
2695 if (nSigOps > MAX_BLOCK_SIGOPS)
2696 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2697 REJECT_INVALID, "bad-blk-sigops", true);
2699 if (fCheckPOW && fCheckMerkleRoot)
2700 block.fChecked = true;
2702 return true;
2705 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2707 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2708 return true;
2710 int nHeight = pindexPrev->nHeight+1;
2711 // Don't accept any forks from the main chain prior to last checkpoint
2712 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2713 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2714 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2716 return true;
2719 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2721 const Consensus::Params& consensusParams = Params().GetConsensus();
2722 // Check proof of work
2723 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2724 return state.DoS(100, error("%s: incorrect proof of work", __func__),
2725 REJECT_INVALID, "bad-diffbits");
2727 // Check timestamp against prev
2728 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2729 return state.Invalid(error("%s: block's timestamp is too early", __func__),
2730 REJECT_INVALID, "time-too-old");
2732 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2733 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2734 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2735 REJECT_OBSOLETE, "bad-version");
2737 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2738 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2739 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2740 REJECT_OBSOLETE, "bad-version");
2742 // Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded:
2743 if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2744 return state.Invalid(error("%s : rejected nVersion=3 block", __func__),
2745 REJECT_OBSOLETE, "bad-version");
2747 return true;
2750 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2752 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2753 const Consensus::Params& consensusParams = Params().GetConsensus();
2755 // Check that all transactions are finalized
2756 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2757 int nLockTimeFlags = 0;
2758 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2759 ? pindexPrev->GetMedianTimePast()
2760 : block.GetBlockTime();
2761 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
2762 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2766 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2767 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2768 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
2770 CScript expect = CScript() << nHeight;
2771 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2772 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2773 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2777 return true;
2780 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2782 const CChainParams& chainparams = Params();
2783 AssertLockHeld(cs_main);
2784 // Check for duplicate
2785 uint256 hash = block.GetHash();
2786 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2787 CBlockIndex *pindex = NULL;
2788 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2790 if (miSelf != mapBlockIndex.end()) {
2791 // Block header is already known.
2792 pindex = miSelf->second;
2793 if (ppindex)
2794 *ppindex = pindex;
2795 if (pindex->nStatus & BLOCK_FAILED_MASK)
2796 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2797 return true;
2800 if (!CheckBlockHeader(block, state))
2801 return false;
2803 // Get prev block index
2804 CBlockIndex* pindexPrev = NULL;
2805 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2806 if (mi == mapBlockIndex.end())
2807 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2808 pindexPrev = (*mi).second;
2809 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2810 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2812 assert(pindexPrev);
2813 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2814 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2816 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2817 return false;
2819 if (pindex == NULL)
2820 pindex = AddToBlockIndex(block);
2822 if (ppindex)
2823 *ppindex = pindex;
2825 return true;
2828 bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
2830 const CChainParams& chainparams = Params();
2831 AssertLockHeld(cs_main);
2833 CBlockIndex *&pindex = *ppindex;
2835 if (!AcceptBlockHeader(block, state, &pindex))
2836 return false;
2838 // Try to process all requested blocks that we don't have, but only
2839 // process an unrequested block if it's new and has enough work to
2840 // advance our tip, and isn't too many blocks ahead.
2841 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2842 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2843 // Blocks that are too out-of-order needlessly limit the effectiveness of
2844 // pruning, because pruning will not delete block files that contain any
2845 // blocks which are too close in height to the tip. Apply this test
2846 // regardless of whether pruning is enabled; it should generally be safe to
2847 // not process unrequested blocks.
2848 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2850 // TODO: deal better with return value and error conditions for duplicate
2851 // and unrequested blocks.
2852 if (fAlreadyHave) return true;
2853 if (!fRequested) { // If we didn't ask for it:
2854 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2855 if (!fHasMoreWork) return true; // Don't process less-work chains
2856 if (fTooFarAhead) return true; // Block height is too high
2859 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2860 if (state.IsInvalid() && !state.CorruptionPossible()) {
2861 pindex->nStatus |= BLOCK_FAILED_VALID;
2862 setDirtyBlockIndex.insert(pindex);
2864 return false;
2867 int nHeight = pindex->nHeight;
2869 // Write block to history file
2870 try {
2871 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2872 CDiskBlockPos blockPos;
2873 if (dbp != NULL)
2874 blockPos = *dbp;
2875 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2876 return error("AcceptBlock(): FindBlockPos failed");
2877 if (dbp == NULL)
2878 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2879 AbortNode(state, "Failed to write block");
2880 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2881 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2882 } catch (const std::runtime_error& e) {
2883 return AbortNode(state, std::string("System error: ") + e.what());
2886 if (fCheckForPruning)
2887 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2889 return true;
2892 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
2894 unsigned int nFound = 0;
2895 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
2897 if (pstart->nVersion >= minVersion)
2898 ++nFound;
2899 pstart = pstart->pprev;
2901 return (nFound >= nRequired);
2905 bool ProcessNewBlock(CValidationState &state, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
2907 // Preliminary checks
2908 bool checked = CheckBlock(*pblock, state);
2911 LOCK(cs_main);
2912 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
2913 fRequested |= fForceProcessing;
2914 if (!checked) {
2915 return error("%s: CheckBlock FAILED", __func__);
2918 // Store to disk
2919 CBlockIndex *pindex = NULL;
2920 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
2921 if (pindex && pfrom) {
2922 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2924 CheckBlockIndex();
2925 if (!ret)
2926 return error("%s: AcceptBlock FAILED", __func__);
2929 if (!ActivateBestChain(state, pblock))
2930 return error("%s: ActivateBestChain failed", __func__);
2932 return true;
2935 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2937 const CChainParams& chainparams = Params();
2938 AssertLockHeld(cs_main);
2939 assert(pindexPrev && pindexPrev == chainActive.Tip());
2940 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
2941 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2943 CCoinsViewCache viewNew(pcoinsTip);
2944 CBlockIndex indexDummy(block);
2945 indexDummy.pprev = pindexPrev;
2946 indexDummy.nHeight = pindexPrev->nHeight + 1;
2948 // NOTE: CheckBlockHeader is called by CheckBlock
2949 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2950 return false;
2951 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2952 return false;
2953 if (!ContextualCheckBlock(block, state, pindexPrev))
2954 return false;
2955 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2956 return false;
2957 assert(state.IsValid());
2959 return true;
2963 * BLOCK PRUNING CODE
2966 /* Calculate the amount of disk space the block & undo files currently use */
2967 uint64_t CalculateCurrentUsage()
2969 uint64_t retval = 0;
2970 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
2971 retval += file.nSize + file.nUndoSize;
2973 return retval;
2976 /* Prune a block file (modify associated database entries)*/
2977 void PruneOneBlockFile(const int fileNumber)
2979 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
2980 CBlockIndex* pindex = it->second;
2981 if (pindex->nFile == fileNumber) {
2982 pindex->nStatus &= ~BLOCK_HAVE_DATA;
2983 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
2984 pindex->nFile = 0;
2985 pindex->nDataPos = 0;
2986 pindex->nUndoPos = 0;
2987 setDirtyBlockIndex.insert(pindex);
2989 // Prune from mapBlocksUnlinked -- any block we prune would have
2990 // to be downloaded again in order to consider its chain, at which
2991 // point it would be considered as a candidate for
2992 // mapBlocksUnlinked or setBlockIndexCandidates.
2993 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
2994 while (range.first != range.second) {
2995 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
2996 range.first++;
2997 if (it->second == pindex) {
2998 mapBlocksUnlinked.erase(it);
3004 vinfoBlockFile[fileNumber].SetNull();
3005 setDirtyFileInfo.insert(fileNumber);
3009 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3011 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3012 CDiskBlockPos pos(*it, 0);
3013 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3014 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3015 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3019 /* Calculate the block/rev files that should be deleted to remain under target*/
3020 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3022 LOCK2(cs_main, cs_LastBlockFile);
3023 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3024 return;
3026 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3027 return;
3030 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3031 uint64_t nCurrentUsage = CalculateCurrentUsage();
3032 // We don't check to prune until after we've allocated new space for files
3033 // So we should leave a buffer under our target to account for another allocation
3034 // before the next pruning.
3035 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3036 uint64_t nBytesToPrune;
3037 int count=0;
3039 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3040 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3041 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3043 if (vinfoBlockFile[fileNumber].nSize == 0)
3044 continue;
3046 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3047 break;
3049 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3050 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3051 continue;
3053 PruneOneBlockFile(fileNumber);
3054 // Queue up the files for removal
3055 setFilesToPrune.insert(fileNumber);
3056 nCurrentUsage -= nBytesToPrune;
3057 count++;
3061 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3062 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3063 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3064 nLastBlockWeCanPrune, count);
3067 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3069 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3071 // Check for nMinDiskSpace bytes (currently 50MB)
3072 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3073 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3075 return true;
3078 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3080 if (pos.IsNull())
3081 return NULL;
3082 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3083 boost::filesystem::create_directories(path.parent_path());
3084 FILE* file = fopen(path.string().c_str(), "rb+");
3085 if (!file && !fReadOnly)
3086 file = fopen(path.string().c_str(), "wb+");
3087 if (!file) {
3088 LogPrintf("Unable to open file %s\n", path.string());
3089 return NULL;
3091 if (pos.nPos) {
3092 if (fseek(file, pos.nPos, SEEK_SET)) {
3093 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3094 fclose(file);
3095 return NULL;
3098 return file;
3101 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3102 return OpenDiskFile(pos, "blk", fReadOnly);
3105 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3106 return OpenDiskFile(pos, "rev", fReadOnly);
3109 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3111 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3114 CBlockIndex * InsertBlockIndex(uint256 hash)
3116 if (hash.IsNull())
3117 return NULL;
3119 // Return existing
3120 BlockMap::iterator mi = mapBlockIndex.find(hash);
3121 if (mi != mapBlockIndex.end())
3122 return (*mi).second;
3124 // Create new
3125 CBlockIndex* pindexNew = new CBlockIndex();
3126 if (!pindexNew)
3127 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3128 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3129 pindexNew->phashBlock = &((*mi).first);
3131 return pindexNew;
3134 bool static LoadBlockIndexDB()
3136 const CChainParams& chainparams = Params();
3137 if (!pblocktree->LoadBlockIndexGuts())
3138 return false;
3140 boost::this_thread::interruption_point();
3142 // Calculate nChainWork
3143 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3144 vSortedByHeight.reserve(mapBlockIndex.size());
3145 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3147 CBlockIndex* pindex = item.second;
3148 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3150 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3151 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3153 CBlockIndex* pindex = item.second;
3154 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3155 // We can link the chain of blocks for which we've received transactions at some point.
3156 // Pruned nodes may have deleted the block.
3157 if (pindex->nTx > 0) {
3158 if (pindex->pprev) {
3159 if (pindex->pprev->nChainTx) {
3160 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3161 } else {
3162 pindex->nChainTx = 0;
3163 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3165 } else {
3166 pindex->nChainTx = pindex->nTx;
3169 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3170 setBlockIndexCandidates.insert(pindex);
3171 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3172 pindexBestInvalid = pindex;
3173 if (pindex->pprev)
3174 pindex->BuildSkip();
3175 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3176 pindexBestHeader = pindex;
3179 // Load block file info
3180 pblocktree->ReadLastBlockFile(nLastBlockFile);
3181 vinfoBlockFile.resize(nLastBlockFile + 1);
3182 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3183 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3184 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3186 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3187 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3188 CBlockFileInfo info;
3189 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3190 vinfoBlockFile.push_back(info);
3191 } else {
3192 break;
3196 // Check presence of blk files
3197 LogPrintf("Checking all blk files are present...\n");
3198 set<int> setBlkDataFiles;
3199 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3201 CBlockIndex* pindex = item.second;
3202 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3203 setBlkDataFiles.insert(pindex->nFile);
3206 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3208 CDiskBlockPos pos(*it, 0);
3209 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3210 return false;
3214 // Check whether we have ever pruned block & undo files
3215 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3216 if (fHavePruned)
3217 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3219 // Check whether we need to continue reindexing
3220 bool fReindexing = false;
3221 pblocktree->ReadReindexing(fReindexing);
3222 fReindex |= fReindexing;
3224 // Check whether we have a transaction index
3225 pblocktree->ReadFlag("txindex", fTxIndex);
3226 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3228 // Load pointer to end of best chain
3229 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3230 if (it == mapBlockIndex.end())
3231 return true;
3232 chainActive.SetTip(it->second);
3234 PruneBlockIndexCandidates();
3236 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3237 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3238 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3239 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3241 return true;
3244 CVerifyDB::CVerifyDB()
3246 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3249 CVerifyDB::~CVerifyDB()
3251 uiInterface.ShowProgress("", 100);
3254 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3256 LOCK(cs_main);
3257 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3258 return true;
3260 // Verify blocks in the best chain
3261 if (nCheckDepth <= 0)
3262 nCheckDepth = 1000000000; // suffices until the year 19000
3263 if (nCheckDepth > chainActive.Height())
3264 nCheckDepth = chainActive.Height();
3265 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3266 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3267 CCoinsViewCache coins(coinsview);
3268 CBlockIndex* pindexState = chainActive.Tip();
3269 CBlockIndex* pindexFailure = NULL;
3270 int nGoodTransactions = 0;
3271 CValidationState state;
3272 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3274 boost::this_thread::interruption_point();
3275 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3276 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3277 break;
3278 CBlock block;
3279 // check level 0: read from disk
3280 if (!ReadBlockFromDisk(block, pindex))
3281 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3282 // check level 1: verify block validity
3283 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3284 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3285 // check level 2: verify undo validity
3286 if (nCheckLevel >= 2 && pindex) {
3287 CBlockUndo undo;
3288 CDiskBlockPos pos = pindex->GetUndoPos();
3289 if (!pos.IsNull()) {
3290 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3291 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3294 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3295 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3296 bool fClean = true;
3297 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3298 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3299 pindexState = pindex->pprev;
3300 if (!fClean) {
3301 nGoodTransactions = 0;
3302 pindexFailure = pindex;
3303 } else
3304 nGoodTransactions += block.vtx.size();
3306 if (ShutdownRequested())
3307 return true;
3309 if (pindexFailure)
3310 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3312 // check level 4: try reconnecting blocks
3313 if (nCheckLevel >= 4) {
3314 CBlockIndex *pindex = pindexState;
3315 while (pindex != chainActive.Tip()) {
3316 boost::this_thread::interruption_point();
3317 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3318 pindex = chainActive.Next(pindex);
3319 CBlock block;
3320 if (!ReadBlockFromDisk(block, pindex))
3321 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3322 if (!ConnectBlock(block, state, pindex, coins))
3323 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3327 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3329 return true;
3332 void UnloadBlockIndex()
3334 LOCK(cs_main);
3335 setBlockIndexCandidates.clear();
3336 chainActive.SetTip(NULL);
3337 pindexBestInvalid = NULL;
3338 pindexBestHeader = NULL;
3339 mempool.clear();
3340 mapOrphanTransactions.clear();
3341 mapOrphanTransactionsByPrev.clear();
3342 nSyncStarted = 0;
3343 mapBlocksUnlinked.clear();
3344 vinfoBlockFile.clear();
3345 nLastBlockFile = 0;
3346 nBlockSequenceId = 1;
3347 mapBlockSource.clear();
3348 mapBlocksInFlight.clear();
3349 nQueuedValidatedHeaders = 0;
3350 nPreferredDownload = 0;
3351 setDirtyBlockIndex.clear();
3352 setDirtyFileInfo.clear();
3353 mapNodeState.clear();
3354 recentRejects.reset(NULL);
3356 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3357 delete entry.second;
3359 mapBlockIndex.clear();
3360 fHavePruned = false;
3363 bool LoadBlockIndex()
3365 // Load block index from databases
3366 if (!fReindex && !LoadBlockIndexDB())
3367 return false;
3368 return true;
3372 bool InitBlockIndex() {
3373 const CChainParams& chainparams = Params();
3374 LOCK(cs_main);
3376 // Initialize global variables that cannot be constructed at startup.
3377 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3379 // Check whether we're already initialized
3380 if (chainActive.Genesis() != NULL)
3381 return true;
3383 // Use the provided setting for -txindex in the new database
3384 fTxIndex = GetBoolArg("-txindex", false);
3385 pblocktree->WriteFlag("txindex", fTxIndex);
3386 LogPrintf("Initializing databases...\n");
3388 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3389 if (!fReindex) {
3390 try {
3391 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3392 // Start new block file
3393 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3394 CDiskBlockPos blockPos;
3395 CValidationState state;
3396 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3397 return error("LoadBlockIndex(): FindBlockPos failed");
3398 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3399 return error("LoadBlockIndex(): writing genesis block to disk failed");
3400 CBlockIndex *pindex = AddToBlockIndex(block);
3401 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3402 return error("LoadBlockIndex(): genesis block not accepted");
3403 if (!ActivateBestChain(state, &block))
3404 return error("LoadBlockIndex(): genesis block cannot be activated");
3405 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3406 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3407 } catch (const std::runtime_error& e) {
3408 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3412 return true;
3417 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3419 const CChainParams& chainparams = Params();
3420 // Map of disk positions for blocks with unknown parent (only used for reindex)
3421 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3422 int64_t nStart = GetTimeMillis();
3424 int nLoaded = 0;
3425 try {
3426 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3427 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3428 uint64_t nRewind = blkdat.GetPos();
3429 while (!blkdat.eof()) {
3430 boost::this_thread::interruption_point();
3432 blkdat.SetPos(nRewind);
3433 nRewind++; // start one byte further next time, in case of failure
3434 blkdat.SetLimit(); // remove former limit
3435 unsigned int nSize = 0;
3436 try {
3437 // locate a header
3438 unsigned char buf[MESSAGE_START_SIZE];
3439 blkdat.FindByte(Params().MessageStart()[0]);
3440 nRewind = blkdat.GetPos()+1;
3441 blkdat >> FLATDATA(buf);
3442 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3443 continue;
3444 // read size
3445 blkdat >> nSize;
3446 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3447 continue;
3448 } catch (const std::exception&) {
3449 // no valid block header found; don't complain
3450 break;
3452 try {
3453 // read block
3454 uint64_t nBlockPos = blkdat.GetPos();
3455 if (dbp)
3456 dbp->nPos = nBlockPos;
3457 blkdat.SetLimit(nBlockPos + nSize);
3458 blkdat.SetPos(nBlockPos);
3459 CBlock block;
3460 blkdat >> block;
3461 nRewind = blkdat.GetPos();
3463 // detect out of order blocks, and store them for later
3464 uint256 hash = block.GetHash();
3465 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3466 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3467 block.hashPrevBlock.ToString());
3468 if (dbp)
3469 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3470 continue;
3473 // process in case the block isn't known yet
3474 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3475 CValidationState state;
3476 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3477 nLoaded++;
3478 if (state.IsError())
3479 break;
3480 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3481 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3484 // Recursively process earlier encountered successors of this block
3485 deque<uint256> queue;
3486 queue.push_back(hash);
3487 while (!queue.empty()) {
3488 uint256 head = queue.front();
3489 queue.pop_front();
3490 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3491 while (range.first != range.second) {
3492 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3493 if (ReadBlockFromDisk(block, it->second))
3495 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3496 head.ToString());
3497 CValidationState dummy;
3498 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3500 nLoaded++;
3501 queue.push_back(block.GetHash());
3504 range.first++;
3505 mapBlocksUnknownParent.erase(it);
3508 } catch (const std::exception& e) {
3509 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3512 } catch (const std::runtime_error& e) {
3513 AbortNode(std::string("System error: ") + e.what());
3515 if (nLoaded > 0)
3516 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3517 return nLoaded > 0;
3520 void static CheckBlockIndex()
3522 const Consensus::Params& consensusParams = Params().GetConsensus();
3523 if (!fCheckBlockIndex) {
3524 return;
3527 LOCK(cs_main);
3529 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3530 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3531 // iterating the block tree require that chainActive has been initialized.)
3532 if (chainActive.Height() < 0) {
3533 assert(mapBlockIndex.size() <= 1);
3534 return;
3537 // Build forward-pointing map of the entire block tree.
3538 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3539 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3540 forward.insert(std::make_pair(it->second->pprev, it->second));
3543 assert(forward.size() == mapBlockIndex.size());
3545 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3546 CBlockIndex *pindex = rangeGenesis.first->second;
3547 rangeGenesis.first++;
3548 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3550 // Iterate over the entire block tree, using depth-first search.
3551 // Along the way, remember whether there are blocks on the path from genesis
3552 // block being explored which are the first to have certain properties.
3553 size_t nNodes = 0;
3554 int nHeight = 0;
3555 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3556 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3557 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3558 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3559 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3560 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3561 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3562 while (pindex != NULL) {
3563 nNodes++;
3564 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3565 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3566 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3567 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3568 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3569 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3570 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3572 // Begin: actual consistency checks.
3573 if (pindex->pprev == NULL) {
3574 // Genesis block checks.
3575 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3576 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3578 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3579 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3580 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3581 if (!fHavePruned) {
3582 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3583 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3584 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3585 } else {
3586 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3587 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3589 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3590 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3591 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3592 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3593 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3594 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3595 assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
3596 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3597 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3598 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3599 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3600 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3601 if (pindexFirstInvalid == NULL) {
3602 // Checks for not-invalid blocks.
3603 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3605 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3606 if (pindexFirstInvalid == NULL) {
3607 // If this block sorts at least as good as the current tip and
3608 // is valid and we have all data for its parents, it must be in
3609 // setBlockIndexCandidates. chainActive.Tip() must also be there
3610 // even if some data has been pruned.
3611 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3612 assert(setBlockIndexCandidates.count(pindex));
3614 // If some parent is missing, then it could be that this block was in
3615 // setBlockIndexCandidates but had to be removed because of the missing data.
3616 // In this case it must be in mapBlocksUnlinked -- see test below.
3618 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3619 assert(setBlockIndexCandidates.count(pindex) == 0);
3621 // Check whether this block is in mapBlocksUnlinked.
3622 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3623 bool foundInUnlinked = false;
3624 while (rangeUnlinked.first != rangeUnlinked.second) {
3625 assert(rangeUnlinked.first->first == pindex->pprev);
3626 if (rangeUnlinked.first->second == pindex) {
3627 foundInUnlinked = true;
3628 break;
3630 rangeUnlinked.first++;
3632 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3633 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3634 assert(foundInUnlinked);
3636 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3637 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3638 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3639 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3640 assert(fHavePruned); // We must have pruned.
3641 // This block may have entered mapBlocksUnlinked if:
3642 // - it has a descendant that at some point had more work than the
3643 // tip, and
3644 // - we tried switching to that descendant but were missing
3645 // data for some intermediate block between chainActive and the
3646 // tip.
3647 // So if this block is itself better than chainActive.Tip() and it wasn't in
3648 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3649 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3650 if (pindexFirstInvalid == NULL) {
3651 assert(foundInUnlinked);
3655 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3656 // End: actual consistency checks.
3658 // Try descending into the first subnode.
3659 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3660 if (range.first != range.second) {
3661 // A subnode was found.
3662 pindex = range.first->second;
3663 nHeight++;
3664 continue;
3666 // This is a leaf node.
3667 // Move upwards until we reach a node of which we have not yet visited the last child.
3668 while (pindex) {
3669 // We are going to either move to a parent or a sibling of pindex.
3670 // If pindex was the first with a certain property, unset the corresponding variable.
3671 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3672 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3673 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3674 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3675 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3676 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3677 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3678 // Find our parent.
3679 CBlockIndex* pindexPar = pindex->pprev;
3680 // Find which child we just visited.
3681 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3682 while (rangePar.first->second != pindex) {
3683 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3684 rangePar.first++;
3686 // Proceed to the next one.
3687 rangePar.first++;
3688 if (rangePar.first != rangePar.second) {
3689 // Move to the sibling.
3690 pindex = rangePar.first->second;
3691 break;
3692 } else {
3693 // Move up further.
3694 pindex = pindexPar;
3695 nHeight--;
3696 continue;
3701 // Check that we actually traversed the entire map.
3702 assert(nNodes == forward.size());
3705 //////////////////////////////////////////////////////////////////////////////
3707 // CAlert
3710 std::string GetWarnings(const std::string& strFor)
3712 int nPriority = 0;
3713 string strStatusBar;
3714 string strRPC;
3716 if (!CLIENT_VERSION_IS_RELEASE)
3717 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3719 if (GetBoolArg("-testsafemode", false))
3720 strStatusBar = strRPC = "testsafemode enabled";
3722 // Misc warnings like out of disk space and clock is wrong
3723 if (strMiscWarning != "")
3725 nPriority = 1000;
3726 strStatusBar = strMiscWarning;
3729 if (fLargeWorkForkFound)
3731 nPriority = 2000;
3732 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3734 else if (fLargeWorkInvalidChainFound)
3736 nPriority = 2000;
3737 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.");
3740 // Alerts
3742 LOCK(cs_mapAlerts);
3743 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3745 const CAlert& alert = item.second;
3746 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3748 nPriority = alert.nPriority;
3749 strStatusBar = alert.strStatusBar;
3754 if (strFor == "statusbar")
3755 return strStatusBar;
3756 else if (strFor == "rpc")
3757 return strRPC;
3758 assert(!"GetWarnings(): invalid parameter");
3759 return "error";
3769 //////////////////////////////////////////////////////////////////////////////
3771 // Messages
3775 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3777 switch (inv.type)
3779 case MSG_TX:
3781 assert(recentRejects);
3782 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
3784 // If the chain tip has changed previously rejected transactions
3785 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
3786 // or a double-spend. Reset the rejects filter and give those
3787 // txs a second chance.
3788 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
3789 recentRejects->reset();
3792 return recentRejects->contains(inv.hash) ||
3793 mempool.exists(inv.hash) ||
3794 mapOrphanTransactions.count(inv.hash) ||
3795 pcoinsTip->HaveCoins(inv.hash);
3797 case MSG_BLOCK:
3798 return mapBlockIndex.count(inv.hash);
3800 // Don't know what it is, just say we already got one
3801 return true;
3804 void static ProcessGetData(CNode* pfrom)
3806 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3808 vector<CInv> vNotFound;
3810 LOCK(cs_main);
3812 while (it != pfrom->vRecvGetData.end()) {
3813 // Don't bother if send buffer is too full to respond anyway
3814 if (pfrom->nSendSize >= SendBufferSize())
3815 break;
3817 const CInv &inv = *it;
3819 boost::this_thread::interruption_point();
3820 it++;
3822 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3824 bool send = false;
3825 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3826 if (mi != mapBlockIndex.end())
3828 if (chainActive.Contains(mi->second)) {
3829 send = true;
3830 } else {
3831 static const int nOneMonth = 30 * 24 * 60 * 60;
3832 // To prevent fingerprinting attacks, only send blocks outside of the active
3833 // chain if they are valid, and no more than a month older (both in time, and in
3834 // best equivalent proof of work) than the best header chain we know about.
3835 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3836 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
3837 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
3838 if (!send) {
3839 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
3843 // disconnect node in case we have reached the outbound limit for serving historical blocks
3844 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
3845 if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) )
3847 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
3849 //disconnect node
3850 pfrom->fDisconnect = true;
3851 send = false;
3853 // Pruned nodes may have deleted the block, so check whether
3854 // it's available before trying to send.
3855 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
3857 // Send block from disk
3858 CBlock block;
3859 if (!ReadBlockFromDisk(block, (*mi).second))
3860 assert(!"cannot load block from disk");
3861 if (inv.type == MSG_BLOCK)
3862 pfrom->PushMessage("block", block);
3863 else // MSG_FILTERED_BLOCK)
3865 LOCK(pfrom->cs_filter);
3866 if (pfrom->pfilter)
3868 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3869 pfrom->PushMessage("merkleblock", merkleBlock);
3870 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3871 // This avoids hurting performance by pointlessly requiring a round-trip
3872 // Note that there is currently no way for a node to request any single transactions we didn't send here -
3873 // they must either disconnect and retry or request the full block.
3874 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3875 // however we MUST always provide at least what the remote peer needs
3876 typedef std::pair<unsigned int, uint256> PairType;
3877 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3878 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3879 pfrom->PushMessage("tx", block.vtx[pair.first]);
3881 // else
3882 // no response
3885 // Trigger the peer node to send a getblocks request for the next batch of inventory
3886 if (inv.hash == pfrom->hashContinue)
3888 // Bypass PushInventory, this must send even if redundant,
3889 // and we want it right after the last block so they don't
3890 // wait for other stuff first.
3891 vector<CInv> vInv;
3892 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3893 pfrom->PushMessage("inv", vInv);
3894 pfrom->hashContinue.SetNull();
3898 else if (inv.IsKnownType())
3900 // Send stream from relay memory
3901 bool pushed = false;
3903 LOCK(cs_mapRelay);
3904 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3905 if (mi != mapRelay.end()) {
3906 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3907 pushed = true;
3910 if (!pushed && inv.type == MSG_TX) {
3911 CTransaction tx;
3912 if (mempool.lookup(inv.hash, tx)) {
3913 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3914 ss.reserve(1000);
3915 ss << tx;
3916 pfrom->PushMessage("tx", ss);
3917 pushed = true;
3920 if (!pushed) {
3921 vNotFound.push_back(inv);
3925 // Track requests for our stuff.
3926 GetMainSignals().Inventory(inv.hash);
3928 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3929 break;
3933 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3935 if (!vNotFound.empty()) {
3936 // Let the peer know that we didn't find what it asked for, so it doesn't
3937 // have to wait around forever. Currently only SPV clients actually care
3938 // about this message: it's needed when they are recursively walking the
3939 // dependencies of relevant unconfirmed transactions. SPV clients want to
3940 // do that because they want to know about (and store and rebroadcast and
3941 // risk analyze) the dependencies of transactions relevant to them, without
3942 // having to download the entire memory pool.
3943 pfrom->PushMessage("notfound", vNotFound);
3947 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3949 const CChainParams& chainparams = Params();
3950 RandAddSeedPerfmon();
3951 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3952 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3954 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3955 return true;
3961 if (strCommand == "version")
3963 // Each connection can only send one version message
3964 if (pfrom->nVersion != 0)
3966 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3967 Misbehaving(pfrom->GetId(), 1);
3968 return false;
3971 int64_t nTime;
3972 CAddress addrMe;
3973 CAddress addrFrom;
3974 uint64_t nNonce = 1;
3975 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3976 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3978 // disconnect from peers older than this proto version
3979 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3980 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3981 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3982 pfrom->fDisconnect = true;
3983 return false;
3986 if (pfrom->nVersion == 10300)
3987 pfrom->nVersion = 300;
3988 if (!vRecv.empty())
3989 vRecv >> addrFrom >> nNonce;
3990 if (!vRecv.empty()) {
3991 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
3992 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3994 if (!vRecv.empty())
3995 vRecv >> pfrom->nStartingHeight;
3996 if (!vRecv.empty())
3997 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3998 else
3999 pfrom->fRelayTxes = true;
4001 // Disconnect if we connected to ourself
4002 if (nNonce == nLocalHostNonce && nNonce > 1)
4004 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4005 pfrom->fDisconnect = true;
4006 return true;
4009 pfrom->addrLocal = addrMe;
4010 if (pfrom->fInbound && addrMe.IsRoutable())
4012 SeenLocal(addrMe);
4015 // Be shy and don't send version until we hear
4016 if (pfrom->fInbound)
4017 pfrom->PushVersion();
4019 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4021 // Potentially mark this peer as a preferred download peer.
4022 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4024 // Change version
4025 pfrom->PushMessage("verack");
4026 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4028 if (!pfrom->fInbound)
4030 // Advertise our address
4031 if (fListen && !IsInitialBlockDownload())
4033 CAddress addr = GetLocalAddress(&pfrom->addr);
4034 if (addr.IsRoutable())
4036 pfrom->PushAddress(addr);
4037 } else if (IsPeerAddrLocalGood(pfrom)) {
4038 addr.SetIP(pfrom->addrLocal);
4039 pfrom->PushAddress(addr);
4043 // Get recent addresses
4044 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4046 pfrom->PushMessage("getaddr");
4047 pfrom->fGetAddr = true;
4049 addrman.Good(pfrom->addr);
4050 } else {
4051 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4053 addrman.Add(addrFrom, addrFrom);
4054 addrman.Good(addrFrom);
4058 // Relay alerts
4060 LOCK(cs_mapAlerts);
4061 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4062 item.second.RelayTo(pfrom);
4065 pfrom->fSuccessfullyConnected = true;
4067 string remoteAddr;
4068 if (fLogIPs)
4069 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4071 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4072 pfrom->cleanSubVer, pfrom->nVersion,
4073 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4074 remoteAddr);
4076 int64_t nTimeOffset = nTime - GetTime();
4077 pfrom->nTimeOffset = nTimeOffset;
4078 AddTimeData(pfrom->addr, nTimeOffset);
4082 else if (pfrom->nVersion == 0)
4084 // Must have a version message before anything else
4085 Misbehaving(pfrom->GetId(), 1);
4086 return false;
4090 else if (strCommand == "verack")
4092 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4094 // Mark this node as currently connected, so we update its timestamp later.
4095 if (pfrom->fNetworkNode) {
4096 LOCK(cs_main);
4097 State(pfrom->GetId())->fCurrentlyConnected = true;
4102 else if (strCommand == "addr")
4104 vector<CAddress> vAddr;
4105 vRecv >> vAddr;
4107 // Don't want addr from older versions unless seeding
4108 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4109 return true;
4110 if (vAddr.size() > 1000)
4112 Misbehaving(pfrom->GetId(), 20);
4113 return error("message addr size() = %u", vAddr.size());
4116 // Store the new addresses
4117 vector<CAddress> vAddrOk;
4118 int64_t nNow = GetAdjustedTime();
4119 int64_t nSince = nNow - 10 * 60;
4120 BOOST_FOREACH(CAddress& addr, vAddr)
4122 boost::this_thread::interruption_point();
4124 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4125 addr.nTime = nNow - 5 * 24 * 60 * 60;
4126 pfrom->AddAddressKnown(addr);
4127 bool fReachable = IsReachable(addr);
4128 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4130 // Relay to a limited number of other nodes
4132 LOCK(cs_vNodes);
4133 // Use deterministic randomness to send to the same nodes for 24 hours
4134 // at a time so the addrKnowns of the chosen nodes prevent repeats
4135 static uint256 hashSalt;
4136 if (hashSalt.IsNull())
4137 hashSalt = GetRandHash();
4138 uint64_t hashAddr = addr.GetHash();
4139 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4140 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4141 multimap<uint256, CNode*> mapMix;
4142 BOOST_FOREACH(CNode* pnode, vNodes)
4144 if (pnode->nVersion < CADDR_TIME_VERSION)
4145 continue;
4146 unsigned int nPointer;
4147 memcpy(&nPointer, &pnode, sizeof(nPointer));
4148 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4149 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4150 mapMix.insert(make_pair(hashKey, pnode));
4152 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4153 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4154 ((*mi).second)->PushAddress(addr);
4157 // Do not store addresses outside our network
4158 if (fReachable)
4159 vAddrOk.push_back(addr);
4161 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4162 if (vAddr.size() < 1000)
4163 pfrom->fGetAddr = false;
4164 if (pfrom->fOneShot)
4165 pfrom->fDisconnect = true;
4169 else if (strCommand == "inv")
4171 vector<CInv> vInv;
4172 vRecv >> vInv;
4173 if (vInv.size() > MAX_INV_SZ)
4175 Misbehaving(pfrom->GetId(), 20);
4176 return error("message inv size() = %u", vInv.size());
4179 LOCK(cs_main);
4181 std::vector<CInv> vToFetch;
4183 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4185 const CInv &inv = vInv[nInv];
4187 boost::this_thread::interruption_point();
4188 pfrom->AddInventoryKnown(inv);
4190 bool fAlreadyHave = AlreadyHave(inv);
4191 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4193 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4194 pfrom->AskFor(inv);
4196 if (inv.type == MSG_BLOCK) {
4197 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4198 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4199 // First request the headers preceding the announced block. In the normal fully-synced
4200 // case where a new block is announced that succeeds the current tip (no reorganization),
4201 // there are no such headers.
4202 // Secondly, and only when we are close to being synced, we request the announced block directly,
4203 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4204 // time the block arrives, the header chain leading up to it is already validated. Not
4205 // doing this will result in the received block being rejected as an orphan in case it is
4206 // not a direct successor.
4207 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4208 CNodeState *nodestate = State(pfrom->GetId());
4209 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4210 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4211 vToFetch.push_back(inv);
4212 // Mark block as in flight already, even though the actual "getdata" message only goes out
4213 // later (within the same cs_main lock, though).
4214 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4216 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4220 // Track requests for our stuff
4221 GetMainSignals().Inventory(inv.hash);
4223 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4224 Misbehaving(pfrom->GetId(), 50);
4225 return error("send buffer size() = %u", pfrom->nSendSize);
4229 if (!vToFetch.empty())
4230 pfrom->PushMessage("getdata", vToFetch);
4234 else if (strCommand == "getdata")
4236 vector<CInv> vInv;
4237 vRecv >> vInv;
4238 if (vInv.size() > MAX_INV_SZ)
4240 Misbehaving(pfrom->GetId(), 20);
4241 return error("message getdata size() = %u", vInv.size());
4244 if (fDebug || (vInv.size() != 1))
4245 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4247 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4248 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4250 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4251 ProcessGetData(pfrom);
4255 else if (strCommand == "getblocks")
4257 CBlockLocator locator;
4258 uint256 hashStop;
4259 vRecv >> locator >> hashStop;
4261 LOCK(cs_main);
4263 // Find the last block the caller has in the main chain
4264 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4266 // Send the rest of the chain
4267 if (pindex)
4268 pindex = chainActive.Next(pindex);
4269 int nLimit = 500;
4270 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4271 for (; pindex; pindex = chainActive.Next(pindex))
4273 if (pindex->GetBlockHash() == hashStop)
4275 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4276 break;
4278 // If pruning, don't inv blocks unless we have on disk and are likely to still have
4279 // for some reasonable time window (1 hour) that block relay might require.
4280 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
4281 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
4283 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4284 break;
4286 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4287 if (--nLimit <= 0)
4289 // When this block is requested, we'll send an inv that'll
4290 // trigger the peer to getblocks the next batch of inventory.
4291 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4292 pfrom->hashContinue = pindex->GetBlockHash();
4293 break;
4299 else if (strCommand == "getheaders")
4301 CBlockLocator locator;
4302 uint256 hashStop;
4303 vRecv >> locator >> hashStop;
4305 LOCK(cs_main);
4307 if (IsInitialBlockDownload())
4308 return true;
4310 CBlockIndex* pindex = NULL;
4311 if (locator.IsNull())
4313 // If locator is null, return the hashStop block
4314 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4315 if (mi == mapBlockIndex.end())
4316 return true;
4317 pindex = (*mi).second;
4319 else
4321 // Find the last block the caller has in the main chain
4322 pindex = FindForkInGlobalIndex(chainActive, locator);
4323 if (pindex)
4324 pindex = chainActive.Next(pindex);
4327 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4328 vector<CBlock> vHeaders;
4329 int nLimit = MAX_HEADERS_RESULTS;
4330 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4331 for (; pindex; pindex = chainActive.Next(pindex))
4333 vHeaders.push_back(pindex->GetBlockHeader());
4334 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4335 break;
4337 pfrom->PushMessage("headers", vHeaders);
4341 else if (strCommand == "tx")
4343 vector<uint256> vWorkQueue;
4344 vector<uint256> vEraseQueue;
4345 CTransaction tx;
4346 vRecv >> tx;
4348 CInv inv(MSG_TX, tx.GetHash());
4349 pfrom->AddInventoryKnown(inv);
4351 LOCK(cs_main);
4353 bool fMissingInputs = false;
4354 CValidationState state;
4356 mapAlreadyAskedFor.erase(inv);
4358 // Check for recently rejected (and do other quick existence checks)
4359 if (AlreadyHave(inv))
4360 return true;
4362 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4364 mempool.check(pcoinsTip);
4365 RelayTransaction(tx);
4366 vWorkQueue.push_back(inv.hash);
4368 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4369 pfrom->id,
4370 tx.GetHash().ToString(),
4371 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
4373 // Recursively process any orphan transactions that depended on this one
4374 set<NodeId> setMisbehaving;
4375 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4377 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4378 if (itByPrev == mapOrphanTransactionsByPrev.end())
4379 continue;
4380 for (set<uint256>::iterator mi = itByPrev->second.begin();
4381 mi != itByPrev->second.end();
4382 ++mi)
4384 const uint256& orphanHash = *mi;
4385 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4386 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4387 bool fMissingInputs2 = false;
4388 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4389 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4390 // anyone relaying LegitTxX banned)
4391 CValidationState stateDummy;
4394 if (setMisbehaving.count(fromPeer))
4395 continue;
4396 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4398 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4399 RelayTransaction(orphanTx);
4400 vWorkQueue.push_back(orphanHash);
4401 vEraseQueue.push_back(orphanHash);
4403 else if (!fMissingInputs2)
4405 int nDos = 0;
4406 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4408 // Punish peer that gave us an invalid orphan tx
4409 Misbehaving(fromPeer, nDos);
4410 setMisbehaving.insert(fromPeer);
4411 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4413 // Has inputs but not accepted to mempool
4414 // Probably non-standard or insufficient fee/priority
4415 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4416 vEraseQueue.push_back(orphanHash);
4417 assert(recentRejects);
4418 recentRejects->insert(orphanHash);
4420 mempool.check(pcoinsTip);
4424 BOOST_FOREACH(uint256 hash, vEraseQueue)
4425 EraseOrphanTx(hash);
4427 else if (fMissingInputs)
4429 AddOrphanTx(tx, pfrom->GetId());
4431 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4432 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4433 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4434 if (nEvicted > 0)
4435 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4436 } else {
4437 assert(recentRejects);
4438 recentRejects->insert(tx.GetHash());
4440 if (pfrom->fWhitelisted) {
4441 // Always relay transactions received from whitelisted peers, even
4442 // if they were rejected from the mempool, allowing the node to
4443 // function as a gateway for nodes hidden behind it.
4445 // FIXME: This includes invalid transactions, which means a
4446 // whitelisted peer could get us banned! We may want to change
4447 // that.
4448 RelayTransaction(tx);
4451 int nDoS = 0;
4452 if (state.IsInvalid(nDoS))
4454 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
4455 pfrom->id,
4456 FormatStateMessage(state));
4457 if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
4458 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4459 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4460 if (nDoS > 0)
4461 Misbehaving(pfrom->GetId(), nDoS);
4466 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4468 std::vector<CBlockHeader> headers;
4470 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4471 unsigned int nCount = ReadCompactSize(vRecv);
4472 if (nCount > MAX_HEADERS_RESULTS) {
4473 Misbehaving(pfrom->GetId(), 20);
4474 return error("headers message size = %u", nCount);
4476 headers.resize(nCount);
4477 for (unsigned int n = 0; n < nCount; n++) {
4478 vRecv >> headers[n];
4479 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4482 LOCK(cs_main);
4484 if (nCount == 0) {
4485 // Nothing interesting. Stop asking this peers for more headers.
4486 return true;
4489 CBlockIndex *pindexLast = NULL;
4490 BOOST_FOREACH(const CBlockHeader& header, headers) {
4491 CValidationState state;
4492 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4493 Misbehaving(pfrom->GetId(), 20);
4494 return error("non-continuous headers sequence");
4496 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4497 int nDoS;
4498 if (state.IsInvalid(nDoS)) {
4499 if (nDoS > 0)
4500 Misbehaving(pfrom->GetId(), nDoS);
4501 return error("invalid header received");
4506 if (pindexLast)
4507 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4509 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4510 // Headers message had its maximum size; the peer may have more headers.
4511 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4512 // from there instead.
4513 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4514 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4517 CheckBlockIndex();
4520 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4522 CBlock block;
4523 vRecv >> block;
4525 CInv inv(MSG_BLOCK, block.GetHash());
4526 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4528 pfrom->AddInventoryKnown(inv);
4530 CValidationState state;
4531 // Process all blocks from whitelisted peers, even if not requested,
4532 // unless we're still syncing with the network.
4533 // Such an unrequested block may still be processed, subject to the
4534 // conditions in AcceptBlock().
4535 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4536 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4537 int nDoS;
4538 if (state.IsInvalid(nDoS)) {
4539 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
4540 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4541 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4542 if (nDoS > 0) {
4543 LOCK(cs_main);
4544 Misbehaving(pfrom->GetId(), nDoS);
4551 // This asymmetric behavior for inbound and outbound connections was introduced
4552 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4553 // to users' AddrMan and later request them by sending getaddr messages.
4554 // Making nodes which are behind NAT and can only make outgoing connections ignore
4555 // the getaddr message mitigates the attack.
4556 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4558 pfrom->vAddrToSend.clear();
4559 vector<CAddress> vAddr = addrman.GetAddr();
4560 BOOST_FOREACH(const CAddress &addr, vAddr)
4561 pfrom->PushAddress(addr);
4565 else if (strCommand == "mempool")
4567 LOCK2(cs_main, pfrom->cs_filter);
4569 std::vector<uint256> vtxid;
4570 mempool.queryHashes(vtxid);
4571 vector<CInv> vInv;
4572 BOOST_FOREACH(uint256& hash, vtxid) {
4573 CInv inv(MSG_TX, hash);
4574 CTransaction tx;
4575 bool fInMemPool = mempool.lookup(hash, tx);
4576 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4577 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4578 (!pfrom->pfilter))
4579 vInv.push_back(inv);
4580 if (vInv.size() == MAX_INV_SZ) {
4581 pfrom->PushMessage("inv", vInv);
4582 vInv.clear();
4585 if (vInv.size() > 0)
4586 pfrom->PushMessage("inv", vInv);
4590 else if (strCommand == "ping")
4592 if (pfrom->nVersion > BIP0031_VERSION)
4594 uint64_t nonce = 0;
4595 vRecv >> nonce;
4596 // Echo the message back with the nonce. This allows for two useful features:
4598 // 1) A remote node can quickly check if the connection is operational
4599 // 2) Remote nodes can measure the latency of the network thread. If this node
4600 // is overloaded it won't respond to pings quickly and the remote node can
4601 // avoid sending us more work, like chain download requests.
4603 // The nonce stops the remote getting confused between different pings: without
4604 // it, if the remote node sends a ping once per second and this node takes 5
4605 // seconds to respond to each, the 5th ping the remote sends would appear to
4606 // return very quickly.
4607 pfrom->PushMessage("pong", nonce);
4612 else if (strCommand == "pong")
4614 int64_t pingUsecEnd = nTimeReceived;
4615 uint64_t nonce = 0;
4616 size_t nAvail = vRecv.in_avail();
4617 bool bPingFinished = false;
4618 std::string sProblem;
4620 if (nAvail >= sizeof(nonce)) {
4621 vRecv >> nonce;
4623 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4624 if (pfrom->nPingNonceSent != 0) {
4625 if (nonce == pfrom->nPingNonceSent) {
4626 // Matching pong received, this ping is no longer outstanding
4627 bPingFinished = true;
4628 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4629 if (pingUsecTime > 0) {
4630 // Successful ping time measurement, replace previous
4631 pfrom->nPingUsecTime = pingUsecTime;
4632 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4633 } else {
4634 // This should never happen
4635 sProblem = "Timing mishap";
4637 } else {
4638 // Nonce mismatches are normal when pings are overlapping
4639 sProblem = "Nonce mismatch";
4640 if (nonce == 0) {
4641 // This is most likely a bug in another implementation somewhere; cancel this ping
4642 bPingFinished = true;
4643 sProblem = "Nonce zero";
4646 } else {
4647 sProblem = "Unsolicited pong without ping";
4649 } else {
4650 // This is most likely a bug in another implementation somewhere; cancel this ping
4651 bPingFinished = true;
4652 sProblem = "Short payload";
4655 if (!(sProblem.empty())) {
4656 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
4657 pfrom->id,
4658 sProblem,
4659 pfrom->nPingNonceSent,
4660 nonce,
4661 nAvail);
4663 if (bPingFinished) {
4664 pfrom->nPingNonceSent = 0;
4669 else if (fAlerts && strCommand == "alert")
4671 CAlert alert;
4672 vRecv >> alert;
4674 uint256 alertHash = alert.GetHash();
4675 if (pfrom->setKnown.count(alertHash) == 0)
4677 if (alert.ProcessAlert(Params().AlertKey()))
4679 // Relay
4680 pfrom->setKnown.insert(alertHash);
4682 LOCK(cs_vNodes);
4683 BOOST_FOREACH(CNode* pnode, vNodes)
4684 alert.RelayTo(pnode);
4687 else {
4688 // Small DoS penalty so peers that send us lots of
4689 // duplicate/expired/invalid-signature/whatever alerts
4690 // eventually get banned.
4691 // This isn't a Misbehaving(100) (immediate ban) because the
4692 // peer might be an older or different implementation with
4693 // a different signature key, etc.
4694 Misbehaving(pfrom->GetId(), 10);
4700 else if (!(nLocalServices & NODE_BLOOM) &&
4701 (strCommand == "filterload" ||
4702 strCommand == "filteradd" ||
4703 strCommand == "filterclear") &&
4704 //TODO: Remove this line after reasonable network upgrade
4705 pfrom->nVersion >= NO_BLOOM_VERSION)
4707 if (pfrom->nVersion >= NO_BLOOM_VERSION)
4708 Misbehaving(pfrom->GetId(), 100);
4709 //TODO: Enable this after reasonable network upgrade
4710 //else
4711 // pfrom->fDisconnect = true;
4715 else if (strCommand == "filterload")
4717 CBloomFilter filter;
4718 vRecv >> filter;
4720 if (!filter.IsWithinSizeConstraints())
4721 // There is no excuse for sending a too-large filter
4722 Misbehaving(pfrom->GetId(), 100);
4723 else
4725 LOCK(pfrom->cs_filter);
4726 delete pfrom->pfilter;
4727 pfrom->pfilter = new CBloomFilter(filter);
4728 pfrom->pfilter->UpdateEmptyFull();
4730 pfrom->fRelayTxes = true;
4734 else if (strCommand == "filteradd")
4736 vector<unsigned char> vData;
4737 vRecv >> vData;
4739 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4740 // and thus, the maximum size any matched object can have) in a filteradd message
4741 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4743 Misbehaving(pfrom->GetId(), 100);
4744 } else {
4745 LOCK(pfrom->cs_filter);
4746 if (pfrom->pfilter)
4747 pfrom->pfilter->insert(vData);
4748 else
4749 Misbehaving(pfrom->GetId(), 100);
4754 else if (strCommand == "filterclear")
4756 LOCK(pfrom->cs_filter);
4757 delete pfrom->pfilter;
4758 pfrom->pfilter = new CBloomFilter();
4759 pfrom->fRelayTxes = true;
4763 else if (strCommand == "reject")
4765 if (fDebug) {
4766 try {
4767 string strMsg; unsigned char ccode; string strReason;
4768 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4770 ostringstream ss;
4771 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4773 if (strMsg == "block" || strMsg == "tx")
4775 uint256 hash;
4776 vRecv >> hash;
4777 ss << ": hash " << hash.ToString();
4779 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4780 } catch (const std::ios_base::failure&) {
4781 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4782 LogPrint("net", "Unparseable reject message received\n");
4787 else
4789 // Ignore unknown commands for extensibility
4790 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4795 return true;
4798 // requires LOCK(cs_vRecvMsg)
4799 bool ProcessMessages(CNode* pfrom)
4801 //if (fDebug)
4802 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
4805 // Message format
4806 // (4) message start
4807 // (12) command
4808 // (4) size
4809 // (4) checksum
4810 // (x) data
4812 bool fOk = true;
4814 if (!pfrom->vRecvGetData.empty())
4815 ProcessGetData(pfrom);
4817 // this maintains the order of responses
4818 if (!pfrom->vRecvGetData.empty()) return fOk;
4820 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4821 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4822 // Don't bother if send buffer is too full to respond anyway
4823 if (pfrom->nSendSize >= SendBufferSize())
4824 break;
4826 // get next message
4827 CNetMessage& msg = *it;
4829 //if (fDebug)
4830 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
4831 // msg.hdr.nMessageSize, msg.vRecv.size(),
4832 // msg.complete() ? "Y" : "N");
4834 // end, if an incomplete message is found
4835 if (!msg.complete())
4836 break;
4838 // at this point, any failure means we can delete the current message
4839 it++;
4841 // Scan for message start
4842 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4843 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4844 fOk = false;
4845 break;
4848 // Read header
4849 CMessageHeader& hdr = msg.hdr;
4850 if (!hdr.IsValid(Params().MessageStart()))
4852 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4853 continue;
4855 string strCommand = hdr.GetCommand();
4857 // Message size
4858 unsigned int nMessageSize = hdr.nMessageSize;
4860 // Checksum
4861 CDataStream& vRecv = msg.vRecv;
4862 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4863 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4864 if (nChecksum != hdr.nChecksum)
4866 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
4867 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4868 continue;
4871 // Process message
4872 bool fRet = false;
4875 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4876 boost::this_thread::interruption_point();
4878 catch (const std::ios_base::failure& e)
4880 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4881 if (strstr(e.what(), "end of data"))
4883 // Allow exceptions from under-length message on vRecv
4884 LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4886 else if (strstr(e.what(), "size too large"))
4888 // Allow exceptions from over-long size
4889 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4891 else
4893 PrintExceptionContinue(&e, "ProcessMessages()");
4896 catch (const boost::thread_interrupted&) {
4897 throw;
4899 catch (const std::exception& e) {
4900 PrintExceptionContinue(&e, "ProcessMessages()");
4901 } catch (...) {
4902 PrintExceptionContinue(NULL, "ProcessMessages()");
4905 if (!fRet)
4906 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
4908 break;
4911 // In case the connection got shut down, its receive buffer was wiped
4912 if (!pfrom->fDisconnect)
4913 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4915 return fOk;
4919 bool SendMessages(CNode* pto, bool fSendTrickle)
4921 const Consensus::Params& consensusParams = Params().GetConsensus();
4923 // Don't send anything until we get its version message
4924 if (pto->nVersion == 0)
4925 return true;
4928 // Message: ping
4930 bool pingSend = false;
4931 if (pto->fPingQueued) {
4932 // RPC ping request by user
4933 pingSend = true;
4935 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4936 // Ping automatically sent as a latency probe & keepalive.
4937 pingSend = true;
4939 if (pingSend) {
4940 uint64_t nonce = 0;
4941 while (nonce == 0) {
4942 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4944 pto->fPingQueued = false;
4945 pto->nPingUsecStart = GetTimeMicros();
4946 if (pto->nVersion > BIP0031_VERSION) {
4947 pto->nPingNonceSent = nonce;
4948 pto->PushMessage("ping", nonce);
4949 } else {
4950 // Peer is too old to support ping command with nonce, pong will never arrive.
4951 pto->nPingNonceSent = 0;
4952 pto->PushMessage("ping");
4956 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4957 if (!lockMain)
4958 return true;
4960 // Address refresh broadcast
4961 static int64_t nLastRebroadcast;
4962 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4964 LOCK(cs_vNodes);
4965 BOOST_FOREACH(CNode* pnode, vNodes)
4967 // Periodically clear addrKnown to allow refresh broadcasts
4968 if (nLastRebroadcast)
4969 pnode->addrKnown.reset();
4971 // Rebroadcast our address
4972 AdvertizeLocal(pnode);
4974 if (!vNodes.empty())
4975 nLastRebroadcast = GetTime();
4979 // Message: addr
4981 if (fSendTrickle)
4983 vector<CAddress> vAddr;
4984 vAddr.reserve(pto->vAddrToSend.size());
4985 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4987 if (!pto->addrKnown.contains(addr.GetKey()))
4989 pto->addrKnown.insert(addr.GetKey());
4990 vAddr.push_back(addr);
4991 // receiver rejects addr messages larger than 1000
4992 if (vAddr.size() >= 1000)
4994 pto->PushMessage("addr", vAddr);
4995 vAddr.clear();
4999 pto->vAddrToSend.clear();
5000 if (!vAddr.empty())
5001 pto->PushMessage("addr", vAddr);
5004 CNodeState &state = *State(pto->GetId());
5005 if (state.fShouldBan) {
5006 if (pto->fWhitelisted)
5007 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5008 else {
5009 pto->fDisconnect = true;
5010 if (pto->addr.IsLocal())
5011 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5012 else
5014 CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
5017 state.fShouldBan = false;
5020 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5021 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5022 state.rejects.clear();
5024 // Start block sync
5025 if (pindexBestHeader == NULL)
5026 pindexBestHeader = chainActive.Tip();
5027 bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
5028 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5029 // Only actively request headers from a single peer, unless we're close to today.
5030 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5031 state.fSyncStarted = true;
5032 nSyncStarted++;
5033 const CBlockIndex *pindexStart = pindexBestHeader;
5034 /* If possible, start at the block preceding the currently
5035 best known header. This ensures that we always get a
5036 non-empty list of headers back as long as the peer
5037 is up-to-date. With a non-empty response, we can initialise
5038 the peer's known best block. This wouldn't be possible
5039 if we requested starting at pindexBestHeader and
5040 got back an empty response. */
5041 if (pindexStart->pprev)
5042 pindexStart = pindexStart->pprev;
5043 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5044 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5048 // Resend wallet transactions that haven't gotten in a block yet
5049 // Except during reindex, importing and IBD, when old wallet
5050 // transactions become unconfirmed and spams other nodes.
5051 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5053 GetMainSignals().Broadcast(nTimeBestReceived);
5057 // Message: inventory
5059 vector<CInv> vInv;
5060 vector<CInv> vInvWait;
5062 LOCK(pto->cs_inventory);
5063 vInv.reserve(pto->vInventoryToSend.size());
5064 vInvWait.reserve(pto->vInventoryToSend.size());
5065 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5067 if (pto->setInventoryKnown.count(inv))
5068 continue;
5070 // trickle out tx inv to protect privacy
5071 if (inv.type == MSG_TX && !fSendTrickle)
5073 // 1/4 of tx invs blast to all immediately
5074 static uint256 hashSalt;
5075 if (hashSalt.IsNull())
5076 hashSalt = GetRandHash();
5077 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5078 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5079 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5081 if (fTrickleWait)
5083 vInvWait.push_back(inv);
5084 continue;
5088 // returns true if wasn't already contained in the set
5089 if (pto->setInventoryKnown.insert(inv).second)
5091 vInv.push_back(inv);
5092 if (vInv.size() >= 1000)
5094 pto->PushMessage("inv", vInv);
5095 vInv.clear();
5099 pto->vInventoryToSend = vInvWait;
5101 if (!vInv.empty())
5102 pto->PushMessage("inv", vInv);
5104 // Detect whether we're stalling
5105 int64_t nNow = GetTimeMicros();
5106 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5107 // Stalling only triggers when the block download window cannot move. During normal steady state,
5108 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5109 // should only happen during initial block download.
5110 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5111 pto->fDisconnect = true;
5113 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5114 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5115 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5116 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5117 // to unreasonably increase our timeout.
5118 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5119 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5120 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5121 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5122 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5123 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5124 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5125 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5126 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5127 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5128 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5130 if (queuedBlock.nTimeDisconnect < nNow) {
5131 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5132 pto->fDisconnect = true;
5137 // Message: getdata (blocks)
5139 vector<CInv> vGetData;
5140 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5141 vector<CBlockIndex*> vToDownload;
5142 NodeId staller = -1;
5143 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5144 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5145 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5146 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5147 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5148 pindex->nHeight, pto->id);
5150 if (state.nBlocksInFlight == 0 && staller != -1) {
5151 if (State(staller)->nStallingSince == 0) {
5152 State(staller)->nStallingSince = nNow;
5153 LogPrint("net", "Stall started peer=%d\n", staller);
5159 // Message: getdata (non-blocks)
5161 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5163 const CInv& inv = (*pto->mapAskFor.begin()).second;
5164 if (!AlreadyHave(inv))
5166 if (fDebug)
5167 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5168 vGetData.push_back(inv);
5169 if (vGetData.size() >= 1000)
5171 pto->PushMessage("getdata", vGetData);
5172 vGetData.clear();
5175 pto->mapAskFor.erase(pto->mapAskFor.begin());
5177 if (!vGetData.empty())
5178 pto->PushMessage("getdata", vGetData);
5181 return true;
5184 std::string CBlockFileInfo::ToString() const {
5185 return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
5190 class CMainCleanup
5192 public:
5193 CMainCleanup() {}
5194 ~CMainCleanup() {
5195 // block headers
5196 BlockMap::iterator it1 = mapBlockIndex.begin();
5197 for (; it1 != mapBlockIndex.end(); it1++)
5198 delete (*it1).second;
5199 mapBlockIndex.clear();
5201 // orphan transactions
5202 mapOrphanTransactions.clear();
5203 mapOrphanTransactionsByPrev.clear();
5205 } instance_of_cmaincleanup;