Limit setAskFor and retire requested entries only when a getdata returns.
[bitcoinplatinum.git] / src / main.cpp
blob2bcc4cbc54437b0293d6424a229baf77798ec5b1
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "main.h"
8 #include "addrman.h"
9 #include "alert.h"
10 #include "arith_uint256.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "consensus/consensus.h"
15 #include "consensus/validation.h"
16 #include "hash.h"
17 #include "init.h"
18 #include "merkleblock.h"
19 #include "net.h"
20 #include "policy/policy.h"
21 #include "pow.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "script/script.h"
25 #include "script/sigcache.h"
26 #include "script/standard.h"
27 #include "tinyformat.h"
28 #include "txdb.h"
29 #include "txmempool.h"
30 #include "ui_interface.h"
31 #include "undo.h"
32 #include "util.h"
33 #include "utilmoneystr.h"
34 #include "utilstrencodings.h"
35 #include "validationinterface.h"
37 #include <sstream>
39 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/filesystem.hpp>
41 #include <boost/filesystem/fstream.hpp>
42 #include <boost/math/distributions/poisson.hpp>
43 #include <boost/thread.hpp>
45 using namespace std;
47 #if defined(NDEBUG)
48 # error "Bitcoin cannot be compiled without assertions."
49 #endif
51 /**
52 * Global state
55 CCriticalSection cs_main;
57 BlockMap mapBlockIndex;
58 CChain chainActive;
59 CBlockIndex *pindexBestHeader = NULL;
60 int64_t nTimeBestReceived = 0;
61 CWaitableCriticalSection csBestBlock;
62 CConditionVariable cvBlockChange;
63 int nScriptCheckThreads = 0;
64 bool fImporting = false;
65 bool fReindex = false;
66 bool fTxIndex = false;
67 bool fHavePruned = false;
68 bool fPruneMode = false;
69 bool fIsBareMultisigStd = true;
70 bool fRequireStandard = true;
71 bool fCheckBlockIndex = false;
72 bool fCheckpointsEnabled = true;
73 size_t nCoinCacheUsage = 5000 * 300;
74 uint64_t nPruneTarget = 0;
75 bool fAlerts = DEFAULT_ALERTS;
77 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying, mining and transaction creation) */
78 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
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(const Consensus::Params& consensusParams);
97 /** Constant stuff for coinbase transactions we create: */
98 CScript COINBASE_FLAGS;
100 const string strMessageMagic = "Bitcoin Signed Message:\n";
102 // Internal stuff
103 namespace {
105 struct CBlockIndexWorkComparator
107 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
108 // First sort by most total work, ...
109 if (pa->nChainWork > pb->nChainWork) return false;
110 if (pa->nChainWork < pb->nChainWork) return true;
112 // ... then by earliest time received, ...
113 if (pa->nSequenceId < pb->nSequenceId) return false;
114 if (pa->nSequenceId > pb->nSequenceId) return true;
116 // Use pointer address as tie breaker (should only happen with blocks
117 // loaded from disk, as those all have id 0).
118 if (pa < pb) return false;
119 if (pa > pb) return true;
121 // Identical blocks.
122 return false;
126 CBlockIndex *pindexBestInvalid;
129 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
130 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
131 * missing the data for the block.
133 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
134 /** Number of nodes with fSyncStarted. */
135 int nSyncStarted = 0;
136 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
137 * Pruned nodes may have entries where B is missing data.
139 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
141 CCriticalSection cs_LastBlockFile;
142 std::vector<CBlockFileInfo> vinfoBlockFile;
143 int nLastBlockFile = 0;
144 /** Global flag to indicate we should check to see if there are
145 * block/undo files that should be deleted. Set on startup
146 * or if we allocate more file space when we're in prune mode
148 bool fCheckForPruning = false;
151 * Every received block is assigned a unique and increasing identifier, so we
152 * know which one to give priority in case of a fork.
154 CCriticalSection cs_nBlockSequenceId;
155 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
156 uint32_t nBlockSequenceId = 1;
159 * Sources of received blocks, saved to be able to send them reject
160 * messages or ban them when processing happens afterwards. Protected by
161 * cs_main.
163 map<uint256, NodeId> mapBlockSource;
166 * Filter for transactions that were recently rejected by
167 * AcceptToMemoryPool. These are not rerequested until the chain tip
168 * changes, at which point the entire filter is reset. Protected by
169 * cs_main.
171 * Without this filter we'd be re-requesting txs from each of our peers,
172 * increasing bandwidth consumption considerably. For instance, with 100
173 * peers, half of which relay a tx we don't accept, that might be a 50x
174 * bandwidth increase. A flooding attacker attempting to roll-over the
175 * filter using minimum-sized, 60byte, transactions might manage to send
176 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
177 * two minute window to send invs to us.
179 * Decreasing the false positive rate is fairly cheap, so we pick one in a
180 * million to make it highly unlikely for users to have issues with this
181 * filter.
183 * Memory used: 1.7MB
185 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
186 uint256 hashRecentRejectsChainTip;
188 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
189 struct QueuedBlock {
190 uint256 hash;
191 CBlockIndex *pindex; //! Optional.
192 int64_t nTime; //! Time of "getdata" request in microseconds.
193 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
194 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
196 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
198 /** Number of blocks in flight with validated headers. */
199 int nQueuedValidatedHeaders = 0;
201 /** Number of preferable block download peers. */
202 int nPreferredDownload = 0;
204 /** Dirty block index entries. */
205 set<CBlockIndex*> setDirtyBlockIndex;
207 /** Dirty block file entries. */
208 set<int> setDirtyFileInfo;
209 } // anon namespace
211 //////////////////////////////////////////////////////////////////////////////
213 // Registration of network node signals.
216 namespace {
218 struct CBlockReject {
219 unsigned char chRejectCode;
220 string strRejectReason;
221 uint256 hashBlock;
225 * Maintain validation-specific state about nodes, protected by cs_main, instead
226 * by CNode's own locks. This simplifies asynchronous operation, where
227 * processing of incoming data is done after the ProcessMessage call returns,
228 * and we're no longer holding the node's locks.
230 struct CNodeState {
231 //! The peer's address
232 CService address;
233 //! Whether we have a fully established connection.
234 bool fCurrentlyConnected;
235 //! Accumulated misbehaviour score for this peer.
236 int nMisbehavior;
237 //! Whether this peer should be disconnected and banned (unless whitelisted).
238 bool fShouldBan;
239 //! String name of this peer (debugging/logging purposes).
240 std::string name;
241 //! List of asynchronously-determined block rejections to notify this peer about.
242 std::vector<CBlockReject> rejects;
243 //! The best known block we know this peer has announced.
244 CBlockIndex *pindexBestKnownBlock;
245 //! The hash of the last unknown block this peer has announced.
246 uint256 hashLastUnknownBlock;
247 //! The last full block we both have.
248 CBlockIndex *pindexLastCommonBlock;
249 //! Whether we've started headers synchronization with this peer.
250 bool fSyncStarted;
251 //! Since when we're stalling block download progress (in microseconds), or 0.
252 int64_t nStallingSince;
253 list<QueuedBlock> vBlocksInFlight;
254 int nBlocksInFlight;
255 int nBlocksInFlightValidHeaders;
256 //! Whether we consider this a preferred download peer.
257 bool fPreferredDownload;
259 CNodeState() {
260 fCurrentlyConnected = false;
261 nMisbehavior = 0;
262 fShouldBan = false;
263 pindexBestKnownBlock = NULL;
264 hashLastUnknownBlock.SetNull();
265 pindexLastCommonBlock = NULL;
266 fSyncStarted = false;
267 nStallingSince = 0;
268 nBlocksInFlight = 0;
269 nBlocksInFlightValidHeaders = 0;
270 fPreferredDownload = false;
274 /** Map maintaining per-node state. Requires cs_main. */
275 map<NodeId, CNodeState> mapNodeState;
277 // Requires cs_main.
278 CNodeState *State(NodeId pnode) {
279 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
280 if (it == mapNodeState.end())
281 return NULL;
282 return &it->second;
285 int GetHeight()
287 LOCK(cs_main);
288 return chainActive.Height();
291 void UpdatePreferredDownload(CNode* node, CNodeState* state)
293 nPreferredDownload -= state->fPreferredDownload;
295 // Whether this node should be marked as a preferred download node.
296 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
298 nPreferredDownload += state->fPreferredDownload;
301 // Returns time at which to timeout block request (nTime in microseconds)
302 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
304 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
307 void InitializeNode(NodeId nodeid, const CNode *pnode) {
308 LOCK(cs_main);
309 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
310 state.name = pnode->addrName;
311 state.address = pnode->addr;
314 void FinalizeNode(NodeId nodeid) {
315 LOCK(cs_main);
316 CNodeState *state = State(nodeid);
318 if (state->fSyncStarted)
319 nSyncStarted--;
321 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
322 AddressCurrentlyConnected(state->address);
325 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
326 mapBlocksInFlight.erase(entry.hash);
327 EraseOrphansFor(nodeid);
328 nPreferredDownload -= state->fPreferredDownload;
330 mapNodeState.erase(nodeid);
333 // Requires cs_main.
334 // Returns a bool indicating whether we requested this block.
335 bool MarkBlockAsReceived(const uint256& hash) {
336 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
337 if (itInFlight != mapBlocksInFlight.end()) {
338 CNodeState *state = State(itInFlight->second.first);
339 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
340 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
341 state->vBlocksInFlight.erase(itInFlight->second.second);
342 state->nBlocksInFlight--;
343 state->nStallingSince = 0;
344 mapBlocksInFlight.erase(itInFlight);
345 return true;
347 return false;
350 // Requires cs_main.
351 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
352 CNodeState *state = State(nodeid);
353 assert(state != NULL);
355 // Make sure it's not listed somewhere already.
356 MarkBlockAsReceived(hash);
358 int64_t nNow = GetTimeMicros();
359 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
360 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
361 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
362 state->nBlocksInFlight++;
363 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
364 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
367 /** Check whether the last unknown block a peer advertized is not yet known. */
368 void ProcessBlockAvailability(NodeId nodeid) {
369 CNodeState *state = State(nodeid);
370 assert(state != NULL);
372 if (!state->hashLastUnknownBlock.IsNull()) {
373 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
374 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
375 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
376 state->pindexBestKnownBlock = itOld->second;
377 state->hashLastUnknownBlock.SetNull();
382 /** Update tracking information about which blocks a peer is assumed to have. */
383 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
384 CNodeState *state = State(nodeid);
385 assert(state != NULL);
387 ProcessBlockAvailability(nodeid);
389 BlockMap::iterator it = mapBlockIndex.find(hash);
390 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
391 // An actually better block was announced.
392 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
393 state->pindexBestKnownBlock = it->second;
394 } else {
395 // An unknown block was announced; just assume that the latest one is the best one.
396 state->hashLastUnknownBlock = hash;
400 /** Find the last common ancestor two blocks have.
401 * Both pa and pb must be non-NULL. */
402 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
403 if (pa->nHeight > pb->nHeight) {
404 pa = pa->GetAncestor(pb->nHeight);
405 } else if (pb->nHeight > pa->nHeight) {
406 pb = pb->GetAncestor(pa->nHeight);
409 while (pa != pb && pa && pb) {
410 pa = pa->pprev;
411 pb = pb->pprev;
414 // Eventually all chain branches meet at the genesis block.
415 assert(pa == pb);
416 return pa;
419 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
420 * at most count entries. */
421 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
422 if (count == 0)
423 return;
425 vBlocks.reserve(vBlocks.size() + count);
426 CNodeState *state = State(nodeid);
427 assert(state != NULL);
429 // Make sure pindexBestKnownBlock is up to date, we'll need it.
430 ProcessBlockAvailability(nodeid);
432 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
433 // This peer has nothing interesting.
434 return;
437 if (state->pindexLastCommonBlock == NULL) {
438 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
439 // Guessing wrong in either direction is not a problem.
440 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
443 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
444 // of its current tip anymore. Go back enough to fix that.
445 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
446 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
447 return;
449 std::vector<CBlockIndex*> vToFetch;
450 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
451 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
452 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
453 // download that next block if the window were 1 larger.
454 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
455 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
456 NodeId waitingfor = -1;
457 while (pindexWalk->nHeight < nMaxHeight) {
458 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
459 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
460 // as iterating over ~100 CBlockIndex* entries anyway.
461 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
462 vToFetch.resize(nToFetch);
463 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
464 vToFetch[nToFetch - 1] = pindexWalk;
465 for (unsigned int i = nToFetch - 1; i > 0; i--) {
466 vToFetch[i - 1] = vToFetch[i]->pprev;
469 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
470 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
471 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
472 // already part of our chain (and therefore don't need it even if pruned).
473 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
474 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
475 // We consider the chain that this peer is on invalid.
476 return;
478 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
479 if (pindex->nChainTx)
480 state->pindexLastCommonBlock = pindex;
481 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
482 // The block is not already downloaded, and not yet in flight.
483 if (pindex->nHeight > nWindowEnd) {
484 // We reached the end of the window.
485 if (vBlocks.size() == 0 && waitingfor != nodeid) {
486 // We aren't able to fetch anything, but we would be if the download window was one larger.
487 nodeStaller = waitingfor;
489 return;
491 vBlocks.push_back(pindex);
492 if (vBlocks.size() == count) {
493 return;
495 } else if (waitingfor == -1) {
496 // This is the first already-in-flight block.
497 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
503 } // anon namespace
505 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
506 LOCK(cs_main);
507 CNodeState *state = State(nodeid);
508 if (state == NULL)
509 return false;
510 stats.nMisbehavior = state->nMisbehavior;
511 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
512 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
513 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
514 if (queue.pindex)
515 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
517 return true;
520 void RegisterNodeSignals(CNodeSignals& nodeSignals)
522 nodeSignals.GetHeight.connect(&GetHeight);
523 nodeSignals.ProcessMessages.connect(&ProcessMessages);
524 nodeSignals.SendMessages.connect(&SendMessages);
525 nodeSignals.InitializeNode.connect(&InitializeNode);
526 nodeSignals.FinalizeNode.connect(&FinalizeNode);
529 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
531 nodeSignals.GetHeight.disconnect(&GetHeight);
532 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
533 nodeSignals.SendMessages.disconnect(&SendMessages);
534 nodeSignals.InitializeNode.disconnect(&InitializeNode);
535 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
538 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
540 // Find the first block the caller has in the main chain
541 BOOST_FOREACH(const uint256& hash, locator.vHave) {
542 BlockMap::iterator mi = mapBlockIndex.find(hash);
543 if (mi != mapBlockIndex.end())
545 CBlockIndex* pindex = (*mi).second;
546 if (chain.Contains(pindex))
547 return pindex;
550 return chain.Genesis();
553 CCoinsViewCache *pcoinsTip = NULL;
554 CBlockTreeDB *pblocktree = NULL;
556 //////////////////////////////////////////////////////////////////////////////
558 // mapOrphanTransactions
561 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
563 uint256 hash = tx.GetHash();
564 if (mapOrphanTransactions.count(hash))
565 return false;
567 // Ignore big transactions, to avoid a
568 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
569 // large transaction with a missing parent then we assume
570 // it will rebroadcast it later, after the parent transaction(s)
571 // have been mined or received.
572 // 10,000 orphans, each of which is at most 5,000 bytes big is
573 // at most 500 megabytes of orphans:
574 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
575 if (sz > 5000)
577 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
578 return false;
581 mapOrphanTransactions[hash].tx = tx;
582 mapOrphanTransactions[hash].fromPeer = peer;
583 BOOST_FOREACH(const CTxIn& txin, tx.vin)
584 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
586 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
587 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
588 return true;
591 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
593 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
594 if (it == mapOrphanTransactions.end())
595 return;
596 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
598 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
599 if (itPrev == mapOrphanTransactionsByPrev.end())
600 continue;
601 itPrev->second.erase(hash);
602 if (itPrev->second.empty())
603 mapOrphanTransactionsByPrev.erase(itPrev);
605 mapOrphanTransactions.erase(it);
608 void EraseOrphansFor(NodeId peer)
610 int nErased = 0;
611 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
612 while (iter != mapOrphanTransactions.end())
614 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
615 if (maybeErase->second.fromPeer == peer)
617 EraseOrphanTx(maybeErase->second.tx.GetHash());
618 ++nErased;
621 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
625 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
627 unsigned int nEvicted = 0;
628 while (mapOrphanTransactions.size() > nMaxOrphans)
630 // Evict a random orphan:
631 uint256 randomhash = GetRandHash();
632 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
633 if (it == mapOrphanTransactions.end())
634 it = mapOrphanTransactions.begin();
635 EraseOrphanTx(it->first);
636 ++nEvicted;
638 return nEvicted;
641 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
643 if (tx.nLockTime == 0)
644 return true;
645 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
646 return true;
647 BOOST_FOREACH(const CTxIn& txin, tx.vin)
648 if (!txin.IsFinal())
649 return false;
650 return true;
653 bool CheckFinalTx(const CTransaction &tx, int flags)
655 AssertLockHeld(cs_main);
657 // By convention a negative value for flags indicates that the
658 // current network-enforced consensus rules should be used. In
659 // a future soft-fork scenario that would mean checking which
660 // rules would be enforced for the next block and setting the
661 // appropriate flags. At the present time no soft-forks are
662 // scheduled, so no flags are set.
663 flags = std::max(flags, 0);
665 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
666 // nLockTime because when IsFinalTx() is called within
667 // CBlock::AcceptBlock(), the height of the block *being*
668 // evaluated is what is used. Thus if we want to know if a
669 // transaction can be part of the *next* block, we need to call
670 // IsFinalTx() with one more than chainActive.Height().
671 const int nBlockHeight = chainActive.Height() + 1;
673 // BIP113 will require that time-locked transactions have nLockTime set to
674 // less than the median time of the previous block they're contained in.
675 // When the next block is created its previous block will be the current
676 // chain tip, so we use that to calculate the median time passed to
677 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
678 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
679 ? chainActive.Tip()->GetMedianTimePast()
680 : GetAdjustedTime();
682 return IsFinalTx(tx, nBlockHeight, nBlockTime);
685 unsigned int GetLegacySigOpCount(const CTransaction& tx)
687 unsigned int nSigOps = 0;
688 BOOST_FOREACH(const CTxIn& txin, tx.vin)
690 nSigOps += txin.scriptSig.GetSigOpCount(false);
692 BOOST_FOREACH(const CTxOut& txout, tx.vout)
694 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
696 return nSigOps;
699 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
701 if (tx.IsCoinBase())
702 return 0;
704 unsigned int nSigOps = 0;
705 for (unsigned int i = 0; i < tx.vin.size(); i++)
707 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
708 if (prevout.scriptPubKey.IsPayToScriptHash())
709 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
711 return nSigOps;
721 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
723 // Basic checks that don't depend on any context
724 if (tx.vin.empty())
725 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
726 if (tx.vout.empty())
727 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
728 // Size limits
729 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
730 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
732 // Check for negative or overflow output values
733 CAmount nValueOut = 0;
734 BOOST_FOREACH(const CTxOut& txout, tx.vout)
736 if (txout.nValue < 0)
737 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
738 if (txout.nValue > MAX_MONEY)
739 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
740 nValueOut += txout.nValue;
741 if (!MoneyRange(nValueOut))
742 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
745 // Check for duplicate inputs
746 set<COutPoint> vInOutPoints;
747 BOOST_FOREACH(const CTxIn& txin, tx.vin)
749 if (vInOutPoints.count(txin.prevout))
750 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
751 vInOutPoints.insert(txin.prevout);
754 if (tx.IsCoinBase())
756 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
757 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
759 else
761 BOOST_FOREACH(const CTxIn& txin, tx.vin)
762 if (txin.prevout.IsNull())
763 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
766 return true;
769 CAmount GetMinRelayFee(const CTransaction& tx, const CTxMemPool& pool, unsigned int nBytes, bool fAllowFree)
771 uint256 hash = tx.GetHash();
772 double dPriorityDelta = 0;
773 CAmount nFeeDelta = 0;
774 pool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
775 if (dPriorityDelta > 0 || nFeeDelta > 0)
776 return 0;
778 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
780 if (fAllowFree)
782 // There is a free transaction area in blocks created by most miners,
783 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
784 // to be considered to fall into this category. We don't want to encourage sending
785 // multiple transactions instead of one big transaction to avoid fees.
786 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
787 nMinFee = 0;
790 if (!MoneyRange(nMinFee))
791 nMinFee = MAX_MONEY;
792 return nMinFee;
795 /** Convert CValidationState to a human-readable message for logging */
796 static std::string FormatStateMessage(const CValidationState &state)
798 return strprintf("%s%s (code %i)",
799 state.GetRejectReason(),
800 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
801 state.GetRejectCode());
804 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
805 bool* pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectAbsurdFee)
807 AssertLockHeld(cs_main);
808 if (pfMissingInputs)
809 *pfMissingInputs = false;
811 if (!CheckTransaction(tx, state))
812 return false;
814 // Coinbase is only valid in a block, not as a loose transaction
815 if (tx.IsCoinBase())
816 return state.DoS(100, false, REJECT_INVALID, "coinbase");
818 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
819 string reason;
820 if (fRequireStandard && !IsStandardTx(tx, reason))
821 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
823 // Only accept nLockTime-using transactions that can be mined in the next
824 // block; we don't want our mempool filled up with transactions that can't
825 // be mined yet.
826 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
827 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
829 // is it already in the memory pool?
830 uint256 hash = tx.GetHash();
831 if (pool.exists(hash))
832 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
834 // Check for conflicts with in-memory transactions
836 LOCK(pool.cs); // protect pool.mapNextTx
837 for (unsigned int i = 0; i < tx.vin.size(); i++)
839 COutPoint outpoint = tx.vin[i].prevout;
840 if (pool.mapNextTx.count(outpoint))
842 // Disable replacement feature for now
843 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
849 CCoinsView dummy;
850 CCoinsViewCache view(&dummy);
852 CAmount nValueIn = 0;
854 LOCK(pool.cs);
855 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
856 view.SetBackend(viewMemPool);
858 // do we already have it?
859 if (view.HaveCoins(hash))
860 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
862 // do all inputs exist?
863 // Note that this does not check for the presence of actual outputs (see the next check for that),
864 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
865 BOOST_FOREACH(const CTxIn txin, tx.vin) {
866 if (!view.HaveCoins(txin.prevout.hash)) {
867 if (pfMissingInputs)
868 *pfMissingInputs = true;
869 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
873 // are the actual inputs available?
874 if (!view.HaveInputs(tx))
875 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
877 // Bring the best block into scope
878 view.GetBestBlock();
880 nValueIn = view.GetValueIn(tx);
882 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
883 view.SetBackend(dummy);
886 // Check for non-standard pay-to-script-hash in inputs
887 if (fRequireStandard && !AreInputsStandard(tx, view))
888 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
890 // Check that the transaction doesn't have an excessive number of
891 // sigops, making it impossible to mine. Since the coinbase transaction
892 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
893 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
894 // merely non-standard transaction.
895 unsigned int nSigOps = GetLegacySigOpCount(tx);
896 nSigOps += GetP2SHSigOpCount(tx, view);
897 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
898 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
899 strprintf("%d > %d", nSigOps, MAX_STANDARD_TX_SIGOPS));
901 CAmount nValueOut = tx.GetValueOut();
902 CAmount nFees = nValueIn-nValueOut;
903 double dPriority = view.GetPriority(tx, chainActive.Height());
905 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), pool.HasNoInputsOf(tx));
906 unsigned int nSize = entry.GetTxSize();
908 // Don't accept it if it can't get into a block
909 CAmount txMinFee = GetMinRelayFee(tx, pool, nSize, true);
910 if (fLimitFree && nFees < txMinFee)
911 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee", false,
912 strprintf("%d < %d", nFees, txMinFee));
914 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
915 if (mempoolRejectFee > 0 && nFees < mempoolRejectFee) {
916 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
917 } else if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
918 // Require that free transactions have sufficient priority to be mined in the next block.
919 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
922 // Continuously rate-limit free (really, very-low-fee) transactions
923 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
924 // be annoying or make others' transactions take longer to confirm.
925 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
927 static CCriticalSection csFreeLimiter;
928 static double dFreeCount;
929 static int64_t nLastTime;
930 int64_t nNow = GetTime();
932 LOCK(csFreeLimiter);
934 // Use an exponentially decaying ~10-minute window:
935 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
936 nLastTime = nNow;
937 // -limitfreerelay unit is thousand-bytes-per-minute
938 // At default rate it would take over a month to fill 1GB
939 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
940 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
941 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
942 dFreeCount += nSize;
945 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
946 return state.Invalid(false,
947 REJECT_HIGHFEE, "absurdly-high-fee",
948 strprintf("%d > %d", nFees, ::minRelayTxFee.GetFee(nSize) * 10000));
950 // Calculate in-mempool ancestors, up to a limit.
951 CTxMemPool::setEntries setAncestors;
952 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
953 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
954 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
955 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
956 std::string errString;
957 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
958 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
961 // Check against previous transactions
962 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
963 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
964 return false;
966 // Check again against just the consensus-critical mandatory script
967 // verification flags, in case of bugs in the standard flags that cause
968 // transactions to pass as valid when they're actually invalid. For
969 // instance the STRICTENC flag was incorrectly allowing certain
970 // CHECKSIG NOT scripts to pass, even though they were invalid.
972 // There is a similar check in CreateNewBlock() to prevent creating
973 // invalid blocks, however allowing such transactions into the mempool
974 // can be exploited as a DoS attack.
975 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
977 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
978 __func__, hash.ToString(), FormatStateMessage(state));
981 // Store transaction in memory
982 pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload());
984 // trim mempool and check if tx was trimmed
985 if (!fOverrideMempoolLimit) {
986 int expired = pool.Expire(GetTime() - GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
987 if (expired != 0)
988 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
990 pool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
991 if (!pool.exists(tx.GetHash()))
992 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
996 SyncWithWallets(tx, NULL);
998 return true;
1001 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1002 bool GetTransaction(const uint256 &hash, CTransaction &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
1004 CBlockIndex *pindexSlow = NULL;
1006 LOCK(cs_main);
1008 if (mempool.lookup(hash, txOut))
1010 return true;
1013 if (fTxIndex) {
1014 CDiskTxPos postx;
1015 if (pblocktree->ReadTxIndex(hash, postx)) {
1016 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1017 if (file.IsNull())
1018 return error("%s: OpenBlockFile failed", __func__);
1019 CBlockHeader header;
1020 try {
1021 file >> header;
1022 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1023 file >> txOut;
1024 } catch (const std::exception& e) {
1025 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1027 hashBlock = header.GetHash();
1028 if (txOut.GetHash() != hash)
1029 return error("%s: txid mismatch", __func__);
1030 return true;
1034 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1035 int nHeight = -1;
1037 CCoinsViewCache &view = *pcoinsTip;
1038 const CCoins* coins = view.AccessCoins(hash);
1039 if (coins)
1040 nHeight = coins->nHeight;
1042 if (nHeight > 0)
1043 pindexSlow = chainActive[nHeight];
1046 if (pindexSlow) {
1047 CBlock block;
1048 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1049 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1050 if (tx.GetHash() == hash) {
1051 txOut = tx;
1052 hashBlock = pindexSlow->GetBlockHash();
1053 return true;
1059 return false;
1067 //////////////////////////////////////////////////////////////////////////////
1069 // CBlock and CBlockIndex
1072 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1074 // Open history file to append
1075 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1076 if (fileout.IsNull())
1077 return error("WriteBlockToDisk: OpenBlockFile failed");
1079 // Write index header
1080 unsigned int nSize = fileout.GetSerializeSize(block);
1081 fileout << FLATDATA(messageStart) << nSize;
1083 // Write block
1084 long fileOutPos = ftell(fileout.Get());
1085 if (fileOutPos < 0)
1086 return error("WriteBlockToDisk: ftell failed");
1087 pos.nPos = (unsigned int)fileOutPos;
1088 fileout << block;
1090 return true;
1093 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1095 block.SetNull();
1097 // Open history file to read
1098 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1099 if (filein.IsNull())
1100 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1102 // Read block
1103 try {
1104 filein >> block;
1106 catch (const std::exception& e) {
1107 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1110 // Check the header
1111 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1112 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1114 return true;
1117 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1119 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1120 return false;
1121 if (block.GetHash() != pindex->GetBlockHash())
1122 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1123 pindex->ToString(), pindex->GetBlockPos().ToString());
1124 return true;
1127 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1129 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1130 // Force block reward to zero when right shift is undefined.
1131 if (halvings >= 64)
1132 return 0;
1134 CAmount nSubsidy = 50 * COIN;
1135 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1136 nSubsidy >>= halvings;
1137 return nSubsidy;
1140 bool IsInitialBlockDownload()
1142 const CChainParams& chainParams = Params();
1143 LOCK(cs_main);
1144 if (fImporting || fReindex)
1145 return true;
1146 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1147 return true;
1148 static bool lockIBDState = false;
1149 if (lockIBDState)
1150 return false;
1151 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1152 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1153 if (!state)
1154 lockIBDState = true;
1155 return state;
1158 bool fLargeWorkForkFound = false;
1159 bool fLargeWorkInvalidChainFound = false;
1160 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1162 void CheckForkWarningConditions()
1164 AssertLockHeld(cs_main);
1165 // Before we get past initial download, we cannot reliably alert about forks
1166 // (we assume we don't get stuck on a fork before the last checkpoint)
1167 if (IsInitialBlockDownload())
1168 return;
1170 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1171 // of our head, drop it
1172 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1173 pindexBestForkTip = NULL;
1175 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1177 if (!fLargeWorkForkFound && pindexBestForkBase)
1179 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1180 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1181 CAlert::Notify(warning, true);
1183 if (pindexBestForkTip && pindexBestForkBase)
1185 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__,
1186 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1187 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1188 fLargeWorkForkFound = true;
1190 else
1192 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1193 fLargeWorkInvalidChainFound = true;
1196 else
1198 fLargeWorkForkFound = false;
1199 fLargeWorkInvalidChainFound = false;
1203 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1205 AssertLockHeld(cs_main);
1206 // If we are on a fork that is sufficiently large, set a warning flag
1207 CBlockIndex* pfork = pindexNewForkTip;
1208 CBlockIndex* plonger = chainActive.Tip();
1209 while (pfork && pfork != plonger)
1211 while (plonger && plonger->nHeight > pfork->nHeight)
1212 plonger = plonger->pprev;
1213 if (pfork == plonger)
1214 break;
1215 pfork = pfork->pprev;
1218 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1219 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1220 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1221 // hash rate operating on the fork.
1222 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1223 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1224 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1225 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1226 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1227 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1229 pindexBestForkTip = pindexNewForkTip;
1230 pindexBestForkBase = pfork;
1233 CheckForkWarningConditions();
1236 // Requires cs_main.
1237 void Misbehaving(NodeId pnode, int howmuch)
1239 if (howmuch == 0)
1240 return;
1242 CNodeState *state = State(pnode);
1243 if (state == NULL)
1244 return;
1246 state->nMisbehavior += howmuch;
1247 int banscore = GetArg("-banscore", 100);
1248 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1250 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1251 state->fShouldBan = true;
1252 } else
1253 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1256 void static InvalidChainFound(CBlockIndex* pindexNew)
1258 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1259 pindexBestInvalid = pindexNew;
1261 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1262 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1263 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1264 pindexNew->GetBlockTime()));
1265 CBlockIndex *tip = chainActive.Tip();
1266 assert (tip);
1267 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1268 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1269 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1270 CheckForkWarningConditions();
1273 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1274 int nDoS = 0;
1275 if (state.IsInvalid(nDoS)) {
1276 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1277 if (it != mapBlockSource.end() && State(it->second)) {
1278 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
1279 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1280 State(it->second)->rejects.push_back(reject);
1281 if (nDoS > 0)
1282 Misbehaving(it->second, nDoS);
1285 if (!state.CorruptionPossible()) {
1286 pindex->nStatus |= BLOCK_FAILED_VALID;
1287 setDirtyBlockIndex.insert(pindex);
1288 setBlockIndexCandidates.erase(pindex);
1289 InvalidChainFound(pindex);
1293 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1295 // mark inputs spent
1296 if (!tx.IsCoinBase()) {
1297 txundo.vprevout.reserve(tx.vin.size());
1298 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1299 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1300 unsigned nPos = txin.prevout.n;
1302 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1303 assert(false);
1304 // mark an outpoint spent, and construct undo information
1305 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1306 coins->Spend(nPos);
1307 if (coins->vout.size() == 0) {
1308 CTxInUndo& undo = txundo.vprevout.back();
1309 undo.nHeight = coins->nHeight;
1310 undo.fCoinBase = coins->fCoinBase;
1311 undo.nVersion = coins->nVersion;
1314 // add outputs
1315 inputs.ModifyNewCoins(tx.GetHash())->FromTx(tx, nHeight);
1317 else {
1318 // add outputs for coinbase tx
1319 // In this case call the full ModifyCoins which will do a database
1320 // lookup to be sure the coins do not already exist otherwise we do not
1321 // know whether to mark them fresh or not. We want the duplicate coinbases
1322 // before BIP30 to still be properly overwritten.
1323 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1327 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1329 CTxUndo txundo;
1330 UpdateCoins(tx, state, inputs, txundo, nHeight);
1333 bool CScriptCheck::operator()() {
1334 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1335 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1336 return false;
1338 return true;
1341 int GetSpendHeight(const CCoinsViewCache& inputs)
1343 LOCK(cs_main);
1344 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1345 return pindexPrev->nHeight + 1;
1348 namespace Consensus {
1349 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1351 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1352 // for an attacker to attempt to split the network.
1353 if (!inputs.HaveInputs(tx))
1354 return state.Invalid(false, 0, "", "Inputs unavailable");
1356 CAmount nValueIn = 0;
1357 CAmount nFees = 0;
1358 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 // If prev is coinbase, check that it's matured
1365 if (coins->IsCoinBase()) {
1366 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1367 return state.Invalid(false,
1368 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1369 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1372 // Check for negative or overflow input values
1373 nValueIn += coins->vout[prevout.n].nValue;
1374 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1375 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1379 if (nValueIn < tx.GetValueOut())
1380 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1381 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1383 // Tally transaction fees
1384 CAmount nTxFee = nValueIn - tx.GetValueOut();
1385 if (nTxFee < 0)
1386 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1387 nFees += nTxFee;
1388 if (!MoneyRange(nFees))
1389 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1390 return true;
1392 }// namespace Consensus
1394 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1396 if (!tx.IsCoinBase())
1398 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1399 return false;
1401 if (pvChecks)
1402 pvChecks->reserve(tx.vin.size());
1404 // The first loop above does all the inexpensive checks.
1405 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1406 // Helps prevent CPU exhaustion attacks.
1408 // Skip ECDSA signature verification when connecting blocks
1409 // before the last block chain checkpoint. This is safe because block merkle hashes are
1410 // still computed and checked, and any change will be caught at the next checkpoint.
1411 if (fScriptChecks) {
1412 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1413 const COutPoint &prevout = tx.vin[i].prevout;
1414 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1415 assert(coins);
1417 // Verify signature
1418 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1419 if (pvChecks) {
1420 pvChecks->push_back(CScriptCheck());
1421 check.swap(pvChecks->back());
1422 } else if (!check()) {
1423 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1424 // Check whether the failure was caused by a
1425 // non-mandatory script verification check, such as
1426 // non-standard DER encodings or non-null dummy
1427 // arguments; if so, don't trigger DoS protection to
1428 // avoid splitting the network between upgraded and
1429 // non-upgraded nodes.
1430 CScriptCheck check(*coins, tx, i,
1431 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1432 if (check())
1433 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1435 // Failures of other flags indicate a transaction that is
1436 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1437 // such nodes as they are not following the protocol. That
1438 // said during an upgrade careful thought should be taken
1439 // as to the correct behavior - we may want to continue
1440 // peering with non-upgraded nodes even after a soft-fork
1441 // super-majority vote has passed.
1442 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1448 return true;
1451 namespace {
1453 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1455 // Open history file to append
1456 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1457 if (fileout.IsNull())
1458 return error("%s: OpenUndoFile failed", __func__);
1460 // Write index header
1461 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1462 fileout << FLATDATA(messageStart) << nSize;
1464 // Write undo data
1465 long fileOutPos = ftell(fileout.Get());
1466 if (fileOutPos < 0)
1467 return error("%s: ftell failed", __func__);
1468 pos.nPos = (unsigned int)fileOutPos;
1469 fileout << blockundo;
1471 // calculate & write checksum
1472 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1473 hasher << hashBlock;
1474 hasher << blockundo;
1475 fileout << hasher.GetHash();
1477 return true;
1480 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1482 // Open history file to read
1483 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1484 if (filein.IsNull())
1485 return error("%s: OpenBlockFile failed", __func__);
1487 // Read block
1488 uint256 hashChecksum;
1489 try {
1490 filein >> blockundo;
1491 filein >> hashChecksum;
1493 catch (const std::exception& e) {
1494 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1497 // Verify checksum
1498 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1499 hasher << hashBlock;
1500 hasher << blockundo;
1501 if (hashChecksum != hasher.GetHash())
1502 return error("%s: Checksum mismatch", __func__);
1504 return true;
1507 /** Abort with a message */
1508 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1510 strMiscWarning = strMessage;
1511 LogPrintf("*** %s\n", strMessage);
1512 uiInterface.ThreadSafeMessageBox(
1513 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1514 "", CClientUIInterface::MSG_ERROR);
1515 StartShutdown();
1516 return false;
1519 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1521 AbortNode(strMessage, userMessage);
1522 return state.Error(strMessage);
1525 } // anon namespace
1528 * Apply the undo operation of a CTxInUndo to the given chain state.
1529 * @param undo The undo object.
1530 * @param view The coins view to which to apply the changes.
1531 * @param out The out point that corresponds to the tx input.
1532 * @return True on success.
1534 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1536 bool fClean = true;
1538 CCoinsModifier coins = view.ModifyCoins(out.hash);
1539 if (undo.nHeight != 0) {
1540 // undo data contains height: this is the last output of the prevout tx being spent
1541 if (!coins->IsPruned())
1542 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1543 coins->Clear();
1544 coins->fCoinBase = undo.fCoinBase;
1545 coins->nHeight = undo.nHeight;
1546 coins->nVersion = undo.nVersion;
1547 } else {
1548 if (coins->IsPruned())
1549 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1551 if (coins->IsAvailable(out.n))
1552 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1553 if (coins->vout.size() < out.n+1)
1554 coins->vout.resize(out.n+1);
1555 coins->vout[out.n] = undo.txout;
1557 return fClean;
1560 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1562 assert(pindex->GetBlockHash() == view.GetBestBlock());
1564 if (pfClean)
1565 *pfClean = false;
1567 bool fClean = true;
1569 CBlockUndo blockUndo;
1570 CDiskBlockPos pos = pindex->GetUndoPos();
1571 if (pos.IsNull())
1572 return error("DisconnectBlock(): no undo data available");
1573 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1574 return error("DisconnectBlock(): failure reading undo data");
1576 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1577 return error("DisconnectBlock(): block and undo data inconsistent");
1579 // undo transactions in reverse order
1580 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1581 const CTransaction &tx = block.vtx[i];
1582 uint256 hash = tx.GetHash();
1584 // Check that all outputs are available and match the outputs in the block itself
1585 // exactly.
1587 CCoinsModifier outs = view.ModifyCoins(hash);
1588 outs->ClearUnspendable();
1590 CCoins outsBlock(tx, pindex->nHeight);
1591 // The CCoins serialization does not serialize negative numbers.
1592 // No network rules currently depend on the version here, so an inconsistency is harmless
1593 // but it must be corrected before txout nversion ever influences a network rule.
1594 if (outsBlock.nVersion < 0)
1595 outs->nVersion = outsBlock.nVersion;
1596 if (*outs != outsBlock)
1597 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1599 // remove outputs
1600 outs->Clear();
1603 // restore inputs
1604 if (i > 0) { // not coinbases
1605 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1606 if (txundo.vprevout.size() != tx.vin.size())
1607 return error("DisconnectBlock(): transaction and undo data inconsistent");
1608 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1609 const COutPoint &out = tx.vin[j].prevout;
1610 const CTxInUndo &undo = txundo.vprevout[j];
1611 if (!ApplyTxInUndo(undo, view, out))
1612 fClean = false;
1617 // move best block pointer to prevout block
1618 view.SetBestBlock(pindex->pprev->GetBlockHash());
1620 if (pfClean) {
1621 *pfClean = fClean;
1622 return true;
1625 return fClean;
1628 void static FlushBlockFile(bool fFinalize = false)
1630 LOCK(cs_LastBlockFile);
1632 CDiskBlockPos posOld(nLastBlockFile, 0);
1634 FILE *fileOld = OpenBlockFile(posOld);
1635 if (fileOld) {
1636 if (fFinalize)
1637 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1638 FileCommit(fileOld);
1639 fclose(fileOld);
1642 fileOld = OpenUndoFile(posOld);
1643 if (fileOld) {
1644 if (fFinalize)
1645 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1646 FileCommit(fileOld);
1647 fclose(fileOld);
1651 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1653 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1655 void ThreadScriptCheck() {
1656 RenameThread("bitcoin-scriptch");
1657 scriptcheckqueue.Thread();
1661 // Called periodically asynchronously; alerts if it smells like
1662 // we're being fed a bad chain (blocks being generated much
1663 // too slowly or too quickly).
1665 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1666 int64_t nPowTargetSpacing)
1668 if (bestHeader == NULL || initialDownloadCheck()) return;
1670 static int64_t lastAlertTime = 0;
1671 int64_t now = GetAdjustedTime();
1672 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1674 const int SPAN_HOURS=4;
1675 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1676 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1678 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1680 std::string strWarning;
1681 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1683 LOCK(cs);
1684 const CBlockIndex* i = bestHeader;
1685 int nBlocks = 0;
1686 while (i->GetBlockTime() >= startTime) {
1687 ++nBlocks;
1688 i = i->pprev;
1689 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
1692 // How likely is it to find that many by chance?
1693 double p = boost::math::pdf(poisson, nBlocks);
1695 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1696 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
1698 // Aim for one false-positive about every fifty years of normal running:
1699 const int FIFTY_YEARS = 50*365*24*60*60;
1700 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
1702 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
1704 // Many fewer blocks than expected: alert!
1705 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
1706 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1708 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
1710 // Many more blocks than expected: alert!
1711 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
1712 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1714 if (!strWarning.empty())
1716 strMiscWarning = strWarning;
1717 CAlert::Notify(strWarning, true);
1718 lastAlertTime = now;
1722 static int64_t nTimeCheck = 0;
1723 static int64_t nTimeForks = 0;
1724 static int64_t nTimeVerify = 0;
1725 static int64_t nTimeConnect = 0;
1726 static int64_t nTimeIndex = 0;
1727 static int64_t nTimeCallbacks = 0;
1728 static int64_t nTimeTotal = 0;
1730 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1732 const CChainParams& chainparams = Params();
1733 AssertLockHeld(cs_main);
1735 int64_t nTimeStart = GetTimeMicros();
1737 // Check it again in case a previous version let a bad block in
1738 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1739 return false;
1741 // verify that the view's current state corresponds to the previous block
1742 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1743 assert(hashPrevBlock == view.GetBestBlock());
1745 // Special case for the genesis block, skipping connection of its transactions
1746 // (its coinbase is unspendable)
1747 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1748 if (!fJustCheck)
1749 view.SetBestBlock(pindex->GetBlockHash());
1750 return true;
1753 bool fScriptChecks = true;
1754 if (fCheckpointsEnabled) {
1755 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
1756 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
1757 // This block is an ancestor of a checkpoint: disable script checks
1758 fScriptChecks = false;
1762 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
1763 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
1765 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1766 // unless those are already completely spent.
1767 // If such overwrites are allowed, coinbases and transactions depending upon those
1768 // can be duplicated to remove the ability to spend the first instance -- even after
1769 // being sent to another address.
1770 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1771 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1772 // already refuses previously-known transaction ids entirely.
1773 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1774 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1775 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1776 // initial block download.
1777 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1778 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1779 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1781 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
1782 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
1783 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
1784 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
1785 // duplicate transactions descending from the known pairs either.
1786 // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
1787 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
1788 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
1789 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
1791 if (fEnforceBIP30) {
1792 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1793 const CCoins* coins = view.AccessCoins(tx.GetHash());
1794 if (coins && !coins->IsPruned())
1795 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1796 REJECT_INVALID, "bad-txns-BIP30");
1800 // BIP16 didn't become active until Apr 1 2012
1801 int64_t nBIP16SwitchTime = 1333238400;
1802 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1804 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1806 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
1807 // when 75% of the network has upgraded:
1808 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1809 flags |= SCRIPT_VERIFY_DERSIG;
1812 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
1813 // blocks, when 75% of the network has upgraded:
1814 if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1815 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1818 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
1819 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
1821 CBlockUndo blockundo;
1823 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1825 CAmount nFees = 0;
1826 int nInputs = 0;
1827 unsigned int nSigOps = 0;
1828 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1829 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1830 vPos.reserve(block.vtx.size());
1831 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1832 for (unsigned int i = 0; i < block.vtx.size(); i++)
1834 const CTransaction &tx = block.vtx[i];
1836 nInputs += tx.vin.size();
1837 nSigOps += GetLegacySigOpCount(tx);
1838 if (nSigOps > MAX_BLOCK_SIGOPS)
1839 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1840 REJECT_INVALID, "bad-blk-sigops");
1842 if (!tx.IsCoinBase())
1844 if (!view.HaveInputs(tx))
1845 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1846 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1848 if (fStrictPayToScriptHash)
1850 // Add in sigops done by pay-to-script-hash inputs;
1851 // this is to prevent a "rogue miner" from creating
1852 // an incredibly-expensive-to-validate block.
1853 nSigOps += GetP2SHSigOpCount(tx, view);
1854 if (nSigOps > MAX_BLOCK_SIGOPS)
1855 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1856 REJECT_INVALID, "bad-blk-sigops");
1859 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1861 std::vector<CScriptCheck> vChecks;
1862 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
1863 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
1864 return error("ConnectBlock(): CheckInputs on %s failed with %s",
1865 tx.GetHash().ToString(), FormatStateMessage(state));
1866 control.Add(vChecks);
1869 CTxUndo undoDummy;
1870 if (i > 0) {
1871 blockundo.vtxundo.push_back(CTxUndo());
1873 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1875 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1876 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1878 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
1879 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime3 - nTime2), 0.001 * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * 0.000001);
1881 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1882 if (block.vtx[0].GetValueOut() > blockReward)
1883 return state.DoS(100,
1884 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1885 block.vtx[0].GetValueOut(), blockReward),
1886 REJECT_INVALID, "bad-cb-amount");
1888 if (!control.Wait())
1889 return state.DoS(100, false);
1890 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
1891 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime4 - nTime2), nInputs <= 1 ? 0 : 0.001 * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * 0.000001);
1893 if (fJustCheck)
1894 return true;
1896 // Write undo information to disk
1897 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1899 if (pindex->GetUndoPos().IsNull()) {
1900 CDiskBlockPos pos;
1901 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1902 return error("ConnectBlock(): FindUndoPos failed");
1903 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1904 return AbortNode(state, "Failed to write undo data");
1906 // update nUndoPos in block index
1907 pindex->nUndoPos = pos.nPos;
1908 pindex->nStatus |= BLOCK_HAVE_UNDO;
1911 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1912 setDirtyBlockIndex.insert(pindex);
1915 if (fTxIndex)
1916 if (!pblocktree->WriteTxIndex(vPos))
1917 return AbortNode(state, "Failed to write transaction index");
1919 // add this block to the view's block chain
1920 view.SetBestBlock(pindex->GetBlockHash());
1922 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
1923 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
1925 // Watch for changes to the previous coinbase transaction.
1926 static uint256 hashPrevBestCoinBase;
1927 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1928 hashPrevBestCoinBase = block.vtx[0].GetHash();
1930 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
1931 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
1933 return true;
1936 enum FlushStateMode {
1937 FLUSH_STATE_NONE,
1938 FLUSH_STATE_IF_NEEDED,
1939 FLUSH_STATE_PERIODIC,
1940 FLUSH_STATE_ALWAYS
1944 * Update the on-disk chain state.
1945 * The caches and indexes are flushed depending on the mode we're called with
1946 * if they're too large, if it's been a while since the last write,
1947 * or always and in all cases if we're in prune mode and are deleting files.
1949 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1950 LOCK2(cs_main, cs_LastBlockFile);
1951 static int64_t nLastWrite = 0;
1952 static int64_t nLastFlush = 0;
1953 static int64_t nLastSetChain = 0;
1954 std::set<int> setFilesToPrune;
1955 bool fFlushForPrune = false;
1956 try {
1957 if (fPruneMode && fCheckForPruning && !fReindex) {
1958 FindFilesToPrune(setFilesToPrune);
1959 fCheckForPruning = false;
1960 if (!setFilesToPrune.empty()) {
1961 fFlushForPrune = true;
1962 if (!fHavePruned) {
1963 pblocktree->WriteFlag("prunedblockfiles", true);
1964 fHavePruned = true;
1968 int64_t nNow = GetTimeMicros();
1969 // Avoid writing/flushing immediately after startup.
1970 if (nLastWrite == 0) {
1971 nLastWrite = nNow;
1973 if (nLastFlush == 0) {
1974 nLastFlush = nNow;
1976 if (nLastSetChain == 0) {
1977 nLastSetChain = nNow;
1979 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1980 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1981 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
1982 // The cache is over the limit, we have to write now.
1983 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
1984 // 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.
1985 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
1986 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
1987 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
1988 // Combine all conditions that result in a full cache flush.
1989 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
1990 // Write blocks and block index to disk.
1991 if (fDoFullFlush || fPeriodicWrite) {
1992 // Depend on nMinDiskSpace to ensure we can write block index
1993 if (!CheckDiskSpace(0))
1994 return state.Error("out of disk space");
1995 // First make sure all block and undo data is flushed to disk.
1996 FlushBlockFile();
1997 // Then update all block file information (which may refer to block and undo files).
1999 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2000 vFiles.reserve(setDirtyFileInfo.size());
2001 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2002 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2003 setDirtyFileInfo.erase(it++);
2005 std::vector<const CBlockIndex*> vBlocks;
2006 vBlocks.reserve(setDirtyBlockIndex.size());
2007 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2008 vBlocks.push_back(*it);
2009 setDirtyBlockIndex.erase(it++);
2011 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2012 return AbortNode(state, "Files to write to block index database");
2015 // Finally remove any pruned files
2016 if (fFlushForPrune)
2017 UnlinkPrunedFiles(setFilesToPrune);
2018 nLastWrite = nNow;
2020 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2021 if (fDoFullFlush) {
2022 // Typical CCoins structures on disk are around 128 bytes in size.
2023 // Pushing a new one to the database can cause it to be written
2024 // twice (once in the log, and once in the tables). This is already
2025 // an overestimation, as most will delete an existing entry or
2026 // overwrite one. Still, use a conservative safety factor of 2.
2027 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2028 return state.Error("out of disk space");
2029 // Flush the chainstate (which may refer to block index entries).
2030 if (!pcoinsTip->Flush())
2031 return AbortNode(state, "Failed to write to coin database");
2032 nLastFlush = nNow;
2034 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2035 // Update best block in wallet (so we can detect restored wallets).
2036 GetMainSignals().SetBestChain(chainActive.GetLocator());
2037 nLastSetChain = nNow;
2039 } catch (const std::runtime_error& e) {
2040 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2042 return true;
2045 void FlushStateToDisk() {
2046 CValidationState state;
2047 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2050 void PruneAndFlush() {
2051 CValidationState state;
2052 fCheckForPruning = true;
2053 FlushStateToDisk(state, FLUSH_STATE_NONE);
2056 /** Update chainActive and related internal data structures. */
2057 void static UpdateTip(CBlockIndex *pindexNew) {
2058 const CChainParams& chainParams = Params();
2059 chainActive.SetTip(pindexNew);
2061 // New best block
2062 nTimeBestReceived = GetTime();
2063 mempool.AddTransactionsUpdated(1);
2065 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2066 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2067 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2068 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2070 cvBlockChange.notify_all();
2072 // Check the version of the last 100 blocks to see if we need to upgrade:
2073 static bool fWarned = false;
2074 if (!IsInitialBlockDownload() && !fWarned)
2076 int nUpgraded = 0;
2077 const CBlockIndex* pindex = chainActive.Tip();
2078 for (int i = 0; i < 100 && pindex != NULL; i++)
2080 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2081 ++nUpgraded;
2082 pindex = pindex->pprev;
2084 if (nUpgraded > 0)
2085 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2086 if (nUpgraded > 100/2)
2088 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2089 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2090 CAlert::Notify(strMiscWarning, true);
2091 fWarned = true;
2096 /** Disconnect chainActive's tip. You want to manually re-limit mempool size after this */
2097 bool static DisconnectTip(CValidationState& state, const Consensus::Params& consensusParams)
2099 CBlockIndex *pindexDelete = chainActive.Tip();
2100 assert(pindexDelete);
2101 mempool.check(pcoinsTip);
2102 // Read block from disk.
2103 CBlock block;
2104 if (!ReadBlockFromDisk(block, pindexDelete, consensusParams))
2105 return AbortNode(state, "Failed to read block");
2106 // Apply the block atomically to the chain state.
2107 int64_t nStart = GetTimeMicros();
2109 CCoinsViewCache view(pcoinsTip);
2110 if (!DisconnectBlock(block, state, pindexDelete, view))
2111 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2112 assert(view.Flush());
2114 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2115 // Write the chain state to disk, if necessary.
2116 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2117 return false;
2118 // Resurrect mempool transactions from the disconnected block.
2119 std::vector<uint256> vHashUpdate;
2120 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2121 // ignore validation errors in resurrected transactions
2122 list<CTransaction> removed;
2123 CValidationState stateDummy;
2124 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) {
2125 mempool.remove(tx, removed, true);
2126 } else if (mempool.exists(tx.GetHash())) {
2127 vHashUpdate.push_back(tx.GetHash());
2130 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2131 // no in-mempool children, which is generally not true when adding
2132 // previously-confirmed transactions back to the mempool.
2133 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2134 // block that were added back and cleans up the mempool state.
2135 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2136 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2137 mempool.check(pcoinsTip);
2138 // Update chainActive and related variables.
2139 UpdateTip(pindexDelete->pprev);
2140 // Let wallets know transactions went from 1-confirmed to
2141 // 0-confirmed or conflicted:
2142 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2143 SyncWithWallets(tx, NULL);
2145 return true;
2148 static int64_t nTimeReadFromDisk = 0;
2149 static int64_t nTimeConnectTotal = 0;
2150 static int64_t nTimeFlush = 0;
2151 static int64_t nTimeChainState = 0;
2152 static int64_t nTimePostConnect = 0;
2155 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2156 * corresponding to pindexNew, to bypass loading it again from disk.
2158 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, const CBlock *pblock) {
2159 const CChainParams& chainparams = Params();
2160 assert(pindexNew->pprev == chainActive.Tip());
2161 mempool.check(pcoinsTip);
2162 // Read block from disk.
2163 int64_t nTime1 = GetTimeMicros();
2164 CBlock block;
2165 if (!pblock) {
2166 if (!ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus()))
2167 return AbortNode(state, "Failed to read block");
2168 pblock = &block;
2170 // Apply the block atomically to the chain state.
2171 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2172 int64_t nTime3;
2173 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2175 CCoinsViewCache view(pcoinsTip);
2176 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2177 GetMainSignals().BlockChecked(*pblock, state);
2178 if (!rv) {
2179 if (state.IsInvalid())
2180 InvalidBlockFound(pindexNew, state);
2181 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2183 mapBlockSource.erase(pindexNew->GetBlockHash());
2184 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2185 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2186 assert(view.Flush());
2188 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2189 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2190 // Write the chain state to disk, if necessary.
2191 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2192 return false;
2193 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2194 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2195 // Remove conflicting transactions from the mempool.
2196 list<CTransaction> txConflicted;
2197 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2198 mempool.check(pcoinsTip);
2199 // Update chainActive & related variables.
2200 UpdateTip(pindexNew);
2201 // Tell wallet about transactions that went from mempool
2202 // to conflicted:
2203 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2204 SyncWithWallets(tx, NULL);
2206 // ... and about transactions that got confirmed:
2207 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2208 SyncWithWallets(tx, pblock);
2211 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2212 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2213 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2214 return true;
2218 * Return the tip of the chain with the most work in it, that isn't
2219 * known to be invalid (it's however far from certain to be valid).
2221 static CBlockIndex* FindMostWorkChain() {
2222 do {
2223 CBlockIndex *pindexNew = NULL;
2225 // Find the best candidate header.
2227 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2228 if (it == setBlockIndexCandidates.rend())
2229 return NULL;
2230 pindexNew = *it;
2233 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2234 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2235 CBlockIndex *pindexTest = pindexNew;
2236 bool fInvalidAncestor = false;
2237 while (pindexTest && !chainActive.Contains(pindexTest)) {
2238 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2240 // Pruned nodes may have entries in setBlockIndexCandidates for
2241 // which block files have been deleted. Remove those as candidates
2242 // for the most work chain if we come across them; we can't switch
2243 // to a chain unless we have all the non-active-chain parent blocks.
2244 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2245 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2246 if (fFailedChain || fMissingData) {
2247 // Candidate chain is not usable (either invalid or missing data)
2248 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2249 pindexBestInvalid = pindexNew;
2250 CBlockIndex *pindexFailed = pindexNew;
2251 // Remove the entire chain from the set.
2252 while (pindexTest != pindexFailed) {
2253 if (fFailedChain) {
2254 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2255 } else if (fMissingData) {
2256 // If we're missing data, then add back to mapBlocksUnlinked,
2257 // so that if the block arrives in the future we can try adding
2258 // to setBlockIndexCandidates again.
2259 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2261 setBlockIndexCandidates.erase(pindexFailed);
2262 pindexFailed = pindexFailed->pprev;
2264 setBlockIndexCandidates.erase(pindexTest);
2265 fInvalidAncestor = true;
2266 break;
2268 pindexTest = pindexTest->pprev;
2270 if (!fInvalidAncestor)
2271 return pindexNew;
2272 } while(true);
2275 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2276 static void PruneBlockIndexCandidates() {
2277 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2278 // reorganization to a better block fails.
2279 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2280 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2281 setBlockIndexCandidates.erase(it++);
2283 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2284 assert(!setBlockIndexCandidates.empty());
2288 * Try to make some progress towards making pindexMostWork the active block.
2289 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2291 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, const CBlock *pblock) {
2292 const CChainParams& chainparams = Params();
2293 AssertLockHeld(cs_main);
2294 bool fInvalidFound = false;
2295 const CBlockIndex *pindexOldTip = chainActive.Tip();
2296 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2298 // Disconnect active blocks which are no longer in the best chain.
2299 bool fBlocksDisconnected = false;
2300 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2301 if (!DisconnectTip(state, chainparams.GetConsensus()))
2302 return false;
2303 fBlocksDisconnected = true;
2306 // Build list of new blocks to connect.
2307 std::vector<CBlockIndex*> vpindexToConnect;
2308 bool fContinue = true;
2309 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2310 while (fContinue && nHeight != pindexMostWork->nHeight) {
2311 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2312 // a few blocks along the way.
2313 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2314 vpindexToConnect.clear();
2315 vpindexToConnect.reserve(nTargetHeight - nHeight);
2316 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2317 while (pindexIter && pindexIter->nHeight != nHeight) {
2318 vpindexToConnect.push_back(pindexIter);
2319 pindexIter = pindexIter->pprev;
2321 nHeight = nTargetHeight;
2323 // Connect new blocks.
2324 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2325 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2326 if (state.IsInvalid()) {
2327 // The block violates a consensus rule.
2328 if (!state.CorruptionPossible())
2329 InvalidChainFound(vpindexToConnect.back());
2330 state = CValidationState();
2331 fInvalidFound = true;
2332 fContinue = false;
2333 break;
2334 } else {
2335 // A system error occurred (disk space, database error, ...).
2336 return false;
2338 } else {
2339 PruneBlockIndexCandidates();
2340 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2341 // We're in a better position than we were. Return temporarily to release the lock.
2342 fContinue = false;
2343 break;
2349 if (fBlocksDisconnected)
2350 mempool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2352 // Callbacks/notifications for a new best chain.
2353 if (fInvalidFound)
2354 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2355 else
2356 CheckForkWarningConditions();
2358 return true;
2362 * Make the best chain active, in multiple steps. The result is either failure
2363 * or an activated best chain. pblock is either NULL or a pointer to a block
2364 * that is already loaded (to avoid loading it again from disk).
2366 bool ActivateBestChain(CValidationState &state, const CBlock *pblock) {
2367 CBlockIndex *pindexNewTip = NULL;
2368 CBlockIndex *pindexMostWork = NULL;
2369 const CChainParams& chainparams = Params();
2370 do {
2371 boost::this_thread::interruption_point();
2373 bool fInitialDownload;
2375 LOCK(cs_main);
2376 pindexMostWork = FindMostWorkChain();
2378 // Whether we have anything to do at all.
2379 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2380 return true;
2382 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2383 return false;
2385 pindexNewTip = chainActive.Tip();
2386 fInitialDownload = IsInitialBlockDownload();
2388 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2390 // Notifications/callbacks that can run without cs_main
2391 if (!fInitialDownload) {
2392 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2393 // Relay inventory, but don't relay old inventory during initial block download.
2394 int nBlockEstimate = 0;
2395 if (fCheckpointsEnabled)
2396 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints());
2398 LOCK(cs_vNodes);
2399 BOOST_FOREACH(CNode* pnode, vNodes)
2400 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2401 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2403 // Notify external listeners about the new tip.
2404 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2405 uiInterface.NotifyBlockTip(hashNewTip);
2407 } while(pindexMostWork != chainActive.Tip());
2408 CheckBlockIndex(chainparams.GetConsensus());
2410 // Write changes periodically to disk, after relay.
2411 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2412 return false;
2415 return true;
2418 bool InvalidateBlock(CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex *pindex)
2420 AssertLockHeld(cs_main);
2422 // Mark the block itself as invalid.
2423 pindex->nStatus |= BLOCK_FAILED_VALID;
2424 setDirtyBlockIndex.insert(pindex);
2425 setBlockIndexCandidates.erase(pindex);
2427 while (chainActive.Contains(pindex)) {
2428 CBlockIndex *pindexWalk = chainActive.Tip();
2429 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2430 setDirtyBlockIndex.insert(pindexWalk);
2431 setBlockIndexCandidates.erase(pindexWalk);
2432 // ActivateBestChain considers blocks already in chainActive
2433 // unconditionally valid already, so force disconnect away from it.
2434 if (!DisconnectTip(state, consensusParams)) {
2435 return false;
2439 mempool.TrimToSize(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000);
2441 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2442 // add it again.
2443 BlockMap::iterator it = mapBlockIndex.begin();
2444 while (it != mapBlockIndex.end()) {
2445 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2446 setBlockIndexCandidates.insert(it->second);
2448 it++;
2451 InvalidChainFound(pindex);
2452 return true;
2455 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2456 AssertLockHeld(cs_main);
2458 int nHeight = pindex->nHeight;
2460 // Remove the invalidity flag from this block and all its descendants.
2461 BlockMap::iterator it = mapBlockIndex.begin();
2462 while (it != mapBlockIndex.end()) {
2463 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2464 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2465 setDirtyBlockIndex.insert(it->second);
2466 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2467 setBlockIndexCandidates.insert(it->second);
2469 if (it->second == pindexBestInvalid) {
2470 // Reset invalid block marker if it was pointing to one of those.
2471 pindexBestInvalid = NULL;
2474 it++;
2477 // Remove the invalidity flag from all ancestors too.
2478 while (pindex != NULL) {
2479 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2480 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2481 setDirtyBlockIndex.insert(pindex);
2483 pindex = pindex->pprev;
2485 return true;
2488 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2490 // Check for duplicate
2491 uint256 hash = block.GetHash();
2492 BlockMap::iterator it = mapBlockIndex.find(hash);
2493 if (it != mapBlockIndex.end())
2494 return it->second;
2496 // Construct new block index object
2497 CBlockIndex* pindexNew = new CBlockIndex(block);
2498 assert(pindexNew);
2499 // We assign the sequence id to blocks only when the full data is available,
2500 // to avoid miners withholding blocks but broadcasting headers, to get a
2501 // competitive advantage.
2502 pindexNew->nSequenceId = 0;
2503 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2504 pindexNew->phashBlock = &((*mi).first);
2505 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2506 if (miPrev != mapBlockIndex.end())
2508 pindexNew->pprev = (*miPrev).second;
2509 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2510 pindexNew->BuildSkip();
2512 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2513 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2514 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2515 pindexBestHeader = pindexNew;
2517 setDirtyBlockIndex.insert(pindexNew);
2519 return pindexNew;
2522 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2523 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2525 pindexNew->nTx = block.vtx.size();
2526 pindexNew->nChainTx = 0;
2527 pindexNew->nFile = pos.nFile;
2528 pindexNew->nDataPos = pos.nPos;
2529 pindexNew->nUndoPos = 0;
2530 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2531 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2532 setDirtyBlockIndex.insert(pindexNew);
2534 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2535 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2536 deque<CBlockIndex*> queue;
2537 queue.push_back(pindexNew);
2539 // Recursively process any descendant blocks that now may be eligible to be connected.
2540 while (!queue.empty()) {
2541 CBlockIndex *pindex = queue.front();
2542 queue.pop_front();
2543 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2545 LOCK(cs_nBlockSequenceId);
2546 pindex->nSequenceId = nBlockSequenceId++;
2548 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2549 setBlockIndexCandidates.insert(pindex);
2551 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2552 while (range.first != range.second) {
2553 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2554 queue.push_back(it->second);
2555 range.first++;
2556 mapBlocksUnlinked.erase(it);
2559 } else {
2560 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2561 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2565 return true;
2568 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2570 LOCK(cs_LastBlockFile);
2572 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2573 if (vinfoBlockFile.size() <= nFile) {
2574 vinfoBlockFile.resize(nFile + 1);
2577 if (!fKnown) {
2578 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2579 nFile++;
2580 if (vinfoBlockFile.size() <= nFile) {
2581 vinfoBlockFile.resize(nFile + 1);
2584 pos.nFile = nFile;
2585 pos.nPos = vinfoBlockFile[nFile].nSize;
2588 if ((int)nFile != nLastBlockFile) {
2589 if (!fKnown) {
2590 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
2592 FlushBlockFile(!fKnown);
2593 nLastBlockFile = nFile;
2596 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2597 if (fKnown)
2598 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2599 else
2600 vinfoBlockFile[nFile].nSize += nAddSize;
2602 if (!fKnown) {
2603 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2604 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2605 if (nNewChunks > nOldChunks) {
2606 if (fPruneMode)
2607 fCheckForPruning = true;
2608 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2609 FILE *file = OpenBlockFile(pos);
2610 if (file) {
2611 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2612 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2613 fclose(file);
2616 else
2617 return state.Error("out of disk space");
2621 setDirtyFileInfo.insert(nFile);
2622 return true;
2625 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2627 pos.nFile = nFile;
2629 LOCK(cs_LastBlockFile);
2631 unsigned int nNewSize;
2632 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2633 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2634 setDirtyFileInfo.insert(nFile);
2636 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2637 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2638 if (nNewChunks > nOldChunks) {
2639 if (fPruneMode)
2640 fCheckForPruning = true;
2641 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2642 FILE *file = OpenUndoFile(pos);
2643 if (file) {
2644 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2645 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2646 fclose(file);
2649 else
2650 return state.Error("out of disk space");
2653 return true;
2656 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2658 // Check proof of work matches claimed amount
2659 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2660 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2661 REJECT_INVALID, "high-hash");
2663 // Check timestamp
2664 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2665 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2666 REJECT_INVALID, "time-too-new");
2668 return true;
2671 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2673 // These are checks that are independent of context.
2675 if (block.fChecked)
2676 return true;
2678 // Check that the header is valid (particularly PoW). This is mostly
2679 // redundant with the call in AcceptBlockHeader.
2680 if (!CheckBlockHeader(block, state, fCheckPOW))
2681 return false;
2683 // Check the merkle root.
2684 if (fCheckMerkleRoot) {
2685 bool mutated;
2686 uint256 hashMerkleRoot2 = block.ComputeMerkleRoot(&mutated);
2687 if (block.hashMerkleRoot != hashMerkleRoot2)
2688 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2689 REJECT_INVALID, "bad-txnmrklroot", true);
2691 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2692 // of transactions in a block without affecting the merkle root of a block,
2693 // while still invalidating it.
2694 if (mutated)
2695 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2696 REJECT_INVALID, "bad-txns-duplicate", true);
2699 // All potential-corruption validation must be done before we do any
2700 // transaction validation, as otherwise we may mark the header as invalid
2701 // because we receive the wrong transactions for it.
2703 // Size limits
2704 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2705 return state.DoS(100, error("CheckBlock(): size limits failed"),
2706 REJECT_INVALID, "bad-blk-length");
2708 // First transaction must be coinbase, the rest must not be
2709 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2710 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2711 REJECT_INVALID, "bad-cb-missing");
2712 for (unsigned int i = 1; i < block.vtx.size(); i++)
2713 if (block.vtx[i].IsCoinBase())
2714 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2715 REJECT_INVALID, "bad-cb-multiple");
2717 // Check transactions
2718 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2719 if (!CheckTransaction(tx, state))
2720 return error("CheckBlock(): CheckTransaction of %s failed with %s",
2721 tx.GetHash().ToString(),
2722 FormatStateMessage(state));
2724 unsigned int nSigOps = 0;
2725 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2727 nSigOps += GetLegacySigOpCount(tx);
2729 if (nSigOps > MAX_BLOCK_SIGOPS)
2730 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2731 REJECT_INVALID, "bad-blk-sigops", true);
2733 if (fCheckPOW && fCheckMerkleRoot)
2734 block.fChecked = true;
2736 return true;
2739 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
2741 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
2742 return true;
2744 int nHeight = pindexPrev->nHeight+1;
2745 // Don't accept any forks from the main chain prior to last checkpoint
2746 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2747 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2748 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2750 return true;
2753 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2755 const Consensus::Params& consensusParams = Params().GetConsensus();
2756 // Check proof of work
2757 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2758 return state.DoS(100, error("%s: incorrect proof of work", __func__),
2759 REJECT_INVALID, "bad-diffbits");
2761 // Check timestamp against prev
2762 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2763 return state.Invalid(error("%s: block's timestamp is too early", __func__),
2764 REJECT_INVALID, "time-too-old");
2766 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2767 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2768 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2769 REJECT_OBSOLETE, "bad-version");
2771 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2772 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2773 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2774 REJECT_OBSOLETE, "bad-version");
2776 // Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded:
2777 if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2778 return state.Invalid(error("%s : rejected nVersion=3 block", __func__),
2779 REJECT_OBSOLETE, "bad-version");
2781 return true;
2784 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2786 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2787 const Consensus::Params& consensusParams = Params().GetConsensus();
2789 // Check that all transactions are finalized
2790 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2791 int nLockTimeFlags = 0;
2792 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
2793 ? pindexPrev->GetMedianTimePast()
2794 : block.GetBlockTime();
2795 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
2796 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2800 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2801 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2802 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
2804 CScript expect = CScript() << nHeight;
2805 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2806 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2807 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2811 return true;
2814 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex=NULL)
2816 AssertLockHeld(cs_main);
2817 // Check for duplicate
2818 uint256 hash = block.GetHash();
2819 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2820 CBlockIndex *pindex = NULL;
2821 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2823 if (miSelf != mapBlockIndex.end()) {
2824 // Block header is already known.
2825 pindex = miSelf->second;
2826 if (ppindex)
2827 *ppindex = pindex;
2828 if (pindex->nStatus & BLOCK_FAILED_MASK)
2829 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2830 return true;
2833 if (!CheckBlockHeader(block, state))
2834 return false;
2836 // Get prev block index
2837 CBlockIndex* pindexPrev = NULL;
2838 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2839 if (mi == mapBlockIndex.end())
2840 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2841 pindexPrev = (*mi).second;
2842 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2843 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2845 assert(pindexPrev);
2846 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
2847 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2849 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2850 return false;
2852 if (pindex == NULL)
2853 pindex = AddToBlockIndex(block);
2855 if (ppindex)
2856 *ppindex = pindex;
2858 return true;
2861 bool AcceptBlock(const CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
2863 const CChainParams& chainparams = Params();
2864 AssertLockHeld(cs_main);
2866 CBlockIndex *&pindex = *ppindex;
2868 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
2869 return false;
2871 // Try to process all requested blocks that we don't have, but only
2872 // process an unrequested block if it's new and has enough work to
2873 // advance our tip, and isn't too many blocks ahead.
2874 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
2875 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
2876 // Blocks that are too out-of-order needlessly limit the effectiveness of
2877 // pruning, because pruning will not delete block files that contain any
2878 // blocks which are too close in height to the tip. Apply this test
2879 // regardless of whether pruning is enabled; it should generally be safe to
2880 // not process unrequested blocks.
2881 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
2883 // TODO: deal better with return value and error conditions for duplicate
2884 // and unrequested blocks.
2885 if (fAlreadyHave) return true;
2886 if (!fRequested) { // If we didn't ask for it:
2887 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
2888 if (!fHasMoreWork) return true; // Don't process less-work chains
2889 if (fTooFarAhead) return true; // Block height is too high
2892 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2893 if (state.IsInvalid() && !state.CorruptionPossible()) {
2894 pindex->nStatus |= BLOCK_FAILED_VALID;
2895 setDirtyBlockIndex.insert(pindex);
2897 return false;
2900 int nHeight = pindex->nHeight;
2902 // Write block to history file
2903 try {
2904 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2905 CDiskBlockPos blockPos;
2906 if (dbp != NULL)
2907 blockPos = *dbp;
2908 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2909 return error("AcceptBlock(): FindBlockPos failed");
2910 if (dbp == NULL)
2911 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2912 AbortNode(state, "Failed to write block");
2913 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2914 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2915 } catch (const std::runtime_error& e) {
2916 return AbortNode(state, std::string("System error: ") + e.what());
2919 if (fCheckForPruning)
2920 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2922 return true;
2925 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
2927 unsigned int nFound = 0;
2928 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
2930 if (pstart->nVersion >= minVersion)
2931 ++nFound;
2932 pstart = pstart->pprev;
2934 return (nFound >= nRequired);
2938 bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, CDiskBlockPos* dbp)
2940 // Preliminary checks
2941 bool checked = CheckBlock(*pblock, state);
2944 LOCK(cs_main);
2945 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
2946 fRequested |= fForceProcessing;
2947 if (!checked) {
2948 return error("%s: CheckBlock FAILED", __func__);
2951 // Store to disk
2952 CBlockIndex *pindex = NULL;
2953 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
2954 if (pindex && pfrom) {
2955 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2957 CheckBlockIndex(chainparams.GetConsensus());
2958 if (!ret)
2959 return error("%s: AcceptBlock FAILED", __func__);
2962 if (!ActivateBestChain(state, pblock))
2963 return error("%s: ActivateBestChain failed", __func__);
2965 return true;
2968 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2970 AssertLockHeld(cs_main);
2971 assert(pindexPrev && pindexPrev == chainActive.Tip());
2972 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
2973 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
2975 CCoinsViewCache viewNew(pcoinsTip);
2976 CBlockIndex indexDummy(block);
2977 indexDummy.pprev = pindexPrev;
2978 indexDummy.nHeight = pindexPrev->nHeight + 1;
2980 // NOTE: CheckBlockHeader is called by CheckBlock
2981 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2982 return false;
2983 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2984 return false;
2985 if (!ContextualCheckBlock(block, state, pindexPrev))
2986 return false;
2987 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2988 return false;
2989 assert(state.IsValid());
2991 return true;
2995 * BLOCK PRUNING CODE
2998 /* Calculate the amount of disk space the block & undo files currently use */
2999 uint64_t CalculateCurrentUsage()
3001 uint64_t retval = 0;
3002 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3003 retval += file.nSize + file.nUndoSize;
3005 return retval;
3008 /* Prune a block file (modify associated database entries)*/
3009 void PruneOneBlockFile(const int fileNumber)
3011 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3012 CBlockIndex* pindex = it->second;
3013 if (pindex->nFile == fileNumber) {
3014 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3015 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3016 pindex->nFile = 0;
3017 pindex->nDataPos = 0;
3018 pindex->nUndoPos = 0;
3019 setDirtyBlockIndex.insert(pindex);
3021 // Prune from mapBlocksUnlinked -- any block we prune would have
3022 // to be downloaded again in order to consider its chain, at which
3023 // point it would be considered as a candidate for
3024 // mapBlocksUnlinked or setBlockIndexCandidates.
3025 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3026 while (range.first != range.second) {
3027 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3028 range.first++;
3029 if (it->second == pindex) {
3030 mapBlocksUnlinked.erase(it);
3036 vinfoBlockFile[fileNumber].SetNull();
3037 setDirtyFileInfo.insert(fileNumber);
3041 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3043 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3044 CDiskBlockPos pos(*it, 0);
3045 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3046 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3047 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3051 /* Calculate the block/rev files that should be deleted to remain under target*/
3052 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3054 LOCK2(cs_main, cs_LastBlockFile);
3055 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3056 return;
3058 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3059 return;
3062 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3063 uint64_t nCurrentUsage = CalculateCurrentUsage();
3064 // We don't check to prune until after we've allocated new space for files
3065 // So we should leave a buffer under our target to account for another allocation
3066 // before the next pruning.
3067 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3068 uint64_t nBytesToPrune;
3069 int count=0;
3071 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3072 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3073 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3075 if (vinfoBlockFile[fileNumber].nSize == 0)
3076 continue;
3078 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3079 break;
3081 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3082 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3083 continue;
3085 PruneOneBlockFile(fileNumber);
3086 // Queue up the files for removal
3087 setFilesToPrune.insert(fileNumber);
3088 nCurrentUsage -= nBytesToPrune;
3089 count++;
3093 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3094 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3095 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3096 nLastBlockWeCanPrune, count);
3099 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3101 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3103 // Check for nMinDiskSpace bytes (currently 50MB)
3104 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3105 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3107 return true;
3110 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3112 if (pos.IsNull())
3113 return NULL;
3114 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3115 boost::filesystem::create_directories(path.parent_path());
3116 FILE* file = fopen(path.string().c_str(), "rb+");
3117 if (!file && !fReadOnly)
3118 file = fopen(path.string().c_str(), "wb+");
3119 if (!file) {
3120 LogPrintf("Unable to open file %s\n", path.string());
3121 return NULL;
3123 if (pos.nPos) {
3124 if (fseek(file, pos.nPos, SEEK_SET)) {
3125 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3126 fclose(file);
3127 return NULL;
3130 return file;
3133 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3134 return OpenDiskFile(pos, "blk", fReadOnly);
3137 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3138 return OpenDiskFile(pos, "rev", fReadOnly);
3141 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3143 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3146 CBlockIndex * InsertBlockIndex(uint256 hash)
3148 if (hash.IsNull())
3149 return NULL;
3151 // Return existing
3152 BlockMap::iterator mi = mapBlockIndex.find(hash);
3153 if (mi != mapBlockIndex.end())
3154 return (*mi).second;
3156 // Create new
3157 CBlockIndex* pindexNew = new CBlockIndex();
3158 if (!pindexNew)
3159 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3160 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3161 pindexNew->phashBlock = &((*mi).first);
3163 return pindexNew;
3166 bool static LoadBlockIndexDB()
3168 const CChainParams& chainparams = Params();
3169 if (!pblocktree->LoadBlockIndexGuts())
3170 return false;
3172 boost::this_thread::interruption_point();
3174 // Calculate nChainWork
3175 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3176 vSortedByHeight.reserve(mapBlockIndex.size());
3177 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3179 CBlockIndex* pindex = item.second;
3180 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3182 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3183 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3185 CBlockIndex* pindex = item.second;
3186 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3187 // We can link the chain of blocks for which we've received transactions at some point.
3188 // Pruned nodes may have deleted the block.
3189 if (pindex->nTx > 0) {
3190 if (pindex->pprev) {
3191 if (pindex->pprev->nChainTx) {
3192 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3193 } else {
3194 pindex->nChainTx = 0;
3195 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3197 } else {
3198 pindex->nChainTx = pindex->nTx;
3201 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3202 setBlockIndexCandidates.insert(pindex);
3203 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3204 pindexBestInvalid = pindex;
3205 if (pindex->pprev)
3206 pindex->BuildSkip();
3207 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3208 pindexBestHeader = pindex;
3211 // Load block file info
3212 pblocktree->ReadLastBlockFile(nLastBlockFile);
3213 vinfoBlockFile.resize(nLastBlockFile + 1);
3214 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3215 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3216 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3218 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3219 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3220 CBlockFileInfo info;
3221 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3222 vinfoBlockFile.push_back(info);
3223 } else {
3224 break;
3228 // Check presence of blk files
3229 LogPrintf("Checking all blk files are present...\n");
3230 set<int> setBlkDataFiles;
3231 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3233 CBlockIndex* pindex = item.second;
3234 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3235 setBlkDataFiles.insert(pindex->nFile);
3238 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3240 CDiskBlockPos pos(*it, 0);
3241 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3242 return false;
3246 // Check whether we have ever pruned block & undo files
3247 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3248 if (fHavePruned)
3249 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3251 // Check whether we need to continue reindexing
3252 bool fReindexing = false;
3253 pblocktree->ReadReindexing(fReindexing);
3254 fReindex |= fReindexing;
3256 // Check whether we have a transaction index
3257 pblocktree->ReadFlag("txindex", fTxIndex);
3258 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3260 // Load pointer to end of best chain
3261 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3262 if (it == mapBlockIndex.end())
3263 return true;
3264 chainActive.SetTip(it->second);
3266 PruneBlockIndexCandidates();
3268 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3269 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3270 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3271 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3273 return true;
3276 CVerifyDB::CVerifyDB()
3278 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3281 CVerifyDB::~CVerifyDB()
3283 uiInterface.ShowProgress("", 100);
3286 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3288 const CChainParams& chainparams = Params();
3289 LOCK(cs_main);
3290 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3291 return true;
3293 // Verify blocks in the best chain
3294 if (nCheckDepth <= 0)
3295 nCheckDepth = 1000000000; // suffices until the year 19000
3296 if (nCheckDepth > chainActive.Height())
3297 nCheckDepth = chainActive.Height();
3298 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3299 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3300 CCoinsViewCache coins(coinsview);
3301 CBlockIndex* pindexState = chainActive.Tip();
3302 CBlockIndex* pindexFailure = NULL;
3303 int nGoodTransactions = 0;
3304 CValidationState state;
3305 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3307 boost::this_thread::interruption_point();
3308 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3309 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3310 break;
3311 CBlock block;
3312 // check level 0: read from disk
3313 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3314 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3315 // check level 1: verify block validity
3316 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3317 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3318 // check level 2: verify undo validity
3319 if (nCheckLevel >= 2 && pindex) {
3320 CBlockUndo undo;
3321 CDiskBlockPos pos = pindex->GetUndoPos();
3322 if (!pos.IsNull()) {
3323 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3324 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3327 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3328 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3329 bool fClean = true;
3330 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3331 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3332 pindexState = pindex->pprev;
3333 if (!fClean) {
3334 nGoodTransactions = 0;
3335 pindexFailure = pindex;
3336 } else
3337 nGoodTransactions += block.vtx.size();
3339 if (ShutdownRequested())
3340 return true;
3342 if (pindexFailure)
3343 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3345 // check level 4: try reconnecting blocks
3346 if (nCheckLevel >= 4) {
3347 CBlockIndex *pindex = pindexState;
3348 while (pindex != chainActive.Tip()) {
3349 boost::this_thread::interruption_point();
3350 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3351 pindex = chainActive.Next(pindex);
3352 CBlock block;
3353 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3354 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3355 if (!ConnectBlock(block, state, pindex, coins))
3356 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3360 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3362 return true;
3365 void UnloadBlockIndex()
3367 LOCK(cs_main);
3368 setBlockIndexCandidates.clear();
3369 chainActive.SetTip(NULL);
3370 pindexBestInvalid = NULL;
3371 pindexBestHeader = NULL;
3372 mempool.clear();
3373 mapOrphanTransactions.clear();
3374 mapOrphanTransactionsByPrev.clear();
3375 nSyncStarted = 0;
3376 mapBlocksUnlinked.clear();
3377 vinfoBlockFile.clear();
3378 nLastBlockFile = 0;
3379 nBlockSequenceId = 1;
3380 mapBlockSource.clear();
3381 mapBlocksInFlight.clear();
3382 nQueuedValidatedHeaders = 0;
3383 nPreferredDownload = 0;
3384 setDirtyBlockIndex.clear();
3385 setDirtyFileInfo.clear();
3386 mapNodeState.clear();
3387 recentRejects.reset(NULL);
3389 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3390 delete entry.second;
3392 mapBlockIndex.clear();
3393 fHavePruned = false;
3396 bool LoadBlockIndex()
3398 // Load block index from databases
3399 if (!fReindex && !LoadBlockIndexDB())
3400 return false;
3401 return true;
3405 bool InitBlockIndex() {
3406 const CChainParams& chainparams = Params();
3407 LOCK(cs_main);
3409 // Initialize global variables that cannot be constructed at startup.
3410 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3412 // Check whether we're already initialized
3413 if (chainActive.Genesis() != NULL)
3414 return true;
3416 // Use the provided setting for -txindex in the new database
3417 fTxIndex = GetBoolArg("-txindex", false);
3418 pblocktree->WriteFlag("txindex", fTxIndex);
3419 LogPrintf("Initializing databases...\n");
3421 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3422 if (!fReindex) {
3423 try {
3424 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3425 // Start new block file
3426 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3427 CDiskBlockPos blockPos;
3428 CValidationState state;
3429 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3430 return error("LoadBlockIndex(): FindBlockPos failed");
3431 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3432 return error("LoadBlockIndex(): writing genesis block to disk failed");
3433 CBlockIndex *pindex = AddToBlockIndex(block);
3434 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3435 return error("LoadBlockIndex(): genesis block not accepted");
3436 if (!ActivateBestChain(state, &block))
3437 return error("LoadBlockIndex(): genesis block cannot be activated");
3438 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3439 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3440 } catch (const std::runtime_error& e) {
3441 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3445 return true;
3450 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3452 const CChainParams& chainparams = Params();
3453 // Map of disk positions for blocks with unknown parent (only used for reindex)
3454 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3455 int64_t nStart = GetTimeMillis();
3457 int nLoaded = 0;
3458 try {
3459 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3460 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3461 uint64_t nRewind = blkdat.GetPos();
3462 while (!blkdat.eof()) {
3463 boost::this_thread::interruption_point();
3465 blkdat.SetPos(nRewind);
3466 nRewind++; // start one byte further next time, in case of failure
3467 blkdat.SetLimit(); // remove former limit
3468 unsigned int nSize = 0;
3469 try {
3470 // locate a header
3471 unsigned char buf[MESSAGE_START_SIZE];
3472 blkdat.FindByte(Params().MessageStart()[0]);
3473 nRewind = blkdat.GetPos()+1;
3474 blkdat >> FLATDATA(buf);
3475 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3476 continue;
3477 // read size
3478 blkdat >> nSize;
3479 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3480 continue;
3481 } catch (const std::exception&) {
3482 // no valid block header found; don't complain
3483 break;
3485 try {
3486 // read block
3487 uint64_t nBlockPos = blkdat.GetPos();
3488 if (dbp)
3489 dbp->nPos = nBlockPos;
3490 blkdat.SetLimit(nBlockPos + nSize);
3491 blkdat.SetPos(nBlockPos);
3492 CBlock block;
3493 blkdat >> block;
3494 nRewind = blkdat.GetPos();
3496 // detect out of order blocks, and store them for later
3497 uint256 hash = block.GetHash();
3498 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3499 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3500 block.hashPrevBlock.ToString());
3501 if (dbp)
3502 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3503 continue;
3506 // process in case the block isn't known yet
3507 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3508 CValidationState state;
3509 if (ProcessNewBlock(state, chainparams, NULL, &block, true, dbp))
3510 nLoaded++;
3511 if (state.IsError())
3512 break;
3513 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3514 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3517 // Recursively process earlier encountered successors of this block
3518 deque<uint256> queue;
3519 queue.push_back(hash);
3520 while (!queue.empty()) {
3521 uint256 head = queue.front();
3522 queue.pop_front();
3523 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3524 while (range.first != range.second) {
3525 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3526 if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()))
3528 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3529 head.ToString());
3530 CValidationState dummy;
3531 if (ProcessNewBlock(dummy, chainparams, NULL, &block, true, &it->second))
3533 nLoaded++;
3534 queue.push_back(block.GetHash());
3537 range.first++;
3538 mapBlocksUnknownParent.erase(it);
3541 } catch (const std::exception& e) {
3542 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3545 } catch (const std::runtime_error& e) {
3546 AbortNode(std::string("System error: ") + e.what());
3548 if (nLoaded > 0)
3549 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3550 return nLoaded > 0;
3553 void static CheckBlockIndex(const Consensus::Params& consensusParams)
3555 if (!fCheckBlockIndex) {
3556 return;
3559 LOCK(cs_main);
3561 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3562 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3563 // iterating the block tree require that chainActive has been initialized.)
3564 if (chainActive.Height() < 0) {
3565 assert(mapBlockIndex.size() <= 1);
3566 return;
3569 // Build forward-pointing map of the entire block tree.
3570 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3571 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3572 forward.insert(std::make_pair(it->second->pprev, it->second));
3575 assert(forward.size() == mapBlockIndex.size());
3577 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3578 CBlockIndex *pindex = rangeGenesis.first->second;
3579 rangeGenesis.first++;
3580 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3582 // Iterate over the entire block tree, using depth-first search.
3583 // Along the way, remember whether there are blocks on the path from genesis
3584 // block being explored which are the first to have certain properties.
3585 size_t nNodes = 0;
3586 int nHeight = 0;
3587 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3588 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3589 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3590 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3591 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3592 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3593 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3594 while (pindex != NULL) {
3595 nNodes++;
3596 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3597 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3598 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3599 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3600 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3601 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3602 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3604 // Begin: actual consistency checks.
3605 if (pindex->pprev == NULL) {
3606 // Genesis block checks.
3607 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3608 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3610 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3611 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3612 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3613 if (!fHavePruned) {
3614 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3615 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3616 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3617 } else {
3618 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3619 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3621 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3622 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3623 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3624 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3625 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3626 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3627 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.
3628 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3629 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3630 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3631 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3632 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3633 if (pindexFirstInvalid == NULL) {
3634 // Checks for not-invalid blocks.
3635 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3637 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3638 if (pindexFirstInvalid == NULL) {
3639 // If this block sorts at least as good as the current tip and
3640 // is valid and we have all data for its parents, it must be in
3641 // setBlockIndexCandidates. chainActive.Tip() must also be there
3642 // even if some data has been pruned.
3643 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3644 assert(setBlockIndexCandidates.count(pindex));
3646 // If some parent is missing, then it could be that this block was in
3647 // setBlockIndexCandidates but had to be removed because of the missing data.
3648 // In this case it must be in mapBlocksUnlinked -- see test below.
3650 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3651 assert(setBlockIndexCandidates.count(pindex) == 0);
3653 // Check whether this block is in mapBlocksUnlinked.
3654 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3655 bool foundInUnlinked = false;
3656 while (rangeUnlinked.first != rangeUnlinked.second) {
3657 assert(rangeUnlinked.first->first == pindex->pprev);
3658 if (rangeUnlinked.first->second == pindex) {
3659 foundInUnlinked = true;
3660 break;
3662 rangeUnlinked.first++;
3664 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3665 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3666 assert(foundInUnlinked);
3668 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3669 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3670 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3671 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3672 assert(fHavePruned); // We must have pruned.
3673 // This block may have entered mapBlocksUnlinked if:
3674 // - it has a descendant that at some point had more work than the
3675 // tip, and
3676 // - we tried switching to that descendant but were missing
3677 // data for some intermediate block between chainActive and the
3678 // tip.
3679 // So if this block is itself better than chainActive.Tip() and it wasn't in
3680 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3681 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3682 if (pindexFirstInvalid == NULL) {
3683 assert(foundInUnlinked);
3687 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3688 // End: actual consistency checks.
3690 // Try descending into the first subnode.
3691 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3692 if (range.first != range.second) {
3693 // A subnode was found.
3694 pindex = range.first->second;
3695 nHeight++;
3696 continue;
3698 // This is a leaf node.
3699 // Move upwards until we reach a node of which we have not yet visited the last child.
3700 while (pindex) {
3701 // We are going to either move to a parent or a sibling of pindex.
3702 // If pindex was the first with a certain property, unset the corresponding variable.
3703 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3704 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3705 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3706 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3707 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3708 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3709 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3710 // Find our parent.
3711 CBlockIndex* pindexPar = pindex->pprev;
3712 // Find which child we just visited.
3713 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3714 while (rangePar.first->second != pindex) {
3715 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3716 rangePar.first++;
3718 // Proceed to the next one.
3719 rangePar.first++;
3720 if (rangePar.first != rangePar.second) {
3721 // Move to the sibling.
3722 pindex = rangePar.first->second;
3723 break;
3724 } else {
3725 // Move up further.
3726 pindex = pindexPar;
3727 nHeight--;
3728 continue;
3733 // Check that we actually traversed the entire map.
3734 assert(nNodes == forward.size());
3737 //////////////////////////////////////////////////////////////////////////////
3739 // CAlert
3742 std::string GetWarnings(const std::string& strFor)
3744 int nPriority = 0;
3745 string strStatusBar;
3746 string strRPC;
3748 if (!CLIENT_VERSION_IS_RELEASE)
3749 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3751 if (GetBoolArg("-testsafemode", false))
3752 strStatusBar = strRPC = "testsafemode enabled";
3754 // Misc warnings like out of disk space and clock is wrong
3755 if (strMiscWarning != "")
3757 nPriority = 1000;
3758 strStatusBar = strMiscWarning;
3761 if (fLargeWorkForkFound)
3763 nPriority = 2000;
3764 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3766 else if (fLargeWorkInvalidChainFound)
3768 nPriority = 2000;
3769 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.");
3772 // Alerts
3774 LOCK(cs_mapAlerts);
3775 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3777 const CAlert& alert = item.second;
3778 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3780 nPriority = alert.nPriority;
3781 strStatusBar = alert.strStatusBar;
3786 if (strFor == "statusbar")
3787 return strStatusBar;
3788 else if (strFor == "rpc")
3789 return strRPC;
3790 assert(!"GetWarnings(): invalid parameter");
3791 return "error";
3801 //////////////////////////////////////////////////////////////////////////////
3803 // Messages
3807 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
3809 switch (inv.type)
3811 case MSG_TX:
3813 assert(recentRejects);
3814 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
3816 // If the chain tip has changed previously rejected transactions
3817 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
3818 // or a double-spend. Reset the rejects filter and give those
3819 // txs a second chance.
3820 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
3821 recentRejects->reset();
3824 return recentRejects->contains(inv.hash) ||
3825 mempool.exists(inv.hash) ||
3826 mapOrphanTransactions.count(inv.hash) ||
3827 pcoinsTip->HaveCoins(inv.hash);
3829 case MSG_BLOCK:
3830 return mapBlockIndex.count(inv.hash);
3832 // Don't know what it is, just say we already got one
3833 return true;
3836 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams)
3838 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3840 vector<CInv> vNotFound;
3842 LOCK(cs_main);
3844 while (it != pfrom->vRecvGetData.end()) {
3845 // Don't bother if send buffer is too full to respond anyway
3846 if (pfrom->nSendSize >= SendBufferSize())
3847 break;
3849 const CInv &inv = *it;
3851 boost::this_thread::interruption_point();
3852 it++;
3854 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3856 bool send = false;
3857 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3858 if (mi != mapBlockIndex.end())
3860 if (chainActive.Contains(mi->second)) {
3861 send = true;
3862 } else {
3863 static const int nOneMonth = 30 * 24 * 60 * 60;
3864 // To prevent fingerprinting attacks, only send blocks outside of the active
3865 // chain if they are valid, and no more than a month older (both in time, and in
3866 // best equivalent proof of work) than the best header chain we know about.
3867 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3868 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
3869 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
3870 if (!send) {
3871 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
3875 // disconnect node in case we have reached the outbound limit for serving historical blocks
3876 // never disconnect whitelisted nodes
3877 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
3878 if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
3880 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
3882 //disconnect node
3883 pfrom->fDisconnect = true;
3884 send = false;
3886 // Pruned nodes may have deleted the block, so check whether
3887 // it's available before trying to send.
3888 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
3890 // Send block from disk
3891 CBlock block;
3892 if (!ReadBlockFromDisk(block, (*mi).second, consensusParams))
3893 assert(!"cannot load block from disk");
3894 if (inv.type == MSG_BLOCK)
3895 pfrom->PushMessage("block", block);
3896 else // MSG_FILTERED_BLOCK)
3898 LOCK(pfrom->cs_filter);
3899 if (pfrom->pfilter)
3901 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3902 pfrom->PushMessage("merkleblock", merkleBlock);
3903 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3904 // This avoids hurting performance by pointlessly requiring a round-trip
3905 // Note that there is currently no way for a node to request any single transactions we didn't send here -
3906 // they must either disconnect and retry or request the full block.
3907 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3908 // however we MUST always provide at least what the remote peer needs
3909 typedef std::pair<unsigned int, uint256> PairType;
3910 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3911 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3912 pfrom->PushMessage("tx", block.vtx[pair.first]);
3914 // else
3915 // no response
3918 // Trigger the peer node to send a getblocks request for the next batch of inventory
3919 if (inv.hash == pfrom->hashContinue)
3921 // Bypass PushInventory, this must send even if redundant,
3922 // and we want it right after the last block so they don't
3923 // wait for other stuff first.
3924 vector<CInv> vInv;
3925 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3926 pfrom->PushMessage("inv", vInv);
3927 pfrom->hashContinue.SetNull();
3931 else if (inv.IsKnownType())
3933 // Send stream from relay memory
3934 bool pushed = false;
3936 LOCK(cs_mapRelay);
3937 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3938 if (mi != mapRelay.end()) {
3939 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3940 pushed = true;
3943 if (!pushed && inv.type == MSG_TX) {
3944 CTransaction tx;
3945 if (mempool.lookup(inv.hash, tx)) {
3946 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3947 ss.reserve(1000);
3948 ss << tx;
3949 pfrom->PushMessage("tx", ss);
3950 pushed = true;
3953 if (!pushed) {
3954 vNotFound.push_back(inv);
3958 // Track requests for our stuff.
3959 GetMainSignals().Inventory(inv.hash);
3961 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3962 break;
3966 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3968 if (!vNotFound.empty()) {
3969 // Let the peer know that we didn't find what it asked for, so it doesn't
3970 // have to wait around forever. Currently only SPV clients actually care
3971 // about this message: it's needed when they are recursively walking the
3972 // dependencies of relevant unconfirmed transactions. SPV clients want to
3973 // do that because they want to know about (and store and rebroadcast and
3974 // risk analyze) the dependencies of transactions relevant to them, without
3975 // having to download the entire memory pool.
3976 pfrom->PushMessage("notfound", vNotFound);
3980 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3982 const CChainParams& chainparams = Params();
3983 RandAddSeedPerfmon();
3984 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3985 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3987 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3988 return true;
3994 if (strCommand == "version")
3996 // Each connection can only send one version message
3997 if (pfrom->nVersion != 0)
3999 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4000 Misbehaving(pfrom->GetId(), 1);
4001 return false;
4004 int64_t nTime;
4005 CAddress addrMe;
4006 CAddress addrFrom;
4007 uint64_t nNonce = 1;
4008 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4009 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4011 // disconnect from peers older than this proto version
4012 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4013 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4014 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4015 pfrom->fDisconnect = true;
4016 return false;
4019 if (pfrom->nVersion == 10300)
4020 pfrom->nVersion = 300;
4021 if (!vRecv.empty())
4022 vRecv >> addrFrom >> nNonce;
4023 if (!vRecv.empty()) {
4024 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
4025 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4027 if (!vRecv.empty())
4028 vRecv >> pfrom->nStartingHeight;
4029 if (!vRecv.empty())
4030 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4031 else
4032 pfrom->fRelayTxes = true;
4034 // Disconnect if we connected to ourself
4035 if (nNonce == nLocalHostNonce && nNonce > 1)
4037 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4038 pfrom->fDisconnect = true;
4039 return true;
4042 pfrom->addrLocal = addrMe;
4043 if (pfrom->fInbound && addrMe.IsRoutable())
4045 SeenLocal(addrMe);
4048 // Be shy and don't send version until we hear
4049 if (pfrom->fInbound)
4050 pfrom->PushVersion();
4052 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4054 // Potentially mark this peer as a preferred download peer.
4055 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4057 // Change version
4058 pfrom->PushMessage("verack");
4059 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4061 if (!pfrom->fInbound)
4063 // Advertise our address
4064 if (fListen && !IsInitialBlockDownload())
4066 CAddress addr = GetLocalAddress(&pfrom->addr);
4067 if (addr.IsRoutable())
4069 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4070 pfrom->PushAddress(addr);
4071 } else if (IsPeerAddrLocalGood(pfrom)) {
4072 addr.SetIP(pfrom->addrLocal);
4073 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4074 pfrom->PushAddress(addr);
4078 // Get recent addresses
4079 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4081 pfrom->PushMessage("getaddr");
4082 pfrom->fGetAddr = true;
4084 addrman.Good(pfrom->addr);
4085 } else {
4086 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4088 addrman.Add(addrFrom, addrFrom);
4089 addrman.Good(addrFrom);
4093 // Relay alerts
4095 LOCK(cs_mapAlerts);
4096 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4097 item.second.RelayTo(pfrom);
4100 pfrom->fSuccessfullyConnected = true;
4102 string remoteAddr;
4103 if (fLogIPs)
4104 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4106 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4107 pfrom->cleanSubVer, pfrom->nVersion,
4108 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4109 remoteAddr);
4111 int64_t nTimeOffset = nTime - GetTime();
4112 pfrom->nTimeOffset = nTimeOffset;
4113 AddTimeData(pfrom->addr, nTimeOffset);
4117 else if (pfrom->nVersion == 0)
4119 // Must have a version message before anything else
4120 Misbehaving(pfrom->GetId(), 1);
4121 return false;
4125 else if (strCommand == "verack")
4127 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4129 // Mark this node as currently connected, so we update its timestamp later.
4130 if (pfrom->fNetworkNode) {
4131 LOCK(cs_main);
4132 State(pfrom->GetId())->fCurrentlyConnected = true;
4137 else if (strCommand == "addr")
4139 vector<CAddress> vAddr;
4140 vRecv >> vAddr;
4142 // Don't want addr from older versions unless seeding
4143 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4144 return true;
4145 if (vAddr.size() > 1000)
4147 Misbehaving(pfrom->GetId(), 20);
4148 return error("message addr size() = %u", vAddr.size());
4151 // Store the new addresses
4152 vector<CAddress> vAddrOk;
4153 int64_t nNow = GetAdjustedTime();
4154 int64_t nSince = nNow - 10 * 60;
4155 BOOST_FOREACH(CAddress& addr, vAddr)
4157 boost::this_thread::interruption_point();
4159 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4160 addr.nTime = nNow - 5 * 24 * 60 * 60;
4161 pfrom->AddAddressKnown(addr);
4162 bool fReachable = IsReachable(addr);
4163 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4165 // Relay to a limited number of other nodes
4167 LOCK(cs_vNodes);
4168 // Use deterministic randomness to send to the same nodes for 24 hours
4169 // at a time so the addrKnowns of the chosen nodes prevent repeats
4170 static uint256 hashSalt;
4171 if (hashSalt.IsNull())
4172 hashSalt = GetRandHash();
4173 uint64_t hashAddr = addr.GetHash();
4174 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4175 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4176 multimap<uint256, CNode*> mapMix;
4177 BOOST_FOREACH(CNode* pnode, vNodes)
4179 if (pnode->nVersion < CADDR_TIME_VERSION)
4180 continue;
4181 unsigned int nPointer;
4182 memcpy(&nPointer, &pnode, sizeof(nPointer));
4183 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4184 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4185 mapMix.insert(make_pair(hashKey, pnode));
4187 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4188 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4189 ((*mi).second)->PushAddress(addr);
4192 // Do not store addresses outside our network
4193 if (fReachable)
4194 vAddrOk.push_back(addr);
4196 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4197 if (vAddr.size() < 1000)
4198 pfrom->fGetAddr = false;
4199 if (pfrom->fOneShot)
4200 pfrom->fDisconnect = true;
4204 else if (strCommand == "inv")
4206 vector<CInv> vInv;
4207 vRecv >> vInv;
4208 if (vInv.size() > MAX_INV_SZ)
4210 Misbehaving(pfrom->GetId(), 20);
4211 return error("message inv size() = %u", vInv.size());
4214 bool fBlocksOnly = GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
4216 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistalwaysrelay is true
4217 if (pfrom->fWhitelisted && GetBoolArg("-whitelistalwaysrelay", DEFAULT_WHITELISTALWAYSRELAY))
4218 fBlocksOnly = false;
4220 LOCK(cs_main);
4222 std::vector<CInv> vToFetch;
4224 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4226 const CInv &inv = vInv[nInv];
4228 boost::this_thread::interruption_point();
4229 pfrom->AddInventoryKnown(inv);
4231 bool fAlreadyHave = AlreadyHave(inv);
4232 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4234 if (inv.type == MSG_BLOCK) {
4235 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4236 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4237 // First request the headers preceding the announced block. In the normal fully-synced
4238 // case where a new block is announced that succeeds the current tip (no reorganization),
4239 // there are no such headers.
4240 // Secondly, and only when we are close to being synced, we request the announced block directly,
4241 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4242 // time the block arrives, the header chain leading up to it is already validated. Not
4243 // doing this will result in the received block being rejected as an orphan in case it is
4244 // not a direct successor.
4245 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4246 CNodeState *nodestate = State(pfrom->GetId());
4247 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4248 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4249 vToFetch.push_back(inv);
4250 // Mark block as in flight already, even though the actual "getdata" message only goes out
4251 // later (within the same cs_main lock, though).
4252 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4254 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4257 else
4259 if (fBlocksOnly)
4260 LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
4261 else if (!fAlreadyHave && !fImporting && !fReindex)
4262 pfrom->AskFor(inv);
4265 // Track requests for our stuff
4266 GetMainSignals().Inventory(inv.hash);
4268 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4269 Misbehaving(pfrom->GetId(), 50);
4270 return error("send buffer size() = %u", pfrom->nSendSize);
4274 if (!vToFetch.empty())
4275 pfrom->PushMessage("getdata", vToFetch);
4279 else if (strCommand == "getdata")
4281 vector<CInv> vInv;
4282 vRecv >> vInv;
4283 if (vInv.size() > MAX_INV_SZ)
4285 Misbehaving(pfrom->GetId(), 20);
4286 return error("message getdata size() = %u", vInv.size());
4289 if (fDebug || (vInv.size() != 1))
4290 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4292 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4293 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4295 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4296 ProcessGetData(pfrom, chainparams.GetConsensus());
4300 else if (strCommand == "getblocks")
4302 CBlockLocator locator;
4303 uint256 hashStop;
4304 vRecv >> locator >> hashStop;
4306 LOCK(cs_main);
4308 // Find the last block the caller has in the main chain
4309 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4311 // Send the rest of the chain
4312 if (pindex)
4313 pindex = chainActive.Next(pindex);
4314 int nLimit = 500;
4315 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4316 for (; pindex; pindex = chainActive.Next(pindex))
4318 if (pindex->GetBlockHash() == hashStop)
4320 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4321 break;
4323 // If pruning, don't inv blocks unless we have on disk and are likely to still have
4324 // for some reasonable time window (1 hour) that block relay might require.
4325 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
4326 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
4328 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4329 break;
4331 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4332 if (--nLimit <= 0)
4334 // When this block is requested, we'll send an inv that'll
4335 // trigger the peer to getblocks the next batch of inventory.
4336 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4337 pfrom->hashContinue = pindex->GetBlockHash();
4338 break;
4344 else if (strCommand == "getheaders")
4346 CBlockLocator locator;
4347 uint256 hashStop;
4348 vRecv >> locator >> hashStop;
4350 LOCK(cs_main);
4351 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
4352 LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
4353 return true;
4355 CBlockIndex* pindex = NULL;
4356 if (locator.IsNull())
4358 // If locator is null, return the hashStop block
4359 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4360 if (mi == mapBlockIndex.end())
4361 return true;
4362 pindex = (*mi).second;
4364 else
4366 // Find the last block the caller has in the main chain
4367 pindex = FindForkInGlobalIndex(chainActive, locator);
4368 if (pindex)
4369 pindex = chainActive.Next(pindex);
4372 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4373 vector<CBlock> vHeaders;
4374 int nLimit = MAX_HEADERS_RESULTS;
4375 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4376 for (; pindex; pindex = chainActive.Next(pindex))
4378 vHeaders.push_back(pindex->GetBlockHeader());
4379 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4380 break;
4382 pfrom->PushMessage("headers", vHeaders);
4386 else if (strCommand == "tx")
4388 // Stop processing the transaction early if
4389 // We are in blocks only mode and peer is either not whitelisted or whitelistalwaysrelay is off
4390 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistalwaysrelay", DEFAULT_WHITELISTALWAYSRELAY)))
4392 LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id);
4393 return true;
4396 vector<uint256> vWorkQueue;
4397 vector<uint256> vEraseQueue;
4398 CTransaction tx;
4399 vRecv >> tx;
4401 CInv inv(MSG_TX, tx.GetHash());
4402 pfrom->AddInventoryKnown(inv);
4404 LOCK(cs_main);
4406 bool fMissingInputs = false;
4407 CValidationState state;
4409 pfrom->setAskFor.erase(inv.hash);
4410 mapAlreadyAskedFor.erase(inv);
4412 // Check for recently rejected (and do other quick existence checks)
4413 if (AlreadyHave(inv))
4414 return true;
4416 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4418 mempool.check(pcoinsTip);
4419 RelayTransaction(tx);
4420 vWorkQueue.push_back(inv.hash);
4422 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
4423 pfrom->id,
4424 tx.GetHash().ToString(),
4425 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
4427 // Recursively process any orphan transactions that depended on this one
4428 set<NodeId> setMisbehaving;
4429 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4431 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4432 if (itByPrev == mapOrphanTransactionsByPrev.end())
4433 continue;
4434 for (set<uint256>::iterator mi = itByPrev->second.begin();
4435 mi != itByPrev->second.end();
4436 ++mi)
4438 const uint256& orphanHash = *mi;
4439 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4440 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4441 bool fMissingInputs2 = false;
4442 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4443 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4444 // anyone relaying LegitTxX banned)
4445 CValidationState stateDummy;
4448 if (setMisbehaving.count(fromPeer))
4449 continue;
4450 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4452 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4453 RelayTransaction(orphanTx);
4454 vWorkQueue.push_back(orphanHash);
4455 vEraseQueue.push_back(orphanHash);
4457 else if (!fMissingInputs2)
4459 int nDos = 0;
4460 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4462 // Punish peer that gave us an invalid orphan tx
4463 Misbehaving(fromPeer, nDos);
4464 setMisbehaving.insert(fromPeer);
4465 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4467 // Has inputs but not accepted to mempool
4468 // Probably non-standard or insufficient fee/priority
4469 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4470 vEraseQueue.push_back(orphanHash);
4471 assert(recentRejects);
4472 recentRejects->insert(orphanHash);
4474 mempool.check(pcoinsTip);
4478 BOOST_FOREACH(uint256 hash, vEraseQueue)
4479 EraseOrphanTx(hash);
4481 else if (fMissingInputs)
4483 AddOrphanTx(tx, pfrom->GetId());
4485 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4486 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4487 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4488 if (nEvicted > 0)
4489 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4490 } else {
4491 assert(recentRejects);
4492 recentRejects->insert(tx.GetHash());
4494 if (pfrom->fWhitelisted && GetBoolArg("-whitelistalwaysrelay", DEFAULT_WHITELISTALWAYSRELAY)) {
4495 // Always relay transactions received from whitelisted peers, even
4496 // if they were rejected from the mempool, allowing the node to
4497 // function as a gateway for nodes hidden behind it.
4499 // FIXME: This includes invalid transactions, which means a
4500 // whitelisted peer could get us banned! We may want to change
4501 // that.
4502 RelayTransaction(tx);
4505 int nDoS = 0;
4506 if (state.IsInvalid(nDoS))
4508 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
4509 pfrom->id,
4510 FormatStateMessage(state));
4511 if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
4512 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4513 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4514 if (nDoS > 0)
4515 Misbehaving(pfrom->GetId(), nDoS);
4520 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4522 std::vector<CBlockHeader> headers;
4524 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4525 unsigned int nCount = ReadCompactSize(vRecv);
4526 if (nCount > MAX_HEADERS_RESULTS) {
4527 Misbehaving(pfrom->GetId(), 20);
4528 return error("headers message size = %u", nCount);
4530 headers.resize(nCount);
4531 for (unsigned int n = 0; n < nCount; n++) {
4532 vRecv >> headers[n];
4533 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4536 LOCK(cs_main);
4538 if (nCount == 0) {
4539 // Nothing interesting. Stop asking this peers for more headers.
4540 return true;
4543 CBlockIndex *pindexLast = NULL;
4544 BOOST_FOREACH(const CBlockHeader& header, headers) {
4545 CValidationState state;
4546 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4547 Misbehaving(pfrom->GetId(), 20);
4548 return error("non-continuous headers sequence");
4550 if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) {
4551 int nDoS;
4552 if (state.IsInvalid(nDoS)) {
4553 if (nDoS > 0)
4554 Misbehaving(pfrom->GetId(), nDoS);
4555 return error("invalid header received");
4560 if (pindexLast)
4561 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4563 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4564 // Headers message had its maximum size; the peer may have more headers.
4565 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4566 // from there instead.
4567 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4568 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4571 CheckBlockIndex(chainparams.GetConsensus());
4574 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4576 CBlock block;
4577 vRecv >> block;
4579 CInv inv(MSG_BLOCK, block.GetHash());
4580 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4582 pfrom->AddInventoryKnown(inv);
4584 CValidationState state;
4585 // Process all blocks from whitelisted peers, even if not requested,
4586 // unless we're still syncing with the network.
4587 // Such an unrequested block may still be processed, subject to the
4588 // conditions in AcceptBlock().
4589 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4590 ProcessNewBlock(state, chainparams, pfrom, &block, forceProcessing, NULL);
4591 int nDoS;
4592 if (state.IsInvalid(nDoS)) {
4593 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
4594 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4595 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4596 if (nDoS > 0) {
4597 LOCK(cs_main);
4598 Misbehaving(pfrom->GetId(), nDoS);
4605 // This asymmetric behavior for inbound and outbound connections was introduced
4606 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4607 // to users' AddrMan and later request them by sending getaddr messages.
4608 // Making nodes which are behind NAT and can only make outgoing connections ignore
4609 // the getaddr message mitigates the attack.
4610 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4612 pfrom->vAddrToSend.clear();
4613 vector<CAddress> vAddr = addrman.GetAddr();
4614 BOOST_FOREACH(const CAddress &addr, vAddr)
4615 pfrom->PushAddress(addr);
4619 else if (strCommand == "mempool")
4621 LOCK2(cs_main, pfrom->cs_filter);
4623 std::vector<uint256> vtxid;
4624 mempool.queryHashes(vtxid);
4625 vector<CInv> vInv;
4626 BOOST_FOREACH(uint256& hash, vtxid) {
4627 CInv inv(MSG_TX, hash);
4628 CTransaction tx;
4629 bool fInMemPool = mempool.lookup(hash, tx);
4630 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4631 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4632 (!pfrom->pfilter))
4633 vInv.push_back(inv);
4634 if (vInv.size() == MAX_INV_SZ) {
4635 pfrom->PushMessage("inv", vInv);
4636 vInv.clear();
4639 if (vInv.size() > 0)
4640 pfrom->PushMessage("inv", vInv);
4644 else if (strCommand == "ping")
4646 if (pfrom->nVersion > BIP0031_VERSION)
4648 uint64_t nonce = 0;
4649 vRecv >> nonce;
4650 // Echo the message back with the nonce. This allows for two useful features:
4652 // 1) A remote node can quickly check if the connection is operational
4653 // 2) Remote nodes can measure the latency of the network thread. If this node
4654 // is overloaded it won't respond to pings quickly and the remote node can
4655 // avoid sending us more work, like chain download requests.
4657 // The nonce stops the remote getting confused between different pings: without
4658 // it, if the remote node sends a ping once per second and this node takes 5
4659 // seconds to respond to each, the 5th ping the remote sends would appear to
4660 // return very quickly.
4661 pfrom->PushMessage("pong", nonce);
4666 else if (strCommand == "pong")
4668 int64_t pingUsecEnd = nTimeReceived;
4669 uint64_t nonce = 0;
4670 size_t nAvail = vRecv.in_avail();
4671 bool bPingFinished = false;
4672 std::string sProblem;
4674 if (nAvail >= sizeof(nonce)) {
4675 vRecv >> nonce;
4677 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4678 if (pfrom->nPingNonceSent != 0) {
4679 if (nonce == pfrom->nPingNonceSent) {
4680 // Matching pong received, this ping is no longer outstanding
4681 bPingFinished = true;
4682 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4683 if (pingUsecTime > 0) {
4684 // Successful ping time measurement, replace previous
4685 pfrom->nPingUsecTime = pingUsecTime;
4686 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4687 } else {
4688 // This should never happen
4689 sProblem = "Timing mishap";
4691 } else {
4692 // Nonce mismatches are normal when pings are overlapping
4693 sProblem = "Nonce mismatch";
4694 if (nonce == 0) {
4695 // This is most likely a bug in another implementation somewhere; cancel this ping
4696 bPingFinished = true;
4697 sProblem = "Nonce zero";
4700 } else {
4701 sProblem = "Unsolicited pong without ping";
4703 } else {
4704 // This is most likely a bug in another implementation somewhere; cancel this ping
4705 bPingFinished = true;
4706 sProblem = "Short payload";
4709 if (!(sProblem.empty())) {
4710 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
4711 pfrom->id,
4712 sProblem,
4713 pfrom->nPingNonceSent,
4714 nonce,
4715 nAvail);
4717 if (bPingFinished) {
4718 pfrom->nPingNonceSent = 0;
4723 else if (fAlerts && strCommand == "alert")
4725 CAlert alert;
4726 vRecv >> alert;
4728 uint256 alertHash = alert.GetHash();
4729 if (pfrom->setKnown.count(alertHash) == 0)
4731 if (alert.ProcessAlert(Params().AlertKey()))
4733 // Relay
4734 pfrom->setKnown.insert(alertHash);
4736 LOCK(cs_vNodes);
4737 BOOST_FOREACH(CNode* pnode, vNodes)
4738 alert.RelayTo(pnode);
4741 else {
4742 // Small DoS penalty so peers that send us lots of
4743 // duplicate/expired/invalid-signature/whatever alerts
4744 // eventually get banned.
4745 // This isn't a Misbehaving(100) (immediate ban) because the
4746 // peer might be an older or different implementation with
4747 // a different signature key, etc.
4748 Misbehaving(pfrom->GetId(), 10);
4754 else if (!(nLocalServices & NODE_BLOOM) &&
4755 (strCommand == "filterload" ||
4756 strCommand == "filteradd" ||
4757 strCommand == "filterclear") &&
4758 //TODO: Remove this line after reasonable network upgrade
4759 pfrom->nVersion >= NO_BLOOM_VERSION)
4761 if (pfrom->nVersion >= NO_BLOOM_VERSION)
4762 Misbehaving(pfrom->GetId(), 100);
4763 //TODO: Enable this after reasonable network upgrade
4764 //else
4765 // pfrom->fDisconnect = true;
4769 else if (strCommand == "filterload")
4771 CBloomFilter filter;
4772 vRecv >> filter;
4774 if (!filter.IsWithinSizeConstraints())
4775 // There is no excuse for sending a too-large filter
4776 Misbehaving(pfrom->GetId(), 100);
4777 else
4779 LOCK(pfrom->cs_filter);
4780 delete pfrom->pfilter;
4781 pfrom->pfilter = new CBloomFilter(filter);
4782 pfrom->pfilter->UpdateEmptyFull();
4784 pfrom->fRelayTxes = true;
4788 else if (strCommand == "filteradd")
4790 vector<unsigned char> vData;
4791 vRecv >> vData;
4793 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4794 // and thus, the maximum size any matched object can have) in a filteradd message
4795 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4797 Misbehaving(pfrom->GetId(), 100);
4798 } else {
4799 LOCK(pfrom->cs_filter);
4800 if (pfrom->pfilter)
4801 pfrom->pfilter->insert(vData);
4802 else
4803 Misbehaving(pfrom->GetId(), 100);
4808 else if (strCommand == "filterclear")
4810 LOCK(pfrom->cs_filter);
4811 delete pfrom->pfilter;
4812 pfrom->pfilter = new CBloomFilter();
4813 pfrom->fRelayTxes = true;
4817 else if (strCommand == "reject")
4819 if (fDebug) {
4820 try {
4821 string strMsg; unsigned char ccode; string strReason;
4822 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4824 ostringstream ss;
4825 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4827 if (strMsg == "block" || strMsg == "tx")
4829 uint256 hash;
4830 vRecv >> hash;
4831 ss << ": hash " << hash.ToString();
4833 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4834 } catch (const std::ios_base::failure&) {
4835 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4836 LogPrint("net", "Unparseable reject message received\n");
4841 else
4843 // Ignore unknown commands for extensibility
4844 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4849 return true;
4852 // requires LOCK(cs_vRecvMsg)
4853 bool ProcessMessages(CNode* pfrom)
4855 const CChainParams& chainparams = Params();
4856 //if (fDebug)
4857 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
4860 // Message format
4861 // (4) message start
4862 // (12) command
4863 // (4) size
4864 // (4) checksum
4865 // (x) data
4867 bool fOk = true;
4869 if (!pfrom->vRecvGetData.empty())
4870 ProcessGetData(pfrom, chainparams.GetConsensus());
4872 // this maintains the order of responses
4873 if (!pfrom->vRecvGetData.empty()) return fOk;
4875 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4876 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4877 // Don't bother if send buffer is too full to respond anyway
4878 if (pfrom->nSendSize >= SendBufferSize())
4879 break;
4881 // get next message
4882 CNetMessage& msg = *it;
4884 //if (fDebug)
4885 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
4886 // msg.hdr.nMessageSize, msg.vRecv.size(),
4887 // msg.complete() ? "Y" : "N");
4889 // end, if an incomplete message is found
4890 if (!msg.complete())
4891 break;
4893 // at this point, any failure means we can delete the current message
4894 it++;
4896 // Scan for message start
4897 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) != 0) {
4898 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4899 fOk = false;
4900 break;
4903 // Read header
4904 CMessageHeader& hdr = msg.hdr;
4905 if (!hdr.IsValid(chainparams.MessageStart()))
4907 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4908 continue;
4910 string strCommand = hdr.GetCommand();
4912 // Message size
4913 unsigned int nMessageSize = hdr.nMessageSize;
4915 // Checksum
4916 CDataStream& vRecv = msg.vRecv;
4917 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4918 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4919 if (nChecksum != hdr.nChecksum)
4921 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
4922 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4923 continue;
4926 // Process message
4927 bool fRet = false;
4930 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4931 boost::this_thread::interruption_point();
4933 catch (const std::ios_base::failure& e)
4935 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4936 if (strstr(e.what(), "end of data"))
4938 // Allow exceptions from under-length message on vRecv
4939 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());
4941 else if (strstr(e.what(), "size too large"))
4943 // Allow exceptions from over-long size
4944 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4946 else
4948 PrintExceptionContinue(&e, "ProcessMessages()");
4951 catch (const boost::thread_interrupted&) {
4952 throw;
4954 catch (const std::exception& e) {
4955 PrintExceptionContinue(&e, "ProcessMessages()");
4956 } catch (...) {
4957 PrintExceptionContinue(NULL, "ProcessMessages()");
4960 if (!fRet)
4961 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
4963 break;
4966 // In case the connection got shut down, its receive buffer was wiped
4967 if (!pfrom->fDisconnect)
4968 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4970 return fOk;
4974 bool SendMessages(CNode* pto, bool fSendTrickle)
4976 const Consensus::Params& consensusParams = Params().GetConsensus();
4978 // Don't send anything until we get its version message
4979 if (pto->nVersion == 0)
4980 return true;
4983 // Message: ping
4985 bool pingSend = false;
4986 if (pto->fPingQueued) {
4987 // RPC ping request by user
4988 pingSend = true;
4990 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4991 // Ping automatically sent as a latency probe & keepalive.
4992 pingSend = true;
4994 if (pingSend) {
4995 uint64_t nonce = 0;
4996 while (nonce == 0) {
4997 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4999 pto->fPingQueued = false;
5000 pto->nPingUsecStart = GetTimeMicros();
5001 if (pto->nVersion > BIP0031_VERSION) {
5002 pto->nPingNonceSent = nonce;
5003 pto->PushMessage("ping", nonce);
5004 } else {
5005 // Peer is too old to support ping command with nonce, pong will never arrive.
5006 pto->nPingNonceSent = 0;
5007 pto->PushMessage("ping");
5011 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5012 if (!lockMain)
5013 return true;
5015 // Address refresh broadcast
5016 static int64_t nLastRebroadcast;
5017 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5019 LOCK(cs_vNodes);
5020 BOOST_FOREACH(CNode* pnode, vNodes)
5022 // Periodically clear addrKnown to allow refresh broadcasts
5023 if (nLastRebroadcast)
5024 pnode->addrKnown.reset();
5026 // Rebroadcast our address
5027 AdvertizeLocal(pnode);
5029 if (!vNodes.empty())
5030 nLastRebroadcast = GetTime();
5034 // Message: addr
5036 if (fSendTrickle)
5038 vector<CAddress> vAddr;
5039 vAddr.reserve(pto->vAddrToSend.size());
5040 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5042 if (!pto->addrKnown.contains(addr.GetKey()))
5044 pto->addrKnown.insert(addr.GetKey());
5045 vAddr.push_back(addr);
5046 // receiver rejects addr messages larger than 1000
5047 if (vAddr.size() >= 1000)
5049 pto->PushMessage("addr", vAddr);
5050 vAddr.clear();
5054 pto->vAddrToSend.clear();
5055 if (!vAddr.empty())
5056 pto->PushMessage("addr", vAddr);
5059 CNodeState &state = *State(pto->GetId());
5060 if (state.fShouldBan) {
5061 if (pto->fWhitelisted)
5062 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5063 else {
5064 pto->fDisconnect = true;
5065 if (pto->addr.IsLocal())
5066 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5067 else
5069 CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
5072 state.fShouldBan = false;
5075 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5076 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5077 state.rejects.clear();
5079 // Start block sync
5080 if (pindexBestHeader == NULL)
5081 pindexBestHeader = chainActive.Tip();
5082 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.
5083 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5084 // Only actively request headers from a single peer, unless we're close to today.
5085 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5086 state.fSyncStarted = true;
5087 nSyncStarted++;
5088 const CBlockIndex *pindexStart = pindexBestHeader;
5089 /* If possible, start at the block preceding the currently
5090 best known header. This ensures that we always get a
5091 non-empty list of headers back as long as the peer
5092 is up-to-date. With a non-empty response, we can initialise
5093 the peer's known best block. This wouldn't be possible
5094 if we requested starting at pindexBestHeader and
5095 got back an empty response. */
5096 if (pindexStart->pprev)
5097 pindexStart = pindexStart->pprev;
5098 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5099 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5103 // Resend wallet transactions that haven't gotten in a block yet
5104 // Except during reindex, importing and IBD, when old wallet
5105 // transactions become unconfirmed and spams other nodes.
5106 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5108 GetMainSignals().Broadcast(nTimeBestReceived);
5112 // Message: inventory
5114 vector<CInv> vInv;
5115 vector<CInv> vInvWait;
5117 LOCK(pto->cs_inventory);
5118 vInv.reserve(pto->vInventoryToSend.size());
5119 vInvWait.reserve(pto->vInventoryToSend.size());
5120 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5122 if (pto->setInventoryKnown.count(inv))
5123 continue;
5125 // trickle out tx inv to protect privacy
5126 if (inv.type == MSG_TX && !fSendTrickle)
5128 // 1/4 of tx invs blast to all immediately
5129 static uint256 hashSalt;
5130 if (hashSalt.IsNull())
5131 hashSalt = GetRandHash();
5132 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5133 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5134 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5136 if (fTrickleWait)
5138 vInvWait.push_back(inv);
5139 continue;
5143 // returns true if wasn't already contained in the set
5144 if (pto->setInventoryKnown.insert(inv).second)
5146 vInv.push_back(inv);
5147 if (vInv.size() >= 1000)
5149 pto->PushMessage("inv", vInv);
5150 vInv.clear();
5154 pto->vInventoryToSend = vInvWait;
5156 if (!vInv.empty())
5157 pto->PushMessage("inv", vInv);
5159 // Detect whether we're stalling
5160 int64_t nNow = GetTimeMicros();
5161 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5162 // Stalling only triggers when the block download window cannot move. During normal steady state,
5163 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5164 // should only happen during initial block download.
5165 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5166 pto->fDisconnect = true;
5168 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5169 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5170 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5171 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5172 // to unreasonably increase our timeout.
5173 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5174 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5175 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5176 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5177 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5178 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5179 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5180 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5181 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5182 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5183 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5185 if (queuedBlock.nTimeDisconnect < nNow) {
5186 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5187 pto->fDisconnect = true;
5192 // Message: getdata (blocks)
5194 vector<CInv> vGetData;
5195 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5196 vector<CBlockIndex*> vToDownload;
5197 NodeId staller = -1;
5198 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5199 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5200 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5201 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5202 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5203 pindex->nHeight, pto->id);
5205 if (state.nBlocksInFlight == 0 && staller != -1) {
5206 if (State(staller)->nStallingSince == 0) {
5207 State(staller)->nStallingSince = nNow;
5208 LogPrint("net", "Stall started peer=%d\n", staller);
5214 // Message: getdata (non-blocks)
5216 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5218 const CInv& inv = (*pto->mapAskFor.begin()).second;
5219 if (!AlreadyHave(inv))
5221 if (fDebug)
5222 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5223 vGetData.push_back(inv);
5224 if (vGetData.size() >= 1000)
5226 pto->PushMessage("getdata", vGetData);
5227 vGetData.clear();
5229 } else {
5230 //If we're not going to ask, don't expect a response.
5231 pto->setAskFor.erase(inv.hash);
5233 pto->mapAskFor.erase(pto->mapAskFor.begin());
5235 if (!vGetData.empty())
5236 pto->PushMessage("getdata", vGetData);
5239 return true;
5242 std::string CBlockFileInfo::ToString() const {
5243 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));
5248 class CMainCleanup
5250 public:
5251 CMainCleanup() {}
5252 ~CMainCleanup() {
5253 // block headers
5254 BlockMap::iterator it1 = mapBlockIndex.begin();
5255 for (; it1 != mapBlockIndex.end(); it1++)
5256 delete (*it1).second;
5257 mapBlockIndex.clear();
5259 // orphan transactions
5260 mapOrphanTransactions.clear();
5261 mapOrphanTransactionsByPrev.clear();
5263 } instance_of_cmaincleanup;