Merge #8077: Consensus: Decouple from chainparams.o and timedata.o
[bitcoinplatinum.git] / src / main.cpp
blob162c8b986caecf3353a7ff470990fff5d6ef7096
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "arith_uint256.h"
10 #include "chainparams.h"
11 #include "checkpoints.h"
12 #include "checkqueue.h"
13 #include "consensus/consensus.h"
14 #include "consensus/merkle.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/fees.h"
21 #include "policy/policy.h"
22 #include "pow.h"
23 #include "primitives/block.h"
24 #include "primitives/transaction.h"
25 #include "random.h"
26 #include "script/script.h"
27 #include "script/sigcache.h"
28 #include "script/standard.h"
29 #include "tinyformat.h"
30 #include "txdb.h"
31 #include "txmempool.h"
32 #include "ui_interface.h"
33 #include "undo.h"
34 #include "util.h"
35 #include "utilmoneystr.h"
36 #include "utilstrencodings.h"
37 #include "validationinterface.h"
38 #include "versionbits.h"
40 #include <sstream>
42 #include <boost/algorithm/string/replace.hpp>
43 #include <boost/algorithm/string/join.hpp>
44 #include <boost/filesystem.hpp>
45 #include <boost/filesystem/fstream.hpp>
46 #include <boost/math/distributions/poisson.hpp>
47 #include <boost/thread.hpp>
49 using namespace std;
51 #if defined(NDEBUG)
52 # error "Bitcoin cannot be compiled without assertions."
53 #endif
55 /**
56 * Global state
59 CCriticalSection cs_main;
61 BlockMap mapBlockIndex;
62 CChain chainActive;
63 CBlockIndex *pindexBestHeader = NULL;
64 int64_t nTimeBestReceived = 0;
65 CWaitableCriticalSection csBestBlock;
66 CConditionVariable cvBlockChange;
67 int nScriptCheckThreads = 0;
68 bool fImporting = false;
69 bool fReindex = false;
70 bool fTxIndex = false;
71 bool fHavePruned = false;
72 bool fPruneMode = false;
73 bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
74 bool fRequireStandard = true;
75 unsigned int nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
76 bool fCheckBlockIndex = false;
77 bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
78 size_t nCoinCacheUsage = 5000 * 300;
79 uint64_t nPruneTarget = 0;
80 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
81 bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
83 std::map<uint256, CTransaction> mapRelay;
84 std::deque<std::pair<int64_t, uint256> > vRelayExpiration;
85 CCriticalSection cs_mapRelay;
87 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
88 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
90 CTxMemPool mempool(::minRelayTxFee);
91 FeeFilterRounder filterRounder(::minRelayTxFee);
93 struct COrphanTx {
94 CTransaction tx;
95 NodeId fromPeer;
97 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
98 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
99 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
102 * Returns true if there are nRequired or more blocks of minVersion or above
103 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
105 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
106 static void CheckBlockIndex(const Consensus::Params& consensusParams);
108 /** Constant stuff for coinbase transactions we create: */
109 CScript COINBASE_FLAGS;
111 const string strMessageMagic = "Bitcoin Signed Message:\n";
113 // Internal stuff
114 namespace {
116 struct CBlockIndexWorkComparator
118 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
119 // First sort by most total work, ...
120 if (pa->nChainWork > pb->nChainWork) return false;
121 if (pa->nChainWork < pb->nChainWork) return true;
123 // ... then by earliest time received, ...
124 if (pa->nSequenceId < pb->nSequenceId) return false;
125 if (pa->nSequenceId > pb->nSequenceId) return true;
127 // Use pointer address as tie breaker (should only happen with blocks
128 // loaded from disk, as those all have id 0).
129 if (pa < pb) return false;
130 if (pa > pb) return true;
132 // Identical blocks.
133 return false;
137 CBlockIndex *pindexBestInvalid;
140 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
141 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
142 * missing the data for the block.
144 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
145 /** Number of nodes with fSyncStarted. */
146 int nSyncStarted = 0;
147 /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
148 * Pruned nodes may have entries where B is missing data.
150 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
152 CCriticalSection cs_LastBlockFile;
153 std::vector<CBlockFileInfo> vinfoBlockFile;
154 int nLastBlockFile = 0;
155 /** Global flag to indicate we should check to see if there are
156 * block/undo files that should be deleted. Set on startup
157 * or if we allocate more file space when we're in prune mode
159 bool fCheckForPruning = false;
162 * Every received block is assigned a unique and increasing identifier, so we
163 * know which one to give priority in case of a fork.
165 CCriticalSection cs_nBlockSequenceId;
166 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
167 uint32_t nBlockSequenceId = 1;
170 * Sources of received blocks, saved to be able to send them reject
171 * messages or ban them when processing happens afterwards. Protected by
172 * cs_main.
174 map<uint256, NodeId> mapBlockSource;
177 * Filter for transactions that were recently rejected by
178 * AcceptToMemoryPool. These are not rerequested until the chain tip
179 * changes, at which point the entire filter is reset. Protected by
180 * cs_main.
182 * Without this filter we'd be re-requesting txs from each of our peers,
183 * increasing bandwidth consumption considerably. For instance, with 100
184 * peers, half of which relay a tx we don't accept, that might be a 50x
185 * bandwidth increase. A flooding attacker attempting to roll-over the
186 * filter using minimum-sized, 60byte, transactions might manage to send
187 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
188 * two minute window to send invs to us.
190 * Decreasing the false positive rate is fairly cheap, so we pick one in a
191 * million to make it highly unlikely for users to have issues with this
192 * filter.
194 * Memory used: 1.3 MB
196 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
197 uint256 hashRecentRejectsChainTip;
199 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
200 struct QueuedBlock {
201 uint256 hash;
202 CBlockIndex* pindex; //!< Optional.
203 bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
205 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
207 /** Number of preferable block download peers. */
208 int nPreferredDownload = 0;
210 /** Dirty block index entries. */
211 set<CBlockIndex*> setDirtyBlockIndex;
213 /** Dirty block file entries. */
214 set<int> setDirtyFileInfo;
216 /** Number of peers from which we're downloading blocks. */
217 int nPeersWithValidatedDownloads = 0;
218 } // anon namespace
220 //////////////////////////////////////////////////////////////////////////////
222 // Registration of network node signals.
225 namespace {
227 struct CBlockReject {
228 unsigned char chRejectCode;
229 string strRejectReason;
230 uint256 hashBlock;
234 * Maintain validation-specific state about nodes, protected by cs_main, instead
235 * by CNode's own locks. This simplifies asynchronous operation, where
236 * processing of incoming data is done after the ProcessMessage call returns,
237 * and we're no longer holding the node's locks.
239 struct CNodeState {
240 //! The peer's address
241 CService address;
242 //! Whether we have a fully established connection.
243 bool fCurrentlyConnected;
244 //! Accumulated misbehaviour score for this peer.
245 int nMisbehavior;
246 //! Whether this peer should be disconnected and banned (unless whitelisted).
247 bool fShouldBan;
248 //! String name of this peer (debugging/logging purposes).
249 std::string name;
250 //! List of asynchronously-determined block rejections to notify this peer about.
251 std::vector<CBlockReject> rejects;
252 //! The best known block we know this peer has announced.
253 CBlockIndex *pindexBestKnownBlock;
254 //! The hash of the last unknown block this peer has announced.
255 uint256 hashLastUnknownBlock;
256 //! The last full block we both have.
257 CBlockIndex *pindexLastCommonBlock;
258 //! The best header we have sent our peer.
259 CBlockIndex *pindexBestHeaderSent;
260 //! Whether we've started headers synchronization with this peer.
261 bool fSyncStarted;
262 //! Since when we're stalling block download progress (in microseconds), or 0.
263 int64_t nStallingSince;
264 list<QueuedBlock> vBlocksInFlight;
265 //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
266 int64_t nDownloadingSince;
267 int nBlocksInFlight;
268 int nBlocksInFlightValidHeaders;
269 //! Whether we consider this a preferred download peer.
270 bool fPreferredDownload;
271 //! Whether this peer wants invs or headers (when possible) for block announcements.
272 bool fPreferHeaders;
274 CNodeState() {
275 fCurrentlyConnected = false;
276 nMisbehavior = 0;
277 fShouldBan = false;
278 pindexBestKnownBlock = NULL;
279 hashLastUnknownBlock.SetNull();
280 pindexLastCommonBlock = NULL;
281 pindexBestHeaderSent = NULL;
282 fSyncStarted = false;
283 nStallingSince = 0;
284 nDownloadingSince = 0;
285 nBlocksInFlight = 0;
286 nBlocksInFlightValidHeaders = 0;
287 fPreferredDownload = false;
288 fPreferHeaders = false;
292 /** Map maintaining per-node state. Requires cs_main. */
293 map<NodeId, CNodeState> mapNodeState;
295 // Requires cs_main.
296 CNodeState *State(NodeId pnode) {
297 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
298 if (it == mapNodeState.end())
299 return NULL;
300 return &it->second;
303 int GetHeight()
305 LOCK(cs_main);
306 return chainActive.Height();
309 void UpdatePreferredDownload(CNode* node, CNodeState* state)
311 nPreferredDownload -= state->fPreferredDownload;
313 // Whether this node should be marked as a preferred download node.
314 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
316 nPreferredDownload += state->fPreferredDownload;
319 void InitializeNode(NodeId nodeid, const CNode *pnode) {
320 LOCK(cs_main);
321 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
322 state.name = pnode->addrName;
323 state.address = pnode->addr;
326 void FinalizeNode(NodeId nodeid) {
327 LOCK(cs_main);
328 CNodeState *state = State(nodeid);
330 if (state->fSyncStarted)
331 nSyncStarted--;
333 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
334 AddressCurrentlyConnected(state->address);
337 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
338 mapBlocksInFlight.erase(entry.hash);
340 EraseOrphansFor(nodeid);
341 nPreferredDownload -= state->fPreferredDownload;
342 nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
343 assert(nPeersWithValidatedDownloads >= 0);
345 mapNodeState.erase(nodeid);
347 if (mapNodeState.empty()) {
348 // Do a consistency check after the last peer is removed.
349 assert(mapBlocksInFlight.empty());
350 assert(nPreferredDownload == 0);
351 assert(nPeersWithValidatedDownloads == 0);
355 // Requires cs_main.
356 // Returns a bool indicating whether we requested this block.
357 bool MarkBlockAsReceived(const uint256& hash) {
358 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
359 if (itInFlight != mapBlocksInFlight.end()) {
360 CNodeState *state = State(itInFlight->second.first);
361 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
362 if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
363 // Last validated block on the queue was received.
364 nPeersWithValidatedDownloads--;
366 if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
367 // First block on the queue was received, update the start download time for the next one
368 state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
370 state->vBlocksInFlight.erase(itInFlight->second.second);
371 state->nBlocksInFlight--;
372 state->nStallingSince = 0;
373 mapBlocksInFlight.erase(itInFlight);
374 return true;
376 return false;
379 // Requires cs_main.
380 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
381 CNodeState *state = State(nodeid);
382 assert(state != NULL);
384 // Make sure it's not listed somewhere already.
385 MarkBlockAsReceived(hash);
387 QueuedBlock newentry = {hash, pindex, pindex != NULL};
388 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
389 state->nBlocksInFlight++;
390 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
391 if (state->nBlocksInFlight == 1) {
392 // We're starting a block download (batch) from this peer.
393 state->nDownloadingSince = GetTimeMicros();
395 if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
396 nPeersWithValidatedDownloads++;
398 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
401 /** Check whether the last unknown block a peer advertised is not yet known. */
402 void ProcessBlockAvailability(NodeId nodeid) {
403 CNodeState *state = State(nodeid);
404 assert(state != NULL);
406 if (!state->hashLastUnknownBlock.IsNull()) {
407 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
408 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
409 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
410 state->pindexBestKnownBlock = itOld->second;
411 state->hashLastUnknownBlock.SetNull();
416 /** Update tracking information about which blocks a peer is assumed to have. */
417 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
418 CNodeState *state = State(nodeid);
419 assert(state != NULL);
421 ProcessBlockAvailability(nodeid);
423 BlockMap::iterator it = mapBlockIndex.find(hash);
424 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
425 // An actually better block was announced.
426 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
427 state->pindexBestKnownBlock = it->second;
428 } else {
429 // An unknown block was announced; just assume that the latest one is the best one.
430 state->hashLastUnknownBlock = hash;
434 // Requires cs_main
435 bool CanDirectFetch(const Consensus::Params &consensusParams)
437 return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
440 // Requires cs_main
441 bool PeerHasHeader(CNodeState *state, CBlockIndex *pindex)
443 if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
444 return true;
445 if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
446 return true;
447 return false;
450 /** Find the last common ancestor two blocks have.
451 * Both pa and pb must be non-NULL. */
452 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
453 if (pa->nHeight > pb->nHeight) {
454 pa = pa->GetAncestor(pb->nHeight);
455 } else if (pb->nHeight > pa->nHeight) {
456 pb = pb->GetAncestor(pa->nHeight);
459 while (pa != pb && pa && pb) {
460 pa = pa->pprev;
461 pb = pb->pprev;
464 // Eventually all chain branches meet at the genesis block.
465 assert(pa == pb);
466 return pa;
469 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
470 * at most count entries. */
471 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
472 if (count == 0)
473 return;
475 vBlocks.reserve(vBlocks.size() + count);
476 CNodeState *state = State(nodeid);
477 assert(state != NULL);
479 // Make sure pindexBestKnownBlock is up to date, we'll need it.
480 ProcessBlockAvailability(nodeid);
482 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
483 // This peer has nothing interesting.
484 return;
487 if (state->pindexLastCommonBlock == NULL) {
488 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
489 // Guessing wrong in either direction is not a problem.
490 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
493 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
494 // of its current tip anymore. Go back enough to fix that.
495 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
496 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
497 return;
499 std::vector<CBlockIndex*> vToFetch;
500 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
501 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
502 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
503 // download that next block if the window were 1 larger.
504 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
505 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
506 NodeId waitingfor = -1;
507 while (pindexWalk->nHeight < nMaxHeight) {
508 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
509 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
510 // as iterating over ~100 CBlockIndex* entries anyway.
511 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
512 vToFetch.resize(nToFetch);
513 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
514 vToFetch[nToFetch - 1] = pindexWalk;
515 for (unsigned int i = nToFetch - 1; i > 0; i--) {
516 vToFetch[i - 1] = vToFetch[i]->pprev;
519 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
520 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
521 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
522 // already part of our chain (and therefore don't need it even if pruned).
523 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
524 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
525 // We consider the chain that this peer is on invalid.
526 return;
528 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
529 if (pindex->nChainTx)
530 state->pindexLastCommonBlock = pindex;
531 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
532 // The block is not already downloaded, and not yet in flight.
533 if (pindex->nHeight > nWindowEnd) {
534 // We reached the end of the window.
535 if (vBlocks.size() == 0 && waitingfor != nodeid) {
536 // We aren't able to fetch anything, but we would be if the download window was one larger.
537 nodeStaller = waitingfor;
539 return;
541 vBlocks.push_back(pindex);
542 if (vBlocks.size() == count) {
543 return;
545 } else if (waitingfor == -1) {
546 // This is the first already-in-flight block.
547 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
553 } // anon namespace
555 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
556 LOCK(cs_main);
557 CNodeState *state = State(nodeid);
558 if (state == NULL)
559 return false;
560 stats.nMisbehavior = state->nMisbehavior;
561 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
562 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
563 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
564 if (queue.pindex)
565 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
567 return true;
570 void RegisterNodeSignals(CNodeSignals& nodeSignals)
572 nodeSignals.GetHeight.connect(&GetHeight);
573 nodeSignals.ProcessMessages.connect(&ProcessMessages);
574 nodeSignals.SendMessages.connect(&SendMessages);
575 nodeSignals.InitializeNode.connect(&InitializeNode);
576 nodeSignals.FinalizeNode.connect(&FinalizeNode);
579 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
581 nodeSignals.GetHeight.disconnect(&GetHeight);
582 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
583 nodeSignals.SendMessages.disconnect(&SendMessages);
584 nodeSignals.InitializeNode.disconnect(&InitializeNode);
585 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
588 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
590 // Find the first block the caller has in the main chain
591 BOOST_FOREACH(const uint256& hash, locator.vHave) {
592 BlockMap::iterator mi = mapBlockIndex.find(hash);
593 if (mi != mapBlockIndex.end())
595 CBlockIndex* pindex = (*mi).second;
596 if (chain.Contains(pindex))
597 return pindex;
600 return chain.Genesis();
603 CCoinsViewCache *pcoinsTip = NULL;
604 CBlockTreeDB *pblocktree = NULL;
606 //////////////////////////////////////////////////////////////////////////////
608 // mapOrphanTransactions
611 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
613 uint256 hash = tx.GetHash();
614 if (mapOrphanTransactions.count(hash))
615 return false;
617 // Ignore big transactions, to avoid a
618 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
619 // large transaction with a missing parent then we assume
620 // it will rebroadcast it later, after the parent transaction(s)
621 // have been mined or received.
622 // 10,000 orphans, each of which is at most 5,000 bytes big is
623 // at most 500 megabytes of orphans:
624 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
625 if (sz > 5000)
627 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
628 return false;
631 mapOrphanTransactions[hash].tx = tx;
632 mapOrphanTransactions[hash].fromPeer = peer;
633 BOOST_FOREACH(const CTxIn& txin, tx.vin)
634 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
636 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
637 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
638 return true;
641 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
643 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
644 if (it == mapOrphanTransactions.end())
645 return;
646 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
648 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
649 if (itPrev == mapOrphanTransactionsByPrev.end())
650 continue;
651 itPrev->second.erase(hash);
652 if (itPrev->second.empty())
653 mapOrphanTransactionsByPrev.erase(itPrev);
655 mapOrphanTransactions.erase(it);
658 void EraseOrphansFor(NodeId peer)
660 int nErased = 0;
661 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
662 while (iter != mapOrphanTransactions.end())
664 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
665 if (maybeErase->second.fromPeer == peer)
667 EraseOrphanTx(maybeErase->second.tx.GetHash());
668 ++nErased;
671 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
675 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
677 unsigned int nEvicted = 0;
678 while (mapOrphanTransactions.size() > nMaxOrphans)
680 // Evict a random orphan:
681 uint256 randomhash = GetRandHash();
682 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
683 if (it == mapOrphanTransactions.end())
684 it = mapOrphanTransactions.begin();
685 EraseOrphanTx(it->first);
686 ++nEvicted;
688 return nEvicted;
691 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
693 if (tx.nLockTime == 0)
694 return true;
695 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
696 return true;
697 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
698 if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
699 return false;
701 return true;
704 bool CheckFinalTx(const CTransaction &tx, int flags)
706 AssertLockHeld(cs_main);
708 // By convention a negative value for flags indicates that the
709 // current network-enforced consensus rules should be used. In
710 // a future soft-fork scenario that would mean checking which
711 // rules would be enforced for the next block and setting the
712 // appropriate flags. At the present time no soft-forks are
713 // scheduled, so no flags are set.
714 flags = std::max(flags, 0);
716 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
717 // nLockTime because when IsFinalTx() is called within
718 // CBlock::AcceptBlock(), the height of the block *being*
719 // evaluated is what is used. Thus if we want to know if a
720 // transaction can be part of the *next* block, we need to call
721 // IsFinalTx() with one more than chainActive.Height().
722 const int nBlockHeight = chainActive.Height() + 1;
724 // BIP113 will require that time-locked transactions have nLockTime set to
725 // less than the median time of the previous block they're contained in.
726 // When the next block is created its previous block will be the current
727 // chain tip, so we use that to calculate the median time passed to
728 // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
729 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
730 ? chainActive.Tip()->GetMedianTimePast()
731 : GetAdjustedTime();
733 return IsFinalTx(tx, nBlockHeight, nBlockTime);
737 * Calculates the block height and previous block's median time past at
738 * which the transaction will be considered final in the context of BIP 68.
739 * Also removes from the vector of input heights any entries which did not
740 * correspond to sequence locked inputs as they do not affect the calculation.
742 static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
744 assert(prevHeights->size() == tx.vin.size());
746 // Will be set to the equivalent height- and time-based nLockTime
747 // values that would be necessary to satisfy all relative lock-
748 // time constraints given our view of block chain history.
749 // The semantics of nLockTime are the last invalid height/time, so
750 // use -1 to have the effect of any height or time being valid.
751 int nMinHeight = -1;
752 int64_t nMinTime = -1;
754 // tx.nVersion is signed integer so requires cast to unsigned otherwise
755 // we would be doing a signed comparison and half the range of nVersion
756 // wouldn't support BIP 68.
757 bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
758 && flags & LOCKTIME_VERIFY_SEQUENCE;
760 // Do not enforce sequence numbers as a relative lock time
761 // unless we have been instructed to
762 if (!fEnforceBIP68) {
763 return std::make_pair(nMinHeight, nMinTime);
766 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
767 const CTxIn& txin = tx.vin[txinIndex];
769 // Sequence numbers with the most significant bit set are not
770 // treated as relative lock-times, nor are they given any
771 // consensus-enforced meaning at this point.
772 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
773 // The height of this input is not relevant for sequence locks
774 (*prevHeights)[txinIndex] = 0;
775 continue;
778 int nCoinHeight = (*prevHeights)[txinIndex];
780 if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
781 int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
782 // NOTE: Subtract 1 to maintain nLockTime semantics
783 // BIP 68 relative lock times have the semantics of calculating
784 // the first block or time at which the transaction would be
785 // valid. When calculating the effective block time or height
786 // for the entire transaction, we switch to using the
787 // semantics of nLockTime which is the last invalid block
788 // time or height. Thus we subtract 1 from the calculated
789 // time or height.
791 // Time-based relative lock-times are measured from the
792 // smallest allowed timestamp of the block containing the
793 // txout being spent, which is the median time past of the
794 // block prior.
795 nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
796 } else {
797 nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
801 return std::make_pair(nMinHeight, nMinTime);
804 static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
806 assert(block.pprev);
807 int64_t nBlockTime = block.pprev->GetMedianTimePast();
808 if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
809 return false;
811 return true;
814 bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
816 return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
819 bool TestLockPointValidity(const LockPoints* lp)
821 AssertLockHeld(cs_main);
822 assert(lp);
823 // If there are relative lock times then the maxInputBlock will be set
824 // If there are no relative lock times, the LockPoints don't depend on the chain
825 if (lp->maxInputBlock) {
826 // Check whether chainActive is an extension of the block at which the LockPoints
827 // calculation was valid. If not LockPoints are no longer valid
828 if (!chainActive.Contains(lp->maxInputBlock)) {
829 return false;
833 // LockPoints still valid
834 return true;
837 bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
839 AssertLockHeld(cs_main);
840 AssertLockHeld(mempool.cs);
842 CBlockIndex* tip = chainActive.Tip();
843 CBlockIndex index;
844 index.pprev = tip;
845 // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
846 // height based locks because when SequenceLocks() is called within
847 // ConnectBlock(), the height of the block *being*
848 // evaluated is what is used.
849 // Thus if we want to know if a transaction can be part of the
850 // *next* block, we need to use one more than chainActive.Height()
851 index.nHeight = tip->nHeight + 1;
853 std::pair<int, int64_t> lockPair;
854 if (useExistingLockPoints) {
855 assert(lp);
856 lockPair.first = lp->height;
857 lockPair.second = lp->time;
859 else {
860 // pcoinsTip contains the UTXO set for chainActive.Tip()
861 CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
862 std::vector<int> prevheights;
863 prevheights.resize(tx.vin.size());
864 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
865 const CTxIn& txin = tx.vin[txinIndex];
866 CCoins coins;
867 if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
868 return error("%s: Missing input", __func__);
870 if (coins.nHeight == MEMPOOL_HEIGHT) {
871 // Assume all mempool transaction confirm in the next block
872 prevheights[txinIndex] = tip->nHeight + 1;
873 } else {
874 prevheights[txinIndex] = coins.nHeight;
877 lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
878 if (lp) {
879 lp->height = lockPair.first;
880 lp->time = lockPair.second;
881 // Also store the hash of the block with the highest height of
882 // all the blocks which have sequence locked prevouts.
883 // This hash needs to still be on the chain
884 // for these LockPoint calculations to be valid
885 // Note: It is impossible to correctly calculate a maxInputBlock
886 // if any of the sequence locked inputs depend on unconfirmed txs,
887 // except in the special case where the relative lock time/height
888 // is 0, which is equivalent to no sequence lock. Since we assume
889 // input height of tip+1 for mempool txs and test the resulting
890 // lockPair from CalculateSequenceLocks against tip+1. We know
891 // EvaluateSequenceLocks will fail if there was a non-zero sequence
892 // lock on a mempool input, so we can use the return value of
893 // CheckSequenceLocks to indicate the LockPoints validity
894 int maxInputHeight = 0;
895 BOOST_FOREACH(int height, prevheights) {
896 // Can ignore mempool inputs since we'll fail if they had non-zero locks
897 if (height != tip->nHeight+1) {
898 maxInputHeight = std::max(maxInputHeight, height);
901 lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
904 return EvaluateSequenceLocks(index, lockPair);
908 unsigned int GetLegacySigOpCount(const CTransaction& tx)
910 unsigned int nSigOps = 0;
911 BOOST_FOREACH(const CTxIn& txin, tx.vin)
913 nSigOps += txin.scriptSig.GetSigOpCount(false);
915 BOOST_FOREACH(const CTxOut& txout, tx.vout)
917 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
919 return nSigOps;
922 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
924 if (tx.IsCoinBase())
925 return 0;
927 unsigned int nSigOps = 0;
928 for (unsigned int i = 0; i < tx.vin.size(); i++)
930 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
931 if (prevout.scriptPubKey.IsPayToScriptHash())
932 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
934 return nSigOps;
944 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
946 // Basic checks that don't depend on any context
947 if (tx.vin.empty())
948 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
949 if (tx.vout.empty())
950 return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
951 // Size limits
952 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
953 return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
955 // Check for negative or overflow output values
956 CAmount nValueOut = 0;
957 BOOST_FOREACH(const CTxOut& txout, tx.vout)
959 if (txout.nValue < 0)
960 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
961 if (txout.nValue > MAX_MONEY)
962 return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
963 nValueOut += txout.nValue;
964 if (!MoneyRange(nValueOut))
965 return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
968 // Check for duplicate inputs
969 set<COutPoint> vInOutPoints;
970 BOOST_FOREACH(const CTxIn& txin, tx.vin)
972 if (vInOutPoints.count(txin.prevout))
973 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
974 vInOutPoints.insert(txin.prevout);
977 if (tx.IsCoinBase())
979 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
980 return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
982 else
984 BOOST_FOREACH(const CTxIn& txin, tx.vin)
985 if (txin.prevout.IsNull())
986 return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
989 return true;
992 void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
993 int expired = pool.Expire(GetTime() - age);
994 if (expired != 0)
995 LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired);
997 std::vector<uint256> vNoSpendsRemaining;
998 pool.TrimToSize(limit, &vNoSpendsRemaining);
999 BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining)
1000 pcoinsTip->Uncache(removed);
1003 /** Convert CValidationState to a human-readable message for logging */
1004 std::string FormatStateMessage(const CValidationState &state)
1006 return strprintf("%s%s (code %i)",
1007 state.GetRejectReason(),
1008 state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
1009 state.GetRejectCode());
1012 bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree,
1013 bool* pfMissingInputs, bool fOverrideMempoolLimit, const CAmount& nAbsurdFee,
1014 std::vector<uint256>& vHashTxnToUncache)
1016 const uint256 hash = tx.GetHash();
1017 AssertLockHeld(cs_main);
1018 if (pfMissingInputs)
1019 *pfMissingInputs = false;
1021 if (!CheckTransaction(tx, state))
1022 return false; // state filled in by CheckTransaction
1024 // Coinbase is only valid in a block, not as a loose transaction
1025 if (tx.IsCoinBase())
1026 return state.DoS(100, false, REJECT_INVALID, "coinbase");
1028 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1029 string reason;
1030 if (fRequireStandard && !IsStandardTx(tx, reason))
1031 return state.DoS(0, false, REJECT_NONSTANDARD, reason);
1033 // Don't relay version 2 transactions until CSV is active, and we can be
1034 // sure that such transactions will be mined (unless we're on
1035 // -testnet/-regtest).
1036 const CChainParams& chainparams = Params();
1037 if (fRequireStandard && tx.nVersion >= 2 && VersionBitsTipState(chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV) != THRESHOLD_ACTIVE) {
1038 return state.DoS(0, false, REJECT_NONSTANDARD, "premature-version2-tx");
1041 // Only accept nLockTime-using transactions that can be mined in the next
1042 // block; we don't want our mempool filled up with transactions that can't
1043 // be mined yet.
1044 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1045 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1047 // is it already in the memory pool?
1048 if (pool.exists(hash))
1049 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-in-mempool");
1051 // Check for conflicts with in-memory transactions
1052 set<uint256> setConflicts;
1054 LOCK(pool.cs); // protect pool.mapNextTx
1055 BOOST_FOREACH(const CTxIn &txin, tx.vin)
1057 if (pool.mapNextTx.count(txin.prevout))
1059 const CTransaction *ptxConflicting = pool.mapNextTx[txin.prevout].ptx;
1060 if (!setConflicts.count(ptxConflicting->GetHash()))
1062 // Allow opt-out of transaction replacement by setting
1063 // nSequence >= maxint-1 on all inputs.
1065 // maxint-1 is picked to still allow use of nLockTime by
1066 // non-replacable transactions. All inputs rather than just one
1067 // is for the sake of multi-party protocols, where we don't
1068 // want a single party to be able to disable replacement.
1070 // The opt-out ignores descendants as anyone relying on
1071 // first-seen mempool behavior should be checking all
1072 // unconfirmed ancestors anyway; doing otherwise is hopelessly
1073 // insecure.
1074 bool fReplacementOptOut = true;
1075 if (fEnableReplacement)
1077 BOOST_FOREACH(const CTxIn &txin, ptxConflicting->vin)
1079 if (txin.nSequence < std::numeric_limits<unsigned int>::max()-1)
1081 fReplacementOptOut = false;
1082 break;
1086 if (fReplacementOptOut)
1087 return state.Invalid(false, REJECT_CONFLICT, "txn-mempool-conflict");
1089 setConflicts.insert(ptxConflicting->GetHash());
1096 CCoinsView dummy;
1097 CCoinsViewCache view(&dummy);
1099 CAmount nValueIn = 0;
1100 LockPoints lp;
1102 LOCK(pool.cs);
1103 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1104 view.SetBackend(viewMemPool);
1106 // do we already have it?
1107 bool fHadTxInCache = pcoinsTip->HaveCoinsInCache(hash);
1108 if (view.HaveCoins(hash)) {
1109 if (!fHadTxInCache)
1110 vHashTxnToUncache.push_back(hash);
1111 return state.Invalid(false, REJECT_ALREADY_KNOWN, "txn-already-known");
1114 // do all inputs exist?
1115 // Note that this does not check for the presence of actual outputs (see the next check for that),
1116 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1117 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1118 if (!pcoinsTip->HaveCoinsInCache(txin.prevout.hash))
1119 vHashTxnToUncache.push_back(txin.prevout.hash);
1120 if (!view.HaveCoins(txin.prevout.hash)) {
1121 if (pfMissingInputs)
1122 *pfMissingInputs = true;
1123 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
1127 // are the actual inputs available?
1128 if (!view.HaveInputs(tx))
1129 return state.Invalid(false, REJECT_DUPLICATE, "bad-txns-inputs-spent");
1131 // Bring the best block into scope
1132 view.GetBestBlock();
1134 nValueIn = view.GetValueIn(tx);
1136 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1137 view.SetBackend(dummy);
1139 // Only accept BIP68 sequence locked transactions that can be mined in the next
1140 // block; we don't want our mempool filled up with transactions that can't
1141 // be mined yet.
1142 // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
1143 // CoinsViewCache instead of create its own
1144 if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
1145 return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
1148 // Check for non-standard pay-to-script-hash in inputs
1149 if (fRequireStandard && !AreInputsStandard(tx, view))
1150 return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
1152 unsigned int nSigOps = GetLegacySigOpCount(tx);
1153 nSigOps += GetP2SHSigOpCount(tx, view);
1155 CAmount nValueOut = tx.GetValueOut();
1156 CAmount nFees = nValueIn-nValueOut;
1157 // nModifiedFees includes any fee deltas from PrioritiseTransaction
1158 CAmount nModifiedFees = nFees;
1159 double nPriorityDummy = 0;
1160 pool.ApplyDeltas(hash, nPriorityDummy, nModifiedFees);
1162 CAmount inChainInputValue;
1163 double dPriority = view.GetPriority(tx, chainActive.Height(), inChainInputValue);
1165 // Keep track of transactions that spend a coinbase, which we re-scan
1166 // during reorgs to ensure COINBASE_MATURITY is still met.
1167 bool fSpendsCoinbase = false;
1168 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1169 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1170 if (coins->IsCoinBase()) {
1171 fSpendsCoinbase = true;
1172 break;
1176 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), pool.HasNoInputsOf(tx), inChainInputValue, fSpendsCoinbase, nSigOps, lp);
1177 unsigned int nSize = entry.GetTxSize();
1179 // Check that the transaction doesn't have an excessive number of
1180 // sigops, making it impossible to mine. Since the coinbase transaction
1181 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1182 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1183 // merely non-standard transaction.
1184 if ((nSigOps > MAX_STANDARD_TX_SIGOPS) || (nBytesPerSigOp && nSigOps > nSize / nBytesPerSigOp))
1185 return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
1186 strprintf("%d", nSigOps));
1188 CAmount mempoolRejectFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
1189 if (mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
1190 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
1191 } else if (GetBoolArg("-relaypriority", DEFAULT_RELAYPRIORITY) && nModifiedFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(entry.GetPriority(chainActive.Height() + 1))) {
1192 // Require that free transactions have sufficient priority to be mined in the next block.
1193 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1196 // Continuously rate-limit free (really, very-low-fee) transactions
1197 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1198 // be annoying or make others' transactions take longer to confirm.
1199 if (fLimitFree && nModifiedFees < ::minRelayTxFee.GetFee(nSize))
1201 static CCriticalSection csFreeLimiter;
1202 static double dFreeCount;
1203 static int64_t nLastTime;
1204 int64_t nNow = GetTime();
1206 LOCK(csFreeLimiter);
1208 // Use an exponentially decaying ~10-minute window:
1209 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1210 nLastTime = nNow;
1211 // -limitfreerelay unit is thousand-bytes-per-minute
1212 // At default rate it would take over a month to fill 1GB
1213 if (dFreeCount + nSize >= GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY) * 10 * 1000)
1214 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1215 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1216 dFreeCount += nSize;
1219 if (nAbsurdFee && nFees > nAbsurdFee)
1220 return state.Invalid(false,
1221 REJECT_HIGHFEE, "absurdly-high-fee",
1222 strprintf("%d > %d", nFees, nAbsurdFee));
1224 // Calculate in-mempool ancestors, up to a limit.
1225 CTxMemPool::setEntries setAncestors;
1226 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
1227 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
1228 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
1229 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
1230 std::string errString;
1231 if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
1232 return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
1235 // A transaction that spends outputs that would be replaced by it is invalid. Now
1236 // that we have the set of all ancestors we can detect this
1237 // pathological case by making sure setConflicts and setAncestors don't
1238 // intersect.
1239 BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors)
1241 const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
1242 if (setConflicts.count(hashAncestor))
1244 return state.DoS(10, false,
1245 REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
1246 strprintf("%s spends conflicting transaction %s",
1247 hash.ToString(),
1248 hashAncestor.ToString()));
1252 // Check if it's economically rational to mine this transaction rather
1253 // than the ones it replaces.
1254 CAmount nConflictingFees = 0;
1255 size_t nConflictingSize = 0;
1256 uint64_t nConflictingCount = 0;
1257 CTxMemPool::setEntries allConflicting;
1259 // If we don't hold the lock allConflicting might be incomplete; the
1260 // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
1261 // mempool consistency for us.
1262 LOCK(pool.cs);
1263 if (setConflicts.size())
1265 CFeeRate newFeeRate(nModifiedFees, nSize);
1266 set<uint256> setConflictsParents;
1267 const int maxDescendantsToVisit = 100;
1268 CTxMemPool::setEntries setIterConflicting;
1269 BOOST_FOREACH(const uint256 &hashConflicting, setConflicts)
1271 CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
1272 if (mi == pool.mapTx.end())
1273 continue;
1275 // Save these to avoid repeated lookups
1276 setIterConflicting.insert(mi);
1278 // Don't allow the replacement to reduce the feerate of the
1279 // mempool.
1281 // We usually don't want to accept replacements with lower
1282 // feerates than what they replaced as that would lower the
1283 // feerate of the next block. Requiring that the feerate always
1284 // be increased is also an easy-to-reason about way to prevent
1285 // DoS attacks via replacements.
1287 // The mining code doesn't (currently) take children into
1288 // account (CPFP) so we only consider the feerates of
1289 // transactions being directly replaced, not their indirect
1290 // descendants. While that does mean high feerate children are
1291 // ignored when deciding whether or not to replace, we do
1292 // require the replacement to pay more overall fees too,
1293 // mitigating most cases.
1294 CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
1295 if (newFeeRate <= oldFeeRate)
1297 return state.DoS(0, false,
1298 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
1299 strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
1300 hash.ToString(),
1301 newFeeRate.ToString(),
1302 oldFeeRate.ToString()));
1305 BOOST_FOREACH(const CTxIn &txin, mi->GetTx().vin)
1307 setConflictsParents.insert(txin.prevout.hash);
1310 nConflictingCount += mi->GetCountWithDescendants();
1312 // This potentially overestimates the number of actual descendants
1313 // but we just want to be conservative to avoid doing too much
1314 // work.
1315 if (nConflictingCount <= maxDescendantsToVisit) {
1316 // If not too many to replace, then calculate the set of
1317 // transactions that would have to be evicted
1318 BOOST_FOREACH(CTxMemPool::txiter it, setIterConflicting) {
1319 pool.CalculateDescendants(it, allConflicting);
1321 BOOST_FOREACH(CTxMemPool::txiter it, allConflicting) {
1322 nConflictingFees += it->GetModifiedFee();
1323 nConflictingSize += it->GetTxSize();
1325 } else {
1326 return state.DoS(0, false,
1327 REJECT_NONSTANDARD, "too many potential replacements", false,
1328 strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
1329 hash.ToString(),
1330 nConflictingCount,
1331 maxDescendantsToVisit));
1334 for (unsigned int j = 0; j < tx.vin.size(); j++)
1336 // We don't want to accept replacements that require low
1337 // feerate junk to be mined first. Ideally we'd keep track of
1338 // the ancestor feerates and make the decision based on that,
1339 // but for now requiring all new inputs to be confirmed works.
1340 if (!setConflictsParents.count(tx.vin[j].prevout.hash))
1342 // Rather than check the UTXO set - potentially expensive -
1343 // it's cheaper to just check if the new input refers to a
1344 // tx that's in the mempool.
1345 if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
1346 return state.DoS(0, false,
1347 REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
1348 strprintf("replacement %s adds unconfirmed input, idx %d",
1349 hash.ToString(), j));
1353 // The replacement must pay greater fees than the transactions it
1354 // replaces - if we did the bandwidth used by those conflicting
1355 // transactions would not be paid for.
1356 if (nModifiedFees < nConflictingFees)
1358 return state.DoS(0, false,
1359 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
1360 strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
1361 hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
1364 // Finally in addition to paying more fees than the conflicts the
1365 // new transaction must pay for its own bandwidth.
1366 CAmount nDeltaFees = nModifiedFees - nConflictingFees;
1367 if (nDeltaFees < ::minRelayTxFee.GetFee(nSize))
1369 return state.DoS(0, false,
1370 REJECT_INSUFFICIENTFEE, "insufficient fee", false,
1371 strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
1372 hash.ToString(),
1373 FormatMoney(nDeltaFees),
1374 FormatMoney(::minRelayTxFee.GetFee(nSize))));
1378 // Check against previous transactions
1379 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1380 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1381 return false; // state filled in by CheckInputs
1383 // Check again against just the consensus-critical mandatory script
1384 // verification flags, in case of bugs in the standard flags that cause
1385 // transactions to pass as valid when they're actually invalid. For
1386 // instance the STRICTENC flag was incorrectly allowing certain
1387 // CHECKSIG NOT scripts to pass, even though they were invalid.
1389 // There is a similar check in CreateNewBlock() to prevent creating
1390 // invalid blocks, however allowing such transactions into the mempool
1391 // can be exploited as a DoS attack.
1392 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1394 return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s, %s",
1395 __func__, hash.ToString(), FormatStateMessage(state));
1398 // Remove conflicting transactions from the mempool
1399 BOOST_FOREACH(const CTxMemPool::txiter it, allConflicting)
1401 LogPrint("mempool", "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
1402 it->GetTx().GetHash().ToString(),
1403 hash.ToString(),
1404 FormatMoney(nModifiedFees - nConflictingFees),
1405 (int)nSize - (int)nConflictingSize);
1407 pool.RemoveStaged(allConflicting, false);
1409 // Store transaction in memory
1410 pool.addUnchecked(hash, entry, setAncestors, !IsInitialBlockDownload());
1412 // trim mempool and check if tx was trimmed
1413 if (!fOverrideMempoolLimit) {
1414 LimitMempoolSize(pool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
1415 if (!pool.exists(hash))
1416 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
1420 SyncWithWallets(tx, NULL, NULL);
1422 return true;
1425 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1426 bool* pfMissingInputs, bool fOverrideMempoolLimit, const CAmount nAbsurdFee)
1428 std::vector<uint256> vHashTxToUncache;
1429 bool res = AcceptToMemoryPoolWorker(pool, state, tx, fLimitFree, pfMissingInputs, fOverrideMempoolLimit, nAbsurdFee, vHashTxToUncache);
1430 if (!res) {
1431 BOOST_FOREACH(const uint256& hashTx, vHashTxToUncache)
1432 pcoinsTip->Uncache(hashTx);
1434 return res;
1437 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1438 bool GetTransaction(const uint256 &hash, CTransaction &txOut, const Consensus::Params& consensusParams, uint256 &hashBlock, bool fAllowSlow)
1440 CBlockIndex *pindexSlow = NULL;
1442 LOCK(cs_main);
1444 if (mempool.lookup(hash, txOut))
1446 return true;
1449 if (fTxIndex) {
1450 CDiskTxPos postx;
1451 if (pblocktree->ReadTxIndex(hash, postx)) {
1452 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1453 if (file.IsNull())
1454 return error("%s: OpenBlockFile failed", __func__);
1455 CBlockHeader header;
1456 try {
1457 file >> header;
1458 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1459 file >> txOut;
1460 } catch (const std::exception& e) {
1461 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1463 hashBlock = header.GetHash();
1464 if (txOut.GetHash() != hash)
1465 return error("%s: txid mismatch", __func__);
1466 return true;
1470 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1471 int nHeight = -1;
1473 const CCoinsViewCache& view = *pcoinsTip;
1474 const CCoins* coins = view.AccessCoins(hash);
1475 if (coins)
1476 nHeight = coins->nHeight;
1478 if (nHeight > 0)
1479 pindexSlow = chainActive[nHeight];
1482 if (pindexSlow) {
1483 CBlock block;
1484 if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
1485 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1486 if (tx.GetHash() == hash) {
1487 txOut = tx;
1488 hashBlock = pindexSlow->GetBlockHash();
1489 return true;
1495 return false;
1503 //////////////////////////////////////////////////////////////////////////////
1505 // CBlock and CBlockIndex
1508 bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1510 // Open history file to append
1511 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1512 if (fileout.IsNull())
1513 return error("WriteBlockToDisk: OpenBlockFile failed");
1515 // Write index header
1516 unsigned int nSize = fileout.GetSerializeSize(block);
1517 fileout << FLATDATA(messageStart) << nSize;
1519 // Write block
1520 long fileOutPos = ftell(fileout.Get());
1521 if (fileOutPos < 0)
1522 return error("WriteBlockToDisk: ftell failed");
1523 pos.nPos = (unsigned int)fileOutPos;
1524 fileout << block;
1526 return true;
1529 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
1531 block.SetNull();
1533 // Open history file to read
1534 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1535 if (filein.IsNull())
1536 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1538 // Read block
1539 try {
1540 filein >> block;
1542 catch (const std::exception& e) {
1543 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1546 // Check the header
1547 if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
1548 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1550 return true;
1553 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
1555 if (!ReadBlockFromDisk(block, pindex->GetBlockPos(), consensusParams))
1556 return false;
1557 if (block.GetHash() != pindex->GetBlockHash())
1558 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1559 pindex->ToString(), pindex->GetBlockPos().ToString());
1560 return true;
1563 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1565 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1566 // Force block reward to zero when right shift is undefined.
1567 if (halvings >= 64)
1568 return 0;
1570 CAmount nSubsidy = 50 * COIN;
1571 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1572 nSubsidy >>= halvings;
1573 return nSubsidy;
1576 bool IsInitialBlockDownload()
1578 const CChainParams& chainParams = Params();
1579 LOCK(cs_main);
1580 if (fImporting || fReindex)
1581 return true;
1582 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1583 return true;
1584 static bool lockIBDState = false;
1585 if (lockIBDState)
1586 return false;
1587 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1588 std::max(chainActive.Tip()->GetBlockTime(), pindexBestHeader->GetBlockTime()) < GetTime() - nMaxTipAge);
1589 if (!state)
1590 lockIBDState = true;
1591 return state;
1594 bool fLargeWorkForkFound = false;
1595 bool fLargeWorkInvalidChainFound = false;
1596 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1598 static void AlertNotify(const std::string& strMessage)
1600 uiInterface.NotifyAlertChanged();
1601 std::string strCmd = GetArg("-alertnotify", "");
1602 if (strCmd.empty()) return;
1604 // Alert text should be plain ascii coming from a trusted source, but to
1605 // be safe we first strip anything not in safeChars, then add single quotes around
1606 // the whole string before passing it to the shell:
1607 std::string singleQuote("'");
1608 std::string safeStatus = SanitizeString(strMessage);
1609 safeStatus = singleQuote+safeStatus+singleQuote;
1610 boost::replace_all(strCmd, "%s", safeStatus);
1612 boost::thread t(runCommand, strCmd); // thread runs free
1615 void CheckForkWarningConditions()
1617 AssertLockHeld(cs_main);
1618 // Before we get past initial download, we cannot reliably alert about forks
1619 // (we assume we don't get stuck on a fork before the last checkpoint)
1620 if (IsInitialBlockDownload())
1621 return;
1623 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1624 // of our head, drop it
1625 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1626 pindexBestForkTip = NULL;
1628 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1630 if (!fLargeWorkForkFound && pindexBestForkBase)
1632 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1633 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1634 AlertNotify(warning);
1636 if (pindexBestForkTip && pindexBestForkBase)
1638 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__,
1639 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1640 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1641 fLargeWorkForkFound = true;
1643 else
1645 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1646 fLargeWorkInvalidChainFound = true;
1649 else
1651 fLargeWorkForkFound = false;
1652 fLargeWorkInvalidChainFound = false;
1656 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1658 AssertLockHeld(cs_main);
1659 // If we are on a fork that is sufficiently large, set a warning flag
1660 CBlockIndex* pfork = pindexNewForkTip;
1661 CBlockIndex* plonger = chainActive.Tip();
1662 while (pfork && pfork != plonger)
1664 while (plonger && plonger->nHeight > pfork->nHeight)
1665 plonger = plonger->pprev;
1666 if (pfork == plonger)
1667 break;
1668 pfork = pfork->pprev;
1671 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1672 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1673 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1674 // hash rate operating on the fork.
1675 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1676 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1677 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1678 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1679 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1680 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1682 pindexBestForkTip = pindexNewForkTip;
1683 pindexBestForkBase = pfork;
1686 CheckForkWarningConditions();
1689 // Requires cs_main.
1690 void Misbehaving(NodeId pnode, int howmuch)
1692 if (howmuch == 0)
1693 return;
1695 CNodeState *state = State(pnode);
1696 if (state == NULL)
1697 return;
1699 state->nMisbehavior += howmuch;
1700 int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
1701 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1703 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1704 state->fShouldBan = true;
1705 } else
1706 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1709 void static InvalidChainFound(CBlockIndex* pindexNew)
1711 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1712 pindexBestInvalid = pindexNew;
1714 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1715 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1716 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1717 pindexNew->GetBlockTime()));
1718 CBlockIndex *tip = chainActive.Tip();
1719 assert (tip);
1720 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1721 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1722 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1723 CheckForkWarningConditions();
1726 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1727 int nDoS = 0;
1728 if (state.IsInvalid(nDoS)) {
1729 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1730 if (it != mapBlockSource.end() && State(it->second)) {
1731 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
1732 CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1733 State(it->second)->rejects.push_back(reject);
1734 if (nDoS > 0)
1735 Misbehaving(it->second, nDoS);
1738 if (!state.CorruptionPossible()) {
1739 pindex->nStatus |= BLOCK_FAILED_VALID;
1740 setDirtyBlockIndex.insert(pindex);
1741 setBlockIndexCandidates.erase(pindex);
1742 InvalidChainFound(pindex);
1746 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1748 // mark inputs spent
1749 if (!tx.IsCoinBase()) {
1750 txundo.vprevout.reserve(tx.vin.size());
1751 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1752 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1753 unsigned nPos = txin.prevout.n;
1755 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1756 assert(false);
1757 // mark an outpoint spent, and construct undo information
1758 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1759 coins->Spend(nPos);
1760 if (coins->vout.size() == 0) {
1761 CTxInUndo& undo = txundo.vprevout.back();
1762 undo.nHeight = coins->nHeight;
1763 undo.fCoinBase = coins->fCoinBase;
1764 undo.nVersion = coins->nVersion;
1768 // add outputs
1769 inputs.ModifyNewCoins(tx.GetHash(), tx.IsCoinBase())->FromTx(tx, nHeight);
1772 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1774 CTxUndo txundo;
1775 UpdateCoins(tx, inputs, txundo, nHeight);
1778 bool CScriptCheck::operator()() {
1779 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1780 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1781 return false;
1783 return true;
1786 int GetSpendHeight(const CCoinsViewCache& inputs)
1788 LOCK(cs_main);
1789 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1790 return pindexPrev->nHeight + 1;
1793 namespace Consensus {
1794 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight)
1796 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1797 // for an attacker to attempt to split the network.
1798 if (!inputs.HaveInputs(tx))
1799 return state.Invalid(false, 0, "", "Inputs unavailable");
1801 CAmount nValueIn = 0;
1802 CAmount nFees = 0;
1803 for (unsigned int i = 0; i < tx.vin.size(); i++)
1805 const COutPoint &prevout = tx.vin[i].prevout;
1806 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1807 assert(coins);
1809 // If prev is coinbase, check that it's matured
1810 if (coins->IsCoinBase()) {
1811 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1812 return state.Invalid(false,
1813 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase",
1814 strprintf("tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight));
1817 // Check for negative or overflow input values
1818 nValueIn += coins->vout[prevout.n].nValue;
1819 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1820 return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1824 if (nValueIn < tx.GetValueOut())
1825 return state.DoS(100, false, REJECT_INVALID, "bad-txns-in-belowout", false,
1826 strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())));
1828 // Tally transaction fees
1829 CAmount nTxFee = nValueIn - tx.GetValueOut();
1830 if (nTxFee < 0)
1831 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-negative");
1832 nFees += nTxFee;
1833 if (!MoneyRange(nFees))
1834 return state.DoS(100, false, REJECT_INVALID, "bad-txns-fee-outofrange");
1835 return true;
1837 }// namespace Consensus
1839 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1841 if (!tx.IsCoinBase())
1843 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs)))
1844 return false;
1846 if (pvChecks)
1847 pvChecks->reserve(tx.vin.size());
1849 // The first loop above does all the inexpensive checks.
1850 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1851 // Helps prevent CPU exhaustion attacks.
1853 // Skip ECDSA signature verification when connecting blocks before the
1854 // last block chain checkpoint. Assuming the checkpoints are valid this
1855 // is safe because block merkle hashes are still computed and checked,
1856 // and any change will be caught at the next checkpoint. Of course, if
1857 // the checkpoint is for a chain that's invalid due to false scriptSigs
1858 // this optimisation would allow an invalid chain to be accepted.
1859 if (fScriptChecks) {
1860 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1861 const COutPoint &prevout = tx.vin[i].prevout;
1862 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1863 assert(coins);
1865 // Verify signature
1866 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1867 if (pvChecks) {
1868 pvChecks->push_back(CScriptCheck());
1869 check.swap(pvChecks->back());
1870 } else if (!check()) {
1871 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1872 // Check whether the failure was caused by a
1873 // non-mandatory script verification check, such as
1874 // non-standard DER encodings or non-null dummy
1875 // arguments; if so, don't trigger DoS protection to
1876 // avoid splitting the network between upgraded and
1877 // non-upgraded nodes.
1878 CScriptCheck check2(*coins, tx, i,
1879 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1880 if (check2())
1881 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1883 // Failures of other flags indicate a transaction that is
1884 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1885 // such nodes as they are not following the protocol. That
1886 // said during an upgrade careful thought should be taken
1887 // as to the correct behavior - we may want to continue
1888 // peering with non-upgraded nodes even after a soft-fork
1889 // super-majority vote has passed.
1890 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1896 return true;
1899 namespace {
1901 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1903 // Open history file to append
1904 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1905 if (fileout.IsNull())
1906 return error("%s: OpenUndoFile failed", __func__);
1908 // Write index header
1909 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1910 fileout << FLATDATA(messageStart) << nSize;
1912 // Write undo data
1913 long fileOutPos = ftell(fileout.Get());
1914 if (fileOutPos < 0)
1915 return error("%s: ftell failed", __func__);
1916 pos.nPos = (unsigned int)fileOutPos;
1917 fileout << blockundo;
1919 // calculate & write checksum
1920 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1921 hasher << hashBlock;
1922 hasher << blockundo;
1923 fileout << hasher.GetHash();
1925 return true;
1928 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1930 // Open history file to read
1931 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1932 if (filein.IsNull())
1933 return error("%s: OpenBlockFile failed", __func__);
1935 // Read block
1936 uint256 hashChecksum;
1937 try {
1938 filein >> blockundo;
1939 filein >> hashChecksum;
1941 catch (const std::exception& e) {
1942 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1945 // Verify checksum
1946 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1947 hasher << hashBlock;
1948 hasher << blockundo;
1949 if (hashChecksum != hasher.GetHash())
1950 return error("%s: Checksum mismatch", __func__);
1952 return true;
1955 /** Abort with a message */
1956 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1958 strMiscWarning = strMessage;
1959 LogPrintf("*** %s\n", strMessage);
1960 uiInterface.ThreadSafeMessageBox(
1961 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1962 "", CClientUIInterface::MSG_ERROR);
1963 StartShutdown();
1964 return false;
1967 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1969 AbortNode(strMessage, userMessage);
1970 return state.Error(strMessage);
1973 } // anon namespace
1976 * Apply the undo operation of a CTxInUndo to the given chain state.
1977 * @param undo The undo object.
1978 * @param view The coins view to which to apply the changes.
1979 * @param out The out point that corresponds to the tx input.
1980 * @return True on success.
1982 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1984 bool fClean = true;
1986 CCoinsModifier coins = view.ModifyCoins(out.hash);
1987 if (undo.nHeight != 0) {
1988 // undo data contains height: this is the last output of the prevout tx being spent
1989 if (!coins->IsPruned())
1990 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1991 coins->Clear();
1992 coins->fCoinBase = undo.fCoinBase;
1993 coins->nHeight = undo.nHeight;
1994 coins->nVersion = undo.nVersion;
1995 } else {
1996 if (coins->IsPruned())
1997 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1999 if (coins->IsAvailable(out.n))
2000 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2001 if (coins->vout.size() < out.n+1)
2002 coins->vout.resize(out.n+1);
2003 coins->vout[out.n] = undo.txout;
2005 return fClean;
2008 bool DisconnectBlock(const CBlock& block, CValidationState& state, const CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2010 assert(pindex->GetBlockHash() == view.GetBestBlock());
2012 if (pfClean)
2013 *pfClean = false;
2015 bool fClean = true;
2017 CBlockUndo blockUndo;
2018 CDiskBlockPos pos = pindex->GetUndoPos();
2019 if (pos.IsNull())
2020 return error("DisconnectBlock(): no undo data available");
2021 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2022 return error("DisconnectBlock(): failure reading undo data");
2024 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2025 return error("DisconnectBlock(): block and undo data inconsistent");
2027 // undo transactions in reverse order
2028 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2029 const CTransaction &tx = block.vtx[i];
2030 uint256 hash = tx.GetHash();
2032 // Check that all outputs are available and match the outputs in the block itself
2033 // exactly.
2035 CCoinsModifier outs = view.ModifyCoins(hash);
2036 outs->ClearUnspendable();
2038 CCoins outsBlock(tx, pindex->nHeight);
2039 // The CCoins serialization does not serialize negative numbers.
2040 // No network rules currently depend on the version here, so an inconsistency is harmless
2041 // but it must be corrected before txout nversion ever influences a network rule.
2042 if (outsBlock.nVersion < 0)
2043 outs->nVersion = outsBlock.nVersion;
2044 if (*outs != outsBlock)
2045 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2047 // remove outputs
2048 outs->Clear();
2051 // restore inputs
2052 if (i > 0) { // not coinbases
2053 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2054 if (txundo.vprevout.size() != tx.vin.size())
2055 return error("DisconnectBlock(): transaction and undo data inconsistent");
2056 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2057 const COutPoint &out = tx.vin[j].prevout;
2058 const CTxInUndo &undo = txundo.vprevout[j];
2059 if (!ApplyTxInUndo(undo, view, out))
2060 fClean = false;
2065 // move best block pointer to prevout block
2066 view.SetBestBlock(pindex->pprev->GetBlockHash());
2068 if (pfClean) {
2069 *pfClean = fClean;
2070 return true;
2073 return fClean;
2076 void static FlushBlockFile(bool fFinalize = false)
2078 LOCK(cs_LastBlockFile);
2080 CDiskBlockPos posOld(nLastBlockFile, 0);
2082 FILE *fileOld = OpenBlockFile(posOld);
2083 if (fileOld) {
2084 if (fFinalize)
2085 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2086 FileCommit(fileOld);
2087 fclose(fileOld);
2090 fileOld = OpenUndoFile(posOld);
2091 if (fileOld) {
2092 if (fFinalize)
2093 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2094 FileCommit(fileOld);
2095 fclose(fileOld);
2099 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2101 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2103 void ThreadScriptCheck() {
2104 RenameThread("bitcoin-scriptch");
2105 scriptcheckqueue.Thread();
2109 // Called periodically asynchronously; alerts if it smells like
2110 // we're being fed a bad chain (blocks being generated much
2111 // too slowly or too quickly).
2113 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2114 int64_t nPowTargetSpacing)
2116 if (bestHeader == NULL || initialDownloadCheck()) return;
2118 static int64_t lastAlertTime = 0;
2119 int64_t now = GetAdjustedTime();
2120 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2122 const int SPAN_HOURS=4;
2123 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2124 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2126 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2128 std::string strWarning;
2129 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2131 LOCK(cs);
2132 const CBlockIndex* i = bestHeader;
2133 int nBlocks = 0;
2134 while (i->GetBlockTime() >= startTime) {
2135 ++nBlocks;
2136 i = i->pprev;
2137 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2140 // How likely is it to find that many by chance?
2141 double p = boost::math::pdf(poisson, nBlocks);
2143 LogPrint("partitioncheck", "%s: Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2144 LogPrint("partitioncheck", "%s: likelihood: %g\n", __func__, p);
2146 // Aim for one false-positive about every fifty years of normal running:
2147 const int FIFTY_YEARS = 50*365*24*60*60;
2148 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2150 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2152 // Many fewer blocks than expected: alert!
2153 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2154 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2156 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2158 // Many more blocks than expected: alert!
2159 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2160 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2162 if (!strWarning.empty())
2164 strMiscWarning = strWarning;
2165 AlertNotify(strWarning);
2166 lastAlertTime = now;
2170 // Protected by cs_main
2171 static VersionBitsCache versionbitscache;
2173 int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
2175 LOCK(cs_main);
2176 int32_t nVersion = VERSIONBITS_TOP_BITS;
2178 for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
2179 ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
2180 if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
2181 nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
2185 return nVersion;
2189 * Threshold condition checker that triggers when unknown versionbits are seen on the network.
2191 class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
2193 private:
2194 int bit;
2196 public:
2197 WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
2199 int64_t BeginTime(const Consensus::Params& params) const { return 0; }
2200 int64_t EndTime(const Consensus::Params& params) const { return std::numeric_limits<int64_t>::max(); }
2201 int Period(const Consensus::Params& params) const { return params.nMinerConfirmationWindow; }
2202 int Threshold(const Consensus::Params& params) const { return params.nRuleChangeActivationThreshold; }
2204 bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const
2206 return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
2207 ((pindex->nVersion >> bit) & 1) != 0 &&
2208 ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
2212 // Protected by cs_main
2213 static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
2215 static int64_t nTimeCheck = 0;
2216 static int64_t nTimeForks = 0;
2217 static int64_t nTimeVerify = 0;
2218 static int64_t nTimeConnect = 0;
2219 static int64_t nTimeIndex = 0;
2220 static int64_t nTimeCallbacks = 0;
2221 static int64_t nTimeTotal = 0;
2223 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
2224 CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
2226 AssertLockHeld(cs_main);
2228 int64_t nTimeStart = GetTimeMicros();
2230 // Check it again in case a previous version let a bad block in
2231 if (!CheckBlock(block, state, chainparams.GetConsensus(), GetAdjustedTime(), !fJustCheck, !fJustCheck))
2232 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
2234 // verify that the view's current state corresponds to the previous block
2235 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2236 assert(hashPrevBlock == view.GetBestBlock());
2238 // Special case for the genesis block, skipping connection of its transactions
2239 // (its coinbase is unspendable)
2240 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2241 if (!fJustCheck)
2242 view.SetBestBlock(pindex->GetBlockHash());
2243 return true;
2246 bool fScriptChecks = true;
2247 if (fCheckpointsEnabled) {
2248 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2249 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2250 // This block is an ancestor of a checkpoint: disable script checks
2251 fScriptChecks = false;
2255 int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
2256 LogPrint("bench", " - Sanity checks: %.2fms [%.2fs]\n", 0.001 * (nTime1 - nTimeStart), nTimeCheck * 0.000001);
2258 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2259 // unless those are already completely spent.
2260 // If such overwrites are allowed, coinbases and transactions depending upon those
2261 // can be duplicated to remove the ability to spend the first instance -- even after
2262 // being sent to another address.
2263 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
2264 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2265 // already refuses previously-known transaction ids entirely.
2266 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2267 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2268 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2269 // initial block download.
2270 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
2271 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2272 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2274 // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
2275 // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
2276 // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
2277 // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
2278 // duplicate transactions descending from the known pairs either.
2279 // 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.
2280 CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
2281 //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
2282 fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
2284 if (fEnforceBIP30) {
2285 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2286 const CCoins* coins = view.AccessCoins(tx.GetHash());
2287 if (coins && !coins->IsPruned())
2288 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2289 REJECT_INVALID, "bad-txns-BIP30");
2293 // BIP16 didn't become active until Apr 1 2012
2294 int64_t nBIP16SwitchTime = 1333238400;
2295 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
2297 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
2299 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2300 // when 75% of the network has upgraded:
2301 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
2302 flags |= SCRIPT_VERIFY_DERSIG;
2305 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2306 // blocks, when 75% of the network has upgraded:
2307 if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
2308 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2311 // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
2312 int nLockTimeFlags = 0;
2313 if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
2314 flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
2315 nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
2318 int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
2319 LogPrint("bench", " - Fork checks: %.2fms [%.2fs]\n", 0.001 * (nTime2 - nTime1), nTimeForks * 0.000001);
2321 CBlockUndo blockundo;
2323 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2325 std::vector<int> prevheights;
2326 CAmount nFees = 0;
2327 int nInputs = 0;
2328 unsigned int nSigOps = 0;
2329 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2330 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2331 vPos.reserve(block.vtx.size());
2332 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2333 for (unsigned int i = 0; i < block.vtx.size(); i++)
2335 const CTransaction &tx = block.vtx[i];
2337 nInputs += tx.vin.size();
2338 nSigOps += GetLegacySigOpCount(tx);
2339 if (nSigOps > MAX_BLOCK_SIGOPS)
2340 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2341 REJECT_INVALID, "bad-blk-sigops");
2343 if (!tx.IsCoinBase())
2345 if (!view.HaveInputs(tx))
2346 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2347 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2349 // Check that transaction is BIP68 final
2350 // BIP68 lock checks (as opposed to nLockTime checks) must
2351 // be in ConnectBlock because they require the UTXO set
2352 prevheights.resize(tx.vin.size());
2353 for (size_t j = 0; j < tx.vin.size(); j++) {
2354 prevheights[j] = view.AccessCoins(tx.vin[j].prevout.hash)->nHeight;
2357 if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
2358 return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
2359 REJECT_INVALID, "bad-txns-nonfinal");
2362 if (fStrictPayToScriptHash)
2364 // Add in sigops done by pay-to-script-hash inputs;
2365 // this is to prevent a "rogue miner" from creating
2366 // an incredibly-expensive-to-validate block.
2367 nSigOps += GetP2SHSigOpCount(tx, view);
2368 if (nSigOps > MAX_BLOCK_SIGOPS)
2369 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2370 REJECT_INVALID, "bad-blk-sigops");
2373 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2375 std::vector<CScriptCheck> vChecks;
2376 bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
2377 if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, nScriptCheckThreads ? &vChecks : NULL))
2378 return error("ConnectBlock(): CheckInputs on %s failed with %s",
2379 tx.GetHash().ToString(), FormatStateMessage(state));
2380 control.Add(vChecks);
2383 CTxUndo undoDummy;
2384 if (i > 0) {
2385 blockundo.vtxundo.push_back(CTxUndo());
2387 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2389 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2390 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2392 int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
2393 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);
2395 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2396 if (block.vtx[0].GetValueOut() > blockReward)
2397 return state.DoS(100,
2398 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2399 block.vtx[0].GetValueOut(), blockReward),
2400 REJECT_INVALID, "bad-cb-amount");
2402 if (!control.Wait())
2403 return state.DoS(100, false);
2404 int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
2405 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);
2407 if (fJustCheck)
2408 return true;
2410 // Write undo information to disk
2411 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2413 if (pindex->GetUndoPos().IsNull()) {
2414 CDiskBlockPos pos;
2415 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2416 return error("ConnectBlock(): FindUndoPos failed");
2417 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2418 return AbortNode(state, "Failed to write undo data");
2420 // update nUndoPos in block index
2421 pindex->nUndoPos = pos.nPos;
2422 pindex->nStatus |= BLOCK_HAVE_UNDO;
2425 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2426 setDirtyBlockIndex.insert(pindex);
2429 if (fTxIndex)
2430 if (!pblocktree->WriteTxIndex(vPos))
2431 return AbortNode(state, "Failed to write transaction index");
2433 // add this block to the view's block chain
2434 view.SetBestBlock(pindex->GetBlockHash());
2436 int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
2437 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime5 - nTime4), nTimeIndex * 0.000001);
2439 // Watch for changes to the previous coinbase transaction.
2440 static uint256 hashPrevBestCoinBase;
2441 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2442 hashPrevBestCoinBase = block.vtx[0].GetHash();
2444 int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
2445 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime6 - nTime5), nTimeCallbacks * 0.000001);
2447 return true;
2450 enum FlushStateMode {
2451 FLUSH_STATE_NONE,
2452 FLUSH_STATE_IF_NEEDED,
2453 FLUSH_STATE_PERIODIC,
2454 FLUSH_STATE_ALWAYS
2458 * Update the on-disk chain state.
2459 * The caches and indexes are flushed depending on the mode we're called with
2460 * if they're too large, if it's been a while since the last write,
2461 * or always and in all cases if we're in prune mode and are deleting files.
2463 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2464 const CChainParams& chainparams = Params();
2465 LOCK2(cs_main, cs_LastBlockFile);
2466 static int64_t nLastWrite = 0;
2467 static int64_t nLastFlush = 0;
2468 static int64_t nLastSetChain = 0;
2469 std::set<int> setFilesToPrune;
2470 bool fFlushForPrune = false;
2471 try {
2472 if (fPruneMode && fCheckForPruning && !fReindex) {
2473 FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
2474 fCheckForPruning = false;
2475 if (!setFilesToPrune.empty()) {
2476 fFlushForPrune = true;
2477 if (!fHavePruned) {
2478 pblocktree->WriteFlag("prunedblockfiles", true);
2479 fHavePruned = true;
2483 int64_t nNow = GetTimeMicros();
2484 // Avoid writing/flushing immediately after startup.
2485 if (nLastWrite == 0) {
2486 nLastWrite = nNow;
2488 if (nLastFlush == 0) {
2489 nLastFlush = nNow;
2491 if (nLastSetChain == 0) {
2492 nLastSetChain = nNow;
2494 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2495 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2496 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2497 // The cache is over the limit, we have to write now.
2498 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2499 // 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.
2500 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2501 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2502 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2503 // Combine all conditions that result in a full cache flush.
2504 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2505 // Write blocks and block index to disk.
2506 if (fDoFullFlush || fPeriodicWrite) {
2507 // Depend on nMinDiskSpace to ensure we can write block index
2508 if (!CheckDiskSpace(0))
2509 return state.Error("out of disk space");
2510 // First make sure all block and undo data is flushed to disk.
2511 FlushBlockFile();
2512 // Then update all block file information (which may refer to block and undo files).
2514 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2515 vFiles.reserve(setDirtyFileInfo.size());
2516 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2517 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2518 setDirtyFileInfo.erase(it++);
2520 std::vector<const CBlockIndex*> vBlocks;
2521 vBlocks.reserve(setDirtyBlockIndex.size());
2522 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2523 vBlocks.push_back(*it);
2524 setDirtyBlockIndex.erase(it++);
2526 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2527 return AbortNode(state, "Files to write to block index database");
2530 // Finally remove any pruned files
2531 if (fFlushForPrune)
2532 UnlinkPrunedFiles(setFilesToPrune);
2533 nLastWrite = nNow;
2535 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2536 if (fDoFullFlush) {
2537 // Typical CCoins structures on disk are around 128 bytes in size.
2538 // Pushing a new one to the database can cause it to be written
2539 // twice (once in the log, and once in the tables). This is already
2540 // an overestimation, as most will delete an existing entry or
2541 // overwrite one. Still, use a conservative safety factor of 2.
2542 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2543 return state.Error("out of disk space");
2544 // Flush the chainstate (which may refer to block index entries).
2545 if (!pcoinsTip->Flush())
2546 return AbortNode(state, "Failed to write to coin database");
2547 nLastFlush = nNow;
2549 if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
2550 // Update best block in wallet (so we can detect restored wallets).
2551 GetMainSignals().SetBestChain(chainActive.GetLocator());
2552 nLastSetChain = nNow;
2554 } catch (const std::runtime_error& e) {
2555 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2557 return true;
2560 void FlushStateToDisk() {
2561 CValidationState state;
2562 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2565 void PruneAndFlush() {
2566 CValidationState state;
2567 fCheckForPruning = true;
2568 FlushStateToDisk(state, FLUSH_STATE_NONE);
2571 /** Update chainActive and related internal data structures. */
2572 void static UpdateTip(CBlockIndex *pindexNew, const CChainParams& chainParams) {
2573 chainActive.SetTip(pindexNew);
2575 // New best block
2576 nTimeBestReceived = GetTime();
2577 mempool.AddTransactionsUpdated(1);
2579 cvBlockChange.notify_all();
2581 static bool fWarned = false;
2582 std::vector<std::string> warningMessages;
2583 if (!IsInitialBlockDownload())
2585 int nUpgraded = 0;
2586 const CBlockIndex* pindex = chainActive.Tip();
2587 for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
2588 WarningBitsConditionChecker checker(bit);
2589 ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
2590 if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
2591 if (state == THRESHOLD_ACTIVE) {
2592 strMiscWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
2593 if (!fWarned) {
2594 AlertNotify(strMiscWarning);
2595 fWarned = true;
2597 } else {
2598 warningMessages.push_back(strprintf("unknown new rules are about to activate (versionbit %i)", bit));
2602 // Check the version of the last 100 blocks to see if we need to upgrade:
2603 for (int i = 0; i < 100 && pindex != NULL; i++)
2605 int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
2606 if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
2607 ++nUpgraded;
2608 pindex = pindex->pprev;
2610 if (nUpgraded > 0)
2611 warningMessages.push_back(strprintf("%d of last 100 blocks have unexpected version", nUpgraded));
2612 if (nUpgraded > 100/2)
2614 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2615 strMiscWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
2616 if (!fWarned) {
2617 AlertNotify(strMiscWarning);
2618 fWarned = true;
2622 LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utx)", __func__,
2623 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion,
2624 log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2625 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2626 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2627 if (!warningMessages.empty())
2628 LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
2629 LogPrintf("\n");
2633 /** Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and manually re-limit mempool size after this, with cs_main held. */
2634 bool static DisconnectTip(CValidationState& state, const CChainParams& chainparams)
2636 CBlockIndex *pindexDelete = chainActive.Tip();
2637 assert(pindexDelete);
2638 // Read block from disk.
2639 CBlock block;
2640 if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
2641 return AbortNode(state, "Failed to read block");
2642 // Apply the block atomically to the chain state.
2643 int64_t nStart = GetTimeMicros();
2645 CCoinsViewCache view(pcoinsTip);
2646 if (!DisconnectBlock(block, state, pindexDelete, view))
2647 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2648 assert(view.Flush());
2650 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2651 // Write the chain state to disk, if necessary.
2652 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2653 return false;
2654 // Resurrect mempool transactions from the disconnected block.
2655 std::vector<uint256> vHashUpdate;
2656 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2657 // ignore validation errors in resurrected transactions
2658 list<CTransaction> removed;
2659 CValidationState stateDummy;
2660 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL, true)) {
2661 mempool.removeRecursive(tx, removed);
2662 } else if (mempool.exists(tx.GetHash())) {
2663 vHashUpdate.push_back(tx.GetHash());
2666 // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
2667 // no in-mempool children, which is generally not true when adding
2668 // previously-confirmed transactions back to the mempool.
2669 // UpdateTransactionsFromBlock finds descendants of any transactions in this
2670 // block that were added back and cleans up the mempool state.
2671 mempool.UpdateTransactionsFromBlock(vHashUpdate);
2672 // Update chainActive and related variables.
2673 UpdateTip(pindexDelete->pprev, chainparams);
2674 // Let wallets know transactions went from 1-confirmed to
2675 // 0-confirmed or conflicted:
2676 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2677 SyncWithWallets(tx, pindexDelete->pprev, NULL);
2679 return true;
2682 static int64_t nTimeReadFromDisk = 0;
2683 static int64_t nTimeConnectTotal = 0;
2684 static int64_t nTimeFlush = 0;
2685 static int64_t nTimeChainState = 0;
2686 static int64_t nTimePostConnect = 0;
2689 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2690 * corresponding to pindexNew, to bypass loading it again from disk.
2692 bool static ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const CBlock* pblock)
2694 assert(pindexNew->pprev == chainActive.Tip());
2695 // Read block from disk.
2696 int64_t nTime1 = GetTimeMicros();
2697 CBlock block;
2698 if (!pblock) {
2699 if (!ReadBlockFromDisk(block, pindexNew, chainparams.GetConsensus()))
2700 return AbortNode(state, "Failed to read block");
2701 pblock = &block;
2703 // Apply the block atomically to the chain state.
2704 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2705 int64_t nTime3;
2706 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2708 CCoinsViewCache view(pcoinsTip);
2709 bool rv = ConnectBlock(*pblock, state, pindexNew, view, chainparams);
2710 GetMainSignals().BlockChecked(*pblock, state);
2711 if (!rv) {
2712 if (state.IsInvalid())
2713 InvalidBlockFound(pindexNew, state);
2714 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2716 mapBlockSource.erase(pindexNew->GetBlockHash());
2717 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2718 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2719 assert(view.Flush());
2721 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2722 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2723 // Write the chain state to disk, if necessary.
2724 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2725 return false;
2726 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2727 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2728 // Remove conflicting transactions from the mempool.
2729 list<CTransaction> txConflicted;
2730 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2731 // Update chainActive & related variables.
2732 UpdateTip(pindexNew, chainparams);
2733 // Tell wallet about transactions that went from mempool
2734 // to conflicted:
2735 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2736 SyncWithWallets(tx, pindexNew, NULL);
2738 // ... and about transactions that got confirmed:
2739 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2740 SyncWithWallets(tx, pindexNew, pblock);
2743 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2744 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2745 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2746 return true;
2750 * Return the tip of the chain with the most work in it, that isn't
2751 * known to be invalid (it's however far from certain to be valid).
2753 static CBlockIndex* FindMostWorkChain() {
2754 do {
2755 CBlockIndex *pindexNew = NULL;
2757 // Find the best candidate header.
2759 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2760 if (it == setBlockIndexCandidates.rend())
2761 return NULL;
2762 pindexNew = *it;
2765 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2766 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2767 CBlockIndex *pindexTest = pindexNew;
2768 bool fInvalidAncestor = false;
2769 while (pindexTest && !chainActive.Contains(pindexTest)) {
2770 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2772 // Pruned nodes may have entries in setBlockIndexCandidates for
2773 // which block files have been deleted. Remove those as candidates
2774 // for the most work chain if we come across them; we can't switch
2775 // to a chain unless we have all the non-active-chain parent blocks.
2776 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2777 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2778 if (fFailedChain || fMissingData) {
2779 // Candidate chain is not usable (either invalid or missing data)
2780 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2781 pindexBestInvalid = pindexNew;
2782 CBlockIndex *pindexFailed = pindexNew;
2783 // Remove the entire chain from the set.
2784 while (pindexTest != pindexFailed) {
2785 if (fFailedChain) {
2786 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2787 } else if (fMissingData) {
2788 // If we're missing data, then add back to mapBlocksUnlinked,
2789 // so that if the block arrives in the future we can try adding
2790 // to setBlockIndexCandidates again.
2791 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2793 setBlockIndexCandidates.erase(pindexFailed);
2794 pindexFailed = pindexFailed->pprev;
2796 setBlockIndexCandidates.erase(pindexTest);
2797 fInvalidAncestor = true;
2798 break;
2800 pindexTest = pindexTest->pprev;
2802 if (!fInvalidAncestor)
2803 return pindexNew;
2804 } while(true);
2807 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2808 static void PruneBlockIndexCandidates() {
2809 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2810 // reorganization to a better block fails.
2811 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2812 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2813 setBlockIndexCandidates.erase(it++);
2815 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2816 assert(!setBlockIndexCandidates.empty());
2820 * Try to make some progress towards making pindexMostWork the active block.
2821 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2823 static bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const CBlock* pblock, bool& fInvalidFound)
2825 AssertLockHeld(cs_main);
2826 const CBlockIndex *pindexOldTip = chainActive.Tip();
2827 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2829 // Disconnect active blocks which are no longer in the best chain.
2830 bool fBlocksDisconnected = false;
2831 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2832 if (!DisconnectTip(state, chainparams))
2833 return false;
2834 fBlocksDisconnected = true;
2837 // Build list of new blocks to connect.
2838 std::vector<CBlockIndex*> vpindexToConnect;
2839 bool fContinue = true;
2840 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2841 while (fContinue && nHeight != pindexMostWork->nHeight) {
2842 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2843 // a few blocks along the way.
2844 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2845 vpindexToConnect.clear();
2846 vpindexToConnect.reserve(nTargetHeight - nHeight);
2847 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2848 while (pindexIter && pindexIter->nHeight != nHeight) {
2849 vpindexToConnect.push_back(pindexIter);
2850 pindexIter = pindexIter->pprev;
2852 nHeight = nTargetHeight;
2854 // Connect new blocks.
2855 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2856 if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2857 if (state.IsInvalid()) {
2858 // The block violates a consensus rule.
2859 if (!state.CorruptionPossible())
2860 InvalidChainFound(vpindexToConnect.back());
2861 state = CValidationState();
2862 fInvalidFound = true;
2863 fContinue = false;
2864 break;
2865 } else {
2866 // A system error occurred (disk space, database error, ...).
2867 return false;
2869 } else {
2870 PruneBlockIndexCandidates();
2871 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2872 // We're in a better position than we were. Return temporarily to release the lock.
2873 fContinue = false;
2874 break;
2880 if (fBlocksDisconnected) {
2881 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2882 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
2884 mempool.check(pcoinsTip);
2886 // Callbacks/notifications for a new best chain.
2887 if (fInvalidFound)
2888 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2889 else
2890 CheckForkWarningConditions();
2892 return true;
2895 static void NotifyHeaderTip() {
2896 bool fNotify = false;
2897 bool fInitialBlockDownload = false;
2898 static CBlockIndex* pindexHeaderOld = NULL;
2899 CBlockIndex* pindexHeader = NULL;
2901 LOCK(cs_main);
2902 if (!setBlockIndexCandidates.empty()) {
2903 pindexHeader = *setBlockIndexCandidates.rbegin();
2905 if (pindexHeader != pindexHeaderOld) {
2906 fNotify = true;
2907 fInitialBlockDownload = IsInitialBlockDownload();
2908 pindexHeaderOld = pindexHeader;
2911 // Send block tip changed notifications without cs_main
2912 if (fNotify) {
2913 uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
2918 * Make the best chain active, in multiple steps. The result is either failure
2919 * or an activated best chain. pblock is either NULL or a pointer to a block
2920 * that is already loaded (to avoid loading it again from disk).
2922 bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, const CBlock *pblock) {
2923 CBlockIndex *pindexMostWork = NULL;
2924 do {
2925 boost::this_thread::interruption_point();
2926 if (ShutdownRequested())
2927 break;
2929 CBlockIndex *pindexNewTip = NULL;
2930 const CBlockIndex *pindexFork;
2931 bool fInitialDownload;
2933 LOCK(cs_main);
2934 CBlockIndex *pindexOldTip = chainActive.Tip();
2935 if (pindexMostWork == NULL) {
2936 pindexMostWork = FindMostWorkChain();
2939 // Whether we have anything to do at all.
2940 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2941 return true;
2943 bool fInvalidFound = false;
2944 if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fInvalidFound))
2945 return false;
2947 if (fInvalidFound) {
2948 // Wipe cache, we may need another branch now.
2949 pindexMostWork = NULL;
2951 pindexNewTip = chainActive.Tip();
2952 pindexFork = chainActive.FindFork(pindexOldTip);
2953 fInitialDownload = IsInitialBlockDownload();
2955 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2957 // Notifications/callbacks that can run without cs_main
2958 // Always notify the UI if a new block tip was connected
2959 if (pindexFork != pindexNewTip) {
2960 uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
2962 if (!fInitialDownload) {
2963 // Find the hashes of all blocks that weren't previously in the best chain.
2964 std::vector<uint256> vHashes;
2965 CBlockIndex *pindexToAnnounce = pindexNewTip;
2966 while (pindexToAnnounce != pindexFork) {
2967 vHashes.push_back(pindexToAnnounce->GetBlockHash());
2968 pindexToAnnounce = pindexToAnnounce->pprev;
2969 if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
2970 // Limit announcements in case of a huge reorganization.
2971 // Rely on the peer's synchronization mechanism in that case.
2972 break;
2975 // Relay inventory, but don't relay old inventory during initial block download.
2976 int nBlockEstimate = 0;
2977 if (fCheckpointsEnabled)
2978 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints());
2980 LOCK(cs_vNodes);
2981 BOOST_FOREACH(CNode* pnode, vNodes) {
2982 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) {
2983 BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
2984 pnode->PushBlockHash(hash);
2989 // Notify external listeners about the new tip.
2990 if (!vHashes.empty()) {
2991 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2995 } while(pindexMostWork != chainActive.Tip());
2996 CheckBlockIndex(chainparams.GetConsensus());
2998 // Write changes periodically to disk, after relay.
2999 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
3000 return false;
3003 return true;
3006 bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
3008 AssertLockHeld(cs_main);
3010 // Mark the block itself as invalid.
3011 pindex->nStatus |= BLOCK_FAILED_VALID;
3012 setDirtyBlockIndex.insert(pindex);
3013 setBlockIndexCandidates.erase(pindex);
3015 while (chainActive.Contains(pindex)) {
3016 CBlockIndex *pindexWalk = chainActive.Tip();
3017 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3018 setDirtyBlockIndex.insert(pindexWalk);
3019 setBlockIndexCandidates.erase(pindexWalk);
3020 // ActivateBestChain considers blocks already in chainActive
3021 // unconditionally valid already, so force disconnect away from it.
3022 if (!DisconnectTip(state, chainparams)) {
3023 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3024 return false;
3028 LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
3030 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3031 // add it again.
3032 BlockMap::iterator it = mapBlockIndex.begin();
3033 while (it != mapBlockIndex.end()) {
3034 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3035 setBlockIndexCandidates.insert(it->second);
3037 it++;
3040 InvalidChainFound(pindex);
3041 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3042 return true;
3045 bool ResetBlockFailureFlags(CBlockIndex *pindex) {
3046 AssertLockHeld(cs_main);
3048 int nHeight = pindex->nHeight;
3050 // Remove the invalidity flag from this block and all its descendants.
3051 BlockMap::iterator it = mapBlockIndex.begin();
3052 while (it != mapBlockIndex.end()) {
3053 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3054 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3055 setDirtyBlockIndex.insert(it->second);
3056 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3057 setBlockIndexCandidates.insert(it->second);
3059 if (it->second == pindexBestInvalid) {
3060 // Reset invalid block marker if it was pointing to one of those.
3061 pindexBestInvalid = NULL;
3064 it++;
3067 // Remove the invalidity flag from all ancestors too.
3068 while (pindex != NULL) {
3069 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3070 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3071 setDirtyBlockIndex.insert(pindex);
3073 pindex = pindex->pprev;
3075 return true;
3078 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3080 // Check for duplicate
3081 uint256 hash = block.GetHash();
3082 BlockMap::iterator it = mapBlockIndex.find(hash);
3083 if (it != mapBlockIndex.end())
3084 return it->second;
3086 // Construct new block index object
3087 CBlockIndex* pindexNew = new CBlockIndex(block);
3088 assert(pindexNew);
3089 // We assign the sequence id to blocks only when the full data is available,
3090 // to avoid miners withholding blocks but broadcasting headers, to get a
3091 // competitive advantage.
3092 pindexNew->nSequenceId = 0;
3093 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3094 pindexNew->phashBlock = &((*mi).first);
3095 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3096 if (miPrev != mapBlockIndex.end())
3098 pindexNew->pprev = (*miPrev).second;
3099 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3100 pindexNew->BuildSkip();
3102 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3103 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3104 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3105 pindexBestHeader = pindexNew;
3107 setDirtyBlockIndex.insert(pindexNew);
3109 return pindexNew;
3112 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3113 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3115 pindexNew->nTx = block.vtx.size();
3116 pindexNew->nChainTx = 0;
3117 pindexNew->nFile = pos.nFile;
3118 pindexNew->nDataPos = pos.nPos;
3119 pindexNew->nUndoPos = 0;
3120 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3121 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3122 setDirtyBlockIndex.insert(pindexNew);
3124 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3125 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3126 deque<CBlockIndex*> queue;
3127 queue.push_back(pindexNew);
3129 // Recursively process any descendant blocks that now may be eligible to be connected.
3130 while (!queue.empty()) {
3131 CBlockIndex *pindex = queue.front();
3132 queue.pop_front();
3133 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3135 LOCK(cs_nBlockSequenceId);
3136 pindex->nSequenceId = nBlockSequenceId++;
3138 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3139 setBlockIndexCandidates.insert(pindex);
3141 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3142 while (range.first != range.second) {
3143 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3144 queue.push_back(it->second);
3145 range.first++;
3146 mapBlocksUnlinked.erase(it);
3149 } else {
3150 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3151 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3155 return true;
3158 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3160 LOCK(cs_LastBlockFile);
3162 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3163 if (vinfoBlockFile.size() <= nFile) {
3164 vinfoBlockFile.resize(nFile + 1);
3167 if (!fKnown) {
3168 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3169 nFile++;
3170 if (vinfoBlockFile.size() <= nFile) {
3171 vinfoBlockFile.resize(nFile + 1);
3174 pos.nFile = nFile;
3175 pos.nPos = vinfoBlockFile[nFile].nSize;
3178 if ((int)nFile != nLastBlockFile) {
3179 if (!fKnown) {
3180 LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
3182 FlushBlockFile(!fKnown);
3183 nLastBlockFile = nFile;
3186 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3187 if (fKnown)
3188 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3189 else
3190 vinfoBlockFile[nFile].nSize += nAddSize;
3192 if (!fKnown) {
3193 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3194 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3195 if (nNewChunks > nOldChunks) {
3196 if (fPruneMode)
3197 fCheckForPruning = true;
3198 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3199 FILE *file = OpenBlockFile(pos);
3200 if (file) {
3201 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3202 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3203 fclose(file);
3206 else
3207 return state.Error("out of disk space");
3211 setDirtyFileInfo.insert(nFile);
3212 return true;
3215 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3217 pos.nFile = nFile;
3219 LOCK(cs_LastBlockFile);
3221 unsigned int nNewSize;
3222 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3223 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3224 setDirtyFileInfo.insert(nFile);
3226 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3227 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3228 if (nNewChunks > nOldChunks) {
3229 if (fPruneMode)
3230 fCheckForPruning = true;
3231 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3232 FILE *file = OpenUndoFile(pos);
3233 if (file) {
3234 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3235 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3236 fclose(file);
3239 else
3240 return state.Error("out of disk space");
3243 return true;
3246 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, int64_t nAdjustedTime, bool fCheckPOW)
3248 // Check proof of work matches claimed amount
3249 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
3250 return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
3252 // Check timestamp
3253 if (block.GetBlockTime() > nAdjustedTime + 2 * 60 * 60)
3254 return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
3256 return true;
3259 bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, int64_t nAdjustedTime, bool fCheckPOW, bool fCheckMerkleRoot)
3261 // These are checks that are independent of context.
3263 if (block.fChecked)
3264 return true;
3266 // Check that the header is valid (particularly PoW). This is mostly
3267 // redundant with the call in AcceptBlockHeader.
3268 if (!CheckBlockHeader(block, state, consensusParams, nAdjustedTime, fCheckPOW))
3269 return false;
3271 // Check the merkle root.
3272 if (fCheckMerkleRoot) {
3273 bool mutated;
3274 uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
3275 if (block.hashMerkleRoot != hashMerkleRoot2)
3276 return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
3278 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3279 // of transactions in a block without affecting the merkle root of a block,
3280 // while still invalidating it.
3281 if (mutated)
3282 return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
3285 // All potential-corruption validation must be done before we do any
3286 // transaction validation, as otherwise we may mark the header as invalid
3287 // because we receive the wrong transactions for it.
3289 // Size limits
3290 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3291 return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
3293 // First transaction must be coinbase, the rest must not be
3294 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3295 return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
3296 for (unsigned int i = 1; i < block.vtx.size(); i++)
3297 if (block.vtx[i].IsCoinBase())
3298 return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
3300 // Check transactions
3301 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3302 if (!CheckTransaction(tx, state))
3303 return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
3304 strprintf("Transaction check failed (tx hash %s) %s", tx.GetHash().ToString(), state.GetDebugMessage()));
3306 unsigned int nSigOps = 0;
3307 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3309 nSigOps += GetLegacySigOpCount(tx);
3311 if (nSigOps > MAX_BLOCK_SIGOPS)
3312 return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
3314 if (fCheckPOW && fCheckMerkleRoot)
3315 block.fChecked = true;
3317 return true;
3320 static bool CheckIndexAgainstCheckpoint(const CBlockIndex* pindexPrev, CValidationState& state, const CChainParams& chainparams, const uint256& hash)
3322 if (*pindexPrev->phashBlock == chainparams.GetConsensus().hashGenesisBlock)
3323 return true;
3325 int nHeight = pindexPrev->nHeight+1;
3326 // Don't accept any forks from the main chain prior to last checkpoint
3327 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
3328 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3329 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3331 return true;
3334 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, CBlockIndex * const pindexPrev)
3336 // Check proof of work
3337 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3338 return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
3340 // Check timestamp against prev
3341 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3342 return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
3344 // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
3345 for (int32_t version = 2; version < 5; ++version) // check for version 2, 3 and 4 upgrades
3346 if (block.nVersion < version && IsSuperMajority(version, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
3347 return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", version - 1),
3348 strprintf("rejected nVersion=0x%08x block", version - 1));
3350 return true;
3353 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3355 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3356 const Consensus::Params& consensusParams = Params().GetConsensus();
3358 // Start enforcing BIP113 (Median Time Past) using versionbits logic.
3359 int nLockTimeFlags = 0;
3360 if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
3361 nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
3364 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3365 ? pindexPrev->GetMedianTimePast()
3366 : block.GetBlockTime();
3368 // Check that all transactions are finalized
3369 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3370 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3371 return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
3375 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3376 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3377 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
3379 CScript expect = CScript() << nHeight;
3380 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3381 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3382 return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
3386 return true;
3389 static bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex=NULL)
3391 AssertLockHeld(cs_main);
3392 // Check for duplicate
3393 uint256 hash = block.GetHash();
3394 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3395 CBlockIndex *pindex = NULL;
3396 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3398 if (miSelf != mapBlockIndex.end()) {
3399 // Block header is already known.
3400 pindex = miSelf->second;
3401 if (ppindex)
3402 *ppindex = pindex;
3403 if (pindex->nStatus & BLOCK_FAILED_MASK)
3404 return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
3405 return true;
3408 if (!CheckBlockHeader(block, state, chainparams.GetConsensus(), GetAdjustedTime()))
3409 return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3411 // Get prev block index
3412 CBlockIndex* pindexPrev = NULL;
3413 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3414 if (mi == mapBlockIndex.end())
3415 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3416 pindexPrev = (*mi).second;
3417 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3418 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3420 assert(pindexPrev);
3421 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, hash))
3422 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3424 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev))
3425 return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
3427 if (pindex == NULL)
3428 pindex = AddToBlockIndex(block);
3430 if (ppindex)
3431 *ppindex = pindex;
3433 return true;
3436 /** Store block on disk. If dbp is non-NULL, the file is known to already reside on disk */
3437 static bool AcceptBlock(const CBlock& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp)
3439 AssertLockHeld(cs_main);
3441 CBlockIndex *pindexDummy = NULL;
3442 CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
3444 if (!AcceptBlockHeader(block, state, chainparams, &pindex))
3445 return false;
3447 // Try to process all requested blocks that we don't have, but only
3448 // process an unrequested block if it's new and has enough work to
3449 // advance our tip, and isn't too many blocks ahead.
3450 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3451 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3452 // Blocks that are too out-of-order needlessly limit the effectiveness of
3453 // pruning, because pruning will not delete block files that contain any
3454 // blocks which are too close in height to the tip. Apply this test
3455 // regardless of whether pruning is enabled; it should generally be safe to
3456 // not process unrequested blocks.
3457 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3459 // TODO: deal better with return value and error conditions for duplicate
3460 // and unrequested blocks.
3461 if (fAlreadyHave) return true;
3462 if (!fRequested) { // If we didn't ask for it:
3463 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3464 if (!fHasMoreWork) return true; // Don't process less-work chains
3465 if (fTooFarAhead) return true; // Block height is too high
3468 if ((!CheckBlock(block, state, chainparams.GetConsensus(), GetAdjustedTime())) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3469 if (state.IsInvalid() && !state.CorruptionPossible()) {
3470 pindex->nStatus |= BLOCK_FAILED_VALID;
3471 setDirtyBlockIndex.insert(pindex);
3473 return error("%s: %s", __func__, FormatStateMessage(state));
3476 int nHeight = pindex->nHeight;
3478 // Write block to history file
3479 try {
3480 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3481 CDiskBlockPos blockPos;
3482 if (dbp != NULL)
3483 blockPos = *dbp;
3484 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3485 return error("AcceptBlock(): FindBlockPos failed");
3486 if (dbp == NULL)
3487 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3488 AbortNode(state, "Failed to write block");
3489 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3490 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3491 } catch (const std::runtime_error& e) {
3492 return AbortNode(state, std::string("System error: ") + e.what());
3495 if (fCheckForPruning)
3496 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3498 return true;
3501 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3503 unsigned int nFound = 0;
3504 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3506 if (pstart->nVersion >= minVersion)
3507 ++nFound;
3508 pstart = pstart->pprev;
3510 return (nFound >= nRequired);
3514 bool ProcessNewBlock(CValidationState& state, const CChainParams& chainparams, const CNode* pfrom, const CBlock* pblock, bool fForceProcessing, const CDiskBlockPos* dbp)
3517 LOCK(cs_main);
3518 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3519 fRequested |= fForceProcessing;
3521 // Store to disk
3522 CBlockIndex *pindex = NULL;
3523 bool ret = AcceptBlock(*pblock, state, chainparams, &pindex, fRequested, dbp);
3524 if (pindex && pfrom) {
3525 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3527 CheckBlockIndex(chainparams.GetConsensus());
3528 if (!ret)
3529 return error("%s: AcceptBlock FAILED", __func__);
3532 NotifyHeaderTip();
3534 if (!ActivateBestChain(state, chainparams, pblock))
3535 return error("%s: ActivateBestChain failed", __func__);
3537 return true;
3540 bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3542 AssertLockHeld(cs_main);
3543 assert(pindexPrev && pindexPrev == chainActive.Tip());
3544 if (fCheckpointsEnabled && !CheckIndexAgainstCheckpoint(pindexPrev, state, chainparams, block.GetHash()))
3545 return error("%s: CheckIndexAgainstCheckpoint(): %s", __func__, state.GetRejectReason().c_str());
3547 CCoinsViewCache viewNew(pcoinsTip);
3548 CBlockIndex indexDummy(block);
3549 indexDummy.pprev = pindexPrev;
3550 indexDummy.nHeight = pindexPrev->nHeight + 1;
3552 // NOTE: CheckBlockHeader is called by CheckBlock
3553 if (!ContextualCheckBlockHeader(block, state, chainparams.GetConsensus(), pindexPrev))
3554 return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
3555 if (!CheckBlock(block, state, chainparams.GetConsensus(), GetAdjustedTime(), fCheckPOW, fCheckMerkleRoot))
3556 return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
3557 if (!ContextualCheckBlock(block, state, pindexPrev))
3558 return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
3559 if (!ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
3560 return false;
3561 assert(state.IsValid());
3563 return true;
3567 * BLOCK PRUNING CODE
3570 /* Calculate the amount of disk space the block & undo files currently use */
3571 uint64_t CalculateCurrentUsage()
3573 uint64_t retval = 0;
3574 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3575 retval += file.nSize + file.nUndoSize;
3577 return retval;
3580 /* Prune a block file (modify associated database entries)*/
3581 void PruneOneBlockFile(const int fileNumber)
3583 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3584 CBlockIndex* pindex = it->second;
3585 if (pindex->nFile == fileNumber) {
3586 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3587 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3588 pindex->nFile = 0;
3589 pindex->nDataPos = 0;
3590 pindex->nUndoPos = 0;
3591 setDirtyBlockIndex.insert(pindex);
3593 // Prune from mapBlocksUnlinked -- any block we prune would have
3594 // to be downloaded again in order to consider its chain, at which
3595 // point it would be considered as a candidate for
3596 // mapBlocksUnlinked or setBlockIndexCandidates.
3597 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3598 while (range.first != range.second) {
3599 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3600 range.first++;
3601 if (it->second == pindex) {
3602 mapBlocksUnlinked.erase(it);
3608 vinfoBlockFile[fileNumber].SetNull();
3609 setDirtyFileInfo.insert(fileNumber);
3613 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3615 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3616 CDiskBlockPos pos(*it, 0);
3617 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3618 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3619 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3623 /* Calculate the block/rev files that should be deleted to remain under target*/
3624 void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
3626 LOCK2(cs_main, cs_LastBlockFile);
3627 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3628 return;
3630 if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
3631 return;
3634 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3635 uint64_t nCurrentUsage = CalculateCurrentUsage();
3636 // We don't check to prune until after we've allocated new space for files
3637 // So we should leave a buffer under our target to account for another allocation
3638 // before the next pruning.
3639 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3640 uint64_t nBytesToPrune;
3641 int count=0;
3643 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3644 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3645 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3647 if (vinfoBlockFile[fileNumber].nSize == 0)
3648 continue;
3650 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3651 break;
3653 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3654 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3655 continue;
3657 PruneOneBlockFile(fileNumber);
3658 // Queue up the files for removal
3659 setFilesToPrune.insert(fileNumber);
3660 nCurrentUsage -= nBytesToPrune;
3661 count++;
3665 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3666 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3667 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3668 nLastBlockWeCanPrune, count);
3671 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3673 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3675 // Check for nMinDiskSpace bytes (currently 50MB)
3676 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3677 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3679 return true;
3682 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3684 if (pos.IsNull())
3685 return NULL;
3686 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3687 boost::filesystem::create_directories(path.parent_path());
3688 FILE* file = fopen(path.string().c_str(), "rb+");
3689 if (!file && !fReadOnly)
3690 file = fopen(path.string().c_str(), "wb+");
3691 if (!file) {
3692 LogPrintf("Unable to open file %s\n", path.string());
3693 return NULL;
3695 if (pos.nPos) {
3696 if (fseek(file, pos.nPos, SEEK_SET)) {
3697 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3698 fclose(file);
3699 return NULL;
3702 return file;
3705 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3706 return OpenDiskFile(pos, "blk", fReadOnly);
3709 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3710 return OpenDiskFile(pos, "rev", fReadOnly);
3713 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3715 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3718 CBlockIndex * InsertBlockIndex(uint256 hash)
3720 if (hash.IsNull())
3721 return NULL;
3723 // Return existing
3724 BlockMap::iterator mi = mapBlockIndex.find(hash);
3725 if (mi != mapBlockIndex.end())
3726 return (*mi).second;
3728 // Create new
3729 CBlockIndex* pindexNew = new CBlockIndex();
3730 if (!pindexNew)
3731 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3732 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3733 pindexNew->phashBlock = &((*mi).first);
3735 return pindexNew;
3738 bool static LoadBlockIndexDB()
3740 const CChainParams& chainparams = Params();
3741 if (!pblocktree->LoadBlockIndexGuts(InsertBlockIndex))
3742 return false;
3744 boost::this_thread::interruption_point();
3746 // Calculate nChainWork
3747 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3748 vSortedByHeight.reserve(mapBlockIndex.size());
3749 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3751 CBlockIndex* pindex = item.second;
3752 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3754 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3755 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3757 CBlockIndex* pindex = item.second;
3758 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3759 // We can link the chain of blocks for which we've received transactions at some point.
3760 // Pruned nodes may have deleted the block.
3761 if (pindex->nTx > 0) {
3762 if (pindex->pprev) {
3763 if (pindex->pprev->nChainTx) {
3764 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3765 } else {
3766 pindex->nChainTx = 0;
3767 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3769 } else {
3770 pindex->nChainTx = pindex->nTx;
3773 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3774 setBlockIndexCandidates.insert(pindex);
3775 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3776 pindexBestInvalid = pindex;
3777 if (pindex->pprev)
3778 pindex->BuildSkip();
3779 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3780 pindexBestHeader = pindex;
3783 // Load block file info
3784 pblocktree->ReadLastBlockFile(nLastBlockFile);
3785 vinfoBlockFile.resize(nLastBlockFile + 1);
3786 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3787 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3788 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3790 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3791 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3792 CBlockFileInfo info;
3793 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3794 vinfoBlockFile.push_back(info);
3795 } else {
3796 break;
3800 // Check presence of blk files
3801 LogPrintf("Checking all blk files are present...\n");
3802 set<int> setBlkDataFiles;
3803 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3805 CBlockIndex* pindex = item.second;
3806 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3807 setBlkDataFiles.insert(pindex->nFile);
3810 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3812 CDiskBlockPos pos(*it, 0);
3813 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3814 return false;
3818 // Check whether we have ever pruned block & undo files
3819 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3820 if (fHavePruned)
3821 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3823 // Check whether we need to continue reindexing
3824 bool fReindexing = false;
3825 pblocktree->ReadReindexing(fReindexing);
3826 fReindex |= fReindexing;
3828 // Check whether we have a transaction index
3829 pblocktree->ReadFlag("txindex", fTxIndex);
3830 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3832 // Load pointer to end of best chain
3833 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3834 if (it == mapBlockIndex.end())
3835 return true;
3836 chainActive.SetTip(it->second);
3838 PruneBlockIndexCandidates();
3840 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3841 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3842 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3843 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3845 return true;
3848 CVerifyDB::CVerifyDB()
3850 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3853 CVerifyDB::~CVerifyDB()
3855 uiInterface.ShowProgress("", 100);
3858 bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3860 LOCK(cs_main);
3861 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3862 return true;
3864 // Verify blocks in the best chain
3865 if (nCheckDepth <= 0)
3866 nCheckDepth = 1000000000; // suffices until the year 19000
3867 if (nCheckDepth > chainActive.Height())
3868 nCheckDepth = chainActive.Height();
3869 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3870 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3871 CCoinsViewCache coins(coinsview);
3872 CBlockIndex* pindexState = chainActive.Tip();
3873 CBlockIndex* pindexFailure = NULL;
3874 int nGoodTransactions = 0;
3875 CValidationState state;
3876 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3878 boost::this_thread::interruption_point();
3879 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3880 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3881 break;
3882 if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
3883 // If pruning, only go back as far as we have data.
3884 LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
3885 break;
3887 CBlock block;
3888 // check level 0: read from disk
3889 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3890 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3891 // check level 1: verify block validity
3892 if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus(), GetAdjustedTime()))
3893 return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
3894 pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
3895 // check level 2: verify undo validity
3896 if (nCheckLevel >= 2 && pindex) {
3897 CBlockUndo undo;
3898 CDiskBlockPos pos = pindex->GetUndoPos();
3899 if (!pos.IsNull()) {
3900 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3901 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3904 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3905 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3906 bool fClean = true;
3907 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3908 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3909 pindexState = pindex->pprev;
3910 if (!fClean) {
3911 nGoodTransactions = 0;
3912 pindexFailure = pindex;
3913 } else
3914 nGoodTransactions += block.vtx.size();
3916 if (ShutdownRequested())
3917 return true;
3919 if (pindexFailure)
3920 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3922 // check level 4: try reconnecting blocks
3923 if (nCheckLevel >= 4) {
3924 CBlockIndex *pindex = pindexState;
3925 while (pindex != chainActive.Tip()) {
3926 boost::this_thread::interruption_point();
3927 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3928 pindex = chainActive.Next(pindex);
3929 CBlock block;
3930 if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
3931 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3932 if (!ConnectBlock(block, state, pindex, coins, chainparams))
3933 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3937 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3939 return true;
3942 void UnloadBlockIndex()
3944 LOCK(cs_main);
3945 setBlockIndexCandidates.clear();
3946 chainActive.SetTip(NULL);
3947 pindexBestInvalid = NULL;
3948 pindexBestHeader = NULL;
3949 mempool.clear();
3950 mapOrphanTransactions.clear();
3951 mapOrphanTransactionsByPrev.clear();
3952 nSyncStarted = 0;
3953 mapBlocksUnlinked.clear();
3954 vinfoBlockFile.clear();
3955 nLastBlockFile = 0;
3956 nBlockSequenceId = 1;
3957 mapBlockSource.clear();
3958 mapBlocksInFlight.clear();
3959 nPreferredDownload = 0;
3960 setDirtyBlockIndex.clear();
3961 setDirtyFileInfo.clear();
3962 mapNodeState.clear();
3963 recentRejects.reset(NULL);
3964 versionbitscache.Clear();
3965 for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
3966 warningcache[b].clear();
3969 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3970 delete entry.second;
3972 mapBlockIndex.clear();
3973 fHavePruned = false;
3976 bool LoadBlockIndex()
3978 // Load block index from databases
3979 if (!fReindex && !LoadBlockIndexDB())
3980 return false;
3981 return true;
3984 bool InitBlockIndex(const CChainParams& chainparams)
3986 LOCK(cs_main);
3988 // Initialize global variables that cannot be constructed at startup.
3989 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3991 // Check whether we're already initialized
3992 if (chainActive.Genesis() != NULL)
3993 return true;
3995 // Use the provided setting for -txindex in the new database
3996 fTxIndex = GetBoolArg("-txindex", DEFAULT_TXINDEX);
3997 pblocktree->WriteFlag("txindex", fTxIndex);
3998 LogPrintf("Initializing databases...\n");
4000 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4001 if (!fReindex) {
4002 try {
4003 CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
4004 // Start new block file
4005 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4006 CDiskBlockPos blockPos;
4007 CValidationState state;
4008 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4009 return error("LoadBlockIndex(): FindBlockPos failed");
4010 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4011 return error("LoadBlockIndex(): writing genesis block to disk failed");
4012 CBlockIndex *pindex = AddToBlockIndex(block);
4013 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4014 return error("LoadBlockIndex(): genesis block not accepted");
4015 if (!ActivateBestChain(state, chainparams, &block))
4016 return error("LoadBlockIndex(): genesis block cannot be activated");
4017 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4018 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4019 } catch (const std::runtime_error& e) {
4020 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4024 return true;
4027 bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
4029 // Map of disk positions for blocks with unknown parent (only used for reindex)
4030 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4031 int64_t nStart = GetTimeMillis();
4033 int nLoaded = 0;
4034 try {
4035 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4036 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4037 uint64_t nRewind = blkdat.GetPos();
4038 while (!blkdat.eof()) {
4039 boost::this_thread::interruption_point();
4041 blkdat.SetPos(nRewind);
4042 nRewind++; // start one byte further next time, in case of failure
4043 blkdat.SetLimit(); // remove former limit
4044 unsigned int nSize = 0;
4045 try {
4046 // locate a header
4047 unsigned char buf[MESSAGE_START_SIZE];
4048 blkdat.FindByte(chainparams.MessageStart()[0]);
4049 nRewind = blkdat.GetPos()+1;
4050 blkdat >> FLATDATA(buf);
4051 if (memcmp(buf, chainparams.MessageStart(), MESSAGE_START_SIZE))
4052 continue;
4053 // read size
4054 blkdat >> nSize;
4055 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4056 continue;
4057 } catch (const std::exception&) {
4058 // no valid block header found; don't complain
4059 break;
4061 try {
4062 // read block
4063 uint64_t nBlockPos = blkdat.GetPos();
4064 if (dbp)
4065 dbp->nPos = nBlockPos;
4066 blkdat.SetLimit(nBlockPos + nSize);
4067 blkdat.SetPos(nBlockPos);
4068 CBlock block;
4069 blkdat >> block;
4070 nRewind = blkdat.GetPos();
4072 // detect out of order blocks, and store them for later
4073 uint256 hash = block.GetHash();
4074 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4075 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4076 block.hashPrevBlock.ToString());
4077 if (dbp)
4078 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4079 continue;
4082 // process in case the block isn't known yet
4083 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4084 LOCK(cs_main);
4085 CValidationState state;
4086 if (AcceptBlock(block, state, chainparams, NULL, true, dbp))
4087 nLoaded++;
4088 if (state.IsError())
4089 break;
4090 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4091 LogPrint("reindex", "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4094 // Activate the genesis block so normal node progress can continue
4095 if (hash == chainparams.GetConsensus().hashGenesisBlock) {
4096 CValidationState state;
4097 if (!ActivateBestChain(state, chainparams)) {
4098 break;
4102 NotifyHeaderTip();
4104 // Recursively process earlier encountered successors of this block
4105 deque<uint256> queue;
4106 queue.push_back(hash);
4107 while (!queue.empty()) {
4108 uint256 head = queue.front();
4109 queue.pop_front();
4110 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4111 while (range.first != range.second) {
4112 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4113 if (ReadBlockFromDisk(block, it->second, chainparams.GetConsensus()))
4115 LogPrint("reindex", "%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4116 head.ToString());
4117 LOCK(cs_main);
4118 CValidationState dummy;
4119 if (AcceptBlock(block, dummy, chainparams, NULL, true, &it->second))
4121 nLoaded++;
4122 queue.push_back(block.GetHash());
4125 range.first++;
4126 mapBlocksUnknownParent.erase(it);
4127 NotifyHeaderTip();
4130 } catch (const std::exception& e) {
4131 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4134 } catch (const std::runtime_error& e) {
4135 AbortNode(std::string("System error: ") + e.what());
4137 if (nLoaded > 0)
4138 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4139 return nLoaded > 0;
4142 void static CheckBlockIndex(const Consensus::Params& consensusParams)
4144 if (!fCheckBlockIndex) {
4145 return;
4148 LOCK(cs_main);
4150 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4151 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4152 // iterating the block tree require that chainActive has been initialized.)
4153 if (chainActive.Height() < 0) {
4154 assert(mapBlockIndex.size() <= 1);
4155 return;
4158 // Build forward-pointing map of the entire block tree.
4159 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4160 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4161 forward.insert(std::make_pair(it->second->pprev, it->second));
4164 assert(forward.size() == mapBlockIndex.size());
4166 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4167 CBlockIndex *pindex = rangeGenesis.first->second;
4168 rangeGenesis.first++;
4169 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4171 // Iterate over the entire block tree, using depth-first search.
4172 // Along the way, remember whether there are blocks on the path from genesis
4173 // block being explored which are the first to have certain properties.
4174 size_t nNodes = 0;
4175 int nHeight = 0;
4176 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4177 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4178 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4179 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4180 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4181 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4182 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4183 while (pindex != NULL) {
4184 nNodes++;
4185 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4186 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4187 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4188 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4189 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4190 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4191 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4193 // Begin: actual consistency checks.
4194 if (pindex->pprev == NULL) {
4195 // Genesis block checks.
4196 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4197 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4199 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4200 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4201 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4202 if (!fHavePruned) {
4203 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4204 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4205 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4206 } else {
4207 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4208 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4210 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4211 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4212 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4213 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4214 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4215 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4216 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.
4217 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4218 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4219 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4220 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4221 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4222 if (pindexFirstInvalid == NULL) {
4223 // Checks for not-invalid blocks.
4224 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4226 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4227 if (pindexFirstInvalid == NULL) {
4228 // If this block sorts at least as good as the current tip and
4229 // is valid and we have all data for its parents, it must be in
4230 // setBlockIndexCandidates. chainActive.Tip() must also be there
4231 // even if some data has been pruned.
4232 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4233 assert(setBlockIndexCandidates.count(pindex));
4235 // If some parent is missing, then it could be that this block was in
4236 // setBlockIndexCandidates but had to be removed because of the missing data.
4237 // In this case it must be in mapBlocksUnlinked -- see test below.
4239 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4240 assert(setBlockIndexCandidates.count(pindex) == 0);
4242 // Check whether this block is in mapBlocksUnlinked.
4243 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4244 bool foundInUnlinked = false;
4245 while (rangeUnlinked.first != rangeUnlinked.second) {
4246 assert(rangeUnlinked.first->first == pindex->pprev);
4247 if (rangeUnlinked.first->second == pindex) {
4248 foundInUnlinked = true;
4249 break;
4251 rangeUnlinked.first++;
4253 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4254 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4255 assert(foundInUnlinked);
4257 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4258 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4259 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4260 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4261 assert(fHavePruned); // We must have pruned.
4262 // This block may have entered mapBlocksUnlinked if:
4263 // - it has a descendant that at some point had more work than the
4264 // tip, and
4265 // - we tried switching to that descendant but were missing
4266 // data for some intermediate block between chainActive and the
4267 // tip.
4268 // So if this block is itself better than chainActive.Tip() and it wasn't in
4269 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4270 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4271 if (pindexFirstInvalid == NULL) {
4272 assert(foundInUnlinked);
4276 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4277 // End: actual consistency checks.
4279 // Try descending into the first subnode.
4280 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4281 if (range.first != range.second) {
4282 // A subnode was found.
4283 pindex = range.first->second;
4284 nHeight++;
4285 continue;
4287 // This is a leaf node.
4288 // Move upwards until we reach a node of which we have not yet visited the last child.
4289 while (pindex) {
4290 // We are going to either move to a parent or a sibling of pindex.
4291 // If pindex was the first with a certain property, unset the corresponding variable.
4292 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4293 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4294 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4295 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4296 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4297 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4298 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4299 // Find our parent.
4300 CBlockIndex* pindexPar = pindex->pprev;
4301 // Find which child we just visited.
4302 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4303 while (rangePar.first->second != pindex) {
4304 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4305 rangePar.first++;
4307 // Proceed to the next one.
4308 rangePar.first++;
4309 if (rangePar.first != rangePar.second) {
4310 // Move to the sibling.
4311 pindex = rangePar.first->second;
4312 break;
4313 } else {
4314 // Move up further.
4315 pindex = pindexPar;
4316 nHeight--;
4317 continue;
4322 // Check that we actually traversed the entire map.
4323 assert(nNodes == forward.size());
4326 std::string GetWarnings(const std::string& strFor)
4328 string strStatusBar;
4329 string strRPC;
4330 string strGUI;
4332 if (!CLIENT_VERSION_IS_RELEASE) {
4333 strStatusBar = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications";
4334 strGUI = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4337 if (GetBoolArg("-testsafemode", DEFAULT_TESTSAFEMODE))
4338 strStatusBar = strRPC = strGUI = "testsafemode enabled";
4340 // Misc warnings like out of disk space and clock is wrong
4341 if (strMiscWarning != "")
4343 strStatusBar = strGUI = strMiscWarning;
4346 if (fLargeWorkForkFound)
4348 strStatusBar = strRPC = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.";
4349 strGUI = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4351 else if (fLargeWorkInvalidChainFound)
4353 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.";
4354 strGUI = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
4357 if (strFor == "gui")
4358 return strGUI;
4359 else if (strFor == "statusbar")
4360 return strStatusBar;
4361 else if (strFor == "rpc")
4362 return strRPC;
4363 assert(!"GetWarnings(): invalid parameter");
4364 return "error";
4374 //////////////////////////////////////////////////////////////////////////////
4376 // Messages
4380 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4382 switch (inv.type)
4384 case MSG_TX:
4386 assert(recentRejects);
4387 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4389 // If the chain tip has changed previously rejected transactions
4390 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4391 // or a double-spend. Reset the rejects filter and give those
4392 // txs a second chance.
4393 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4394 recentRejects->reset();
4397 // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
4398 // requesting or processing some txs which have already been included in a block
4399 return recentRejects->contains(inv.hash) ||
4400 mempool.exists(inv.hash) ||
4401 mapOrphanTransactions.count(inv.hash) ||
4402 pcoinsTip->HaveCoinsInCache(inv.hash);
4404 case MSG_BLOCK:
4405 return mapBlockIndex.count(inv.hash);
4407 // Don't know what it is, just say we already got one
4408 return true;
4411 void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams)
4413 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4415 vector<CInv> vNotFound;
4417 LOCK(cs_main);
4419 while (it != pfrom->vRecvGetData.end()) {
4420 // Don't bother if send buffer is too full to respond anyway
4421 if (pfrom->nSendSize >= SendBufferSize())
4422 break;
4424 const CInv &inv = *it;
4426 boost::this_thread::interruption_point();
4427 it++;
4429 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4431 bool send = false;
4432 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4433 if (mi != mapBlockIndex.end())
4435 if (chainActive.Contains(mi->second)) {
4436 send = true;
4437 } else {
4438 static const int nOneMonth = 30 * 24 * 60 * 60;
4439 // To prevent fingerprinting attacks, only send blocks outside of the active
4440 // chain if they are valid, and no more than a month older (both in time, and in
4441 // best equivalent proof of work) than the best header chain we know about.
4442 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4443 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4444 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
4445 if (!send) {
4446 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4450 // disconnect node in case we have reached the outbound limit for serving historical blocks
4451 // never disconnect whitelisted nodes
4452 static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
4453 if (send && CNode::OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
4455 LogPrint("net", "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
4457 //disconnect node
4458 pfrom->fDisconnect = true;
4459 send = false;
4461 // Pruned nodes may have deleted the block, so check whether
4462 // it's available before trying to send.
4463 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4465 // Send block from disk
4466 CBlock block;
4467 if (!ReadBlockFromDisk(block, (*mi).second, consensusParams))
4468 assert(!"cannot load block from disk");
4469 if (inv.type == MSG_BLOCK)
4470 pfrom->PushMessage(NetMsgType::BLOCK, block);
4471 else // MSG_FILTERED_BLOCK)
4473 LOCK(pfrom->cs_filter);
4474 if (pfrom->pfilter)
4476 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4477 pfrom->PushMessage(NetMsgType::MERKLEBLOCK, merkleBlock);
4478 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4479 // This avoids hurting performance by pointlessly requiring a round-trip
4480 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4481 // they must either disconnect and retry or request the full block.
4482 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4483 // however we MUST always provide at least what the remote peer needs
4484 typedef std::pair<unsigned int, uint256> PairType;
4485 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4486 pfrom->PushMessage(NetMsgType::TX, block.vtx[pair.first]);
4488 // else
4489 // no response
4492 // Trigger the peer node to send a getblocks request for the next batch of inventory
4493 if (inv.hash == pfrom->hashContinue)
4495 // Bypass PushInventory, this must send even if redundant,
4496 // and we want it right after the last block so they don't
4497 // wait for other stuff first.
4498 vector<CInv> vInv;
4499 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4500 pfrom->PushMessage(NetMsgType::INV, vInv);
4501 pfrom->hashContinue.SetNull();
4505 else if (inv.IsKnownType())
4507 CTransaction tx;
4508 // Send stream from relay memory
4509 bool push = false;
4511 LOCK(cs_mapRelay);
4512 map<uint256, CTransaction>::iterator mi = mapRelay.find(inv.hash);
4513 if (mi != mapRelay.end()) {
4514 tx = (*mi).second;
4515 push = true;
4518 if (!push && inv.type == MSG_TX) {
4519 int64_t txtime;
4520 // To protect privacy, do not answer getdata using the mempool when
4521 // that TX couldn't have been INVed in reply to a MEMPOOL request.
4522 if (mempool.lookup(inv.hash, tx, txtime) && txtime <= pfrom->timeLastMempoolReq) {
4523 push = true;
4526 if (push) {
4527 pfrom->PushMessage(inv.GetCommand(), tx);
4528 } else {
4529 vNotFound.push_back(inv);
4533 // Track requests for our stuff.
4534 GetMainSignals().Inventory(inv.hash);
4536 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4537 break;
4541 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4543 if (!vNotFound.empty()) {
4544 // Let the peer know that we didn't find what it asked for, so it doesn't
4545 // have to wait around forever. Currently only SPV clients actually care
4546 // about this message: it's needed when they are recursively walking the
4547 // dependencies of relevant unconfirmed transactions. SPV clients want to
4548 // do that because they want to know about (and store and rebroadcast and
4549 // risk analyze) the dependencies of transactions relevant to them, without
4550 // having to download the entire memory pool.
4551 pfrom->PushMessage(NetMsgType::NOTFOUND, vNotFound);
4555 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams)
4557 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4558 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4560 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4561 return true;
4565 if (!(nLocalServices & NODE_BLOOM) &&
4566 (strCommand == NetMsgType::FILTERLOAD ||
4567 strCommand == NetMsgType::FILTERADD ||
4568 strCommand == NetMsgType::FILTERCLEAR))
4570 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
4571 Misbehaving(pfrom->GetId(), 100);
4572 return false;
4573 } else {
4574 pfrom->fDisconnect = true;
4575 return false;
4580 if (strCommand == NetMsgType::VERSION)
4582 // Each connection can only send one version message
4583 if (pfrom->nVersion != 0)
4585 pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4586 Misbehaving(pfrom->GetId(), 1);
4587 return false;
4590 int64_t nTime;
4591 CAddress addrMe;
4592 CAddress addrFrom;
4593 uint64_t nNonce = 1;
4594 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4595 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4597 // disconnect from peers older than this proto version
4598 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4599 pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
4600 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4601 pfrom->fDisconnect = true;
4602 return false;
4605 if (pfrom->nVersion == 10300)
4606 pfrom->nVersion = 300;
4607 if (!vRecv.empty())
4608 vRecv >> addrFrom >> nNonce;
4609 if (!vRecv.empty()) {
4610 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
4611 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4613 if (!vRecv.empty()) {
4614 vRecv >> pfrom->nStartingHeight;
4617 LOCK(pfrom->cs_filter);
4618 if (!vRecv.empty())
4619 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4620 else
4621 pfrom->fRelayTxes = true;
4624 // Disconnect if we connected to ourself
4625 if (nNonce == nLocalHostNonce && nNonce > 1)
4627 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4628 pfrom->fDisconnect = true;
4629 return true;
4632 pfrom->addrLocal = addrMe;
4633 if (pfrom->fInbound && addrMe.IsRoutable())
4635 SeenLocal(addrMe);
4638 // Be shy and don't send version until we hear
4639 if (pfrom->fInbound)
4640 pfrom->PushVersion();
4642 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4644 // Potentially mark this peer as a preferred download peer.
4645 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4647 // Change version
4648 pfrom->PushMessage(NetMsgType::VERACK);
4649 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4651 if (!pfrom->fInbound)
4653 // Advertise our address
4654 if (fListen && !IsInitialBlockDownload())
4656 CAddress addr = GetLocalAddress(&pfrom->addr);
4657 if (addr.IsRoutable())
4659 LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString());
4660 pfrom->PushAddress(addr);
4661 } else if (IsPeerAddrLocalGood(pfrom)) {
4662 addr.SetIP(pfrom->addrLocal);
4663 LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString());
4664 pfrom->PushAddress(addr);
4668 // Get recent addresses
4669 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4671 pfrom->PushMessage(NetMsgType::GETADDR);
4672 pfrom->fGetAddr = true;
4674 addrman.Good(pfrom->addr);
4675 } else {
4676 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4678 addrman.Add(addrFrom, addrFrom);
4679 addrman.Good(addrFrom);
4683 pfrom->fSuccessfullyConnected = true;
4685 string remoteAddr;
4686 if (fLogIPs)
4687 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4689 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4690 pfrom->cleanSubVer, pfrom->nVersion,
4691 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4692 remoteAddr);
4694 int64_t nTimeOffset = nTime - GetTime();
4695 pfrom->nTimeOffset = nTimeOffset;
4696 AddTimeData(pfrom->addr, nTimeOffset);
4700 else if (pfrom->nVersion == 0)
4702 // Must have a version message before anything else
4703 Misbehaving(pfrom->GetId(), 1);
4704 return false;
4708 else if (strCommand == NetMsgType::VERACK)
4710 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4712 // Mark this node as currently connected, so we update its timestamp later.
4713 if (pfrom->fNetworkNode) {
4714 LOCK(cs_main);
4715 State(pfrom->GetId())->fCurrentlyConnected = true;
4718 if (pfrom->nVersion >= SENDHEADERS_VERSION) {
4719 // Tell our peer we prefer to receive headers rather than inv's
4720 // We send this to non-NODE NETWORK peers as well, because even
4721 // non-NODE NETWORK peers can announce blocks (such as pruning
4722 // nodes)
4723 pfrom->PushMessage(NetMsgType::SENDHEADERS);
4728 else if (strCommand == NetMsgType::ADDR)
4730 vector<CAddress> vAddr;
4731 vRecv >> vAddr;
4733 // Don't want addr from older versions unless seeding
4734 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4735 return true;
4736 if (vAddr.size() > 1000)
4738 Misbehaving(pfrom->GetId(), 20);
4739 return error("message addr size() = %u", vAddr.size());
4742 // Store the new addresses
4743 vector<CAddress> vAddrOk;
4744 int64_t nNow = GetAdjustedTime();
4745 int64_t nSince = nNow - 10 * 60;
4746 BOOST_FOREACH(CAddress& addr, vAddr)
4748 boost::this_thread::interruption_point();
4750 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4751 addr.nTime = nNow - 5 * 24 * 60 * 60;
4752 pfrom->AddAddressKnown(addr);
4753 bool fReachable = IsReachable(addr);
4754 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4756 // Relay to a limited number of other nodes
4758 LOCK(cs_vNodes);
4759 // Use deterministic randomness to send to the same nodes for 24 hours
4760 // at a time so the addrKnowns of the chosen nodes prevent repeats
4761 static uint64_t salt0 = 0, salt1 = 0;
4762 while (salt0 == 0 && salt1 == 0) {
4763 GetRandBytes((unsigned char*)&salt0, sizeof(salt0));
4764 GetRandBytes((unsigned char*)&salt1, sizeof(salt1));
4766 uint64_t hashAddr = addr.GetHash();
4767 multimap<uint64_t, CNode*> mapMix;
4768 const CSipHasher hasher = CSipHasher(salt0, salt1).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
4769 BOOST_FOREACH(CNode* pnode, vNodes)
4771 if (pnode->nVersion < CADDR_TIME_VERSION)
4772 continue;
4773 uint64_t hashKey = CSipHasher(hasher).Write(pnode->id).Finalize();
4774 mapMix.insert(make_pair(hashKey, pnode));
4776 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4777 for (multimap<uint64_t, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4778 ((*mi).second)->PushAddress(addr);
4781 // Do not store addresses outside our network
4782 if (fReachable)
4783 vAddrOk.push_back(addr);
4785 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4786 if (vAddr.size() < 1000)
4787 pfrom->fGetAddr = false;
4788 if (pfrom->fOneShot)
4789 pfrom->fDisconnect = true;
4792 else if (strCommand == NetMsgType::SENDHEADERS)
4794 LOCK(cs_main);
4795 State(pfrom->GetId())->fPreferHeaders = true;
4799 else if (strCommand == NetMsgType::INV)
4801 vector<CInv> vInv;
4802 vRecv >> vInv;
4803 if (vInv.size() > MAX_INV_SZ)
4805 Misbehaving(pfrom->GetId(), 20);
4806 return error("message inv size() = %u", vInv.size());
4809 bool fBlocksOnly = !fRelayTxes;
4811 // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
4812 if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
4813 fBlocksOnly = false;
4815 LOCK(cs_main);
4817 std::vector<CInv> vToFetch;
4819 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4821 const CInv &inv = vInv[nInv];
4823 boost::this_thread::interruption_point();
4825 bool fAlreadyHave = AlreadyHave(inv);
4826 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4828 if (inv.type == MSG_BLOCK) {
4829 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4830 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4831 // First request the headers preceding the announced block. In the normal fully-synced
4832 // case where a new block is announced that succeeds the current tip (no reorganization),
4833 // there are no such headers.
4834 // Secondly, and only when we are close to being synced, we request the announced block directly,
4835 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4836 // time the block arrives, the header chain leading up to it is already validated. Not
4837 // doing this will result in the received block being rejected as an orphan in case it is
4838 // not a direct successor.
4839 pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash);
4840 CNodeState *nodestate = State(pfrom->GetId());
4841 if (CanDirectFetch(chainparams.GetConsensus()) &&
4842 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4843 vToFetch.push_back(inv);
4844 // Mark block as in flight already, even though the actual "getdata" message only goes out
4845 // later (within the same cs_main lock, though).
4846 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4848 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4851 else
4853 pfrom->AddInventoryKnown(inv);
4854 if (fBlocksOnly)
4855 LogPrint("net", "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
4856 else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload())
4857 pfrom->AskFor(inv);
4860 // Track requests for our stuff
4861 GetMainSignals().Inventory(inv.hash);
4863 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4864 Misbehaving(pfrom->GetId(), 50);
4865 return error("send buffer size() = %u", pfrom->nSendSize);
4869 if (!vToFetch.empty())
4870 pfrom->PushMessage(NetMsgType::GETDATA, vToFetch);
4874 else if (strCommand == NetMsgType::GETDATA)
4876 vector<CInv> vInv;
4877 vRecv >> vInv;
4878 if (vInv.size() > MAX_INV_SZ)
4880 Misbehaving(pfrom->GetId(), 20);
4881 return error("message getdata size() = %u", vInv.size());
4884 if (fDebug || (vInv.size() != 1))
4885 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4887 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4888 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4890 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4891 ProcessGetData(pfrom, chainparams.GetConsensus());
4895 else if (strCommand == NetMsgType::GETBLOCKS)
4897 CBlockLocator locator;
4898 uint256 hashStop;
4899 vRecv >> locator >> hashStop;
4901 LOCK(cs_main);
4903 // Find the last block the caller has in the main chain
4904 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4906 // Send the rest of the chain
4907 if (pindex)
4908 pindex = chainActive.Next(pindex);
4909 int nLimit = 500;
4910 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4911 for (; pindex; pindex = chainActive.Next(pindex))
4913 if (pindex->GetBlockHash() == hashStop)
4915 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4916 break;
4918 // If pruning, don't inv blocks unless we have on disk and are likely to still have
4919 // for some reasonable time window (1 hour) that block relay might require.
4920 const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
4921 if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
4923 LogPrint("net", " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4924 break;
4926 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4927 if (--nLimit <= 0)
4929 // When this block is requested, we'll send an inv that'll
4930 // trigger the peer to getblocks the next batch of inventory.
4931 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4932 pfrom->hashContinue = pindex->GetBlockHash();
4933 break;
4939 else if (strCommand == NetMsgType::GETHEADERS)
4941 CBlockLocator locator;
4942 uint256 hashStop;
4943 vRecv >> locator >> hashStop;
4945 LOCK(cs_main);
4946 if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
4947 LogPrint("net", "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
4948 return true;
4951 CNodeState *nodestate = State(pfrom->GetId());
4952 CBlockIndex* pindex = NULL;
4953 if (locator.IsNull())
4955 // If locator is null, return the hashStop block
4956 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4957 if (mi == mapBlockIndex.end())
4958 return true;
4959 pindex = (*mi).second;
4961 else
4963 // Find the last block the caller has in the main chain
4964 pindex = FindForkInGlobalIndex(chainActive, locator);
4965 if (pindex)
4966 pindex = chainActive.Next(pindex);
4969 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4970 vector<CBlock> vHeaders;
4971 int nLimit = MAX_HEADERS_RESULTS;
4972 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4973 for (; pindex; pindex = chainActive.Next(pindex))
4975 vHeaders.push_back(pindex->GetBlockHeader());
4976 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4977 break;
4979 // pindex can be NULL either if we sent chainActive.Tip() OR
4980 // if our peer has chainActive.Tip() (and thus we are sending an empty
4981 // headers message). In both cases it's safe to update
4982 // pindexBestHeaderSent to be our tip.
4983 nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
4984 pfrom->PushMessage(NetMsgType::HEADERS, vHeaders);
4988 else if (strCommand == NetMsgType::TX)
4990 // Stop processing the transaction early if
4991 // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
4992 if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
4994 LogPrint("net", "transaction sent in violation of protocol peer=%d\n", pfrom->id);
4995 return true;
4998 vector<uint256> vWorkQueue;
4999 vector<uint256> vEraseQueue;
5000 CTransaction tx;
5001 vRecv >> tx;
5003 CInv inv(MSG_TX, tx.GetHash());
5004 pfrom->AddInventoryKnown(inv);
5006 LOCK(cs_main);
5008 bool fMissingInputs = false;
5009 CValidationState state;
5011 pfrom->setAskFor.erase(inv.hash);
5012 mapAlreadyAskedFor.erase(inv.hash);
5014 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) {
5015 mempool.check(pcoinsTip);
5016 RelayTransaction(tx);
5017 vWorkQueue.push_back(inv.hash);
5019 LogPrint("mempool", "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
5020 pfrom->id,
5021 tx.GetHash().ToString(),
5022 mempool.size(), mempool.DynamicMemoryUsage() / 1000);
5024 // Recursively process any orphan transactions that depended on this one
5025 set<NodeId> setMisbehaving;
5026 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5028 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5029 if (itByPrev == mapOrphanTransactionsByPrev.end())
5030 continue;
5031 for (set<uint256>::iterator mi = itByPrev->second.begin();
5032 mi != itByPrev->second.end();
5033 ++mi)
5035 const uint256& orphanHash = *mi;
5036 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5037 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5038 bool fMissingInputs2 = false;
5039 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5040 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5041 // anyone relaying LegitTxX banned)
5042 CValidationState stateDummy;
5045 if (setMisbehaving.count(fromPeer))
5046 continue;
5047 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
5048 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5049 RelayTransaction(orphanTx);
5050 vWorkQueue.push_back(orphanHash);
5051 vEraseQueue.push_back(orphanHash);
5053 else if (!fMissingInputs2)
5055 int nDos = 0;
5056 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5058 // Punish peer that gave us an invalid orphan tx
5059 Misbehaving(fromPeer, nDos);
5060 setMisbehaving.insert(fromPeer);
5061 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5063 // Has inputs but not accepted to mempool
5064 // Probably non-standard or insufficient fee/priority
5065 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5066 vEraseQueue.push_back(orphanHash);
5067 assert(recentRejects);
5068 recentRejects->insert(orphanHash);
5070 mempool.check(pcoinsTip);
5074 BOOST_FOREACH(uint256 hash, vEraseQueue)
5075 EraseOrphanTx(hash);
5077 else if (fMissingInputs)
5079 AddOrphanTx(tx, pfrom->GetId());
5081 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5082 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5083 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5084 if (nEvicted > 0)
5085 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5086 } else {
5087 assert(recentRejects);
5088 recentRejects->insert(tx.GetHash());
5090 if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
5091 // Always relay transactions received from whitelisted peers, even
5092 // if they were already in the mempool or rejected from it due
5093 // to policy, allowing the node to function as a gateway for
5094 // nodes hidden behind it.
5096 // Never relay transactions that we would assign a non-zero DoS
5097 // score for, as we expect peers to do the same with us in that
5098 // case.
5099 int nDoS = 0;
5100 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5101 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5102 RelayTransaction(tx);
5103 } else {
5104 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state));
5108 int nDoS = 0;
5109 if (state.IsInvalid(nDoS))
5111 LogPrint("mempoolrej", "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
5112 pfrom->id,
5113 FormatStateMessage(state));
5114 if (state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
5115 pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
5116 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5117 if (nDoS > 0)
5118 Misbehaving(pfrom->GetId(), nDoS);
5120 FlushStateToDisk(state, FLUSH_STATE_PERIODIC);
5124 else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
5126 std::vector<CBlockHeader> headers;
5128 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5129 unsigned int nCount = ReadCompactSize(vRecv);
5130 if (nCount > MAX_HEADERS_RESULTS) {
5131 Misbehaving(pfrom->GetId(), 20);
5132 return error("headers message size = %u", nCount);
5134 headers.resize(nCount);
5135 for (unsigned int n = 0; n < nCount; n++) {
5136 vRecv >> headers[n];
5137 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5141 LOCK(cs_main);
5143 if (nCount == 0) {
5144 // Nothing interesting. Stop asking this peers for more headers.
5145 return true;
5148 // If we already know the last header in the message, then it contains
5149 // no new information for us. In this case, we do not request
5150 // more headers later. This prevents multiple chains of redundant
5151 // getheader requests from running in parallel if triggered by incoming
5152 // blocks while the node is still in initial headers sync.
5153 const bool hasNewHeaders = (mapBlockIndex.count(headers.back().GetHash()) == 0);
5155 CBlockIndex *pindexLast = NULL;
5156 BOOST_FOREACH(const CBlockHeader& header, headers) {
5157 CValidationState state;
5158 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5159 Misbehaving(pfrom->GetId(), 20);
5160 return error("non-continuous headers sequence");
5162 if (!AcceptBlockHeader(header, state, chainparams, &pindexLast)) {
5163 int nDoS;
5164 if (state.IsInvalid(nDoS)) {
5165 if (nDoS > 0)
5166 Misbehaving(pfrom->GetId(), nDoS);
5167 return error("invalid header received");
5172 if (pindexLast)
5173 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5175 if (nCount == MAX_HEADERS_RESULTS && pindexLast && hasNewHeaders) {
5176 // Headers message had its maximum size; the peer may have more headers.
5177 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5178 // from there instead.
5179 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5180 pfrom->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256());
5183 bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
5184 CNodeState *nodestate = State(pfrom->GetId());
5185 // If this set of headers is valid and ends in a block with at least as
5186 // much work as our tip, download as much as possible.
5187 if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
5188 vector<CBlockIndex *> vToFetch;
5189 CBlockIndex *pindexWalk = pindexLast;
5190 // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
5191 while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5192 if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
5193 !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) {
5194 // We don't have this block, and it's not yet in flight.
5195 vToFetch.push_back(pindexWalk);
5197 pindexWalk = pindexWalk->pprev;
5199 // If pindexWalk still isn't on our main chain, we're looking at a
5200 // very large reorg at a time we think we're close to caught up to
5201 // the main chain -- this shouldn't really happen. Bail out on the
5202 // direct fetch and rely on parallel download instead.
5203 if (!chainActive.Contains(pindexWalk)) {
5204 LogPrint("net", "Large reorg, won't direct fetch to %s (%d)\n",
5205 pindexLast->GetBlockHash().ToString(),
5206 pindexLast->nHeight);
5207 } else {
5208 vector<CInv> vGetData;
5209 // Download as much as possible, from earliest to latest.
5210 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vToFetch) {
5211 if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5212 // Can't download any more from this peer
5213 break;
5215 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5216 MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex);
5217 LogPrint("net", "Requesting block %s from peer=%d\n",
5218 pindex->GetBlockHash().ToString(), pfrom->id);
5220 if (vGetData.size() > 1) {
5221 LogPrint("net", "Downloading blocks toward %s (%d) via headers direct fetch\n",
5222 pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
5224 if (vGetData.size() > 0) {
5225 pfrom->PushMessage(NetMsgType::GETDATA, vGetData);
5230 CheckBlockIndex(chainparams.GetConsensus());
5233 NotifyHeaderTip();
5236 else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
5238 CBlock block;
5239 vRecv >> block;
5241 LogPrint("net", "received block %s peer=%d\n", block.GetHash().ToString(), pfrom->id);
5243 CValidationState state;
5244 // Process all blocks from whitelisted peers, even if not requested,
5245 // unless we're still syncing with the network.
5246 // Such an unrequested block may still be processed, subject to the
5247 // conditions in AcceptBlock().
5248 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5249 ProcessNewBlock(state, chainparams, pfrom, &block, forceProcessing, NULL);
5250 int nDoS;
5251 if (state.IsInvalid(nDoS)) {
5252 assert (state.GetRejectCode() < REJECT_INTERNAL); // Blocks are never rejected with internal reject codes
5253 pfrom->PushMessage(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
5254 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), block.GetHash());
5255 if (nDoS > 0) {
5256 LOCK(cs_main);
5257 Misbehaving(pfrom->GetId(), nDoS);
5264 else if (strCommand == NetMsgType::GETADDR)
5266 // This asymmetric behavior for inbound and outbound connections was introduced
5267 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5268 // to users' AddrMan and later request them by sending getaddr messages.
5269 // Making nodes which are behind NAT and can only make outgoing connections ignore
5270 // the getaddr message mitigates the attack.
5271 if (!pfrom->fInbound) {
5272 LogPrint("net", "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id);
5273 return true;
5276 // Only send one GetAddr response per connection to reduce resource waste
5277 // and discourage addr stamping of INV announcements.
5278 if (pfrom->fSentAddr) {
5279 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5280 return true;
5282 pfrom->fSentAddr = true;
5284 pfrom->vAddrToSend.clear();
5285 vector<CAddress> vAddr = addrman.GetAddr();
5286 BOOST_FOREACH(const CAddress &addr, vAddr)
5287 pfrom->PushAddress(addr);
5291 else if (strCommand == NetMsgType::MEMPOOL)
5293 if (CNode::OutboundTargetReached(false) && !pfrom->fWhitelisted)
5295 LogPrint("net", "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
5296 pfrom->fDisconnect = true;
5297 return true;
5300 LOCK(pfrom->cs_inventory);
5301 pfrom->fSendMempool = true;
5305 else if (strCommand == NetMsgType::PING)
5307 if (pfrom->nVersion > BIP0031_VERSION)
5309 uint64_t nonce = 0;
5310 vRecv >> nonce;
5311 // Echo the message back with the nonce. This allows for two useful features:
5313 // 1) A remote node can quickly check if the connection is operational
5314 // 2) Remote nodes can measure the latency of the network thread. If this node
5315 // is overloaded it won't respond to pings quickly and the remote node can
5316 // avoid sending us more work, like chain download requests.
5318 // The nonce stops the remote getting confused between different pings: without
5319 // it, if the remote node sends a ping once per second and this node takes 5
5320 // seconds to respond to each, the 5th ping the remote sends would appear to
5321 // return very quickly.
5322 pfrom->PushMessage(NetMsgType::PONG, nonce);
5327 else if (strCommand == NetMsgType::PONG)
5329 int64_t pingUsecEnd = nTimeReceived;
5330 uint64_t nonce = 0;
5331 size_t nAvail = vRecv.in_avail();
5332 bool bPingFinished = false;
5333 std::string sProblem;
5335 if (nAvail >= sizeof(nonce)) {
5336 vRecv >> nonce;
5338 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5339 if (pfrom->nPingNonceSent != 0) {
5340 if (nonce == pfrom->nPingNonceSent) {
5341 // Matching pong received, this ping is no longer outstanding
5342 bPingFinished = true;
5343 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5344 if (pingUsecTime > 0) {
5345 // Successful ping time measurement, replace previous
5346 pfrom->nPingUsecTime = pingUsecTime;
5347 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5348 } else {
5349 // This should never happen
5350 sProblem = "Timing mishap";
5352 } else {
5353 // Nonce mismatches are normal when pings are overlapping
5354 sProblem = "Nonce mismatch";
5355 if (nonce == 0) {
5356 // This is most likely a bug in another implementation somewhere; cancel this ping
5357 bPingFinished = true;
5358 sProblem = "Nonce zero";
5361 } else {
5362 sProblem = "Unsolicited pong without ping";
5364 } else {
5365 // This is most likely a bug in another implementation somewhere; cancel this ping
5366 bPingFinished = true;
5367 sProblem = "Short payload";
5370 if (!(sProblem.empty())) {
5371 LogPrint("net", "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
5372 pfrom->id,
5373 sProblem,
5374 pfrom->nPingNonceSent,
5375 nonce,
5376 nAvail);
5378 if (bPingFinished) {
5379 pfrom->nPingNonceSent = 0;
5384 else if (strCommand == NetMsgType::FILTERLOAD)
5386 CBloomFilter filter;
5387 vRecv >> filter;
5389 LOCK(pfrom->cs_filter);
5391 if (!filter.IsWithinSizeConstraints())
5392 // There is no excuse for sending a too-large filter
5393 Misbehaving(pfrom->GetId(), 100);
5394 else
5396 delete pfrom->pfilter;
5397 pfrom->pfilter = new CBloomFilter(filter);
5398 pfrom->pfilter->UpdateEmptyFull();
5400 pfrom->fRelayTxes = true;
5404 else if (strCommand == NetMsgType::FILTERADD)
5406 vector<unsigned char> vData;
5407 vRecv >> vData;
5409 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5410 // and thus, the maximum size any matched object can have) in a filteradd message
5411 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5413 Misbehaving(pfrom->GetId(), 100);
5414 } else {
5415 LOCK(pfrom->cs_filter);
5416 if (pfrom->pfilter)
5417 pfrom->pfilter->insert(vData);
5418 else
5419 Misbehaving(pfrom->GetId(), 100);
5424 else if (strCommand == NetMsgType::FILTERCLEAR)
5426 LOCK(pfrom->cs_filter);
5427 delete pfrom->pfilter;
5428 pfrom->pfilter = new CBloomFilter();
5429 pfrom->fRelayTxes = true;
5433 else if (strCommand == NetMsgType::REJECT)
5435 if (fDebug) {
5436 try {
5437 string strMsg; unsigned char ccode; string strReason;
5438 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5440 ostringstream ss;
5441 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5443 if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
5445 uint256 hash;
5446 vRecv >> hash;
5447 ss << ": hash " << hash.ToString();
5449 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5450 } catch (const std::ios_base::failure&) {
5451 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5452 LogPrint("net", "Unparseable reject message received\n");
5457 else if (strCommand == NetMsgType::FEEFILTER) {
5458 CAmount newFeeFilter = 0;
5459 vRecv >> newFeeFilter;
5460 if (MoneyRange(newFeeFilter)) {
5462 LOCK(pfrom->cs_feeFilter);
5463 pfrom->minFeeFilter = newFeeFilter;
5465 LogPrint("net", "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->id);
5469 else {
5470 // Ignore unknown commands for extensibility
5471 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5476 return true;
5479 // requires LOCK(cs_vRecvMsg)
5480 bool ProcessMessages(CNode* pfrom)
5482 const CChainParams& chainparams = Params();
5483 //if (fDebug)
5484 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5487 // Message format
5488 // (4) message start
5489 // (12) command
5490 // (4) size
5491 // (4) checksum
5492 // (x) data
5494 bool fOk = true;
5496 if (!pfrom->vRecvGetData.empty())
5497 ProcessGetData(pfrom, chainparams.GetConsensus());
5499 // this maintains the order of responses
5500 if (!pfrom->vRecvGetData.empty()) return fOk;
5502 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5503 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5504 // Don't bother if send buffer is too full to respond anyway
5505 if (pfrom->nSendSize >= SendBufferSize())
5506 break;
5508 // get next message
5509 CNetMessage& msg = *it;
5511 //if (fDebug)
5512 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5513 // msg.hdr.nMessageSize, msg.vRecv.size(),
5514 // msg.complete() ? "Y" : "N");
5516 // end, if an incomplete message is found
5517 if (!msg.complete())
5518 break;
5520 // at this point, any failure means we can delete the current message
5521 it++;
5523 // Scan for message start
5524 if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), MESSAGE_START_SIZE) != 0) {
5525 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5526 fOk = false;
5527 break;
5530 // Read header
5531 CMessageHeader& hdr = msg.hdr;
5532 if (!hdr.IsValid(chainparams.MessageStart()))
5534 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5535 continue;
5537 string strCommand = hdr.GetCommand();
5539 // Message size
5540 unsigned int nMessageSize = hdr.nMessageSize;
5542 // Checksum
5543 CDataStream& vRecv = msg.vRecv;
5544 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5545 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5546 if (nChecksum != hdr.nChecksum)
5548 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5549 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5550 continue;
5553 // Process message
5554 bool fRet = false;
5557 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams);
5558 boost::this_thread::interruption_point();
5560 catch (const std::ios_base::failure& e)
5562 pfrom->PushMessage(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, string("error parsing message"));
5563 if (strstr(e.what(), "end of data"))
5565 // Allow exceptions from under-length message on vRecv
5566 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());
5568 else if (strstr(e.what(), "size too large"))
5570 // Allow exceptions from over-long size
5571 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5573 else
5575 PrintExceptionContinue(&e, "ProcessMessages()");
5578 catch (const boost::thread_interrupted&) {
5579 throw;
5581 catch (const std::exception& e) {
5582 PrintExceptionContinue(&e, "ProcessMessages()");
5583 } catch (...) {
5584 PrintExceptionContinue(NULL, "ProcessMessages()");
5587 if (!fRet)
5588 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5590 break;
5593 // In case the connection got shut down, its receive buffer was wiped
5594 if (!pfrom->fDisconnect)
5595 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5597 return fOk;
5600 class CompareInvMempoolOrder
5602 CTxMemPool *mp;
5603 public:
5604 CompareInvMempoolOrder(CTxMemPool *mempool)
5606 mp = mempool;
5609 bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
5611 /* As std::make_heap produces a max-heap, we want the entries with the
5612 * fewest ancestors/highest fee to sort later. */
5613 return mp->CompareDepthAndScore(*b, *a);
5617 bool SendMessages(CNode* pto)
5619 const Consensus::Params& consensusParams = Params().GetConsensus();
5621 // Don't send anything until we get its version message
5622 if (pto->nVersion == 0)
5623 return true;
5626 // Message: ping
5628 bool pingSend = false;
5629 if (pto->fPingQueued) {
5630 // RPC ping request by user
5631 pingSend = true;
5633 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5634 // Ping automatically sent as a latency probe & keepalive.
5635 pingSend = true;
5637 if (pingSend) {
5638 uint64_t nonce = 0;
5639 while (nonce == 0) {
5640 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5642 pto->fPingQueued = false;
5643 pto->nPingUsecStart = GetTimeMicros();
5644 if (pto->nVersion > BIP0031_VERSION) {
5645 pto->nPingNonceSent = nonce;
5646 pto->PushMessage(NetMsgType::PING, nonce);
5647 } else {
5648 // Peer is too old to support ping command with nonce, pong will never arrive.
5649 pto->nPingNonceSent = 0;
5650 pto->PushMessage(NetMsgType::PING);
5654 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5655 if (!lockMain)
5656 return true;
5658 // Address refresh broadcast
5659 int64_t nNow = GetTimeMicros();
5660 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
5661 AdvertiseLocal(pto);
5662 pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
5666 // Message: addr
5668 if (pto->nNextAddrSend < nNow) {
5669 pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
5670 vector<CAddress> vAddr;
5671 vAddr.reserve(pto->vAddrToSend.size());
5672 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5674 if (!pto->addrKnown.contains(addr.GetKey()))
5676 pto->addrKnown.insert(addr.GetKey());
5677 vAddr.push_back(addr);
5678 // receiver rejects addr messages larger than 1000
5679 if (vAddr.size() >= 1000)
5681 pto->PushMessage(NetMsgType::ADDR, vAddr);
5682 vAddr.clear();
5686 pto->vAddrToSend.clear();
5687 if (!vAddr.empty())
5688 pto->PushMessage(NetMsgType::ADDR, vAddr);
5691 CNodeState &state = *State(pto->GetId());
5692 if (state.fShouldBan) {
5693 if (pto->fWhitelisted)
5694 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5695 else {
5696 pto->fDisconnect = true;
5697 if (pto->addr.IsLocal())
5698 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5699 else
5701 CNode::Ban(pto->addr, BanReasonNodeMisbehaving);
5704 state.fShouldBan = false;
5707 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5708 pto->PushMessage(NetMsgType::REJECT, (string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5709 state.rejects.clear();
5711 // Start block sync
5712 if (pindexBestHeader == NULL)
5713 pindexBestHeader = chainActive.Tip();
5714 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.
5715 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5716 // Only actively request headers from a single peer, unless we're close to today.
5717 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5718 state.fSyncStarted = true;
5719 nSyncStarted++;
5720 const CBlockIndex *pindexStart = pindexBestHeader;
5721 /* If possible, start at the block preceding the currently
5722 best known header. This ensures that we always get a
5723 non-empty list of headers back as long as the peer
5724 is up-to-date. With a non-empty response, we can initialise
5725 the peer's known best block. This wouldn't be possible
5726 if we requested starting at pindexBestHeader and
5727 got back an empty response. */
5728 if (pindexStart->pprev)
5729 pindexStart = pindexStart->pprev;
5730 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5731 pto->PushMessage(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256());
5735 // Resend wallet transactions that haven't gotten in a block yet
5736 // Except during reindex, importing and IBD, when old wallet
5737 // transactions become unconfirmed and spams other nodes.
5738 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5740 GetMainSignals().Broadcast(nTimeBestReceived);
5744 // Try sending block announcements via headers
5747 // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
5748 // list of block hashes we're relaying, and our peer wants
5749 // headers announcements, then find the first header
5750 // not yet known to our peer but would connect, and send.
5751 // If no header would connect, or if we have too many
5752 // blocks, or if the peer doesn't want headers, just
5753 // add all to the inv queue.
5754 LOCK(pto->cs_inventory);
5755 vector<CBlock> vHeaders;
5756 bool fRevertToInv = (!state.fPreferHeaders || pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
5757 CBlockIndex *pBestIndex = NULL; // last header queued for delivery
5758 ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date
5760 if (!fRevertToInv) {
5761 bool fFoundStartingHeader = false;
5762 // Try to find first header that our peer doesn't have, and
5763 // then send all headers past that one. If we come across any
5764 // headers that aren't on chainActive, give up.
5765 BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
5766 BlockMap::iterator mi = mapBlockIndex.find(hash);
5767 assert(mi != mapBlockIndex.end());
5768 CBlockIndex *pindex = mi->second;
5769 if (chainActive[pindex->nHeight] != pindex) {
5770 // Bail out if we reorged away from this block
5771 fRevertToInv = true;
5772 break;
5774 if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
5775 // This means that the list of blocks to announce don't
5776 // connect to each other.
5777 // This shouldn't really be possible to hit during
5778 // regular operation (because reorgs should take us to
5779 // a chain that has some block not on the prior chain,
5780 // which should be caught by the prior check), but one
5781 // way this could happen is by using invalidateblock /
5782 // reconsiderblock repeatedly on the tip, causing it to
5783 // be added multiple times to vBlockHashesToAnnounce.
5784 // Robustly deal with this rare situation by reverting
5785 // to an inv.
5786 fRevertToInv = true;
5787 break;
5789 pBestIndex = pindex;
5790 if (fFoundStartingHeader) {
5791 // add this to the headers message
5792 vHeaders.push_back(pindex->GetBlockHeader());
5793 } else if (PeerHasHeader(&state, pindex)) {
5794 continue; // keep looking for the first new block
5795 } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
5796 // Peer doesn't have this header but they do have the prior one.
5797 // Start sending headers.
5798 fFoundStartingHeader = true;
5799 vHeaders.push_back(pindex->GetBlockHeader());
5800 } else {
5801 // Peer doesn't have this header or the prior one -- nothing will
5802 // connect, so bail out.
5803 fRevertToInv = true;
5804 break;
5808 if (fRevertToInv) {
5809 // If falling back to using an inv, just try to inv the tip.
5810 // The last entry in vBlockHashesToAnnounce was our tip at some point
5811 // in the past.
5812 if (!pto->vBlockHashesToAnnounce.empty()) {
5813 const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
5814 BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
5815 assert(mi != mapBlockIndex.end());
5816 CBlockIndex *pindex = mi->second;
5818 // Warn if we're announcing a block that is not on the main chain.
5819 // This should be very rare and could be optimized out.
5820 // Just log for now.
5821 if (chainActive[pindex->nHeight] != pindex) {
5822 LogPrint("net", "Announcing block %s not on main chain (tip=%s)\n",
5823 hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
5826 // If the peer's chain has this block, don't inv it back.
5827 if (!PeerHasHeader(&state, pindex)) {
5828 pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
5829 LogPrint("net", "%s: sending inv peer=%d hash=%s\n", __func__,
5830 pto->id, hashToAnnounce.ToString());
5833 } else if (!vHeaders.empty()) {
5834 if (vHeaders.size() > 1) {
5835 LogPrint("net", "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
5836 vHeaders.size(),
5837 vHeaders.front().GetHash().ToString(),
5838 vHeaders.back().GetHash().ToString(), pto->id);
5839 } else {
5840 LogPrint("net", "%s: sending header %s to peer=%d\n", __func__,
5841 vHeaders.front().GetHash().ToString(), pto->id);
5843 pto->PushMessage(NetMsgType::HEADERS, vHeaders);
5844 state.pindexBestHeaderSent = pBestIndex;
5846 pto->vBlockHashesToAnnounce.clear();
5850 // Message: inventory
5852 vector<CInv> vInv;
5854 LOCK(pto->cs_inventory);
5855 vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
5857 // Add blocks
5858 BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
5859 vInv.push_back(CInv(MSG_BLOCK, hash));
5860 if (vInv.size() == MAX_INV_SZ) {
5861 pto->PushMessage(NetMsgType::INV, vInv);
5862 vInv.clear();
5865 pto->vInventoryBlockToSend.clear();
5867 // Check whether periodic sends should happen
5868 bool fSendTrickle = pto->fWhitelisted;
5869 if (pto->nNextInvSend < nNow) {
5870 fSendTrickle = true;
5871 // Use half the delay for outbound peers, as there is less privacy concern for them.
5872 pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
5875 // Time to send but the peer has requested we not relay transactions.
5876 if (fSendTrickle) {
5877 LOCK(pto->cs_filter);
5878 if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
5881 // Respond to BIP35 mempool requests
5882 if (fSendTrickle && pto->fSendMempool) {
5883 std::vector<uint256> vtxid;
5884 mempool.queryHashes(vtxid);
5885 pto->fSendMempool = false;
5886 CAmount filterrate = 0;
5888 LOCK(pto->cs_feeFilter);
5889 filterrate = pto->minFeeFilter;
5892 LOCK(pto->cs_filter);
5894 BOOST_FOREACH(const uint256& hash, vtxid) {
5895 CInv inv(MSG_TX, hash);
5896 pto->setInventoryTxToSend.erase(hash);
5897 if (filterrate) {
5898 CFeeRate feeRate;
5899 mempool.lookupFeeRate(hash, feeRate);
5900 if (feeRate.GetFeePerK() < filterrate)
5901 continue;
5903 if (pto->pfilter) {
5904 CTransaction tx;
5905 bool fInMemPool = mempool.lookup(hash, tx);
5906 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5907 if (!pto->pfilter->IsRelevantAndUpdate(tx)) continue;
5909 pto->filterInventoryKnown.insert(hash);
5910 vInv.push_back(inv);
5911 if (vInv.size() == MAX_INV_SZ) {
5912 pto->PushMessage(NetMsgType::INV, vInv);
5913 vInv.clear();
5916 pto->timeLastMempoolReq = GetTime();
5919 // Determine transactions to relay
5920 if (fSendTrickle) {
5921 // Produce a vector with all candidates for sending
5922 vector<std::set<uint256>::iterator> vInvTx;
5923 vInvTx.reserve(pto->setInventoryTxToSend.size());
5924 for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
5925 vInvTx.push_back(it);
5927 CAmount filterrate = 0;
5929 LOCK(pto->cs_feeFilter);
5930 filterrate = pto->minFeeFilter;
5932 // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
5933 // A heap is used so that not all items need sorting if only a few are being sent.
5934 CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
5935 std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5936 // No reason to drain out at many times the network's capacity,
5937 // especially since we have many peers and some will draw much shorter delays.
5938 unsigned int nRelayedTransactions = 0;
5939 LOCK(pto->cs_filter);
5940 while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
5941 // Fetch the top element from the heap
5942 std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
5943 std::set<uint256>::iterator it = vInvTx.back();
5944 vInvTx.pop_back();
5945 uint256 hash = *it;
5946 // Remove it from the to-be-sent set
5947 pto->setInventoryTxToSend.erase(it);
5948 // Check if not in the filter already
5949 if (pto->filterInventoryKnown.contains(hash)) {
5950 continue;
5952 // Not in the mempool anymore? don't bother sending it.
5953 CFeeRate feeRate;
5954 if (!mempool.lookupFeeRate(hash, feeRate)) {
5955 continue;
5957 if (filterrate && feeRate.GetFeePerK() < filterrate) {
5958 continue;
5960 CTransaction tx;
5961 if (!mempool.lookup(hash, tx)) continue;
5962 if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(tx)) continue;
5963 // Send
5964 vInv.push_back(CInv(MSG_TX, hash));
5965 nRelayedTransactions++;
5967 LOCK(cs_mapRelay);
5968 // Expire old relay messages
5969 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
5971 mapRelay.erase(vRelayExpiration.front().second);
5972 vRelayExpiration.pop_front();
5975 auto ret = mapRelay.insert(std::make_pair(hash, tx));
5976 if (ret.second) {
5977 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, hash));
5980 if (vInv.size() == MAX_INV_SZ) {
5981 pto->PushMessage(NetMsgType::INV, vInv);
5982 vInv.clear();
5984 pto->filterInventoryKnown.insert(hash);
5988 if (!vInv.empty())
5989 pto->PushMessage(NetMsgType::INV, vInv);
5991 // Detect whether we're stalling
5992 nNow = GetTimeMicros();
5993 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5994 // Stalling only triggers when the block download window cannot move. During normal steady state,
5995 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5996 // should only happen during initial block download.
5997 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5998 pto->fDisconnect = true;
6000 // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
6001 // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
6002 // We compensate for other peers to prevent killing off peers due to our own downstream link
6003 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6004 // to unreasonably increase our timeout.
6005 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
6006 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
6007 int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
6008 if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
6009 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
6010 pto->fDisconnect = true;
6015 // Message: getdata (blocks)
6017 vector<CInv> vGetData;
6018 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
6019 vector<CBlockIndex*> vToDownload;
6020 NodeId staller = -1;
6021 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
6022 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
6023 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
6024 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
6025 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6026 pindex->nHeight, pto->id);
6028 if (state.nBlocksInFlight == 0 && staller != -1) {
6029 if (State(staller)->nStallingSince == 0) {
6030 State(staller)->nStallingSince = nNow;
6031 LogPrint("net", "Stall started peer=%d\n", staller);
6037 // Message: getdata (non-blocks)
6039 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
6041 const CInv& inv = (*pto->mapAskFor.begin()).second;
6042 if (!AlreadyHave(inv))
6044 if (fDebug)
6045 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
6046 vGetData.push_back(inv);
6047 if (vGetData.size() >= 1000)
6049 pto->PushMessage(NetMsgType::GETDATA, vGetData);
6050 vGetData.clear();
6052 } else {
6053 //If we're not going to ask, don't expect a response.
6054 pto->setAskFor.erase(inv.hash);
6056 pto->mapAskFor.erase(pto->mapAskFor.begin());
6058 if (!vGetData.empty())
6059 pto->PushMessage(NetMsgType::GETDATA, vGetData);
6062 // Message: feefilter
6064 // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
6065 if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
6066 !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
6067 CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
6068 int64_t timeNow = GetTimeMicros();
6069 if (timeNow > pto->nextSendTimeFeeFilter) {
6070 CAmount filterToSend = filterRounder.round(currentFilter);
6071 if (filterToSend != pto->lastSentFeeFilter) {
6072 pto->PushMessage(NetMsgType::FEEFILTER, filterToSend);
6073 pto->lastSentFeeFilter = filterToSend;
6075 pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
6077 // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
6078 // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
6079 else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
6080 (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
6081 pto->nextSendTimeFeeFilter = timeNow + (insecure_rand() % MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
6085 return true;
6088 std::string CBlockFileInfo::ToString() const {
6089 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));
6092 ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
6094 LOCK(cs_main);
6095 return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
6098 class CMainCleanup
6100 public:
6101 CMainCleanup() {}
6102 ~CMainCleanup() {
6103 // block headers
6104 BlockMap::iterator it1 = mapBlockIndex.begin();
6105 for (; it1 != mapBlockIndex.end(); it1++)
6106 delete (*it1).second;
6107 mapBlockIndex.clear();
6109 // orphan transactions
6110 mapOrphanTransactions.clear();
6111 mapOrphanTransactionsByPrev.clear();
6113 } instance_of_cmaincleanup;