Merge pull request #6599
[bitcoinplatinum.git] / src / main.cpp
blob33b57a52858c91b2226de88043889df45787aee7
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 and mining) */
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)
655 AssertLockHeld(cs_main);
656 return IsFinalTx(tx, chainActive.Height() + 1, GetAdjustedTime());
659 unsigned int GetLegacySigOpCount(const CTransaction& tx)
661 unsigned int nSigOps = 0;
662 BOOST_FOREACH(const CTxIn& txin, tx.vin)
664 nSigOps += txin.scriptSig.GetSigOpCount(false);
666 BOOST_FOREACH(const CTxOut& txout, tx.vout)
668 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
670 return nSigOps;
673 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
675 if (tx.IsCoinBase())
676 return 0;
678 unsigned int nSigOps = 0;
679 for (unsigned int i = 0; i < tx.vin.size(); i++)
681 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
682 if (prevout.scriptPubKey.IsPayToScriptHash())
683 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
685 return nSigOps;
695 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
697 // Basic checks that don't depend on any context
698 if (tx.vin.empty())
699 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
700 if (tx.vout.empty())
701 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
702 // Size limits
703 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
704 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
706 // Check for negative or overflow output values
707 CAmount nValueOut = 0;
708 BOOST_FOREACH(const CTxOut& txout, tx.vout)
710 if (txout.nValue < 0)
711 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
712 if (txout.nValue > MAX_MONEY)
713 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
714 nValueOut += txout.nValue;
715 if (!MoneyRange(nValueOut))
716 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
719 // Check for duplicate inputs
720 set<COutPoint> vInOutPoints;
721 BOOST_FOREACH(const CTxIn& txin, tx.vin)
723 if (vInOutPoints.count(txin.prevout))
724 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
725 vInOutPoints.insert(txin.prevout);
728 if (tx.IsCoinBase())
730 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
731 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
733 else
735 BOOST_FOREACH(const CTxIn& txin, tx.vin)
736 if (txin.prevout.IsNull())
737 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
740 return true;
743 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
746 LOCK(mempool.cs);
747 uint256 hash = tx.GetHash();
748 double dPriorityDelta = 0;
749 CAmount nFeeDelta = 0;
750 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
751 if (dPriorityDelta > 0 || nFeeDelta > 0)
752 return 0;
755 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
757 if (fAllowFree)
759 // There is a free transaction area in blocks created by most miners,
760 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
761 // to be considered to fall into this category. We don't want to encourage sending
762 // multiple transactions instead of one big transaction to avoid fees.
763 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
764 nMinFee = 0;
767 if (!MoneyRange(nMinFee))
768 nMinFee = MAX_MONEY;
769 return nMinFee;
772 /** Convert CValidationState to a human-readable message for logging */
773 static std::string FormatStateMessage(const CValidationState &state)
775 return strprintf("%s%s (code %i)",
776 state.GetRejectReason(),
777 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
778 state.GetRejectCode());
781 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
782 bool* pfMissingInputs, bool fRejectAbsurdFee)
784 AssertLockHeld(cs_main);
785 if (pfMissingInputs)
786 *pfMissingInputs = false;
788 if (!CheckTransaction(tx, state))
789 return false;
791 // Coinbase is only valid in a block, not as a loose transaction
792 if (tx.IsCoinBase())
793 return state.DoS(100, false, REJECT_INVALID, "coinbase");
795 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
796 string reason;
797 if (fRequireStandard && !IsStandardTx(tx, reason))
798 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
800 // Only accept nLockTime-using transactions that can be mined in the next
801 // block; we don't want our mempool filled up with transactions that can't
802 // be mined yet.
803 if (!CheckFinalTx(tx))
804 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
806 // is it already in the memory pool?
807 uint256 hash = tx.GetHash();
808 if (pool.exists(hash))
809 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
811 // Check for conflicts with in-memory transactions
813 LOCK(pool.cs); // protect pool.mapNextTx
814 for (unsigned int i = 0; i < tx.vin.size(); i++)
816 COutPoint outpoint = tx.vin[i].prevout;
817 if (pool.mapNextTx.count(outpoint))
819 // Disable replacement feature for now
820 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
826 CCoinsView dummy;
827 CCoinsViewCache view(&dummy);
829 CAmount nValueIn = 0;
831 LOCK(pool.cs);
832 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
833 view.SetBackend(viewMemPool);
835 // do we already have it?
836 if (view.HaveCoins(hash))
837 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
839 // do all inputs exist?
840 // Note that this does not check for the presence of actual outputs (see the next check for that),
841 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
842 BOOST_FOREACH(const CTxIn txin, tx.vin) {
843 if (!view.HaveCoins(txin.prevout.hash)) {
844 if (pfMissingInputs)
845 *pfMissingInputs = true;
846 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
850 // are the actual inputs available?
851 if (!view.HaveInputs(tx))
852 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
854 // Bring the best block into scope
855 view.GetBestBlock();
857 nValueIn = view.GetValueIn(tx);
859 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
860 view.SetBackend(dummy);
863 // Check for non-standard pay-to-script-hash in inputs
864 if (fRequireStandard && !AreInputsStandard(tx, view))
865 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
867 // Check that the transaction doesn't have an excessive number of
868 // sigops, making it impossible to mine. Since the coinbase transaction
869 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
870 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
871 // merely non-standard transaction.
872 unsigned int nSigOps = GetLegacySigOpCount(tx);
873 nSigOps += GetP2SHSigOpCount(tx, view);
874 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
875 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
876 strprintf("%d > %d", nSigOps, MAX_STANDARD_TX_SIGOPS));
878 CAmount nValueOut = tx.GetValueOut();
879 CAmount nFees = nValueIn-nValueOut;
880 double dPriority = view.GetPriority(tx, chainActive.Height());
882 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
883 unsigned int nSize = entry.GetTxSize();
885 // Don't accept it if it can't get into a block
886 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
887 if (fLimitFree && nFees < txMinFee)
888 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false,
889 strprintf("%d < %d", nFees, txMinFee));
891 // Require that free transactions have sufficient priority to be mined in the next block.
892 if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
893 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
896 // Continuously rate-limit free (really, very-low-fee) transactions
897 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
898 // be annoying or make others' transactions take longer to confirm.
899 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
901 static CCriticalSection csFreeLimiter;
902 static double dFreeCount;
903 static int64_t nLastTime;
904 int64_t nNow = GetTime();
906 LOCK(csFreeLimiter);
908 // Use an exponentially decaying ~10-minute window:
909 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
910 nLastTime = nNow;
911 // -limitfreerelay unit is thousand-bytes-per-minute
912 // At default rate it would take over a month to fill 1GB
913 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
914 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
915 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
916 dFreeCount += nSize;
919 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
920 return state.Invalid(false,
921 REJECT_HIGHFEE, "absurdly-high-fee",
922 strprintf("%d > %d", nFees, ::minRelayTxFee.GetFee(nSize) * 10000));
924 // Check against previous transactions
925 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
926 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
927 return false;
929 // Check again against just the consensus-critical mandatory script
930 // verification flags, in case of bugs in the standard flags that cause
931 // transactions to pass as valid when they're actually invalid. For
932 // instance the STRICTENC flag was incorrectly allowing certain
933 // CHECKSIG NOT scripts to pass, even though they were invalid.
935 // There is a similar check in CreateNewBlock() to prevent creating
936 // invalid blocks, however allowing such transactions into the mempool
937 // can be exploited as a DoS attack.
938 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
940 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
941 __func__, hash.ToString(), FormatStateMessage(state));
944 // Store transaction in memory
945 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
948 SyncWithWallets(tx, NULL);
950 return true;
953 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
954 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
956 CBlockIndex *pindexSlow = NULL;
958 LOCK(cs_main);
960 if (mempool.lookup(hash, txOut))
962 return true;
966 if (fTxIndex) {
967 CDiskTxPos postx;
968 if (pblocktree->ReadTxIndex(hash, postx)) {
969 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
970 if (file.IsNull())
971 return error("%s: OpenBlockFile failed", __func__);
972 CBlockHeader header;
973 try {
974 file >> header;
975 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
976 file >> txOut;
977 } catch (const std::exception& e) {
978 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
980 hashBlock = header.GetHash();
981 if (txOut.GetHash() != hash)
982 return error("%s: txid mismatch", __func__);
983 return true;
987 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
988 int nHeight = -1;
990 CCoinsViewCache &view = *pcoinsTip;
991 const CCoins* coins = view.AccessCoins(hash);
992 if (coins)
993 nHeight = coins->nHeight;
995 if (nHeight > 0)
996 pindexSlow = chainActive[nHeight];
1000 if (pindexSlow) {
1001 CBlock block;
1002 if (ReadBlockFromDisk(block, pindexSlow)) {
1003 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1004 if (tx.GetHash() == hash) {
1005 txOut = tx;
1006 hashBlock = pindexSlow->GetBlockHash();
1007 return true;
1013 return false;
1021 //////////////////////////////////////////////////////////////////////////////
1023 // CBlock and CBlockIndex
1026 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1028 // Open history file to append
1029 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1030 if (fileout.IsNull())
1031 return error("WriteBlockToDisk: OpenBlockFile failed");
1033 // Write index header
1034 unsigned int nSize = fileout.GetSerializeSize(block);
1035 fileout << FLATDATA(messageStart) << nSize;
1037 // Write block
1038 long fileOutPos = ftell(fileout.Get());
1039 if (fileOutPos < 0)
1040 return error("WriteBlockToDisk: ftell failed");
1041 pos.nPos = (unsigned int)fileOutPos;
1042 fileout << block;
1044 return true;
1047 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1049 block.SetNull();
1051 // Open history file to read
1052 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1053 if (filein.IsNull())
1054 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1056 // Read block
1057 try {
1058 filein >> block;
1060 catch (const std::exception& e) {
1061 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1064 // Check the header
1065 if (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
1066 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1068 return true;
1071 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1073 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1074 return false;
1075 if (block.GetHash() != pindex->GetBlockHash())
1076 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1077 pindex->ToString(), pindex->GetBlockPos().ToString());
1078 return true;
1081 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1083 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1084 // Force block reward to zero when right shift is undefined.
1085 if (halvings >= 64)
1086 return 0;
1088 CAmount nSubsidy = 50 * COIN;
1089 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1090 nSubsidy >>= halvings;
1091 return nSubsidy;
1094 bool IsInitialBlockDownload()
1096 const CChainParams& chainParams = Params();
1097 LOCK(cs_main);
1098 if (fImporting || fReindex)
1099 return true;
1100 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1101 return true;
1102 static bool lockIBDState = false;
1103 if (lockIBDState)
1104 return false;
1105 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1106 pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1107 if (!state)
1108 lockIBDState = true;
1109 return state;
1112 bool fLargeWorkForkFound = false;
1113 bool fLargeWorkInvalidChainFound = false;
1114 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1116 void CheckForkWarningConditions()
1118 AssertLockHeld(cs_main);
1119 // Before we get past initial download, we cannot reliably alert about forks
1120 // (we assume we don't get stuck on a fork before the last checkpoint)
1121 if (IsInitialBlockDownload())
1122 return;
1124 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1125 // of our head, drop it
1126 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1127 pindexBestForkTip = NULL;
1129 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1131 if (!fLargeWorkForkFound && pindexBestForkBase)
1133 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1134 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1135 CAlert::Notify(warning, true);
1137 if (pindexBestForkTip && pindexBestForkBase)
1139 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__,
1140 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1141 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1142 fLargeWorkForkFound = true;
1144 else
1146 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1147 fLargeWorkInvalidChainFound = true;
1150 else
1152 fLargeWorkForkFound = false;
1153 fLargeWorkInvalidChainFound = false;
1157 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1159 AssertLockHeld(cs_main);
1160 // If we are on a fork that is sufficiently large, set a warning flag
1161 CBlockIndex* pfork = pindexNewForkTip;
1162 CBlockIndex* plonger = chainActive.Tip();
1163 while (pfork && pfork != plonger)
1165 while (plonger && plonger->nHeight > pfork->nHeight)
1166 plonger = plonger->pprev;
1167 if (pfork == plonger)
1168 break;
1169 pfork = pfork->pprev;
1172 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1173 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1174 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1175 // hash rate operating on the fork.
1176 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1177 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1178 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1179 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1180 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1181 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1183 pindexBestForkTip = pindexNewForkTip;
1184 pindexBestForkBase = pfork;
1187 CheckForkWarningConditions();
1190 // Requires cs_main.
1191 void Misbehaving(NodeId pnode, int howmuch)
1193 if (howmuch == 0)
1194 return;
1196 CNodeState *state = State(pnode);
1197 if (state == NULL)
1198 return;
1200 state->nMisbehavior += howmuch;
1201 int banscore = GetArg("-banscore", 100);
1202 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1204 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1205 state->fShouldBan = true;
1206 } else
1207 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1210 void static InvalidChainFound(CBlockIndex* pindexNew)
1212 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1213 pindexBestInvalid = pindexNew;
1215 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1216 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1217 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1218 pindexNew->GetBlockTime()));
1219 CBlockIndex *tip = chainActive.Tip();
1220 assert (tip);
1221 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1222 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1223 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1224 CheckForkWarningConditions();
1227 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1228 int nDoS = 0;
1229 if (state.IsInvalid(nDoS)) {
1230 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1231 if (it != mapBlockSource.end() && State(it->second)) {
1232 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
1233 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1234 State(it->second)->rejects.push_back(reject);
1235 if (nDoS > 0)
1236 Misbehaving(it->second, nDoS);
1239 if (!state.CorruptionPossible()) {
1240 pindex->nStatus |= BLOCK_FAILED_VALID;
1241 setDirtyBlockIndex.insert(pindex);
1242 setBlockIndexCandidates.erase(pindex);
1243 InvalidChainFound(pindex);
1247 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1249 // mark inputs spent
1250 if (!tx.IsCoinBase()) {
1251 txundo.vprevout.reserve(tx.vin.size());
1252 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1253 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1254 unsigned nPos = txin.prevout.n;
1256 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1257 assert(false);
1258 // mark an outpoint spent, and construct undo information
1259 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1260 coins->Spend(nPos);
1261 if (coins->vout.size() == 0) {
1262 CTxInUndo& undo = txundo.vprevout.back();
1263 undo.nHeight = coins->nHeight;
1264 undo.fCoinBase = coins->fCoinBase;
1265 undo.nVersion = coins->nVersion;
1270 // add outputs
1271 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1274 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1276 CTxUndo txundo;
1277 UpdateCoins(tx, state, inputs, txundo, nHeight);
1280 bool CScriptCheck::operator()() {
1281 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1282 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1283 return false;
1285 return true;
1288 int GetSpendHeight(const CCoinsViewCache& inputs)
1290 LOCK(cs_main);
1291 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1292 return pindexPrev->nHeight + 1;
1295 namespace Consensus {
1296 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1298 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1299 // for an attacker to attempt to split the network.
1300 if (!inputs.HaveInputs(tx))
1301 return state.Invalid(false, 0, "", "Inputs unavailable");
1303 CAmount nValueIn = 0;
1304 CAmount nFees = 0;
1305 for (unsigned int i = 0; i < tx.vin.size(); i++)
1307 const COutPoint &prevout = tx.vin[i].prevout;
1308 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1309 assert(coins);
1311 // If prev is coinbase, check that it's matured
1312 if (coins->IsCoinBase()) {
1313 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1314 return state.Invalid(false,
1315 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1316 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1319 // Check for negative or overflow input values
1320 nValueIn += coins->vout[prevout.n].nValue;
1321 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1322 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1326 if (nValueIn < tx.GetValueOut())
1327 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1328 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1330 // Tally transaction fees
1331 CAmount nTxFee = nValueIn - tx.GetValueOut();
1332 if (nTxFee < 0)
1333 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1334 nFees += nTxFee;
1335 if (!MoneyRange(nFees))
1336 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1337 return true;
1339 }// namespace Consensus
1341 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1343 if (!tx.IsCoinBase())
1345 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1346 return false;
1348 if (pvChecks)
1349 pvChecks->reserve(tx.vin.size());
1351 // The first loop above does all the inexpensive checks.
1352 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1353 // Helps prevent CPU exhaustion attacks.
1355 // Skip ECDSA signature verification when connecting blocks
1356 // before the last block chain checkpoint. This is safe because block merkle hashes are
1357 // still computed and checked, and any change will be caught at the next checkpoint.
1358 if (fScriptChecks) {
1359 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1360 const COutPoint &prevout = tx.vin[i].prevout;
1361 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1362 assert(coins);
1364 // Verify signature
1365 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1366 if (pvChecks) {
1367 pvChecks->push_back(CScriptCheck());
1368 check.swap(pvChecks->back());
1369 } else if (!check()) {
1370 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1371 // Check whether the failure was caused by a
1372 // non-mandatory script verification check, such as
1373 // non-standard DER encodings or non-null dummy
1374 // arguments; if so, don't trigger DoS protection to
1375 // avoid splitting the network between upgraded and
1376 // non-upgraded nodes.
1377 CScriptCheck check(*coins, tx, i,
1378 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1379 if (check())
1380 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1382 // Failures of other flags indicate a transaction that is
1383 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1384 // such nodes as they are not following the protocol. That
1385 // said during an upgrade careful thought should be taken
1386 // as to the correct behavior - we may want to continue
1387 // peering with non-upgraded nodes even after a soft-fork
1388 // super-majority vote has passed.
1389 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1395 return true;
1398 namespace {
1400 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1402 // Open history file to append
1403 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1404 if (fileout.IsNull())
1405 return error("%s: OpenUndoFile failed", __func__);
1407 // Write index header
1408 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1409 fileout << FLATDATA(messageStart) << nSize;
1411 // Write undo data
1412 long fileOutPos = ftell(fileout.Get());
1413 if (fileOutPos < 0)
1414 return error("%s: ftell failed", __func__);
1415 pos.nPos = (unsigned int)fileOutPos;
1416 fileout << blockundo;
1418 // calculate & write checksum
1419 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1420 hasher << hashBlock;
1421 hasher << blockundo;
1422 fileout << hasher.GetHash();
1424 return true;
1427 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1429 // Open history file to read
1430 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1431 if (filein.IsNull())
1432 return error("%s: OpenBlockFile failed", __func__);
1434 // Read block
1435 uint256 hashChecksum;
1436 try {
1437 filein >> blockundo;
1438 filein >> hashChecksum;
1440 catch (const std::exception& e) {
1441 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1444 // Verify checksum
1445 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1446 hasher << hashBlock;
1447 hasher << blockundo;
1448 if (hashChecksum != hasher.GetHash())
1449 return error("%s: Checksum mismatch", __func__);
1451 return true;
1454 /** Abort with a message */
1455 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1457 strMiscWarning = strMessage;
1458 LogPrintf("*** %s\n", strMessage);
1459 uiInterface.ThreadSafeMessageBox(
1460 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1461 "", CClientUIInterface::MSG_ERROR);
1462 StartShutdown();
1463 return false;
1466 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1468 AbortNode(strMessage, userMessage);
1469 return state.Error(strMessage);
1472 } // anon namespace
1475 * Apply the undo operation of a CTxInUndo to the given chain state.
1476 * @param undo The undo object.
1477 * @param view The coins view to which to apply the changes.
1478 * @param out The out point that corresponds to the tx input.
1479 * @return True on success.
1481 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1483 bool fClean = true;
1485 CCoinsModifier coins = view.ModifyCoins(out.hash);
1486 if (undo.nHeight != 0) {
1487 // undo data contains height: this is the last output of the prevout tx being spent
1488 if (!coins->IsPruned())
1489 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1490 coins->Clear();
1491 coins->fCoinBase = undo.fCoinBase;
1492 coins->nHeight = undo.nHeight;
1493 coins->nVersion = undo.nVersion;
1494 } else {
1495 if (coins->IsPruned())
1496 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1498 if (coins->IsAvailable(out.n))
1499 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1500 if (coins->vout.size() < out.n+1)
1501 coins->vout.resize(out.n+1);
1502 coins->vout[out.n] = undo.txout;
1504 return fClean;
1507 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1509 assert(pindex->GetBlockHash() == view.GetBestBlock());
1511 if (pfClean)
1512 *pfClean = false;
1514 bool fClean = true;
1516 CBlockUndo blockUndo;
1517 CDiskBlockPos pos = pindex->GetUndoPos();
1518 if (pos.IsNull())
1519 return error("DisconnectBlock(): no undo data available");
1520 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1521 return error("DisconnectBlock(): failure reading undo data");
1523 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1524 return error("DisconnectBlock(): block and undo data inconsistent");
1526 // undo transactions in reverse order
1527 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1528 const CTransaction &tx = block.vtx[i];
1529 uint256 hash = tx.GetHash();
1531 // Check that all outputs are available and match the outputs in the block itself
1532 // exactly.
1534 CCoinsModifier outs = view.ModifyCoins(hash);
1535 outs->ClearUnspendable();
1537 CCoins outsBlock(tx, pindex->nHeight);
1538 // The CCoins serialization does not serialize negative numbers.
1539 // No network rules currently depend on the version here, so an inconsistency is harmless
1540 // but it must be corrected before txout nversion ever influences a network rule.
1541 if (outsBlock.nVersion < 0)
1542 outs->nVersion = outsBlock.nVersion;
1543 if (*outs != outsBlock)
1544 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1546 // remove outputs
1547 outs->Clear();
1550 // restore inputs
1551 if (i > 0) { // not coinbases
1552 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1553 if (txundo.vprevout.size() != tx.vin.size())
1554 return error("DisconnectBlock(): transaction and undo data inconsistent");
1555 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1556 const COutPoint &out = tx.vin[j].prevout;
1557 const CTxInUndo &undo = txundo.vprevout[j];
1558 if (!ApplyTxInUndo(undo, view, out))
1559 fClean = false;
1564 // move best block pointer to prevout block
1565 view.SetBestBlock(pindex->pprev->GetBlockHash());
1567 if (pfClean) {
1568 *pfClean = fClean;
1569 return true;
1572 return fClean;
1575 void static FlushBlockFile(bool fFinalize = false)
1577 LOCK(cs_LastBlockFile);
1579 CDiskBlockPos posOld(nLastBlockFile, 0);
1581 FILE *fileOld = OpenBlockFile(posOld);
1582 if (fileOld) {
1583 if (fFinalize)
1584 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1585 FileCommit(fileOld);
1586 fclose(fileOld);
1589 fileOld = OpenUndoFile(posOld);
1590 if (fileOld) {
1591 if (fFinalize)
1592 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1593 FileCommit(fileOld);
1594 fclose(fileOld);
1598 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1600 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1602 void ThreadScriptCheck() {
1603 RenameThread("bitcoin-scriptch");
1604 scriptcheckqueue.Thread();
1608 // Called periodically asynchronously; alerts if it smells like
1609 // we're being fed a bad chain (blocks being generated much
1610 // too slowly or too quickly).
1612 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1613 int64_t nPowTargetSpacing)
1615 if (bestHeader == NULL || initialDownloadCheck()) return;
1617 static int64_t lastAlertTime = 0;
1618 int64_t now = GetAdjustedTime();
1619 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1621 const int SPAN_HOURS=4;
1622 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1623 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1625 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1627 std::string strWarning;
1628 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1630 LOCK(cs);
1631 const CBlockIndex* i = bestHeader;
1632 int nBlocks = 0;
1633 while (i->GetBlockTime() >= startTime) {
1634 ++nBlocks;
1635 i = i->pprev;
1636 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
1639 // How likely is it to find that many by chance?
1640 double p = boost::math::pdf(poisson, nBlocks);
1642 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1643 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
1645 // Aim for one false-positive about every fifty years of normal running:
1646 const int FIFTY_YEARS = 50*365*24*60*60;
1647 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
1649 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
1651 // Many fewer blocks than expected: alert!
1652 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
1653 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1655 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
1657 // Many more blocks than expected: alert!
1658 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
1659 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1661 if (!strWarning.empty())
1663 strMiscWarning = strWarning;
1664 CAlert::Notify(strWarning, true);
1665 lastAlertTime = now;
1669 static int64_t nTimeVerify = 0;
1670 static int64_t nTimeConnect = 0;
1671 static int64_t nTimeIndex = 0;
1672 static int64_t nTimeCallbacks = 0;
1673 static int64_t nTimeTotal = 0;
1675 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1677 const CChainParams& chainparams = Params();
1678 AssertLockHeld(cs_main);
1679 // Check it again in case a previous version let a bad block in
1680 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1681 return false;
1683 // verify that the view's current state corresponds to the previous block
1684 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1685 assert(hashPrevBlock == view.GetBestBlock());
1687 // Special case for the genesis block, skipping connection of its transactions
1688 // (its coinbase is unspendable)
1689 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1690 if (!fJustCheck)
1691 view.SetBestBlock(pindex->GetBlockHash());
1692 return true;
1695 bool fScriptChecks = true;
1696 if (fCheckpointsEnabled) {
1697 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
1698 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
1699 // This block is an ancestor of a checkpoint: disable script checks
1700 fScriptChecks = false;
1704 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1705 // unless those are already completely spent.
1706 // If such overwrites are allowed, coinbases and transactions depending upon those
1707 // can be duplicated to remove the ability to spend the first instance -- even after
1708 // being sent to another address.
1709 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1710 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1711 // already refuses previously-known transaction ids entirely.
1712 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1713 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1714 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1715 // initial block download.
1716 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1717 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1718 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1719 if (fEnforceBIP30) {
1720 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1721 const CCoins* coins = view.AccessCoins(tx.GetHash());
1722 if (coins && !coins->IsPruned())
1723 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1724 REJECT_INVALID, "bad-txns-BIP30");
1728 // BIP16 didn't become active until Apr 1 2012
1729 int64_t nBIP16SwitchTime = 1333238400;
1730 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1732 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1734 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1735 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1736 flags |= SCRIPT_VERIFY_DERSIG;
1739 CBlockUndo blockundo;
1741 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1743 int64_t nTimeStart = GetTimeMicros();
1744 CAmount nFees = 0;
1745 int nInputs = 0;
1746 unsigned int nSigOps = 0;
1747 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1748 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1749 vPos.reserve(block.vtx.size());
1750 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1751 for (unsigned int i = 0; i < block.vtx.size(); i++)
1753 const CTransaction &tx = block.vtx[i];
1755 nInputs += tx.vin.size();
1756 nSigOps += GetLegacySigOpCount(tx);
1757 if (nSigOps > MAX_BLOCK_SIGOPS)
1758 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1759 REJECT_INVALID, "bad-blk-sigops");
1761 if (!tx.IsCoinBase())
1763 if (!view.HaveInputs(tx))
1764 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1765 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1767 if (fStrictPayToScriptHash)
1769 // Add in sigops done by pay-to-script-hash inputs;
1770 // this is to prevent a "rogue miner" from creating
1771 // an incredibly-expensive-to-validate block.
1772 nSigOps += GetP2SHSigOpCount(tx, view);
1773 if (nSigOps > MAX_BLOCK_SIGOPS)
1774 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1775 REJECT_INVALID, "bad-blk-sigops");
1778 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1780 std::vector<CScriptCheck> vChecks;
1781 if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1782 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1783 tx.GetHash().ToString(), FormatStateMessage(state));
1784 control.Add(vChecks);
1787 CTxUndo undoDummy;
1788 if (i > 0) {
1789 blockundo.vtxundo.push_back(CTxUndo());
1791 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1793 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1794 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1796 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1797 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);
1799 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1800 if (block.vtx[0].GetValueOut() > blockReward)
1801 return state.DoS(100,
1802 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1803 block.vtx[0].GetValueOut(), blockReward),
1804 REJECT_INVALID, "bad-cb-amount");
1806 if (!control.Wait())
1807 return state.DoS(100, false);
1808 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1809 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);
1811 if (fJustCheck)
1812 return true;
1814 // Write undo information to disk
1815 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1817 if (pindex->GetUndoPos().IsNull()) {
1818 CDiskBlockPos pos;
1819 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1820 return error("ConnectBlock(): FindUndoPos failed");
1821 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1822 return AbortNode(state, "Failed to write undo data");
1824 // update nUndoPos in block index
1825 pindex->nUndoPos = pos.nPos;
1826 pindex->nStatus |= BLOCK_HAVE_UNDO;
1829 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1830 setDirtyBlockIndex.insert(pindex);
1833 if (fTxIndex)
1834 if (!pblocktree->WriteTxIndex(vPos))
1835 return AbortNode(state, "Failed to write transaction index");
1837 // add this block to the view's block chain
1838 view.SetBestBlock(pindex->GetBlockHash());
1840 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1841 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1843 // Watch for changes to the previous coinbase transaction.
1844 static uint256 hashPrevBestCoinBase;
1845 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1846 hashPrevBestCoinBase = block.vtx[0].GetHash();
1848 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1849 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1851 return true;
1854 enum FlushStateMode {
1855 FLUSH_STATE_NONE,
1856 FLUSH_STATE_IF_NEEDED,
1857 FLUSH_STATE_PERIODIC,
1858 FLUSH_STATE_ALWAYS
1862 * Update the on-disk chain state.
1863 * The caches and indexes are flushed depending on the mode we're called with
1864 * if they're too large, if it's been a while since the last write,
1865 * or always and in all cases if we're in prune mode and are deleting files.
1867 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1868 LOCK2(cs_main, cs_LastBlockFile);
1869 static int64_t nLastWrite = 0;
1870 static int64_t nLastFlush = 0;
1871 static int64_t nLastSetChain = 0;
1872 std::set<int> setFilesToPrune;
1873 bool fFlushForPrune = false;
1874 try {
1875 if (fPruneMode && fCheckForPruning) {
1876 FindFilesToPrune(setFilesToPrune);
1877 fCheckForPruning = false;
1878 if (!setFilesToPrune.empty()) {
1879 fFlushForPrune = true;
1880 if (!fHavePruned) {
1881 pblocktree->WriteFlag("prunedblockfiles", true);
1882 fHavePruned = true;
1886 int64_t nNow = GetTimeMicros();
1887 // Avoid writing/flushing immediately after startup.
1888 if (nLastWrite == 0) {
1889 nLastWrite = nNow;
1891 if (nLastFlush == 0) {
1892 nLastFlush = nNow;
1894 if (nLastSetChain == 0) {
1895 nLastSetChain = nNow;
1897 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1898 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1899 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
1900 // The cache is over the limit, we have to write now.
1901 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
1902 // 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.
1903 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1904 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1905 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1906 // Combine all conditions that result in a full cache flush.
1907 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1908 // Write blocks and block index to disk.
1909 if (fDoFullFlush || fPeriodicWrite) {
1910 // Depend on nMinDiskSpace to ensure we can write block index
1911 if (!CheckDiskSpace(0))
1912 return state.Error("out of disk space");
1913 // First make sure all block and undo data is flushed to disk.
1914 FlushBlockFile();
1915 // Then update all block file information (which may refer to block and undo files).
1917 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1918 vFiles.reserve(setDirtyFileInfo.size());
1919 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1920 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
1921 setDirtyFileInfo.erase(it++);
1923 std::vector<const CBlockIndex*> vBlocks;
1924 vBlocks.reserve(setDirtyBlockIndex.size());
1925 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1926 vBlocks.push_back(*it);
1927 setDirtyBlockIndex.erase(it++);
1929 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1930 return AbortNode(state, "Files to write to block index database");
1933 // Finally remove any pruned files
1934 if (fFlushForPrune)
1935 UnlinkPrunedFiles(setFilesToPrune);
1936 nLastWrite = nNow;
1938 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
1939 if (fDoFullFlush) {
1940 // Typical CCoins structures on disk are around 128 bytes in size.
1941 // Pushing a new one to the database can cause it to be written
1942 // twice (once in the log, and once in the tables). This is already
1943 // an overestimation, as most will delete an existing entry or
1944 // overwrite one. Still, use a conservative safety factor of 2.
1945 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
1946 return state.Error("out of disk space");
1947 // Flush the chainstate (which may refer to block index entries).
1948 if (!pcoinsTip->Flush())
1949 return AbortNode(state, "Failed to write to coin database");
1950 nLastFlush = nNow;
1952 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
1953 // Update best block in wallet (so we can detect restored wallets).
1954 GetMainSignals().SetBestChain(chainActive.GetLocator());
1955 nLastSetChain = nNow;
1957 } catch (const std::runtime_error& e) {
1958 return AbortNode(state, std::string("System error while flushing: ") + e.what());
1960 return true;
1963 void FlushStateToDisk() {
1964 CValidationState state;
1965 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1968 void PruneAndFlush() {
1969 CValidationState state;
1970 fCheckForPruning = true;
1971 FlushStateToDisk(state, FLUSH_STATE_NONE);
1974 /** Update chainActive and related internal data structures. */
1975 void static UpdateTip(CBlockIndex *pindexNew) {
1976 const CChainParams& chainParams = Params();
1977 chainActive.SetTip(pindexNew);
1979 // New best block
1980 nTimeBestReceived = GetTime();
1981 mempool.AddTransactionsUpdated(1);
1983 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
1984 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1985 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1986 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
1988 cvBlockChange.notify_all();
1990 // Check the version of the last 100 blocks to see if we need to upgrade:
1991 static bool fWarned = false;
1992 if (!IsInitialBlockDownload() && !fWarned)
1994 int nUpgraded = 0;
1995 const CBlockIndex* pindex = chainActive.Tip();
1996 for (int i = 0; i < 100 && pindex != NULL; i++)
1998 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1999 ++nUpgraded;
2000 pindex = pindex->pprev;
2002 if (nUpgraded > 0)
2003 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2004 if (nUpgraded > 100/2)
2006 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2007 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2008 CAlert::Notify(strMiscWarning, true);
2009 fWarned = true;
2014 /** Disconnect chainActive's tip. */
2015 bool static DisconnectTip(CValidationState &state) {
2016 CBlockIndex *pindexDelete = chainActive.Tip();
2017 assert(pindexDelete);
2018 mempool.check(pcoinsTip);
2019 // Read block from disk.
2020 CBlock block;
2021 if (!ReadBlockFromDisk(block, pindexDelete))
2022 return AbortNode(state, "Failed to read block");
2023 // Apply the block atomically to the chain state.
2024 int64_t nStart = GetTimeMicros();
2026 CCoinsViewCache view(pcoinsTip);
2027 if (!DisconnectBlock(block, state, pindexDelete, view))
2028 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2029 assert(view.Flush());
2031 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2032 // Write the chain state to disk, if necessary.
2033 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2034 return false;
2035 // Resurrect mempool transactions from the disconnected block.
2036 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2037 // ignore validation errors in resurrected transactions
2038 list<CTransaction> removed;
2039 CValidationState stateDummy;
2040 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2041 mempool.remove(tx, removed, true);
2043 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2044 mempool.check(pcoinsTip);
2045 // Update chainActive and related variables.
2046 UpdateTip(pindexDelete->pprev);
2047 // Let wallets know transactions went from 1-confirmed to
2048 // 0-confirmed or conflicted:
2049 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2050 SyncWithWallets(tx, NULL);
2052 return true;
2055 static int64_t nTimeReadFromDisk = 0;
2056 static int64_t nTimeConnectTotal = 0;
2057 static int64_t nTimeFlush = 0;
2058 static int64_t nTimeChainState = 0;
2059 static int64_t nTimePostConnect = 0;
2062 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2063 * corresponding to pindexNew, to bypass loading it again from disk.
2065 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, const CBlock *pblock) {
2066 assert(pindexNew->pprev == chainActive.Tip());
2067 mempool.check(pcoinsTip);
2068 // Read block from disk.
2069 int64_t nTime1 = GetTimeMicros();
2070 CBlock block;
2071 if (!pblock) {
2072 if (!ReadBlockFromDisk(block, pindexNew))
2073 return AbortNode(state, "Failed to read block");
2074 pblock = &block;
2076 // Apply the block atomically to the chain state.
2077 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2078 int64_t nTime3;
2079 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2081 CCoinsViewCache view(pcoinsTip);
2082 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2083 GetMainSignals().BlockChecked(*pblock, state);
2084 if (!rv) {
2085 if (state.IsInvalid())
2086 InvalidBlockFound(pindexNew, state);
2087 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2089 mapBlockSource.erase(pindexNew->GetBlockHash());
2090 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2091 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2092 assert(view.Flush());
2094 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2095 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2096 // Write the chain state to disk, if necessary.
2097 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2098 return false;
2099 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2100 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2101 // Remove conflicting transactions from the mempool.
2102 list<CTransaction> txConflicted;
2103 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2104 mempool.check(pcoinsTip);
2105 // Update chainActive & related variables.
2106 UpdateTip(pindexNew);
2107 // Tell wallet about transactions that went from mempool
2108 // to conflicted:
2109 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2110 SyncWithWallets(tx, NULL);
2112 // ... and about transactions that got confirmed:
2113 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2114 SyncWithWallets(tx, pblock);
2117 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2118 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2119 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2120 return true;
2124 * Return the tip of the chain with the most work in it, that isn't
2125 * known to be invalid (it's however far from certain to be valid).
2127 static CBlockIndex* FindMostWorkChain() {
2128 do {
2129 CBlockIndex *pindexNew = NULL;
2131 // Find the best candidate header.
2133 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2134 if (it == setBlockIndexCandidates.rend())
2135 return NULL;
2136 pindexNew = *it;
2139 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2140 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2141 CBlockIndex *pindexTest = pindexNew;
2142 bool fInvalidAncestor = false;
2143 while (pindexTest && !chainActive.Contains(pindexTest)) {
2144 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2146 // Pruned nodes may have entries in setBlockIndexCandidates for
2147 // which block files have been deleted. Remove those as candidates
2148 // for the most work chain if we come across them; we can't switch
2149 // to a chain unless we have all the non-active-chain parent blocks.
2150 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2151 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2152 if (fFailedChain || fMissingData) {
2153 // Candidate chain is not usable (either invalid or missing data)
2154 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2155 pindexBestInvalid = pindexNew;
2156 CBlockIndex *pindexFailed = pindexNew;
2157 // Remove the entire chain from the set.
2158 while (pindexTest != pindexFailed) {
2159 if (fFailedChain) {
2160 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2161 } else if (fMissingData) {
2162 // If we're missing data, then add back to mapBlocksUnlinked,
2163 // so that if the block arrives in the future we can try adding
2164 // to setBlockIndexCandidates again.
2165 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2167 setBlockIndexCandidates.erase(pindexFailed);
2168 pindexFailed = pindexFailed->pprev;
2170 setBlockIndexCandidates.erase(pindexTest);
2171 fInvalidAncestor = true;
2172 break;
2174 pindexTest = pindexTest->pprev;
2176 if (!fInvalidAncestor)
2177 return pindexNew;
2178 } while(true);
2181 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2182 static void PruneBlockIndexCandidates() {
2183 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2184 // reorganization to a better block fails.
2185 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2186 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2187 setBlockIndexCandidates.erase(it++);
2189 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2190 assert(!setBlockIndexCandidates.empty());
2194 * Try to make some progress towards making pindexMostWork the active block.
2195 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2197 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, const CBlock *pblock) {
2198 AssertLockHeld(cs_main);
2199 bool fInvalidFound = false;
2200 const CBlockIndex *pindexOldTip = chainActive.Tip();
2201 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2203 // Disconnect active blocks which are no longer in the best chain.
2204 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2205 if (!DisconnectTip(state))
2206 return false;
2209 // Build list of new blocks to connect.
2210 std::vector<CBlockIndex*> vpindexToConnect;
2211 bool fContinue = true;
2212 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2213 while (fContinue && nHeight != pindexMostWork->nHeight) {
2214 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2215 // a few blocks along the way.
2216 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2217 vpindexToConnect.clear();
2218 vpindexToConnect.reserve(nTargetHeight - nHeight);
2219 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2220 while (pindexIter && pindexIter->nHeight != nHeight) {
2221 vpindexToConnect.push_back(pindexIter);
2222 pindexIter = pindexIter->pprev;
2224 nHeight = nTargetHeight;
2226 // Connect new blocks.
2227 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2228 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2229 if (state.IsInvalid()) {
2230 // The block violates a consensus rule.
2231 if (!state.CorruptionPossible())
2232 InvalidChainFound(vpindexToConnect.back());
2233 state = CValidationState();
2234 fInvalidFound = true;
2235 fContinue = false;
2236 break;
2237 } else {
2238 // A system error occurred (disk space, database error, ...).
2239 return false;
2241 } else {
2242 PruneBlockIndexCandidates();
2243 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2244 // We're in a better position than we were. Return temporarily to release the lock.
2245 fContinue = false;
2246 break;
2252 // Callbacks/notifications for a new best chain.
2253 if (fInvalidFound)
2254 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2255 else
2256 CheckForkWarningConditions();
2258 return true;
2262 * Make the best chain active, in multiple steps. The result is either failure
2263 * or an activated best chain. pblock is either NULL or a pointer to a block
2264 * that is already loaded (to avoid loading it again from disk).
2266 bool ActivateBestChain(CValidationState &state, const CBlock *pblock) {
2267 CBlockIndex *pindexNewTip = NULL;
2268 CBlockIndex *pindexMostWork = NULL;
2269 const CChainParams& chainParams = Params();
2270 do {
2271 boost::this_thread::interruption_point();
2273 bool fInitialDownload;
2275 LOCK(cs_main);
2276 pindexMostWork = FindMostWorkChain();
2278 // Whether we have anything to do at all.
2279 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2280 return true;
2282 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2283 return false;
2285 pindexNewTip = chainActive.Tip();
2286 fInitialDownload = IsInitialBlockDownload();
2288 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2290 // Notifications/callbacks that can run without cs_main
2291 if (!fInitialDownload) {
2292 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2293 // Relay inventory, but don't relay old inventory during initial block download.
2294 int nBlockEstimate = 0;
2295 if (fCheckpointsEnabled)
2296 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2297 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2298 // in a stalled download if the block file is pruned before the request.
2299 if (nLocalServices & NODE_NETWORK) {
2300 LOCK(cs_vNodes);
2301 BOOST_FOREACH(CNode* pnode, vNodes)
2302 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2303 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2305 // Notify external listeners about the new tip.
2306 uiInterface.NotifyBlockTip(hashNewTip);
2308 } while(pindexMostWork != chainActive.Tip());
2309 CheckBlockIndex();
2311 // Write changes periodically to disk, after relay.
2312 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2313 return false;
2316 return true;
2319 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2320 AssertLockHeld(cs_main);
2322 // Mark the block itself as invalid.
2323 pindex->nStatus |= BLOCK_FAILED_VALID;
2324 setDirtyBlockIndex.insert(pindex);
2325 setBlockIndexCandidates.erase(pindex);
2327 while (chainActive.Contains(pindex)) {
2328 CBlockIndex *pindexWalk = chainActive.Tip();
2329 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2330 setDirtyBlockIndex.insert(pindexWalk);
2331 setBlockIndexCandidates.erase(pindexWalk);
2332 // ActivateBestChain considers blocks already in chainActive
2333 // unconditionally valid already, so force disconnect away from it.
2334 if (!DisconnectTip(state)) {
2335 return false;
2339 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2340 // add it again.
2341 BlockMap::iterator it = mapBlockIndex.begin();
2342 while (it != mapBlockIndex.end()) {
2343 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2344 setBlockIndexCandidates.insert(it->second);
2346 it++;
2349 InvalidChainFound(pindex);
2350 return true;
2353 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2354 AssertLockHeld(cs_main);
2356 int nHeight = pindex->nHeight;
2358 // Remove the invalidity flag from this block and all its descendants.
2359 BlockMap::iterator it = mapBlockIndex.begin();
2360 while (it != mapBlockIndex.end()) {
2361 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2362 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2363 setDirtyBlockIndex.insert(it->second);
2364 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2365 setBlockIndexCandidates.insert(it->second);
2367 if (it->second == pindexBestInvalid) {
2368 // Reset invalid block marker if it was pointing to one of those.
2369 pindexBestInvalid = NULL;
2372 it++;
2375 // Remove the invalidity flag from all ancestors too.
2376 while (pindex != NULL) {
2377 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2378 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2379 setDirtyBlockIndex.insert(pindex);
2381 pindex = pindex->pprev;
2383 return true;
2386 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2388 // Check for duplicate
2389 uint256 hash = block.GetHash();
2390 BlockMap::iterator it = mapBlockIndex.find(hash);
2391 if (it != mapBlockIndex.end())
2392 return it->second;
2394 // Construct new block index object
2395 CBlockIndex* pindexNew = new CBlockIndex(block);
2396 assert(pindexNew);
2397 // We assign the sequence id to blocks only when the full data is available,
2398 // to avoid miners withholding blocks but broadcasting headers, to get a
2399 // competitive advantage.
2400 pindexNew->nSequenceId = 0;
2401 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2402 pindexNew->phashBlock = &((*mi).first);
2403 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2404 if (miPrev != mapBlockIndex.end())
2406 pindexNew->pprev = (*miPrev).second;
2407 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2408 pindexNew->BuildSkip();
2410 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2411 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2412 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2413 pindexBestHeader = pindexNew;
2415 setDirtyBlockIndex.insert(pindexNew);
2417 return pindexNew;
2420 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2421 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2423 pindexNew->nTx = block.vtx.size();
2424 pindexNew->nChainTx = 0;
2425 pindexNew->nFile = pos.nFile;
2426 pindexNew->nDataPos = pos.nPos;
2427 pindexNew->nUndoPos = 0;
2428 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2429 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2430 setDirtyBlockIndex.insert(pindexNew);
2432 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2433 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2434 deque<CBlockIndex*> queue;
2435 queue.push_back(pindexNew);
2437 // Recursively process any descendant blocks that now may be eligible to be connected.
2438 while (!queue.empty()) {
2439 CBlockIndex *pindex = queue.front();
2440 queue.pop_front();
2441 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2443 LOCK(cs_nBlockSequenceId);
2444 pindex->nSequenceId = nBlockSequenceId++;
2446 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2447 setBlockIndexCandidates.insert(pindex);
2449 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2450 while (range.first != range.second) {
2451 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2452 queue.push_back(it->second);
2453 range.first++;
2454 mapBlocksUnlinked.erase(it);
2457 } else {
2458 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2459 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2463 return true;
2466 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2468 LOCK(cs_LastBlockFile);
2470 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2471 if (vinfoBlockFile.size() <= nFile) {
2472 vinfoBlockFile.resize(nFile + 1);
2475 if (!fKnown) {
2476 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2477 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2478 FlushBlockFile(true);
2479 nFile++;
2480 if (vinfoBlockFile.size() <= nFile) {
2481 vinfoBlockFile.resize(nFile + 1);
2484 pos.nFile = nFile;
2485 pos.nPos = vinfoBlockFile[nFile].nSize;
2488 nLastBlockFile = nFile;
2489 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2490 if (fKnown)
2491 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2492 else
2493 vinfoBlockFile[nFile].nSize += nAddSize;
2495 if (!fKnown) {
2496 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2497 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2498 if (nNewChunks > nOldChunks) {
2499 if (fPruneMode)
2500 fCheckForPruning = true;
2501 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2502 FILE *file = OpenBlockFile(pos);
2503 if (file) {
2504 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2505 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2506 fclose(file);
2509 else
2510 return state.Error("out of disk space");
2514 setDirtyFileInfo.insert(nFile);
2515 return true;
2518 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2520 pos.nFile = nFile;
2522 LOCK(cs_LastBlockFile);
2524 unsigned int nNewSize;
2525 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2526 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2527 setDirtyFileInfo.insert(nFile);
2529 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2530 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2531 if (nNewChunks > nOldChunks) {
2532 if (fPruneMode)
2533 fCheckForPruning = true;
2534 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2535 FILE *file = OpenUndoFile(pos);
2536 if (file) {
2537 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2538 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2539 fclose(file);
2542 else
2543 return state.Error("out of disk space");
2546 return true;
2549 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2551 // Check proof of work matches claimed amount
2552 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2553 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2554 REJECT_INVALID, "high-hash");
2556 // Check timestamp
2557 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2558 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2559 REJECT_INVALID, "time-too-new");
2561 return true;
2564 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2566 // These are checks that are independent of context.
2568 // Check that the header is valid (particularly PoW). This is mostly
2569 // redundant with the call in AcceptBlockHeader.
2570 if (!CheckBlockHeader(block, state, fCheckPOW))
2571 return false;
2573 // Check the merkle root.
2574 if (fCheckMerkleRoot) {
2575 bool mutated;
2576 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2577 if (block.hashMerkleRoot != hashMerkleRoot2)
2578 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2579 REJECT_INVALID, "bad-txnmrklroot", true);
2581 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2582 // of transactions in a block without affecting the merkle root of a block,
2583 // while still invalidating it.
2584 if (mutated)
2585 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2586 REJECT_INVALID, "bad-txns-duplicate", true);
2589 // All potential-corruption validation must be done before we do any
2590 // transaction validation, as otherwise we may mark the header as invalid
2591 // because we receive the wrong transactions for it.
2593 // Size limits
2594 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2595 return state.DoS(100, error("CheckBlock(): size limits failed"),
2596 REJECT_INVALID, "bad-blk-length");
2598 // First transaction must be coinbase, the rest must not be
2599 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2600 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2601 REJECT_INVALID, "bad-cb-missing");
2602 for (unsigned int i = 1; i < block.vtx.size(); i++)
2603 if (block.vtx[i].IsCoinBase())
2604 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2605 REJECT_INVALID, "bad-cb-multiple");
2607 // Check transactions
2608 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2609 if (!CheckTransaction(tx, state))
2610 return error("CheckBlock(): CheckTransaction of %s failed with %s",
2611 tx.GetHash().ToString(),
2612 FormatStateMessage(state));
2614 unsigned int nSigOps = 0;
2615 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2617 nSigOps += GetLegacySigOpCount(tx);
2619 if (nSigOps > MAX_BLOCK_SIGOPS)
2620 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2621 REJECT_INVALID, "bad-blk-sigops", true);
2623 return true;
2626 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2628 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2629 return true;
2631 int nHeight = pindexPrev->nHeight+1;
2632 // Don't accept any forks from the main chain prior to last checkpoint
2633 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2634 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2635 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2637 return true;
2640 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2642 const Consensus::Params& consensusParams = Params().GetConsensus();
2643 // Check proof of work
2644 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2645 return state.DoS(100, error("%s: incorrect proof of work", __func__),
2646 REJECT_INVALID, "bad-diffbits");
2648 // Check timestamp against prev
2649 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2650 return state.Invalid(error("%s: block's timestamp is too early", __func__),
2651 REJECT_INVALID, "time-too-old");
2653 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2654 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2655 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2656 REJECT_OBSOLETE, "bad-version");
2658 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2659 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2660 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2661 REJECT_OBSOLETE, "bad-version");
2663 return true;
2666 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2668 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2669 const Consensus::Params& consensusParams = Params().GetConsensus();
2671 // Check that all transactions are finalized
2672 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2673 if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2674 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2677 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2678 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2679 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
2681 CScript expect = CScript() << nHeight;
2682 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2683 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2684 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2688 return true;
2691 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2693 const CChainParams& chainparams = Params();
2694 AssertLockHeld(cs_main);
2695 // Check for duplicate
2696 uint256 hash = block.GetHash();
2697 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2698 CBlockIndex *pindex = NULL;
2699 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2701 if (miSelf != mapBlockIndex.end()) {
2702 // Block header is already known.
2703 pindex = miSelf->second;
2704 if (ppindex)
2705 *ppindex = pindex;
2706 if (pindex->nStatus & BLOCK_FAILED_MASK)
2707 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2708 return true;
2711 if (!CheckBlockHeader(block, state))
2712 return false;
2714 // Get prev block index
2715 CBlockIndex* pindexPrev = NULL;
2716 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2717 if (mi == mapBlockIndex.end())
2718 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2719 pindexPrev = (*mi).second;
2720 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2721 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2723 assert(pindexPrev);
2724 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2725 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2727 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2728 return false;
2730 if (pindex == NULL)
2731 pindex = AddToBlockIndex(block);
2733 if (ppindex)
2734 *ppindex = pindex;
2736 return true;
2739 bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
2741 const CChainParams& chainparams = Params();
2742 AssertLockHeld(cs_main);
2744 CBlockIndex *&pindex = *ppindex;
2746 if (!AcceptBlockHeader(block, state, &pindex))
2747 return false;
2749 // Try to process all requested blocks that we don't have, but only
2750 // process an unrequested block if it's new and has enough work to
2751 // advance our tip, and isn't too many blocks ahead.
2752 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2753 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2754 // Blocks that are too out-of-order needlessly limit the effectiveness of
2755 // pruning, because pruning will not delete block files that contain any
2756 // blocks which are too close in height to the tip. Apply this test
2757 // regardless of whether pruning is enabled; it should generally be safe to
2758 // not process unrequested blocks.
2759 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2761 // TODO: deal better with return value and error conditions for duplicate
2762 // and unrequested blocks.
2763 if (fAlreadyHave) return true;
2764 if (!fRequested) { // If we didn't ask for it:
2765 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2766 if (!fHasMoreWork) return true; // Don't process less-work chains
2767 if (fTooFarAhead) return true; // Block height is too high
2770 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2771 if (state.IsInvalid() && !state.CorruptionPossible()) {
2772 pindex->nStatus |= BLOCK_FAILED_VALID;
2773 setDirtyBlockIndex.insert(pindex);
2775 return false;
2778 int nHeight = pindex->nHeight;
2780 // Write block to history file
2781 try {
2782 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2783 CDiskBlockPos blockPos;
2784 if (dbp != NULL)
2785 blockPos = *dbp;
2786 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2787 return error("AcceptBlock(): FindBlockPos failed");
2788 if (dbp == NULL)
2789 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2790 AbortNode(state, "Failed to write block");
2791 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2792 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2793 } catch (const std::runtime_error& e) {
2794 return AbortNode(state, std::string("System error: ") + e.what());
2797 if (fCheckForPruning)
2798 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2800 return true;
2803 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
2805 unsigned int nFound = 0;
2806 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
2808 if (pstart->nVersion >= minVersion)
2809 ++nFound;
2810 pstart = pstart->pprev;
2812 return (nFound >= nRequired);
2816 bool ProcessNewBlock(CValidationState &state, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
2818 // Preliminary checks
2819 bool checked = CheckBlock(*pblock, state);
2822 LOCK(cs_main);
2823 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
2824 fRequested |= fForceProcessing;
2825 if (!checked) {
2826 return error("%s: CheckBlock FAILED", __func__);
2829 // Store to disk
2830 CBlockIndex *pindex = NULL;
2831 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
2832 if (pindex && pfrom) {
2833 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2835 CheckBlockIndex();
2836 if (!ret)
2837 return error("%s: AcceptBlock FAILED", __func__);
2840 if (!ActivateBestChain(state, pblock))
2841 return error("%s: ActivateBestChain failed", __func__);
2843 return true;
2846 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2848 const CChainParams& chainparams = Params();
2849 AssertLockHeld(cs_main);
2850 assert(pindexPrev && pindexPrev == chainActive.Tip());
2851 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
2852 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2854 CCoinsViewCache viewNew(pcoinsTip);
2855 CBlockIndex indexDummy(block);
2856 indexDummy.pprev = pindexPrev;
2857 indexDummy.nHeight = pindexPrev->nHeight + 1;
2859 // NOTE: CheckBlockHeader is called by CheckBlock
2860 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2861 return false;
2862 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2863 return false;
2864 if (!ContextualCheckBlock(block, state, pindexPrev))
2865 return false;
2866 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2867 return false;
2868 assert(state.IsValid());
2870 return true;
2874 * BLOCK PRUNING CODE
2877 /* Calculate the amount of disk space the block & undo files currently use */
2878 uint64_t CalculateCurrentUsage()
2880 uint64_t retval = 0;
2881 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
2882 retval += file.nSize + file.nUndoSize;
2884 return retval;
2887 /* Prune a block file (modify associated database entries)*/
2888 void PruneOneBlockFile(const int fileNumber)
2890 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
2891 CBlockIndex* pindex = it->second;
2892 if (pindex->nFile == fileNumber) {
2893 pindex->nStatus &= ~BLOCK_HAVE_DATA;
2894 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
2895 pindex->nFile = 0;
2896 pindex->nDataPos = 0;
2897 pindex->nUndoPos = 0;
2898 setDirtyBlockIndex.insert(pindex);
2900 // Prune from mapBlocksUnlinked -- any block we prune would have
2901 // to be downloaded again in order to consider its chain, at which
2902 // point it would be considered as a candidate for
2903 // mapBlocksUnlinked or setBlockIndexCandidates.
2904 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
2905 while (range.first != range.second) {
2906 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
2907 range.first++;
2908 if (it->second == pindex) {
2909 mapBlocksUnlinked.erase(it);
2915 vinfoBlockFile[fileNumber].SetNull();
2916 setDirtyFileInfo.insert(fileNumber);
2920 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
2922 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
2923 CDiskBlockPos pos(*it, 0);
2924 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
2925 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
2926 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
2930 /* Calculate the block/rev files that should be deleted to remain under target*/
2931 void FindFilesToPrune(std::set<int>& setFilesToPrune)
2933 LOCK2(cs_main, cs_LastBlockFile);
2934 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
2935 return;
2937 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
2938 return;
2941 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
2942 uint64_t nCurrentUsage = CalculateCurrentUsage();
2943 // We don't check to prune until after we've allocated new space for files
2944 // So we should leave a buffer under our target to account for another allocation
2945 // before the next pruning.
2946 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
2947 uint64_t nBytesToPrune;
2948 int count=0;
2950 if (nCurrentUsage + nBuffer >= nPruneTarget) {
2951 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
2952 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
2954 if (vinfoBlockFile[fileNumber].nSize == 0)
2955 continue;
2957 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
2958 break;
2960 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
2961 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
2962 continue;
2964 PruneOneBlockFile(fileNumber);
2965 // Queue up the files for removal
2966 setFilesToPrune.insert(fileNumber);
2967 nCurrentUsage -= nBytesToPrune;
2968 count++;
2972 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
2973 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
2974 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
2975 nLastBlockWeCanPrune, count);
2978 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2980 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2982 // Check for nMinDiskSpace bytes (currently 50MB)
2983 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2984 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
2986 return true;
2989 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2991 if (pos.IsNull())
2992 return NULL;
2993 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
2994 boost::filesystem::create_directories(path.parent_path());
2995 FILE* file = fopen(path.string().c_str(), "rb+");
2996 if (!file && !fReadOnly)
2997 file = fopen(path.string().c_str(), "wb+");
2998 if (!file) {
2999 LogPrintf("Unable to open file %s\n", path.string());
3000 return NULL;
3002 if (pos.nPos) {
3003 if (fseek(file, pos.nPos, SEEK_SET)) {
3004 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3005 fclose(file);
3006 return NULL;
3009 return file;
3012 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3013 return OpenDiskFile(pos, "blk", fReadOnly);
3016 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3017 return OpenDiskFile(pos, "rev", fReadOnly);
3020 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3022 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3025 CBlockIndex * InsertBlockIndex(uint256 hash)
3027 if (hash.IsNull())
3028 return NULL;
3030 // Return existing
3031 BlockMap::iterator mi = mapBlockIndex.find(hash);
3032 if (mi != mapBlockIndex.end())
3033 return (*mi).second;
3035 // Create new
3036 CBlockIndex* pindexNew = new CBlockIndex();
3037 if (!pindexNew)
3038 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3039 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3040 pindexNew->phashBlock = &((*mi).first);
3042 return pindexNew;
3045 bool static LoadBlockIndexDB()
3047 const CChainParams& chainparams = Params();
3048 if (!pblocktree->LoadBlockIndexGuts())
3049 return false;
3051 boost::this_thread::interruption_point();
3053 // Calculate nChainWork
3054 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3055 vSortedByHeight.reserve(mapBlockIndex.size());
3056 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3058 CBlockIndex* pindex = item.second;
3059 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3061 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3062 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3064 CBlockIndex* pindex = item.second;
3065 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3066 // We can link the chain of blocks for which we've received transactions at some point.
3067 // Pruned nodes may have deleted the block.
3068 if (pindex->nTx > 0) {
3069 if (pindex->pprev) {
3070 if (pindex->pprev->nChainTx) {
3071 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3072 } else {
3073 pindex->nChainTx = 0;
3074 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3076 } else {
3077 pindex->nChainTx = pindex->nTx;
3080 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3081 setBlockIndexCandidates.insert(pindex);
3082 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3083 pindexBestInvalid = pindex;
3084 if (pindex->pprev)
3085 pindex->BuildSkip();
3086 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3087 pindexBestHeader = pindex;
3090 // Load block file info
3091 pblocktree->ReadLastBlockFile(nLastBlockFile);
3092 vinfoBlockFile.resize(nLastBlockFile + 1);
3093 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3094 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3095 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3097 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3098 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3099 CBlockFileInfo info;
3100 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3101 vinfoBlockFile.push_back(info);
3102 } else {
3103 break;
3107 // Check presence of blk files
3108 LogPrintf("Checking all blk files are present...\n");
3109 set<int> setBlkDataFiles;
3110 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3112 CBlockIndex* pindex = item.second;
3113 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3114 setBlkDataFiles.insert(pindex->nFile);
3117 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3119 CDiskBlockPos pos(*it, 0);
3120 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3121 return false;
3125 // Check whether we have ever pruned block & undo files
3126 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3127 if (fHavePruned)
3128 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3130 // Check whether we need to continue reindexing
3131 bool fReindexing = false;
3132 pblocktree->ReadReindexing(fReindexing);
3133 fReindex |= fReindexing;
3135 // Check whether we have a transaction index
3136 pblocktree->ReadFlag("txindex", fTxIndex);
3137 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3139 // Load pointer to end of best chain
3140 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3141 if (it == mapBlockIndex.end())
3142 return true;
3143 chainActive.SetTip(it->second);
3145 PruneBlockIndexCandidates();
3147 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3148 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3149 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3150 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3152 return true;
3155 CVerifyDB::CVerifyDB()
3157 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3160 CVerifyDB::~CVerifyDB()
3162 uiInterface.ShowProgress("", 100);
3165 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3167 LOCK(cs_main);
3168 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3169 return true;
3171 // Verify blocks in the best chain
3172 if (nCheckDepth <= 0)
3173 nCheckDepth = 1000000000; // suffices until the year 19000
3174 if (nCheckDepth > chainActive.Height())
3175 nCheckDepth = chainActive.Height();
3176 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3177 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3178 CCoinsViewCache coins(coinsview);
3179 CBlockIndex* pindexState = chainActive.Tip();
3180 CBlockIndex* pindexFailure = NULL;
3181 int nGoodTransactions = 0;
3182 CValidationState state;
3183 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3185 boost::this_thread::interruption_point();
3186 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3187 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3188 break;
3189 CBlock block;
3190 // check level 0: read from disk
3191 if (!ReadBlockFromDisk(block, pindex))
3192 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3193 // check level 1: verify block validity
3194 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3195 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3196 // check level 2: verify undo validity
3197 if (nCheckLevel >= 2 && pindex) {
3198 CBlockUndo undo;
3199 CDiskBlockPos pos = pindex->GetUndoPos();
3200 if (!pos.IsNull()) {
3201 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3202 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3205 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3206 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3207 bool fClean = true;
3208 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3209 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3210 pindexState = pindex->pprev;
3211 if (!fClean) {
3212 nGoodTransactions = 0;
3213 pindexFailure = pindex;
3214 } else
3215 nGoodTransactions += block.vtx.size();
3217 if (ShutdownRequested())
3218 return true;
3220 if (pindexFailure)
3221 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3223 // check level 4: try reconnecting blocks
3224 if (nCheckLevel >= 4) {
3225 CBlockIndex *pindex = pindexState;
3226 while (pindex != chainActive.Tip()) {
3227 boost::this_thread::interruption_point();
3228 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3229 pindex = chainActive.Next(pindex);
3230 CBlock block;
3231 if (!ReadBlockFromDisk(block, pindex))
3232 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3233 if (!ConnectBlock(block, state, pindex, coins))
3234 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3238 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3240 return true;
3243 void UnloadBlockIndex()
3245 LOCK(cs_main);
3246 setBlockIndexCandidates.clear();
3247 chainActive.SetTip(NULL);
3248 pindexBestInvalid = NULL;
3249 pindexBestHeader = NULL;
3250 mempool.clear();
3251 mapOrphanTransactions.clear();
3252 mapOrphanTransactionsByPrev.clear();
3253 nSyncStarted = 0;
3254 mapBlocksUnlinked.clear();
3255 vinfoBlockFile.clear();
3256 nLastBlockFile = 0;
3257 nBlockSequenceId = 1;
3258 mapBlockSource.clear();
3259 mapBlocksInFlight.clear();
3260 nQueuedValidatedHeaders = 0;
3261 nPreferredDownload = 0;
3262 setDirtyBlockIndex.clear();
3263 setDirtyFileInfo.clear();
3264 mapNodeState.clear();
3265 recentRejects.reset(NULL);
3267 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3268 delete entry.second;
3270 mapBlockIndex.clear();
3271 fHavePruned = false;
3274 bool LoadBlockIndex()
3276 // Load block index from databases
3277 if (!fReindex && !LoadBlockIndexDB())
3278 return false;
3279 return true;
3283 bool InitBlockIndex() {
3284 const CChainParams& chainparams = Params();
3285 LOCK(cs_main);
3287 // Initialize global variables that cannot be constructed at startup.
3288 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3290 // Check whether we're already initialized
3291 if (chainActive.Genesis() != NULL)
3292 return true;
3294 // Use the provided setting for -txindex in the new database
3295 fTxIndex = GetBoolArg("-txindex", false);
3296 pblocktree->WriteFlag("txindex", fTxIndex);
3297 LogPrintf("Initializing databases...\n");
3299 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3300 if (!fReindex) {
3301 try {
3302 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3303 // Start new block file
3304 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3305 CDiskBlockPos blockPos;
3306 CValidationState state;
3307 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3308 return error("LoadBlockIndex(): FindBlockPos failed");
3309 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3310 return error("LoadBlockIndex(): writing genesis block to disk failed");
3311 CBlockIndex *pindex = AddToBlockIndex(block);
3312 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3313 return error("LoadBlockIndex(): genesis block not accepted");
3314 if (!ActivateBestChain(state, &block))
3315 return error("LoadBlockIndex(): genesis block cannot be activated");
3316 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3317 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3318 } catch (const std::runtime_error& e) {
3319 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3323 return true;
3328 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3330 const CChainParams& chainparams = Params();
3331 // Map of disk positions for blocks with unknown parent (only used for reindex)
3332 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3333 int64_t nStart = GetTimeMillis();
3335 int nLoaded = 0;
3336 try {
3337 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3338 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3339 uint64_t nRewind = blkdat.GetPos();
3340 while (!blkdat.eof()) {
3341 boost::this_thread::interruption_point();
3343 blkdat.SetPos(nRewind);
3344 nRewind++; // start one byte further next time, in case of failure
3345 blkdat.SetLimit(); // remove former limit
3346 unsigned int nSize = 0;
3347 try {
3348 // locate a header
3349 unsigned char buf[MESSAGE_START_SIZE];
3350 blkdat.FindByte(Params().MessageStart()[0]);
3351 nRewind = blkdat.GetPos()+1;
3352 blkdat >> FLATDATA(buf);
3353 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3354 continue;
3355 // read size
3356 blkdat >> nSize;
3357 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3358 continue;
3359 } catch (const std::exception&) {
3360 // no valid block header found; don't complain
3361 break;
3363 try {
3364 // read block
3365 uint64_t nBlockPos = blkdat.GetPos();
3366 if (dbp)
3367 dbp->nPos = nBlockPos;
3368 blkdat.SetLimit(nBlockPos + nSize);
3369 blkdat.SetPos(nBlockPos);
3370 CBlock block;
3371 blkdat >> block;
3372 nRewind = blkdat.GetPos();
3374 // detect out of order blocks, and store them for later
3375 uint256 hash = block.GetHash();
3376 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3377 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3378 block.hashPrevBlock.ToString());
3379 if (dbp)
3380 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3381 continue;
3384 // process in case the block isn't known yet
3385 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3386 CValidationState state;
3387 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3388 nLoaded++;
3389 if (state.IsError())
3390 break;
3391 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3392 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3395 // Recursively process earlier encountered successors of this block
3396 deque<uint256> queue;
3397 queue.push_back(hash);
3398 while (!queue.empty()) {
3399 uint256 head = queue.front();
3400 queue.pop_front();
3401 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3402 while (range.first != range.second) {
3403 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3404 if (ReadBlockFromDisk(block, it->second))
3406 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3407 head.ToString());
3408 CValidationState dummy;
3409 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3411 nLoaded++;
3412 queue.push_back(block.GetHash());
3415 range.first++;
3416 mapBlocksUnknownParent.erase(it);
3419 } catch (const std::exception& e) {
3420 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3423 } catch (const std::runtime_error& e) {
3424 AbortNode(std::string("System error: ") + e.what());
3426 if (nLoaded > 0)
3427 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3428 return nLoaded > 0;
3431 void static CheckBlockIndex()
3433 const Consensus::Params& consensusParams = Params().GetConsensus();
3434 if (!fCheckBlockIndex) {
3435 return;
3438 LOCK(cs_main);
3440 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3441 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3442 // iterating the block tree require that chainActive has been initialized.)
3443 if (chainActive.Height() < 0) {
3444 assert(mapBlockIndex.size() <= 1);
3445 return;
3448 // Build forward-pointing map of the entire block tree.
3449 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3450 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3451 forward.insert(std::make_pair(it->second->pprev, it->second));
3454 assert(forward.size() == mapBlockIndex.size());
3456 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3457 CBlockIndex *pindex = rangeGenesis.first->second;
3458 rangeGenesis.first++;
3459 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3461 // Iterate over the entire block tree, using depth-first search.
3462 // Along the way, remember whether there are blocks on the path from genesis
3463 // block being explored which are the first to have certain properties.
3464 size_t nNodes = 0;
3465 int nHeight = 0;
3466 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3467 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3468 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3469 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3470 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3471 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3472 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3473 while (pindex != NULL) {
3474 nNodes++;
3475 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3476 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3477 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3478 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3479 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3480 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3481 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3483 // Begin: actual consistency checks.
3484 if (pindex->pprev == NULL) {
3485 // Genesis block checks.
3486 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3487 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3489 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3490 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3491 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3492 if (!fHavePruned) {
3493 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3494 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3495 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3496 } else {
3497 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3498 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3500 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3501 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3502 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3503 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3504 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3505 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3506 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.
3507 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3508 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3509 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3510 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3511 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3512 if (pindexFirstInvalid == NULL) {
3513 // Checks for not-invalid blocks.
3514 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3516 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3517 if (pindexFirstInvalid == NULL) {
3518 // If this block sorts at least as good as the current tip and
3519 // is valid and we have all data for its parents, it must be in
3520 // setBlockIndexCandidates. chainActive.Tip() must also be there
3521 // even if some data has been pruned.
3522 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3523 assert(setBlockIndexCandidates.count(pindex));
3525 // If some parent is missing, then it could be that this block was in
3526 // setBlockIndexCandidates but had to be removed because of the missing data.
3527 // In this case it must be in mapBlocksUnlinked -- see test below.
3529 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3530 assert(setBlockIndexCandidates.count(pindex) == 0);
3532 // Check whether this block is in mapBlocksUnlinked.
3533 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3534 bool foundInUnlinked = false;
3535 while (rangeUnlinked.first != rangeUnlinked.second) {
3536 assert(rangeUnlinked.first->first == pindex->pprev);
3537 if (rangeUnlinked.first->second == pindex) {
3538 foundInUnlinked = true;
3539 break;
3541 rangeUnlinked.first++;
3543 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3544 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3545 assert(foundInUnlinked);
3547 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3548 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3549 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3550 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3551 assert(fHavePruned); // We must have pruned.
3552 // This block may have entered mapBlocksUnlinked if:
3553 // - it has a descendant that at some point had more work than the
3554 // tip, and
3555 // - we tried switching to that descendant but were missing
3556 // data for some intermediate block between chainActive and the
3557 // tip.
3558 // So if this block is itself better than chainActive.Tip() and it wasn't in
3559 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3560 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3561 if (pindexFirstInvalid == NULL) {
3562 assert(foundInUnlinked);
3566 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3567 // End: actual consistency checks.
3569 // Try descending into the first subnode.
3570 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3571 if (range.first != range.second) {
3572 // A subnode was found.
3573 pindex = range.first->second;
3574 nHeight++;
3575 continue;
3577 // This is a leaf node.
3578 // Move upwards until we reach a node of which we have not yet visited the last child.
3579 while (pindex) {
3580 // We are going to either move to a parent or a sibling of pindex.
3581 // If pindex was the first with a certain property, unset the corresponding variable.
3582 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3583 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3584 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3585 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3586 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3587 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3588 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3589 // Find our parent.
3590 CBlockIndex* pindexPar = pindex->pprev;
3591 // Find which child we just visited.
3592 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3593 while (rangePar.first->second != pindex) {
3594 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3595 rangePar.first++;
3597 // Proceed to the next one.
3598 rangePar.first++;
3599 if (rangePar.first != rangePar.second) {
3600 // Move to the sibling.
3601 pindex = rangePar.first->second;
3602 break;
3603 } else {
3604 // Move up further.
3605 pindex = pindexPar;
3606 nHeight--;
3607 continue;
3612 // Check that we actually traversed the entire map.
3613 assert(nNodes == forward.size());
3616 //////////////////////////////////////////////////////////////////////////////
3618 // CAlert
3621 std::string GetWarnings(const std::string& strFor)
3623 int nPriority = 0;
3624 string strStatusBar;
3625 string strRPC;
3627 if (!CLIENT_VERSION_IS_RELEASE)
3628 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3630 if (GetBoolArg("-testsafemode", false))
3631 strStatusBar = strRPC = "testsafemode enabled";
3633 // Misc warnings like out of disk space and clock is wrong
3634 if (strMiscWarning != "")
3636 nPriority = 1000;
3637 strStatusBar = strMiscWarning;
3640 if (fLargeWorkForkFound)
3642 nPriority = 2000;
3643 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3645 else if (fLargeWorkInvalidChainFound)
3647 nPriority = 2000;
3648 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.");
3651 // Alerts
3653 LOCK(cs_mapAlerts);
3654 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3656 const CAlert& alert = item.second;
3657 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3659 nPriority = alert.nPriority;
3660 strStatusBar = alert.strStatusBar;
3665 if (strFor == "statusbar")
3666 return strStatusBar;
3667 else if (strFor == "rpc")
3668 return strRPC;
3669 assert(!"GetWarnings(): invalid parameter");
3670 return "error";
3680 //////////////////////////////////////////////////////////////////////////////
3682 // Messages
3686 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3688 switch (inv.type)
3690 case MSG_TX:
3692 assert(recentRejects);
3693 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
3695 // If the chain tip has changed previously rejected transactions
3696 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
3697 // or a double-spend. Reset the rejects filter and give those
3698 // txs a second chance.
3699 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
3700 recentRejects->reset();
3703 return recentRejects->contains(inv.hash) ||
3704 mempool.exists(inv.hash) ||
3705 mapOrphanTransactions.count(inv.hash) ||
3706 pcoinsTip->HaveCoins(inv.hash);
3708 case MSG_BLOCK:
3709 return mapBlockIndex.count(inv.hash);
3711 // Don't know what it is, just say we already got one
3712 return true;
3715 void static ProcessGetData(CNode* pfrom)
3717 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3719 vector<CInv> vNotFound;
3721 LOCK(cs_main);
3723 while (it != pfrom->vRecvGetData.end()) {
3724 // Don't bother if send buffer is too full to respond anyway
3725 if (pfrom->nSendSize >= SendBufferSize())
3726 break;
3728 const CInv &inv = *it;
3730 boost::this_thread::interruption_point();
3731 it++;
3733 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3735 bool send = false;
3736 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3737 if (mi != mapBlockIndex.end())
3739 if (chainActive.Contains(mi->second)) {
3740 send = true;
3741 } else {
3742 static const int nOneMonth = 30 * 24 * 60 * 60;
3743 // To prevent fingerprinting attacks, only send blocks outside of the active
3744 // chain if they are valid, and no more than a month older (both in time, and in
3745 // best equivalent proof of work) than the best header chain we know about.
3746 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3747 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
3748 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
3749 if (!send) {
3750 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
3754 // Pruned nodes may have deleted the block, so check whether
3755 // it's available before trying to send.
3756 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
3758 // Send block from disk
3759 CBlock block;
3760 if (!ReadBlockFromDisk(block, (*mi).second))
3761 assert(!"cannot load block from disk");
3762 if (inv.type == MSG_BLOCK)
3763 pfrom->PushMessage("block", block);
3764 else // MSG_FILTERED_BLOCK)
3766 LOCK(pfrom->cs_filter);
3767 if (pfrom->pfilter)
3769 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3770 pfrom->PushMessage("merkleblock", merkleBlock);
3771 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3772 // This avoids hurting performance by pointlessly requiring a round-trip
3773 // Note that there is currently no way for a node to request any single transactions we didn't send here -
3774 // they must either disconnect and retry or request the full block.
3775 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3776 // however we MUST always provide at least what the remote peer needs
3777 typedef std::pair<unsigned int, uint256> PairType;
3778 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3779 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3780 pfrom->PushMessage("tx", block.vtx[pair.first]);
3782 // else
3783 // no response
3786 // Trigger the peer node to send a getblocks request for the next batch of inventory
3787 if (inv.hash == pfrom->hashContinue)
3789 // Bypass PushInventory, this must send even if redundant,
3790 // and we want it right after the last block so they don't
3791 // wait for other stuff first.
3792 vector<CInv> vInv;
3793 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3794 pfrom->PushMessage("inv", vInv);
3795 pfrom->hashContinue.SetNull();
3799 else if (inv.IsKnownType())
3801 // Send stream from relay memory
3802 bool pushed = false;
3804 LOCK(cs_mapRelay);
3805 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3806 if (mi != mapRelay.end()) {
3807 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3808 pushed = true;
3811 if (!pushed && inv.type == MSG_TX) {
3812 CTransaction tx;
3813 if (mempool.lookup(inv.hash, tx)) {
3814 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3815 ss.reserve(1000);
3816 ss << tx;
3817 pfrom->PushMessage("tx", ss);
3818 pushed = true;
3821 if (!pushed) {
3822 vNotFound.push_back(inv);
3826 // Track requests for our stuff.
3827 GetMainSignals().Inventory(inv.hash);
3829 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3830 break;
3834 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3836 if (!vNotFound.empty()) {
3837 // Let the peer know that we didn't find what it asked for, so it doesn't
3838 // have to wait around forever. Currently only SPV clients actually care
3839 // about this message: it's needed when they are recursively walking the
3840 // dependencies of relevant unconfirmed transactions. SPV clients want to
3841 // do that because they want to know about (and store and rebroadcast and
3842 // risk analyze) the dependencies of transactions relevant to them, without
3843 // having to download the entire memory pool.
3844 pfrom->PushMessage("notfound", vNotFound);
3848 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3850 const CChainParams& chainparams = Params();
3851 RandAddSeedPerfmon();
3852 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3853 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3855 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3856 return true;
3862 if (strCommand == "version")
3864 // Each connection can only send one version message
3865 if (pfrom->nVersion != 0)
3867 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3868 Misbehaving(pfrom->GetId(), 1);
3869 return false;
3872 int64_t nTime;
3873 CAddress addrMe;
3874 CAddress addrFrom;
3875 uint64_t nNonce = 1;
3876 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3877 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3879 // disconnect from peers older than this proto version
3880 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3881 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3882 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3883 pfrom->fDisconnect = true;
3884 return false;
3887 if (pfrom->nVersion == 10300)
3888 pfrom->nVersion = 300;
3889 if (!vRecv.empty())
3890 vRecv >> addrFrom >> nNonce;
3891 if (!vRecv.empty()) {
3892 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
3893 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3895 if (!vRecv.empty())
3896 vRecv >> pfrom->nStartingHeight;
3897 if (!vRecv.empty())
3898 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3899 else
3900 pfrom->fRelayTxes = true;
3902 // Disconnect if we connected to ourself
3903 if (nNonce == nLocalHostNonce && nNonce > 1)
3905 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3906 pfrom->fDisconnect = true;
3907 return true;
3910 pfrom->addrLocal = addrMe;
3911 if (pfrom->fInbound && addrMe.IsRoutable())
3913 SeenLocal(addrMe);
3916 // Be shy and don't send version until we hear
3917 if (pfrom->fInbound)
3918 pfrom->PushVersion();
3920 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3922 // Potentially mark this peer as a preferred download peer.
3923 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3925 // Change version
3926 pfrom->PushMessage("verack");
3927 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3929 if (!pfrom->fInbound)
3931 // Advertise our address
3932 if (fListen && !IsInitialBlockDownload())
3934 CAddress addr = GetLocalAddress(&pfrom->addr);
3935 if (addr.IsRoutable())
3937 pfrom->PushAddress(addr);
3938 } else if (IsPeerAddrLocalGood(pfrom)) {
3939 addr.SetIP(pfrom->addrLocal);
3940 pfrom->PushAddress(addr);
3944 // Get recent addresses
3945 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3947 pfrom->PushMessage("getaddr");
3948 pfrom->fGetAddr = true;
3950 addrman.Good(pfrom->addr);
3951 } else {
3952 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3954 addrman.Add(addrFrom, addrFrom);
3955 addrman.Good(addrFrom);
3959 // Relay alerts
3961 LOCK(cs_mapAlerts);
3962 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3963 item.second.RelayTo(pfrom);
3966 pfrom->fSuccessfullyConnected = true;
3968 string remoteAddr;
3969 if (fLogIPs)
3970 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
3972 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
3973 pfrom->cleanSubVer, pfrom->nVersion,
3974 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
3975 remoteAddr);
3977 int64_t nTimeOffset = nTime - GetTime();
3978 pfrom->nTimeOffset = nTimeOffset;
3979 AddTimeData(pfrom->addr, nTimeOffset);
3983 else if (pfrom->nVersion == 0)
3985 // Must have a version message before anything else
3986 Misbehaving(pfrom->GetId(), 1);
3987 return false;
3991 else if (strCommand == "verack")
3993 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3995 // Mark this node as currently connected, so we update its timestamp later.
3996 if (pfrom->fNetworkNode) {
3997 LOCK(cs_main);
3998 State(pfrom->GetId())->fCurrentlyConnected = true;
4003 else if (strCommand == "addr")
4005 vector<CAddress> vAddr;
4006 vRecv >> vAddr;
4008 // Don't want addr from older versions unless seeding
4009 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4010 return true;
4011 if (vAddr.size() > 1000)
4013 Misbehaving(pfrom->GetId(), 20);
4014 return error("message addr size() = %u", vAddr.size());
4017 // Store the new addresses
4018 vector<CAddress> vAddrOk;
4019 int64_t nNow = GetAdjustedTime();
4020 int64_t nSince = nNow - 10 * 60;
4021 BOOST_FOREACH(CAddress& addr, vAddr)
4023 boost::this_thread::interruption_point();
4025 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4026 addr.nTime = nNow - 5 * 24 * 60 * 60;
4027 pfrom->AddAddressKnown(addr);
4028 bool fReachable = IsReachable(addr);
4029 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4031 // Relay to a limited number of other nodes
4033 LOCK(cs_vNodes);
4034 // Use deterministic randomness to send to the same nodes for 24 hours
4035 // at a time so the addrKnowns of the chosen nodes prevent repeats
4036 static uint256 hashSalt;
4037 if (hashSalt.IsNull())
4038 hashSalt = GetRandHash();
4039 uint64_t hashAddr = addr.GetHash();
4040 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4041 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4042 multimap<uint256, CNode*> mapMix;
4043 BOOST_FOREACH(CNode* pnode, vNodes)
4045 if (pnode->nVersion < CADDR_TIME_VERSION)
4046 continue;
4047 unsigned int nPointer;
4048 memcpy(&nPointer, &pnode, sizeof(nPointer));
4049 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4050 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4051 mapMix.insert(make_pair(hashKey, pnode));
4053 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4054 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4055 ((*mi).second)->PushAddress(addr);
4058 // Do not store addresses outside our network
4059 if (fReachable)
4060 vAddrOk.push_back(addr);
4062 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4063 if (vAddr.size() < 1000)
4064 pfrom->fGetAddr = false;
4065 if (pfrom->fOneShot)
4066 pfrom->fDisconnect = true;
4070 else if (strCommand == "inv")
4072 vector<CInv> vInv;
4073 vRecv >> vInv;
4074 if (vInv.size() > MAX_INV_SZ)
4076 Misbehaving(pfrom->GetId(), 20);
4077 return error("message inv size() = %u", vInv.size());
4080 LOCK(cs_main);
4082 std::vector<CInv> vToFetch;
4084 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4086 const CInv &inv = vInv[nInv];
4088 boost::this_thread::interruption_point();
4089 pfrom->AddInventoryKnown(inv);
4091 bool fAlreadyHave = AlreadyHave(inv);
4092 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4094 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4095 pfrom->AskFor(inv);
4097 if (inv.type == MSG_BLOCK) {
4098 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4099 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4100 // First request the headers preceding the announced block. In the normal fully-synced
4101 // case where a new block is announced that succeeds the current tip (no reorganization),
4102 // there are no such headers.
4103 // Secondly, and only when we are close to being synced, we request the announced block directly,
4104 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4105 // time the block arrives, the header chain leading up to it is already validated. Not
4106 // doing this will result in the received block being rejected as an orphan in case it is
4107 // not a direct successor.
4108 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4109 CNodeState *nodestate = State(pfrom->GetId());
4110 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4111 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4112 vToFetch.push_back(inv);
4113 // Mark block as in flight already, even though the actual "getdata" message only goes out
4114 // later (within the same cs_main lock, though).
4115 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4117 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4121 // Track requests for our stuff
4122 GetMainSignals().Inventory(inv.hash);
4124 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4125 Misbehaving(pfrom->GetId(), 50);
4126 return error("send buffer size() = %u", pfrom->nSendSize);
4130 if (!vToFetch.empty())
4131 pfrom->PushMessage("getdata", vToFetch);
4135 else if (strCommand == "getdata")
4137 vector<CInv> vInv;
4138 vRecv >> vInv;
4139 if (vInv.size() > MAX_INV_SZ)
4141 Misbehaving(pfrom->GetId(), 20);
4142 return error("message getdata size() = %u", vInv.size());
4145 if (fDebug || (vInv.size() != 1))
4146 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4148 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4149 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4151 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4152 ProcessGetData(pfrom);
4156 else if (strCommand == "getblocks")
4158 CBlockLocator locator;
4159 uint256 hashStop;
4160 vRecv >> locator >> hashStop;
4162 LOCK(cs_main);
4164 // Find the last block the caller has in the main chain
4165 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4167 // Send the rest of the chain
4168 if (pindex)
4169 pindex = chainActive.Next(pindex);
4170 int nLimit = 500;
4171 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4172 for (; pindex; pindex = chainActive.Next(pindex))
4174 if (pindex->GetBlockHash() == hashStop)
4176 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4177 break;
4179 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4180 if (--nLimit <= 0)
4182 // When this block is requested, we'll send an inv that'll
4183 // trigger the peer to getblocks the next batch of inventory.
4184 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4185 pfrom->hashContinue = pindex->GetBlockHash();
4186 break;
4192 else if (strCommand == "getheaders")
4194 CBlockLocator locator;
4195 uint256 hashStop;
4196 vRecv >> locator >> hashStop;
4198 LOCK(cs_main);
4200 if (IsInitialBlockDownload())
4201 return true;
4203 CBlockIndex* pindex = NULL;
4204 if (locator.IsNull())
4206 // If locator is null, return the hashStop block
4207 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4208 if (mi == mapBlockIndex.end())
4209 return true;
4210 pindex = (*mi).second;
4212 else
4214 // Find the last block the caller has in the main chain
4215 pindex = FindForkInGlobalIndex(chainActive, locator);
4216 if (pindex)
4217 pindex = chainActive.Next(pindex);
4220 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4221 vector<CBlock> vHeaders;
4222 int nLimit = MAX_HEADERS_RESULTS;
4223 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4224 for (; pindex; pindex = chainActive.Next(pindex))
4226 vHeaders.push_back(pindex->GetBlockHeader());
4227 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4228 break;
4230 pfrom->PushMessage("headers", vHeaders);
4234 else if (strCommand == "tx")
4236 vector<uint256> vWorkQueue;
4237 vector<uint256> vEraseQueue;
4238 CTransaction tx;
4239 vRecv >> tx;
4241 CInv inv(MSG_TX, tx.GetHash());
4242 pfrom->AddInventoryKnown(inv);
4244 LOCK(cs_main);
4246 bool fMissingInputs = false;
4247 CValidationState state;
4249 mapAlreadyAskedFor.erase(inv);
4251 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4253 mempool.check(pcoinsTip);
4254 RelayTransaction(tx);
4255 vWorkQueue.push_back(inv.hash);
4257 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4258 pfrom->id, pfrom->cleanSubVer,
4259 tx.GetHash().ToString(),
4260 mempool.mapTx.size());
4262 // Recursively process any orphan transactions that depended on this one
4263 set<NodeId> setMisbehaving;
4264 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4266 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4267 if (itByPrev == mapOrphanTransactionsByPrev.end())
4268 continue;
4269 for (set<uint256>::iterator mi = itByPrev->second.begin();
4270 mi != itByPrev->second.end();
4271 ++mi)
4273 const uint256& orphanHash = *mi;
4274 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4275 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4276 bool fMissingInputs2 = false;
4277 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4278 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4279 // anyone relaying LegitTxX banned)
4280 CValidationState stateDummy;
4283 if (setMisbehaving.count(fromPeer))
4284 continue;
4285 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4287 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4288 RelayTransaction(orphanTx);
4289 vWorkQueue.push_back(orphanHash);
4290 vEraseQueue.push_back(orphanHash);
4292 else if (!fMissingInputs2)
4294 int nDos = 0;
4295 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4297 // Punish peer that gave us an invalid orphan tx
4298 Misbehaving(fromPeer, nDos);
4299 setMisbehaving.insert(fromPeer);
4300 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4302 // Has inputs but not accepted to mempool
4303 // Probably non-standard or insufficient fee/priority
4304 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4305 vEraseQueue.push_back(orphanHash);
4306 assert(recentRejects);
4307 recentRejects->insert(orphanHash);
4309 mempool.check(pcoinsTip);
4313 BOOST_FOREACH(uint256 hash, vEraseQueue)
4314 EraseOrphanTx(hash);
4316 else if (fMissingInputs)
4318 AddOrphanTx(tx, pfrom->GetId());
4320 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4321 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4322 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4323 if (nEvicted > 0)
4324 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4325 } else {
4326 // AcceptToMemoryPool() returned false, possibly because the tx is
4327 // already in the mempool; if the tx isn't in the mempool that
4328 // means it was rejected and we shouldn't ask for it again.
4329 if (!mempool.exists(tx.GetHash())) {
4330 assert(recentRejects);
4331 recentRejects->insert(tx.GetHash());
4333 if (pfrom->fWhitelisted) {
4334 // Always relay transactions received from whitelisted peers, even
4335 // if they were rejected from the mempool, allowing the node to
4336 // function as a gateway for nodes hidden behind it.
4338 // FIXME: This includes invalid transactions, which means a
4339 // whitelisted peer could get us banned! We may want to change
4340 // that.
4341 RelayTransaction(tx);
4344 int nDoS = 0;
4345 if (state.IsInvalid(nDoS))
4347 LogPrint("mempoolrej", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4348 pfrom->id, pfrom->cleanSubVer,
4349 FormatStateMessage(state));
4350 if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
4351 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4352 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4353 if (nDoS > 0)
4354 Misbehaving(pfrom->GetId(), nDoS);
4359 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4361 std::vector<CBlockHeader> headers;
4363 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4364 unsigned int nCount = ReadCompactSize(vRecv);
4365 if (nCount > MAX_HEADERS_RESULTS) {
4366 Misbehaving(pfrom->GetId(), 20);
4367 return error("headers message size = %u", nCount);
4369 headers.resize(nCount);
4370 for (unsigned int n = 0; n < nCount; n++) {
4371 vRecv >> headers[n];
4372 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4375 LOCK(cs_main);
4377 if (nCount == 0) {
4378 // Nothing interesting. Stop asking this peers for more headers.
4379 return true;
4382 CBlockIndex *pindexLast = NULL;
4383 BOOST_FOREACH(const CBlockHeader& header, headers) {
4384 CValidationState state;
4385 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4386 Misbehaving(pfrom->GetId(), 20);
4387 return error("non-continuous headers sequence");
4389 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4390 int nDoS;
4391 if (state.IsInvalid(nDoS)) {
4392 if (nDoS > 0)
4393 Misbehaving(pfrom->GetId(), nDoS);
4394 return error("invalid header received");
4399 if (pindexLast)
4400 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4402 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4403 // Headers message had its maximum size; the peer may have more headers.
4404 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4405 // from there instead.
4406 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4407 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4410 CheckBlockIndex();
4413 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4415 CBlock block;
4416 vRecv >> block;
4418 CInv inv(MSG_BLOCK, block.GetHash());
4419 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4421 pfrom->AddInventoryKnown(inv);
4423 CValidationState state;
4424 // Process all blocks from whitelisted peers, even if not requested,
4425 // unless we're still syncing with the network.
4426 // Such an unrequested block may still be processed, subject to the
4427 // conditions in AcceptBlock().
4428 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4429 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4430 int nDoS;
4431 if (state.IsInvalid(nDoS)) {
4432 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
4433 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4434 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4435 if (nDoS > 0) {
4436 LOCK(cs_main);
4437 Misbehaving(pfrom->GetId(), nDoS);
4444 // This asymmetric behavior for inbound and outbound connections was introduced
4445 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4446 // to users' AddrMan and later request them by sending getaddr messages.
4447 // Making nodes which are behind NAT and can only make outgoing connections ignore
4448 // the getaddr message mitigates the attack.
4449 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4451 pfrom->vAddrToSend.clear();
4452 vector<CAddress> vAddr = addrman.GetAddr();
4453 BOOST_FOREACH(const CAddress &addr, vAddr)
4454 pfrom->PushAddress(addr);
4458 else if (strCommand == "mempool")
4460 LOCK2(cs_main, pfrom->cs_filter);
4462 std::vector<uint256> vtxid;
4463 mempool.queryHashes(vtxid);
4464 vector<CInv> vInv;
4465 BOOST_FOREACH(uint256& hash, vtxid) {
4466 CInv inv(MSG_TX, hash);
4467 CTransaction tx;
4468 bool fInMemPool = mempool.lookup(hash, tx);
4469 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4470 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4471 (!pfrom->pfilter))
4472 vInv.push_back(inv);
4473 if (vInv.size() == MAX_INV_SZ) {
4474 pfrom->PushMessage("inv", vInv);
4475 vInv.clear();
4478 if (vInv.size() > 0)
4479 pfrom->PushMessage("inv", vInv);
4483 else if (strCommand == "ping")
4485 if (pfrom->nVersion > BIP0031_VERSION)
4487 uint64_t nonce = 0;
4488 vRecv >> nonce;
4489 // Echo the message back with the nonce. This allows for two useful features:
4491 // 1) A remote node can quickly check if the connection is operational
4492 // 2) Remote nodes can measure the latency of the network thread. If this node
4493 // is overloaded it won't respond to pings quickly and the remote node can
4494 // avoid sending us more work, like chain download requests.
4496 // The nonce stops the remote getting confused between different pings: without
4497 // it, if the remote node sends a ping once per second and this node takes 5
4498 // seconds to respond to each, the 5th ping the remote sends would appear to
4499 // return very quickly.
4500 pfrom->PushMessage("pong", nonce);
4505 else if (strCommand == "pong")
4507 int64_t pingUsecEnd = nTimeReceived;
4508 uint64_t nonce = 0;
4509 size_t nAvail = vRecv.in_avail();
4510 bool bPingFinished = false;
4511 std::string sProblem;
4513 if (nAvail >= sizeof(nonce)) {
4514 vRecv >> nonce;
4516 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4517 if (pfrom->nPingNonceSent != 0) {
4518 if (nonce == pfrom->nPingNonceSent) {
4519 // Matching pong received, this ping is no longer outstanding
4520 bPingFinished = true;
4521 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4522 if (pingUsecTime > 0) {
4523 // Successful ping time measurement, replace previous
4524 pfrom->nPingUsecTime = pingUsecTime;
4525 } else {
4526 // This should never happen
4527 sProblem = "Timing mishap";
4529 } else {
4530 // Nonce mismatches are normal when pings are overlapping
4531 sProblem = "Nonce mismatch";
4532 if (nonce == 0) {
4533 // This is most likely a bug in another implementation somewhere; cancel this ping
4534 bPingFinished = true;
4535 sProblem = "Nonce zero";
4538 } else {
4539 sProblem = "Unsolicited pong without ping";
4541 } else {
4542 // This is most likely a bug in another implementation somewhere; cancel this ping
4543 bPingFinished = true;
4544 sProblem = "Short payload";
4547 if (!(sProblem.empty())) {
4548 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4549 pfrom->id,
4550 pfrom->cleanSubVer,
4551 sProblem,
4552 pfrom->nPingNonceSent,
4553 nonce,
4554 nAvail);
4556 if (bPingFinished) {
4557 pfrom->nPingNonceSent = 0;
4562 else if (fAlerts && strCommand == "alert")
4564 CAlert alert;
4565 vRecv >> alert;
4567 uint256 alertHash = alert.GetHash();
4568 if (pfrom->setKnown.count(alertHash) == 0)
4570 if (alert.ProcessAlert(Params().AlertKey()))
4572 // Relay
4573 pfrom->setKnown.insert(alertHash);
4575 LOCK(cs_vNodes);
4576 BOOST_FOREACH(CNode* pnode, vNodes)
4577 alert.RelayTo(pnode);
4580 else {
4581 // Small DoS penalty so peers that send us lots of
4582 // duplicate/expired/invalid-signature/whatever alerts
4583 // eventually get banned.
4584 // This isn't a Misbehaving(100) (immediate ban) because the
4585 // peer might be an older or different implementation with
4586 // a different signature key, etc.
4587 Misbehaving(pfrom->GetId(), 10);
4593 else if (strCommand == "filterload")
4595 CBloomFilter filter;
4596 vRecv >> filter;
4598 if (!filter.IsWithinSizeConstraints())
4599 // There is no excuse for sending a too-large filter
4600 Misbehaving(pfrom->GetId(), 100);
4601 else
4603 LOCK(pfrom->cs_filter);
4604 delete pfrom->pfilter;
4605 pfrom->pfilter = new CBloomFilter(filter);
4606 pfrom->pfilter->UpdateEmptyFull();
4608 pfrom->fRelayTxes = true;
4612 else if (strCommand == "filteradd")
4614 vector<unsigned char> vData;
4615 vRecv >> vData;
4617 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4618 // and thus, the maximum size any matched object can have) in a filteradd message
4619 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4621 Misbehaving(pfrom->GetId(), 100);
4622 } else {
4623 LOCK(pfrom->cs_filter);
4624 if (pfrom->pfilter)
4625 pfrom->pfilter->insert(vData);
4626 else
4627 Misbehaving(pfrom->GetId(), 100);
4632 else if (strCommand == "filterclear")
4634 LOCK(pfrom->cs_filter);
4635 delete pfrom->pfilter;
4636 pfrom->pfilter = new CBloomFilter();
4637 pfrom->fRelayTxes = true;
4641 else if (strCommand == "reject")
4643 if (fDebug) {
4644 try {
4645 string strMsg; unsigned char ccode; string strReason;
4646 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4648 ostringstream ss;
4649 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4651 if (strMsg == "block" || strMsg == "tx")
4653 uint256 hash;
4654 vRecv >> hash;
4655 ss << ": hash " << hash.ToString();
4657 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4658 } catch (const std::ios_base::failure&) {
4659 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4660 LogPrint("net", "Unparseable reject message received\n");
4665 else
4667 // Ignore unknown commands for extensibility
4668 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4673 return true;
4676 // requires LOCK(cs_vRecvMsg)
4677 bool ProcessMessages(CNode* pfrom)
4679 //if (fDebug)
4680 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
4683 // Message format
4684 // (4) message start
4685 // (12) command
4686 // (4) size
4687 // (4) checksum
4688 // (x) data
4690 bool fOk = true;
4692 if (!pfrom->vRecvGetData.empty())
4693 ProcessGetData(pfrom);
4695 // this maintains the order of responses
4696 if (!pfrom->vRecvGetData.empty()) return fOk;
4698 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4699 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4700 // Don't bother if send buffer is too full to respond anyway
4701 if (pfrom->nSendSize >= SendBufferSize())
4702 break;
4704 // get next message
4705 CNetMessage& msg = *it;
4707 //if (fDebug)
4708 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
4709 // msg.hdr.nMessageSize, msg.vRecv.size(),
4710 // msg.complete() ? "Y" : "N");
4712 // end, if an incomplete message is found
4713 if (!msg.complete())
4714 break;
4716 // at this point, any failure means we can delete the current message
4717 it++;
4719 // Scan for message start
4720 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4721 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4722 fOk = false;
4723 break;
4726 // Read header
4727 CMessageHeader& hdr = msg.hdr;
4728 if (!hdr.IsValid(Params().MessageStart()))
4730 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4731 continue;
4733 string strCommand = hdr.GetCommand();
4735 // Message size
4736 unsigned int nMessageSize = hdr.nMessageSize;
4738 // Checksum
4739 CDataStream& vRecv = msg.vRecv;
4740 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4741 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4742 if (nChecksum != hdr.nChecksum)
4744 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
4745 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4746 continue;
4749 // Process message
4750 bool fRet = false;
4753 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4754 boost::this_thread::interruption_point();
4756 catch (const std::ios_base::failure& e)
4758 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4759 if (strstr(e.what(), "end of data"))
4761 // Allow exceptions from under-length message on vRecv
4762 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());
4764 else if (strstr(e.what(), "size too large"))
4766 // Allow exceptions from over-long size
4767 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4769 else
4771 PrintExceptionContinue(&e, "ProcessMessages()");
4774 catch (const boost::thread_interrupted&) {
4775 throw;
4777 catch (const std::exception& e) {
4778 PrintExceptionContinue(&e, "ProcessMessages()");
4779 } catch (...) {
4780 PrintExceptionContinue(NULL, "ProcessMessages()");
4783 if (!fRet)
4784 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
4786 break;
4789 // In case the connection got shut down, its receive buffer was wiped
4790 if (!pfrom->fDisconnect)
4791 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4793 return fOk;
4797 bool SendMessages(CNode* pto, bool fSendTrickle)
4799 const Consensus::Params& consensusParams = Params().GetConsensus();
4801 // Don't send anything until we get its version message
4802 if (pto->nVersion == 0)
4803 return true;
4806 // Message: ping
4808 bool pingSend = false;
4809 if (pto->fPingQueued) {
4810 // RPC ping request by user
4811 pingSend = true;
4813 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4814 // Ping automatically sent as a latency probe & keepalive.
4815 pingSend = true;
4817 if (pingSend) {
4818 uint64_t nonce = 0;
4819 while (nonce == 0) {
4820 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4822 pto->fPingQueued = false;
4823 pto->nPingUsecStart = GetTimeMicros();
4824 if (pto->nVersion > BIP0031_VERSION) {
4825 pto->nPingNonceSent = nonce;
4826 pto->PushMessage("ping", nonce);
4827 } else {
4828 // Peer is too old to support ping command with nonce, pong will never arrive.
4829 pto->nPingNonceSent = 0;
4830 pto->PushMessage("ping");
4834 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4835 if (!lockMain)
4836 return true;
4838 // Address refresh broadcast
4839 static int64_t nLastRebroadcast;
4840 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4842 LOCK(cs_vNodes);
4843 BOOST_FOREACH(CNode* pnode, vNodes)
4845 // Periodically clear addrKnown to allow refresh broadcasts
4846 if (nLastRebroadcast)
4847 pnode->addrKnown.reset();
4849 // Rebroadcast our address
4850 AdvertizeLocal(pnode);
4852 if (!vNodes.empty())
4853 nLastRebroadcast = GetTime();
4857 // Message: addr
4859 if (fSendTrickle)
4861 vector<CAddress> vAddr;
4862 vAddr.reserve(pto->vAddrToSend.size());
4863 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4865 if (!pto->addrKnown.contains(addr.GetKey()))
4867 pto->addrKnown.insert(addr.GetKey());
4868 vAddr.push_back(addr);
4869 // receiver rejects addr messages larger than 1000
4870 if (vAddr.size() >= 1000)
4872 pto->PushMessage("addr", vAddr);
4873 vAddr.clear();
4877 pto->vAddrToSend.clear();
4878 if (!vAddr.empty())
4879 pto->PushMessage("addr", vAddr);
4882 CNodeState &state = *State(pto->GetId());
4883 if (state.fShouldBan) {
4884 if (pto->fWhitelisted)
4885 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4886 else {
4887 pto->fDisconnect = true;
4888 if (pto->addr.IsLocal())
4889 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4890 else
4892 CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
4895 state.fShouldBan = false;
4898 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4899 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4900 state.rejects.clear();
4902 // Start block sync
4903 if (pindexBestHeader == NULL)
4904 pindexBestHeader = chainActive.Tip();
4905 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.
4906 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
4907 // Only actively request headers from a single peer, unless we're close to today.
4908 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4909 state.fSyncStarted = true;
4910 nSyncStarted++;
4911 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4912 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4913 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
4917 // Resend wallet transactions that haven't gotten in a block yet
4918 // Except during reindex, importing and IBD, when old wallet
4919 // transactions become unconfirmed and spams other nodes.
4920 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4922 GetMainSignals().Broadcast(nTimeBestReceived);
4926 // Message: inventory
4928 vector<CInv> vInv;
4929 vector<CInv> vInvWait;
4931 LOCK(pto->cs_inventory);
4932 vInv.reserve(pto->vInventoryToSend.size());
4933 vInvWait.reserve(pto->vInventoryToSend.size());
4934 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4936 if (pto->setInventoryKnown.count(inv))
4937 continue;
4939 // trickle out tx inv to protect privacy
4940 if (inv.type == MSG_TX && !fSendTrickle)
4942 // 1/4 of tx invs blast to all immediately
4943 static uint256 hashSalt;
4944 if (hashSalt.IsNull())
4945 hashSalt = GetRandHash();
4946 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
4947 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4948 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
4950 if (fTrickleWait)
4952 vInvWait.push_back(inv);
4953 continue;
4957 // returns true if wasn't already contained in the set
4958 if (pto->setInventoryKnown.insert(inv).second)
4960 vInv.push_back(inv);
4961 if (vInv.size() >= 1000)
4963 pto->PushMessage("inv", vInv);
4964 vInv.clear();
4968 pto->vInventoryToSend = vInvWait;
4970 if (!vInv.empty())
4971 pto->PushMessage("inv", vInv);
4973 // Detect whether we're stalling
4974 int64_t nNow = GetTimeMicros();
4975 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4976 // Stalling only triggers when the block download window cannot move. During normal steady state,
4977 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4978 // should only happen during initial block download.
4979 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
4980 pto->fDisconnect = true;
4982 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
4983 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
4984 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
4985 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
4986 // to unreasonably increase our timeout.
4987 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
4988 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
4989 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
4990 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
4991 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
4992 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
4993 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
4994 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
4995 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
4996 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
4997 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
4999 if (queuedBlock.nTimeDisconnect < nNow) {
5000 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5001 pto->fDisconnect = true;
5006 // Message: getdata (blocks)
5008 vector<CInv> vGetData;
5009 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5010 vector<CBlockIndex*> vToDownload;
5011 NodeId staller = -1;
5012 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5013 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5014 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5015 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5016 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5017 pindex->nHeight, pto->id);
5019 if (state.nBlocksInFlight == 0 && staller != -1) {
5020 if (State(staller)->nStallingSince == 0) {
5021 State(staller)->nStallingSince = nNow;
5022 LogPrint("net", "Stall started peer=%d\n", staller);
5028 // Message: getdata (non-blocks)
5030 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5032 const CInv& inv = (*pto->mapAskFor.begin()).second;
5033 if (!AlreadyHave(inv))
5035 if (fDebug)
5036 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5037 vGetData.push_back(inv);
5038 if (vGetData.size() >= 1000)
5040 pto->PushMessage("getdata", vGetData);
5041 vGetData.clear();
5044 pto->mapAskFor.erase(pto->mapAskFor.begin());
5046 if (!vGetData.empty())
5047 pto->PushMessage("getdata", vGetData);
5050 return true;
5053 std::string CBlockFileInfo::ToString() const {
5054 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));
5059 class CMainCleanup
5061 public:
5062 CMainCleanup() {}
5063 ~CMainCleanup() {
5064 // block headers
5065 BlockMap::iterator it1 = mapBlockIndex.begin();
5066 for (; it1 != mapBlockIndex.end(); it1++)
5067 delete (*it1).second;
5068 mapBlockIndex.clear();
5070 // orphan transactions
5071 mapOrphanTransactions.clear();
5072 mapOrphanTransactionsByPrev.clear();
5074 } instance_of_cmaincleanup;