1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "arith_uint256.h"
13 #include "chainparams.h"
14 #include "checkpoints.h"
15 #include "checkqueue.h"
16 #include "consensus/validation.h"
18 #include "merkleblock.h"
23 #include "txmempool.h"
24 #include "ui_interface.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
29 #include "wallet/asyncrpcoperation_sendmany.h"
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/filesystem/fstream.hpp>
36 #include <boost/math/distributions/poisson.hpp>
37 #include <boost/thread.hpp>
38 #include <boost/static_assert.hpp>
43 # error "Zcash cannot be compiled without assertions."
50 CCriticalSection cs_main;
52 BlockMap mapBlockIndex;
54 CBlockIndex *pindexBestHeader = NULL;
55 int64_t nTimeBestReceived = 0;
56 CWaitableCriticalSection csBestBlock;
57 CConditionVariable cvBlockChange;
58 int nScriptCheckThreads = 0;
59 bool fExperimentalMode = false;
60 bool fImporting = false;
61 bool fReindex = false;
62 bool fTxIndex = false;
63 bool fHavePruned = false;
64 bool fPruneMode = false;
65 bool fIsBareMultisigStd = true;
66 bool fCheckBlockIndex = false;
67 bool fCheckpointsEnabled = true;
68 bool fCoinbaseEnforcedProtectionEnabled = true;
69 size_t nCoinCacheUsage = 5000 * 300;
70 uint64_t nPruneTarget = 0;
71 bool fAlerts = DEFAULT_ALERTS;
73 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
74 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
76 CTxMemPool mempool(::minRelayTxFee);
82 map<uint256, COrphanTx> mapOrphanTransactions;
83 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
84 void EraseOrphansFor(NodeId peer);
87 * Returns true if there are nRequired or more blocks of minVersion or above
88 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
90 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
91 static void CheckBlockIndex();
93 /** Constant stuff for coinbase transactions we create: */
94 CScript COINBASE_FLAGS;
96 const string strMessageMagic = "Zcash Signed Message:\n";
101 struct CBlockIndexWorkComparator
103 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
104 // First sort by most total work, ...
105 if (pa->nChainWork > pb->nChainWork) return false;
106 if (pa->nChainWork < pb->nChainWork) return true;
108 // ... then by earliest time received, ...
109 if (pa->nSequenceId < pb->nSequenceId) return false;
110 if (pa->nSequenceId > pb->nSequenceId) return true;
112 // Use pointer address as tie breaker (should only happen with blocks
113 // loaded from disk, as those all have id 0).
114 if (pa < pb) return false;
115 if (pa > pb) return true;
122 CBlockIndex *pindexBestInvalid;
125 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
126 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
127 * missing the data for the block.
129 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
130 /** Number of nodes with fSyncStarted. */
131 int nSyncStarted = 0;
132 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
133 * Pruned nodes may have entries where B is missing data.
135 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
137 CCriticalSection cs_LastBlockFile;
138 std::vector<CBlockFileInfo> vinfoBlockFile;
139 int nLastBlockFile = 0;
140 /** Global flag to indicate we should check to see if there are
141 * block/undo files that should be deleted. Set on startup
142 * or if we allocate more file space when we're in prune mode
144 bool fCheckForPruning = false;
147 * Every received block is assigned a unique and increasing identifier, so we
148 * know which one to give priority in case of a fork.
150 CCriticalSection cs_nBlockSequenceId;
151 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
152 uint32_t nBlockSequenceId = 1;
155 * Sources of received blocks, saved to be able to send them reject
156 * messages or ban them when processing happens afterwards. Protected by
159 map<uint256, NodeId> mapBlockSource;
162 * Filter for transactions that were recently rejected by
163 * AcceptToMemoryPool. These are not rerequested until the chain tip
164 * changes, at which point the entire filter is reset. Protected by
167 * Without this filter we'd be re-requesting txs from each of our peers,
168 * increasing bandwidth consumption considerably. For instance, with 100
169 * peers, half of which relay a tx we don't accept, that might be a 50x
170 * bandwidth increase. A flooding attacker attempting to roll-over the
171 * filter using minimum-sized, 60byte, transactions might manage to send
172 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
173 * two minute window to send invs to us.
175 * Decreasing the false positive rate is fairly cheap, so we pick one in a
176 * million to make it highly unlikely for users to have issues with this
181 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
182 uint256 hashRecentRejectsChainTip;
184 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
187 CBlockIndex *pindex; //! Optional.
188 int64_t nTime; //! Time of "getdata" request in microseconds.
189 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
190 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
192 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
194 /** Number of blocks in flight with validated headers. */
195 int nQueuedValidatedHeaders = 0;
197 /** Number of preferable block download peers. */
198 int nPreferredDownload = 0;
200 /** Dirty block index entries. */
201 set<CBlockIndex*> setDirtyBlockIndex;
203 /** Dirty block file entries. */
204 set<int> setDirtyFileInfo;
207 //////////////////////////////////////////////////////////////////////////////
209 // Registration of network node signals.
214 struct CBlockReject {
215 unsigned char chRejectCode;
216 string strRejectReason;
221 * Maintain validation-specific state about nodes, protected by cs_main, instead
222 * by CNode's own locks. This simplifies asynchronous operation, where
223 * processing of incoming data is done after the ProcessMessage call returns,
224 * and we're no longer holding the node's locks.
227 //! The peer's address
229 //! Whether we have a fully established connection.
230 bool fCurrentlyConnected;
231 //! Accumulated misbehaviour score for this peer.
233 //! Whether this peer should be disconnected and banned (unless whitelisted).
235 //! String name of this peer (debugging/logging purposes).
237 //! List of asynchronously-determined block rejections to notify this peer about.
238 std::vector<CBlockReject> rejects;
239 //! The best known block we know this peer has announced.
240 CBlockIndex *pindexBestKnownBlock;
241 //! The hash of the last unknown block this peer has announced.
242 uint256 hashLastUnknownBlock;
243 //! The last full block we both have.
244 CBlockIndex *pindexLastCommonBlock;
245 //! Whether we've started headers synchronization with this peer.
247 //! Since when we're stalling block download progress (in microseconds), or 0.
248 int64_t nStallingSince;
249 list<QueuedBlock> vBlocksInFlight;
251 int nBlocksInFlightValidHeaders;
252 //! Whether we consider this a preferred download peer.
253 bool fPreferredDownload;
256 fCurrentlyConnected = false;
259 pindexBestKnownBlock = NULL;
260 hashLastUnknownBlock.SetNull();
261 pindexLastCommonBlock = NULL;
262 fSyncStarted = false;
265 nBlocksInFlightValidHeaders = 0;
266 fPreferredDownload = false;
270 /** Map maintaining per-node state. Requires cs_main. */
271 map<NodeId, CNodeState> mapNodeState;
274 CNodeState *State(NodeId pnode) {
275 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
276 if (it == mapNodeState.end())
284 return chainActive.Height();
287 void UpdatePreferredDownload(CNode* node, CNodeState* state)
289 nPreferredDownload -= state->fPreferredDownload;
291 // Whether this node should be marked as a preferred download node.
292 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
294 nPreferredDownload += state->fPreferredDownload;
297 // Returns time at which to timeout block request (nTime in microseconds)
298 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
300 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
303 void InitializeNode(NodeId nodeid, const CNode *pnode) {
305 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
306 state.name = pnode->addrName;
307 state.address = pnode->addr;
310 void FinalizeNode(NodeId nodeid) {
312 CNodeState *state = State(nodeid);
314 if (state->fSyncStarted)
317 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
318 AddressCurrentlyConnected(state->address);
321 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
322 mapBlocksInFlight.erase(entry.hash);
323 EraseOrphansFor(nodeid);
324 nPreferredDownload -= state->fPreferredDownload;
326 mapNodeState.erase(nodeid);
330 // Returns a bool indicating whether we requested this block.
331 bool MarkBlockAsReceived(const uint256& hash) {
332 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
333 if (itInFlight != mapBlocksInFlight.end()) {
334 CNodeState *state = State(itInFlight->second.first);
335 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
336 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
337 state->vBlocksInFlight.erase(itInFlight->second.second);
338 state->nBlocksInFlight--;
339 state->nStallingSince = 0;
340 mapBlocksInFlight.erase(itInFlight);
347 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
348 CNodeState *state = State(nodeid);
349 assert(state != NULL);
351 // Make sure it's not listed somewhere already.
352 MarkBlockAsReceived(hash);
354 int64_t nNow = GetTimeMicros();
355 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
356 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
357 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
358 state->nBlocksInFlight++;
359 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
360 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
363 /** Check whether the last unknown block a peer advertized is not yet known. */
364 void ProcessBlockAvailability(NodeId nodeid) {
365 CNodeState *state = State(nodeid);
366 assert(state != NULL);
368 if (!state->hashLastUnknownBlock.IsNull()) {
369 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
370 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
371 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
372 state->pindexBestKnownBlock = itOld->second;
373 state->hashLastUnknownBlock.SetNull();
378 /** Update tracking information about which blocks a peer is assumed to have. */
379 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
380 CNodeState *state = State(nodeid);
381 assert(state != NULL);
383 ProcessBlockAvailability(nodeid);
385 BlockMap::iterator it = mapBlockIndex.find(hash);
386 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
387 // An actually better block was announced.
388 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
389 state->pindexBestKnownBlock = it->second;
391 // An unknown block was announced; just assume that the latest one is the best one.
392 state->hashLastUnknownBlock = hash;
396 /** Find the last common ancestor two blocks have.
397 * Both pa and pb must be non-NULL. */
398 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
399 if (pa->nHeight > pb->nHeight) {
400 pa = pa->GetAncestor(pb->nHeight);
401 } else if (pb->nHeight > pa->nHeight) {
402 pb = pb->GetAncestor(pa->nHeight);
405 while (pa != pb && pa && pb) {
410 // Eventually all chain branches meet at the genesis block.
415 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
416 * at most count entries. */
417 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
421 vBlocks.reserve(vBlocks.size() + count);
422 CNodeState *state = State(nodeid);
423 assert(state != NULL);
425 // Make sure pindexBestKnownBlock is up to date, we'll need it.
426 ProcessBlockAvailability(nodeid);
428 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
429 // This peer has nothing interesting.
433 if (state->pindexLastCommonBlock == NULL) {
434 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
435 // Guessing wrong in either direction is not a problem.
436 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
439 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
440 // of its current tip anymore. Go back enough to fix that.
441 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
442 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
445 std::vector<CBlockIndex*> vToFetch;
446 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
447 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
448 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
449 // download that next block if the window were 1 larger.
450 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
451 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
452 NodeId waitingfor = -1;
453 while (pindexWalk->nHeight < nMaxHeight) {
454 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
455 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
456 // as iterating over ~100 CBlockIndex* entries anyway.
457 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
458 vToFetch.resize(nToFetch);
459 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
460 vToFetch[nToFetch - 1] = pindexWalk;
461 for (unsigned int i = nToFetch - 1; i > 0; i--) {
462 vToFetch[i - 1] = vToFetch[i]->pprev;
465 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
466 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
467 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
468 // already part of our chain (and therefore don't need it even if pruned).
469 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
470 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
471 // We consider the chain that this peer is on invalid.
474 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
475 if (pindex->nChainTx)
476 state->pindexLastCommonBlock = pindex;
477 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
478 // The block is not already downloaded, and not yet in flight.
479 if (pindex->nHeight > nWindowEnd) {
480 // We reached the end of the window.
481 if (vBlocks.size() == 0 && waitingfor != nodeid) {
482 // We aren't able to fetch anything, but we would be if the download window was one larger.
483 nodeStaller = waitingfor;
487 vBlocks.push_back(pindex);
488 if (vBlocks.size() == count) {
491 } else if (waitingfor == -1) {
492 // This is the first already-in-flight block.
493 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
501 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
503 CNodeState *state = State(nodeid);
506 stats.nMisbehavior = state->nMisbehavior;
507 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
508 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
509 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
511 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
516 void RegisterNodeSignals(CNodeSignals& nodeSignals)
518 nodeSignals.GetHeight.connect(&GetHeight);
519 nodeSignals.ProcessMessages.connect(&ProcessMessages);
520 nodeSignals.SendMessages.connect(&SendMessages);
521 nodeSignals.InitializeNode.connect(&InitializeNode);
522 nodeSignals.FinalizeNode.connect(&FinalizeNode);
525 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
527 nodeSignals.GetHeight.disconnect(&GetHeight);
528 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
529 nodeSignals.SendMessages.disconnect(&SendMessages);
530 nodeSignals.InitializeNode.disconnect(&InitializeNode);
531 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
534 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
536 // Find the first block the caller has in the main chain
537 BOOST_FOREACH(const uint256& hash, locator.vHave) {
538 BlockMap::iterator mi = mapBlockIndex.find(hash);
539 if (mi != mapBlockIndex.end())
541 CBlockIndex* pindex = (*mi).second;
542 if (chain.Contains(pindex))
546 return chain.Genesis();
549 CCoinsViewCache *pcoinsTip = NULL;
550 CBlockTreeDB *pblocktree = NULL;
552 //////////////////////////////////////////////////////////////////////////////
554 // mapOrphanTransactions
557 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
559 uint256 hash = tx.GetHash();
560 if (mapOrphanTransactions.count(hash))
563 // Ignore big transactions, to avoid a
564 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
565 // large transaction with a missing parent then we assume
566 // it will rebroadcast it later, after the parent transaction(s)
567 // have been mined or received.
568 // 10,000 orphans, each of which is at most 5,000 bytes big is
569 // at most 500 megabytes of orphans:
570 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
573 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
577 mapOrphanTransactions[hash].tx = tx;
578 mapOrphanTransactions[hash].fromPeer = peer;
579 BOOST_FOREACH(const CTxIn& txin, tx.vin)
580 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
582 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
583 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
587 void static EraseOrphanTx(uint256 hash)
589 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
590 if (it == mapOrphanTransactions.end())
592 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
594 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
595 if (itPrev == mapOrphanTransactionsByPrev.end())
597 itPrev->second.erase(hash);
598 if (itPrev->second.empty())
599 mapOrphanTransactionsByPrev.erase(itPrev);
601 mapOrphanTransactions.erase(it);
604 void EraseOrphansFor(NodeId peer)
607 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
608 while (iter != mapOrphanTransactions.end())
610 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
611 if (maybeErase->second.fromPeer == peer)
613 EraseOrphanTx(maybeErase->second.tx.GetHash());
617 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
621 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
623 unsigned int nEvicted = 0;
624 while (mapOrphanTransactions.size() > nMaxOrphans)
626 // Evict a random orphan:
627 uint256 randomhash = GetRandHash();
628 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
629 if (it == mapOrphanTransactions.end())
630 it = mapOrphanTransactions.begin();
631 EraseOrphanTx(it->first);
643 bool IsStandardTx(const CTransaction& tx, string& reason)
645 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
650 BOOST_FOREACH(const CTxIn& txin, tx.vin)
652 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
653 // keys. (remember the 520 byte limit on redeemScript size) That works
654 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
655 // bytes of scriptSig, which we round off to 1650 bytes for some minor
656 // future-proofing. That's also enough to spend a 20-of-20
657 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
658 // considered standard)
659 if (txin.scriptSig.size() > 1650) {
660 reason = "scriptsig-size";
663 if (!txin.scriptSig.IsPushOnly()) {
664 reason = "scriptsig-not-pushonly";
669 unsigned int nDataOut = 0;
670 txnouttype whichType;
671 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
672 if (!::IsStandard(txout.scriptPubKey, whichType)) {
673 reason = "scriptpubkey";
677 if (whichType == TX_NULL_DATA)
679 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
680 reason = "bare-multisig";
682 } else if (txout.IsDust(::minRelayTxFee)) {
688 // only one OP_RETURN txout is permitted
690 reason = "multi-op-return";
697 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
699 if (tx.nLockTime == 0)
701 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
703 BOOST_FOREACH(const CTxIn& txin, tx.vin)
709 bool CheckFinalTx(const CTransaction &tx, int flags)
711 AssertLockHeld(cs_main);
713 // By convention a negative value for flags indicates that the
714 // current network-enforced consensus rules should be used. In
715 // a future soft-fork scenario that would mean checking which
716 // rules would be enforced for the next block and setting the
717 // appropriate flags. At the present time no soft-forks are
718 // scheduled, so no flags are set.
719 flags = std::max(flags, 0);
721 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
722 // nLockTime because when IsFinalTx() is called within
723 // CBlock::AcceptBlock(), the height of the block *being*
724 // evaluated is what is used. Thus if we want to know if a
725 // transaction can be part of the *next* block, we need to call
726 // IsFinalTx() with one more than chainActive.Height().
727 const int nBlockHeight = chainActive.Height() + 1;
729 // Timestamps on the other hand don't get any special treatment,
730 // because we can't know what timestamp the next block will have,
731 // and there aren't timestamp applications where it matters.
732 // However this changes once median past time-locks are enforced:
733 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
734 ? chainActive.Tip()->GetMedianTimePast()
737 return IsFinalTx(tx, nBlockHeight, nBlockTime);
741 * Check transaction inputs to mitigate two
742 * potential denial-of-service attacks:
744 * 1. scriptSigs with extra data stuffed into them,
745 * not consumed by scriptPubKey (or P2SH script)
746 * 2. P2SH scripts with a crazy number of expensive
747 * CHECKSIG/CHECKMULTISIG operations
749 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
752 return true; // Coinbases don't use vin normally
754 for (unsigned int i = 0; i < tx.vin.size(); i++)
756 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
758 vector<vector<unsigned char> > vSolutions;
759 txnouttype whichType;
760 // get the scriptPubKey corresponding to this input:
761 const CScript& prevScript = prev.scriptPubKey;
762 if (!Solver(prevScript, whichType, vSolutions))
764 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
765 if (nArgsExpected < 0)
768 // Transactions with extra stuff in their scriptSigs are
769 // non-standard. Note that this EvalScript() call will
770 // be quick, because if there are any operations
771 // beside "push data" in the scriptSig
772 // IsStandardTx() will have already returned false
773 // and this method isn't called.
774 vector<vector<unsigned char> > stack;
775 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
778 if (whichType == TX_SCRIPTHASH)
782 CScript subscript(stack.back().begin(), stack.back().end());
783 vector<vector<unsigned char> > vSolutions2;
784 txnouttype whichType2;
785 if (Solver(subscript, whichType2, vSolutions2))
787 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
790 nArgsExpected += tmpExpected;
794 // Any other Script with less than 15 sigops OK:
795 unsigned int sigops = subscript.GetSigOpCount(true);
796 // ... extra data left on the stack after execution is OK, too:
797 return (sigops <= MAX_P2SH_SIGOPS);
801 if (stack.size() != (unsigned int)nArgsExpected)
808 unsigned int GetLegacySigOpCount(const CTransaction& tx)
810 unsigned int nSigOps = 0;
811 BOOST_FOREACH(const CTxIn& txin, tx.vin)
813 nSigOps += txin.scriptSig.GetSigOpCount(false);
815 BOOST_FOREACH(const CTxOut& txout, tx.vout)
817 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
822 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
827 unsigned int nSigOps = 0;
828 for (unsigned int i = 0; i < tx.vin.size(); i++)
830 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
831 if (prevout.scriptPubKey.IsPayToScriptHash())
832 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
837 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
838 libzcash::ProofVerifier& verifier)
840 // Don't count coinbase transactions because mining skews the count
841 if (!tx.IsCoinBase()) {
842 transactionsValidated.increment();
845 if (!CheckTransactionWithoutProofVerification(tx, state)) {
848 // Ensure that zk-SNARKs verify
849 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
850 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
851 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
852 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
859 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
861 // Basic checks that don't depend on any context
863 // Check transaction version
864 if (tx.nVersion < MIN_TX_VERSION) {
865 return state.DoS(100, error("CheckTransaction(): version too low"),
866 REJECT_INVALID, "bad-txns-version-too-low");
869 // Transactions can contain empty `vin` and `vout` so long as
870 // `vjoinsplit` is non-empty.
871 if (tx.vin.empty() && tx.vjoinsplit.empty())
872 return state.DoS(10, error("CheckTransaction(): vin empty"),
873 REJECT_INVALID, "bad-txns-vin-empty");
874 if (tx.vout.empty() && tx.vjoinsplit.empty())
875 return state.DoS(10, error("CheckTransaction(): vout empty"),
876 REJECT_INVALID, "bad-txns-vout-empty");
879 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
880 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
881 return state.DoS(100, error("CheckTransaction(): size limits failed"),
882 REJECT_INVALID, "bad-txns-oversize");
884 // Check for negative or overflow output values
885 CAmount nValueOut = 0;
886 BOOST_FOREACH(const CTxOut& txout, tx.vout)
888 if (txout.nValue < 0)
889 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
890 REJECT_INVALID, "bad-txns-vout-negative");
891 if (txout.nValue > MAX_MONEY)
892 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
893 REJECT_INVALID, "bad-txns-vout-toolarge");
894 nValueOut += txout.nValue;
895 if (!MoneyRange(nValueOut))
896 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
897 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
900 // Ensure that joinsplit values are well-formed
901 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
903 if (joinsplit.vpub_old < 0) {
904 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
905 REJECT_INVALID, "bad-txns-vpub_old-negative");
908 if (joinsplit.vpub_new < 0) {
909 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
910 REJECT_INVALID, "bad-txns-vpub_new-negative");
913 if (joinsplit.vpub_old > MAX_MONEY) {
914 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
915 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
918 if (joinsplit.vpub_new > MAX_MONEY) {
919 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
920 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
923 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
924 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
925 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
928 nValueOut += joinsplit.vpub_old;
929 if (!MoneyRange(nValueOut)) {
930 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
931 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
935 // Ensure input values do not exceed MAX_MONEY
936 // We have not resolved the txin values at this stage,
937 // but we do know what the joinsplits claim to add
938 // to the value pool.
940 CAmount nValueIn = 0;
941 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
943 nValueIn += it->vpub_new;
945 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
946 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
947 REJECT_INVALID, "bad-txns-txintotal-toolarge");
953 // Check for duplicate inputs
954 set<COutPoint> vInOutPoints;
955 BOOST_FOREACH(const CTxIn& txin, tx.vin)
957 if (vInOutPoints.count(txin.prevout))
958 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
959 REJECT_INVALID, "bad-txns-inputs-duplicate");
960 vInOutPoints.insert(txin.prevout);
963 // Check for duplicate joinsplit nullifiers in this transaction
964 set<uint256> vJoinSplitNullifiers;
965 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
967 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
969 if (vJoinSplitNullifiers.count(nf))
970 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
971 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
973 vJoinSplitNullifiers.insert(nf);
979 // There should be no joinsplits in a coinbase transaction
980 if (tx.vjoinsplit.size() > 0)
981 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
982 REJECT_INVALID, "bad-cb-has-joinsplits");
984 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
985 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
986 REJECT_INVALID, "bad-cb-length");
990 BOOST_FOREACH(const CTxIn& txin, tx.vin)
991 if (txin.prevout.IsNull())
992 return state.DoS(10, error("CheckTransaction(): prevout is null"),
993 REJECT_INVALID, "bad-txns-prevout-null");
995 if (tx.vjoinsplit.size() > 0) {
996 // Empty output script.
998 uint256 dataToBeSigned;
1000 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1001 } catch (std::logic_error ex) {
1002 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1003 REJECT_INVALID, "error-computing-signature-hash");
1006 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1008 // We rely on libsodium to check that the signature is canonical.
1009 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1010 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1011 dataToBeSigned.begin(), 32,
1012 tx.joinSplitPubKey.begin()
1014 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1015 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1023 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1027 uint256 hash = tx.GetHash();
1028 double dPriorityDelta = 0;
1029 CAmount nFeeDelta = 0;
1030 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1031 if (dPriorityDelta > 0 || nFeeDelta > 0)
1035 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1039 // There is a free transaction area in blocks created by most miners,
1040 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1041 // to be considered to fall into this category. We don't want to encourage sending
1042 // multiple transactions instead of one big transaction to avoid fees.
1043 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1047 if (!MoneyRange(nMinFee))
1048 nMinFee = MAX_MONEY;
1053 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1054 bool* pfMissingInputs, bool fRejectAbsurdFee)
1056 AssertLockHeld(cs_main);
1057 if (pfMissingInputs)
1058 *pfMissingInputs = false;
1060 auto verifier = libzcash::ProofVerifier::Strict();
1061 if (!CheckTransaction(tx, state, verifier))
1062 return error("AcceptToMemoryPool: CheckTransaction failed");
1064 // Coinbase is only valid in a block, not as a loose transaction
1065 if (tx.IsCoinBase())
1066 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1067 REJECT_INVALID, "coinbase");
1069 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1071 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1073 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1074 REJECT_NONSTANDARD, reason);
1076 // Only accept nLockTime-using transactions that can be mined in the next
1077 // block; we don't want our mempool filled up with transactions that can't
1079 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1080 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1082 // is it already in the memory pool?
1083 uint256 hash = tx.GetHash();
1084 if (pool.exists(hash))
1087 // Check for conflicts with in-memory transactions
1089 LOCK(pool.cs); // protect pool.mapNextTx
1090 for (unsigned int i = 0; i < tx.vin.size(); i++)
1092 COutPoint outpoint = tx.vin[i].prevout;
1093 if (pool.mapNextTx.count(outpoint))
1095 // Disable replacement feature for now
1099 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1100 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1101 if (pool.mapNullifiers.count(nf))
1111 CCoinsViewCache view(&dummy);
1113 CAmount nValueIn = 0;
1116 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1117 view.SetBackend(viewMemPool);
1119 // do we already have it?
1120 if (view.HaveCoins(hash))
1123 // do all inputs exist?
1124 // Note that this does not check for the presence of actual outputs (see the next check for that),
1125 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1126 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1127 if (!view.HaveCoins(txin.prevout.hash)) {
1128 if (pfMissingInputs)
1129 *pfMissingInputs = true;
1134 // are the actual inputs available?
1135 if (!view.HaveInputs(tx))
1136 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1137 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1139 // are the joinsplit's requirements met?
1140 if (!view.HaveJoinSplitRequirements(tx))
1141 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1142 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1144 // Bring the best block into scope
1145 view.GetBestBlock();
1147 nValueIn = view.GetValueIn(tx);
1149 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1150 view.SetBackend(dummy);
1153 // Check for non-standard pay-to-script-hash in inputs
1154 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1155 return error("AcceptToMemoryPool: nonstandard transaction input");
1157 // Check that the transaction doesn't have an excessive number of
1158 // sigops, making it impossible to mine. Since the coinbase transaction
1159 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1160 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1161 // merely non-standard transaction.
1162 unsigned int nSigOps = GetLegacySigOpCount(tx);
1163 nSigOps += GetP2SHSigOpCount(tx, view);
1164 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1166 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1167 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1168 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1170 CAmount nValueOut = tx.GetValueOut();
1171 CAmount nFees = nValueIn-nValueOut;
1172 double dPriority = view.GetPriority(tx, chainActive.Height());
1174 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1175 unsigned int nSize = entry.GetTxSize();
1177 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1178 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1179 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1181 // Don't accept it if it can't get into a block
1182 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1183 if (fLimitFree && nFees < txMinFee)
1184 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1185 hash.ToString(), nFees, txMinFee),
1186 REJECT_INSUFFICIENTFEE, "insufficient fee");
1189 // Require that free transactions have sufficient priority to be mined in the next block.
1190 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1191 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1194 // Continuously rate-limit free (really, very-low-fee) transactions
1195 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1196 // be annoying or make others' transactions take longer to confirm.
1197 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1199 static CCriticalSection csFreeLimiter;
1200 static double dFreeCount;
1201 static int64_t nLastTime;
1202 int64_t nNow = GetTime();
1204 LOCK(csFreeLimiter);
1206 // Use an exponentially decaying ~10-minute window:
1207 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1209 // -limitfreerelay unit is thousand-bytes-per-minute
1210 // At default rate it would take over a month to fill 1GB
1211 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1212 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1213 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1214 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1215 dFreeCount += nSize;
1218 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1219 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1221 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1223 // Check against previous transactions
1224 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1225 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1227 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1230 // Check again against just the consensus-critical mandatory script
1231 // verification flags, in case of bugs in the standard flags that cause
1232 // transactions to pass as valid when they're actually invalid. For
1233 // instance the STRICTENC flag was incorrectly allowing certain
1234 // CHECKSIG NOT scripts to pass, even though they were invalid.
1236 // There is a similar check in CreateNewBlock() to prevent creating
1237 // invalid blocks, however allowing such transactions into the mempool
1238 // can be exploited as a DoS attack.
1239 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1241 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1244 // Store transaction in memory
1245 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1248 SyncWithWallets(tx, NULL);
1253 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1254 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1256 CBlockIndex *pindexSlow = NULL;
1260 if (mempool.lookup(hash, txOut))
1267 if (pblocktree->ReadTxIndex(hash, postx)) {
1268 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1270 return error("%s: OpenBlockFile failed", __func__);
1271 CBlockHeader header;
1274 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1276 } catch (const std::exception& e) {
1277 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1279 hashBlock = header.GetHash();
1280 if (txOut.GetHash() != hash)
1281 return error("%s: txid mismatch", __func__);
1286 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1289 CCoinsViewCache &view = *pcoinsTip;
1290 const CCoins* coins = view.AccessCoins(hash);
1292 nHeight = coins->nHeight;
1295 pindexSlow = chainActive[nHeight];
1300 if (ReadBlockFromDisk(block, pindexSlow)) {
1301 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1302 if (tx.GetHash() == hash) {
1304 hashBlock = pindexSlow->GetBlockHash();
1319 //////////////////////////////////////////////////////////////////////////////
1321 // CBlock and CBlockIndex
1324 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1326 // Open history file to append
1327 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1328 if (fileout.IsNull())
1329 return error("WriteBlockToDisk: OpenBlockFile failed");
1331 // Write index header
1332 unsigned int nSize = fileout.GetSerializeSize(block);
1333 fileout << FLATDATA(messageStart) << nSize;
1336 long fileOutPos = ftell(fileout.Get());
1338 return error("WriteBlockToDisk: ftell failed");
1339 pos.nPos = (unsigned int)fileOutPos;
1345 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1349 // Open history file to read
1350 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1351 if (filein.IsNull())
1352 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1358 catch (const std::exception& e) {
1359 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1363 if (!(CheckEquihashSolution(&block, Params()) &&
1364 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1365 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1370 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1372 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1374 if (block.GetHash() != pindex->GetBlockHash())
1375 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1376 pindex->ToString(), pindex->GetBlockPos().ToString());
1380 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1382 CAmount nSubsidy = 12.5 * COIN;
1384 // Mining slow start
1385 // The subsidy is ramped up linearly, skipping the middle payout of
1386 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1387 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1388 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1389 nSubsidy *= nHeight;
1391 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1392 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1393 nSubsidy *= (nHeight+1);
1397 assert(nHeight > consensusParams.SubsidySlowStartShift());
1398 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1399 // Force block reward to zero when right shift is undefined.
1403 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1404 nSubsidy >>= halvings;
1408 bool IsInitialBlockDownload()
1410 const CChainParams& chainParams = Params();
1412 if (fImporting || fReindex)
1414 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1416 static bool lockIBDState = false;
1419 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1420 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1422 lockIBDState = true;
1426 bool fLargeWorkForkFound = false;
1427 bool fLargeWorkInvalidChainFound = false;
1428 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1430 void CheckForkWarningConditions()
1432 AssertLockHeld(cs_main);
1433 // Before we get past initial download, we cannot reliably alert about forks
1434 // (we assume we don't get stuck on a fork before the last checkpoint)
1435 if (IsInitialBlockDownload())
1438 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1439 // of our head, drop it
1440 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1441 pindexBestForkTip = NULL;
1443 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1445 if (!fLargeWorkForkFound && pindexBestForkBase)
1447 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1448 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1449 CAlert::Notify(warning, true);
1451 if (pindexBestForkTip && pindexBestForkBase)
1453 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__,
1454 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1455 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1456 fLargeWorkForkFound = true;
1460 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1461 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1462 CAlert::Notify(warning, true);
1463 fLargeWorkInvalidChainFound = true;
1468 fLargeWorkForkFound = false;
1469 fLargeWorkInvalidChainFound = false;
1473 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1475 AssertLockHeld(cs_main);
1476 // If we are on a fork that is sufficiently large, set a warning flag
1477 CBlockIndex* pfork = pindexNewForkTip;
1478 CBlockIndex* plonger = chainActive.Tip();
1479 while (pfork && pfork != plonger)
1481 while (plonger && plonger->nHeight > pfork->nHeight)
1482 plonger = plonger->pprev;
1483 if (pfork == plonger)
1485 pfork = pfork->pprev;
1488 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1489 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1490 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1491 // hash rate operating on the fork.
1492 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1493 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1494 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1495 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1496 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1497 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1499 pindexBestForkTip = pindexNewForkTip;
1500 pindexBestForkBase = pfork;
1503 CheckForkWarningConditions();
1506 // Requires cs_main.
1507 void Misbehaving(NodeId pnode, int howmuch)
1512 CNodeState *state = State(pnode);
1516 state->nMisbehavior += howmuch;
1517 int banscore = GetArg("-banscore", 100);
1518 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1520 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1521 state->fShouldBan = true;
1523 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1526 void static InvalidChainFound(CBlockIndex* pindexNew)
1528 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1529 pindexBestInvalid = pindexNew;
1531 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1532 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1533 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1534 pindexNew->GetBlockTime()));
1535 CBlockIndex *tip = chainActive.Tip();
1537 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1538 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1539 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1540 CheckForkWarningConditions();
1543 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1545 if (state.IsInvalid(nDoS)) {
1546 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1547 if (it != mapBlockSource.end() && State(it->second)) {
1548 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1549 State(it->second)->rejects.push_back(reject);
1551 Misbehaving(it->second, nDoS);
1554 if (!state.CorruptionPossible()) {
1555 pindex->nStatus |= BLOCK_FAILED_VALID;
1556 setDirtyBlockIndex.insert(pindex);
1557 setBlockIndexCandidates.erase(pindex);
1558 InvalidChainFound(pindex);
1562 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1564 // mark inputs spent
1565 if (!tx.IsCoinBase()) {
1566 txundo.vprevout.reserve(tx.vin.size());
1567 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1568 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1569 unsigned nPos = txin.prevout.n;
1571 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1573 // mark an outpoint spent, and construct undo information
1574 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1576 if (coins->vout.size() == 0) {
1577 CTxInUndo& undo = txundo.vprevout.back();
1578 undo.nHeight = coins->nHeight;
1579 undo.fCoinBase = coins->fCoinBase;
1580 undo.nVersion = coins->nVersion;
1586 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1587 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1588 inputs.SetNullifier(nf, true);
1593 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1596 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1599 UpdateCoins(tx, state, inputs, txundo, nHeight);
1602 bool CScriptCheck::operator()() {
1603 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1604 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1605 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1610 bool NonContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1612 if (!tx.IsCoinBase())
1615 pvChecks->reserve(tx.vin.size());
1617 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1618 // for an attacker to attempt to split the network.
1619 if (!inputs.HaveInputs(tx))
1620 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1622 // are the JoinSplit's requirements met?
1623 if (!inputs.HaveJoinSplitRequirements(tx))
1624 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1626 CAmount nValueIn = 0;
1628 for (unsigned int i = 0; i < tx.vin.size(); i++)
1630 const COutPoint &prevout = tx.vin[i].prevout;
1631 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1634 if (coins->IsCoinBase()) {
1635 // Ensure that coinbases cannot be spent to transparent outputs
1636 // Disabled on regtest
1637 if (fCoinbaseEnforcedProtectionEnabled &&
1638 consensusParams.fCoinbaseMustBeProtected &&
1640 return state.Invalid(
1641 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1642 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1646 // Check for negative or overflow input values
1647 nValueIn += coins->vout[prevout.n].nValue;
1648 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1649 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1650 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1654 nValueIn += tx.GetJoinSplitValueIn();
1655 if (!MoneyRange(nValueIn))
1656 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1657 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1659 if (nValueIn < tx.GetValueOut())
1660 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1661 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1662 REJECT_INVALID, "bad-txns-in-belowout");
1664 // Tally transaction fees
1665 CAmount nTxFee = nValueIn - tx.GetValueOut();
1667 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1668 REJECT_INVALID, "bad-txns-fee-negative");
1670 if (!MoneyRange(nFees))
1671 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1672 REJECT_INVALID, "bad-txns-fee-outofrange");
1674 // The first loop above does all the inexpensive checks.
1675 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1676 // Helps prevent CPU exhaustion attacks.
1678 // Skip ECDSA signature verification when connecting blocks
1679 // before the last block chain checkpoint. This is safe because block merkle hashes are
1680 // still computed and checked, and any change will be caught at the next checkpoint.
1681 if (fScriptChecks) {
1682 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1683 const COutPoint &prevout = tx.vin[i].prevout;
1684 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1688 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1690 pvChecks->push_back(CScriptCheck());
1691 check.swap(pvChecks->back());
1692 } else if (!check()) {
1693 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1694 // Check whether the failure was caused by a
1695 // non-mandatory script verification check, such as
1696 // non-standard DER encodings or non-null dummy
1697 // arguments; if so, don't trigger DoS protection to
1698 // avoid splitting the network between upgraded and
1699 // non-upgraded nodes.
1700 CScriptCheck check(*coins, tx, i,
1701 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1703 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1705 // Failures of other flags indicate a transaction that is
1706 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1707 // such nodes as they are not following the protocol. That
1708 // said during an upgrade careful thought should be taken
1709 // as to the correct behavior - we may want to continue
1710 // peering with non-upgraded nodes even after a soft-fork
1711 // super-majority vote has passed.
1712 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1721 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1723 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1727 if (!tx.IsCoinBase())
1729 // While checking, GetBestBlock() refers to the parent block.
1730 // This is also true for mempool checks.
1731 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1732 int nSpendHeight = pindexPrev->nHeight + 1;
1733 for (unsigned int i = 0; i < tx.vin.size(); i++)
1735 const COutPoint &prevout = tx.vin[i].prevout;
1736 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1737 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1741 // If prev is coinbase, check that it's matured
1742 if (coins->IsCoinBase()) {
1743 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1744 return state.Invalid(
1745 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1746 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1757 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1759 // Open history file to append
1760 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1761 if (fileout.IsNull())
1762 return error("%s: OpenUndoFile failed", __func__);
1764 // Write index header
1765 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1766 fileout << FLATDATA(messageStart) << nSize;
1769 long fileOutPos = ftell(fileout.Get());
1771 return error("%s: ftell failed", __func__);
1772 pos.nPos = (unsigned int)fileOutPos;
1773 fileout << blockundo;
1775 // calculate & write checksum
1776 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1777 hasher << hashBlock;
1778 hasher << blockundo;
1779 fileout << hasher.GetHash();
1784 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1786 // Open history file to read
1787 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1788 if (filein.IsNull())
1789 return error("%s: OpenBlockFile failed", __func__);
1792 uint256 hashChecksum;
1794 filein >> blockundo;
1795 filein >> hashChecksum;
1797 catch (const std::exception& e) {
1798 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1802 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1803 hasher << hashBlock;
1804 hasher << blockundo;
1805 if (hashChecksum != hasher.GetHash())
1806 return error("%s: Checksum mismatch", __func__);
1811 /** Abort with a message */
1812 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1814 strMiscWarning = strMessage;
1815 LogPrintf("*** %s\n", strMessage);
1816 uiInterface.ThreadSafeMessageBox(
1817 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1818 "", CClientUIInterface::MSG_ERROR);
1823 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1825 AbortNode(strMessage, userMessage);
1826 return state.Error(strMessage);
1832 * Apply the undo operation of a CTxInUndo to the given chain state.
1833 * @param undo The undo object.
1834 * @param view The coins view to which to apply the changes.
1835 * @param out The out point that corresponds to the tx input.
1836 * @return True on success.
1838 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1842 CCoinsModifier coins = view.ModifyCoins(out.hash);
1843 if (undo.nHeight != 0) {
1844 // undo data contains height: this is the last output of the prevout tx being spent
1845 if (!coins->IsPruned())
1846 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1848 coins->fCoinBase = undo.fCoinBase;
1849 coins->nHeight = undo.nHeight;
1850 coins->nVersion = undo.nVersion;
1852 if (coins->IsPruned())
1853 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1855 if (coins->IsAvailable(out.n))
1856 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1857 if (coins->vout.size() < out.n+1)
1858 coins->vout.resize(out.n+1);
1859 coins->vout[out.n] = undo.txout;
1864 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1866 assert(pindex->GetBlockHash() == view.GetBestBlock());
1873 CBlockUndo blockUndo;
1874 CDiskBlockPos pos = pindex->GetUndoPos();
1876 return error("DisconnectBlock(): no undo data available");
1877 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1878 return error("DisconnectBlock(): failure reading undo data");
1880 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1881 return error("DisconnectBlock(): block and undo data inconsistent");
1883 // undo transactions in reverse order
1884 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1885 const CTransaction &tx = block.vtx[i];
1886 uint256 hash = tx.GetHash();
1888 // Check that all outputs are available and match the outputs in the block itself
1891 CCoinsModifier outs = view.ModifyCoins(hash);
1892 outs->ClearUnspendable();
1894 CCoins outsBlock(tx, pindex->nHeight);
1895 // The CCoins serialization does not serialize negative numbers.
1896 // No network rules currently depend on the version here, so an inconsistency is harmless
1897 // but it must be corrected before txout nversion ever influences a network rule.
1898 if (outsBlock.nVersion < 0)
1899 outs->nVersion = outsBlock.nVersion;
1900 if (*outs != outsBlock)
1901 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1907 // unspend nullifiers
1908 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1909 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1910 view.SetNullifier(nf, false);
1915 if (i > 0) { // not coinbases
1916 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1917 if (txundo.vprevout.size() != tx.vin.size())
1918 return error("DisconnectBlock(): transaction and undo data inconsistent");
1919 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1920 const COutPoint &out = tx.vin[j].prevout;
1921 const CTxInUndo &undo = txundo.vprevout[j];
1922 if (!ApplyTxInUndo(undo, view, out))
1928 // set the old best anchor back
1929 view.PopAnchor(blockUndo.old_tree_root);
1931 // move best block pointer to prevout block
1932 view.SetBestBlock(pindex->pprev->GetBlockHash());
1942 void static FlushBlockFile(bool fFinalize = false)
1944 LOCK(cs_LastBlockFile);
1946 CDiskBlockPos posOld(nLastBlockFile, 0);
1948 FILE *fileOld = OpenBlockFile(posOld);
1951 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1952 FileCommit(fileOld);
1956 fileOld = OpenUndoFile(posOld);
1959 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1960 FileCommit(fileOld);
1965 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1967 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1969 void ThreadScriptCheck() {
1970 RenameThread("zcash-scriptch");
1971 scriptcheckqueue.Thread();
1975 // Called periodically asynchronously; alerts if it smells like
1976 // we're being fed a bad chain (blocks being generated much
1977 // too slowly or too quickly).
1979 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1980 int64_t nPowTargetSpacing)
1982 if (bestHeader == NULL || initialDownloadCheck()) return;
1984 static int64_t lastAlertTime = 0;
1985 int64_t now = GetAdjustedTime();
1986 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1988 const int SPAN_HOURS=4;
1989 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1990 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1992 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1994 std::string strWarning;
1995 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1998 const CBlockIndex* i = bestHeader;
2000 while (i->GetBlockTime() >= startTime) {
2003 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2006 // How likely is it to find that many by chance?
2007 double p = boost::math::pdf(poisson, nBlocks);
2009 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2010 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2012 // Aim for one false-positive about every fifty years of normal running:
2013 const int FIFTY_YEARS = 50*365*24*60*60;
2014 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2016 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2018 // Many fewer blocks than expected: alert!
2019 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2020 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2022 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2024 // Many more blocks than expected: alert!
2025 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2026 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2028 if (!strWarning.empty())
2030 strMiscWarning = strWarning;
2031 CAlert::Notify(strWarning, true);
2032 lastAlertTime = now;
2036 static int64_t nTimeVerify = 0;
2037 static int64_t nTimeConnect = 0;
2038 static int64_t nTimeIndex = 0;
2039 static int64_t nTimeCallbacks = 0;
2040 static int64_t nTimeTotal = 0;
2042 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2044 const CChainParams& chainparams = Params();
2045 AssertLockHeld(cs_main);
2047 bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2048 auto verifier = libzcash::ProofVerifier::Strict();
2049 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2051 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2052 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2055 // verify that the view's current state corresponds to the previous block
2056 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2057 assert(hashPrevBlock == view.GetBestBlock());
2059 // Special case for the genesis block, skipping connection of its transactions
2060 // (its coinbase is unspendable)
2061 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2063 view.SetBestBlock(pindex->GetBlockHash());
2064 // Before the genesis block, there was an empty tree
2065 ZCIncrementalMerkleTree tree;
2066 pindex->hashAnchor = tree.root();
2071 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2072 // unless those are already completely spent.
2073 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2074 const CCoins* coins = view.AccessCoins(tx.GetHash());
2075 if (coins && !coins->IsPruned())
2076 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2077 REJECT_INVALID, "bad-txns-BIP30");
2080 unsigned int flags = SCRIPT_VERIFY_P2SH;
2082 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2083 // when 75% of the network has upgraded:
2084 if (block.nVersion >= 3) {
2085 flags |= SCRIPT_VERIFY_DERSIG;
2088 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2089 // blocks, when 75% of the network has upgraded:
2090 if (block.nVersion >= 4) {
2091 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2094 CBlockUndo blockundo;
2096 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2098 int64_t nTimeStart = GetTimeMicros();
2101 unsigned int nSigOps = 0;
2102 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2103 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2104 vPos.reserve(block.vtx.size());
2105 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2107 // Construct the incremental merkle tree at the current
2109 auto old_tree_root = view.GetBestAnchor();
2110 // saving the top anchor in the block index as we go.
2112 pindex->hashAnchor = old_tree_root;
2114 ZCIncrementalMerkleTree tree;
2115 // This should never fail: we should always be able to get the root
2116 // that is on the tip of our chain
2117 assert(view.GetAnchorAt(old_tree_root, tree));
2120 // Consistency check: the root of the tree we're given should
2121 // match what we asked for.
2122 assert(tree.root() == old_tree_root);
2125 for (unsigned int i = 0; i < block.vtx.size(); i++)
2127 const CTransaction &tx = block.vtx[i];
2129 nInputs += tx.vin.size();
2130 nSigOps += GetLegacySigOpCount(tx);
2131 if (nSigOps > MAX_BLOCK_SIGOPS)
2132 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2133 REJECT_INVALID, "bad-blk-sigops");
2135 if (!tx.IsCoinBase())
2137 if (!view.HaveInputs(tx))
2138 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2139 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2141 // are the JoinSplit's requirements met?
2142 if (!view.HaveJoinSplitRequirements(tx))
2143 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2144 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2146 // Add in sigops done by pay-to-script-hash inputs;
2147 // this is to prevent a "rogue miner" from creating
2148 // an incredibly-expensive-to-validate block.
2149 nSigOps += GetP2SHSigOpCount(tx, view);
2150 if (nSigOps > MAX_BLOCK_SIGOPS)
2151 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2152 REJECT_INVALID, "bad-blk-sigops");
2154 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2156 std::vector<CScriptCheck> vChecks;
2157 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2159 control.Add(vChecks);
2164 blockundo.vtxundo.push_back(CTxUndo());
2166 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2168 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2169 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2170 // Insert the note commitments into our temporary tree.
2172 tree.append(note_commitment);
2176 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2177 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2180 view.PushAnchor(tree);
2181 blockundo.old_tree_root = old_tree_root;
2183 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2184 LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
2186 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2187 if (block.vtx[0].GetValueOut() > blockReward)
2188 return state.DoS(100,
2189 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2190 block.vtx[0].GetValueOut(), blockReward),
2191 REJECT_INVALID, "bad-cb-amount");
2193 if (!control.Wait())
2194 return state.DoS(100, false);
2195 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2196 LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
2201 // Write undo information to disk
2202 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2204 if (pindex->GetUndoPos().IsNull()) {
2206 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2207 return error("ConnectBlock(): FindUndoPos failed");
2208 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2209 return AbortNode(state, "Failed to write undo data");
2211 // update nUndoPos in block index
2212 pindex->nUndoPos = pos.nPos;
2213 pindex->nStatus |= BLOCK_HAVE_UNDO;
2216 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2217 setDirtyBlockIndex.insert(pindex);
2221 if (!pblocktree->WriteTxIndex(vPos))
2222 return AbortNode(state, "Failed to write transaction index");
2224 // add this block to the view's block chain
2225 view.SetBestBlock(pindex->GetBlockHash());
2227 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2228 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2230 // Watch for changes to the previous coinbase transaction.
2231 static uint256 hashPrevBestCoinBase;
2232 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2233 hashPrevBestCoinBase = block.vtx[0].GetHash();
2235 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2236 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2241 enum FlushStateMode {
2243 FLUSH_STATE_IF_NEEDED,
2244 FLUSH_STATE_PERIODIC,
2249 * Update the on-disk chain state.
2250 * The caches and indexes are flushed depending on the mode we're called with
2251 * if they're too large, if it's been a while since the last write,
2252 * or always and in all cases if we're in prune mode and are deleting files.
2254 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2255 LOCK2(cs_main, cs_LastBlockFile);
2256 static int64_t nLastWrite = 0;
2257 static int64_t nLastFlush = 0;
2258 static int64_t nLastSetChain = 0;
2259 std::set<int> setFilesToPrune;
2260 bool fFlushForPrune = false;
2262 if (fPruneMode && fCheckForPruning && !fReindex) {
2263 FindFilesToPrune(setFilesToPrune);
2264 fCheckForPruning = false;
2265 if (!setFilesToPrune.empty()) {
2266 fFlushForPrune = true;
2268 pblocktree->WriteFlag("prunedblockfiles", true);
2273 int64_t nNow = GetTimeMicros();
2274 // Avoid writing/flushing immediately after startup.
2275 if (nLastWrite == 0) {
2278 if (nLastFlush == 0) {
2281 if (nLastSetChain == 0) {
2282 nLastSetChain = nNow;
2284 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2285 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2286 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2287 // The cache is over the limit, we have to write now.
2288 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2289 // 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.
2290 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2291 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2292 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2293 // Combine all conditions that result in a full cache flush.
2294 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2295 // Write blocks and block index to disk.
2296 if (fDoFullFlush || fPeriodicWrite) {
2297 // Depend on nMinDiskSpace to ensure we can write block index
2298 if (!CheckDiskSpace(0))
2299 return state.Error("out of disk space");
2300 // First make sure all block and undo data is flushed to disk.
2302 // Then update all block file information (which may refer to block and undo files).
2304 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2305 vFiles.reserve(setDirtyFileInfo.size());
2306 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2307 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2308 setDirtyFileInfo.erase(it++);
2310 std::vector<const CBlockIndex*> vBlocks;
2311 vBlocks.reserve(setDirtyBlockIndex.size());
2312 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2313 vBlocks.push_back(*it);
2314 setDirtyBlockIndex.erase(it++);
2316 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2317 return AbortNode(state, "Files to write to block index database");
2320 // Finally remove any pruned files
2322 UnlinkPrunedFiles(setFilesToPrune);
2325 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2327 // Typical CCoins structures on disk are around 128 bytes in size.
2328 // Pushing a new one to the database can cause it to be written
2329 // twice (once in the log, and once in the tables). This is already
2330 // an overestimation, as most will delete an existing entry or
2331 // overwrite one. Still, use a conservative safety factor of 2.
2332 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2333 return state.Error("out of disk space");
2334 // Flush the chainstate (which may refer to block index entries).
2335 if (!pcoinsTip->Flush())
2336 return AbortNode(state, "Failed to write to coin database");
2339 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2340 // Update best block in wallet (so we can detect restored wallets).
2341 GetMainSignals().SetBestChain(chainActive.GetLocator());
2342 nLastSetChain = nNow;
2344 } catch (const std::runtime_error& e) {
2345 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2350 void FlushStateToDisk() {
2351 CValidationState state;
2352 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2355 void PruneAndFlush() {
2356 CValidationState state;
2357 fCheckForPruning = true;
2358 FlushStateToDisk(state, FLUSH_STATE_NONE);
2361 /** Update chainActive and related internal data structures. */
2362 void static UpdateTip(CBlockIndex *pindexNew) {
2363 const CChainParams& chainParams = Params();
2364 chainActive.SetTip(pindexNew);
2367 nTimeBestReceived = GetTime();
2368 mempool.AddTransactionsUpdated(1);
2370 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2371 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2372 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2373 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2375 cvBlockChange.notify_all();
2377 // Check the version of the last 100 blocks to see if we need to upgrade:
2378 static bool fWarned = false;
2379 if (!IsInitialBlockDownload() && !fWarned)
2382 const CBlockIndex* pindex = chainActive.Tip();
2383 for (int i = 0; i < 100 && pindex != NULL; i++)
2385 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2387 pindex = pindex->pprev;
2390 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2391 if (nUpgraded > 100/2)
2393 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2394 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2395 CAlert::Notify(strMiscWarning, true);
2401 /** Disconnect chainActive's tip. */
2402 bool static DisconnectTip(CValidationState &state) {
2403 CBlockIndex *pindexDelete = chainActive.Tip();
2404 assert(pindexDelete);
2405 mempool.check(pcoinsTip);
2406 // Read block from disk.
2408 if (!ReadBlockFromDisk(block, pindexDelete))
2409 return AbortNode(state, "Failed to read block");
2410 // Apply the block atomically to the chain state.
2411 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2412 int64_t nStart = GetTimeMicros();
2414 CCoinsViewCache view(pcoinsTip);
2415 if (!DisconnectBlock(block, state, pindexDelete, view))
2416 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2417 assert(view.Flush());
2419 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2420 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2421 // Write the chain state to disk, if necessary.
2422 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2424 // Resurrect mempool transactions from the disconnected block.
2425 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2426 // ignore validation errors in resurrected transactions
2427 list<CTransaction> removed;
2428 CValidationState stateDummy;
2429 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2430 mempool.remove(tx, removed, true);
2432 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2433 // The anchor may not change between block disconnects,
2434 // in which case we don't want to evict from the mempool yet!
2435 mempool.removeWithAnchor(anchorBeforeDisconnect);
2437 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2438 mempool.check(pcoinsTip);
2439 // Update chainActive and related variables.
2440 UpdateTip(pindexDelete->pprev);
2441 // Get the current commitment tree
2442 ZCIncrementalMerkleTree newTree;
2443 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2444 // Let wallets know transactions went from 1-confirmed to
2445 // 0-confirmed or conflicted:
2446 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2447 SyncWithWallets(tx, NULL);
2449 // Update cached incremental witnesses
2450 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2454 static int64_t nTimeReadFromDisk = 0;
2455 static int64_t nTimeConnectTotal = 0;
2456 static int64_t nTimeFlush = 0;
2457 static int64_t nTimeChainState = 0;
2458 static int64_t nTimePostConnect = 0;
2461 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2462 * corresponding to pindexNew, to bypass loading it again from disk.
2464 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2465 assert(pindexNew->pprev == chainActive.Tip());
2466 mempool.check(pcoinsTip);
2467 // Read block from disk.
2468 int64_t nTime1 = GetTimeMicros();
2471 if (!ReadBlockFromDisk(block, pindexNew))
2472 return AbortNode(state, "Failed to read block");
2475 // Get the current commitment tree
2476 ZCIncrementalMerkleTree oldTree;
2477 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2478 // Apply the block atomically to the chain state.
2479 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2481 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2483 CCoinsViewCache view(pcoinsTip);
2484 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2485 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2486 GetMainSignals().BlockChecked(*pblock, state);
2488 if (state.IsInvalid())
2489 InvalidBlockFound(pindexNew, state);
2490 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2492 mapBlockSource.erase(inv.hash);
2493 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2494 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2495 assert(view.Flush());
2497 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2498 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2499 // Write the chain state to disk, if necessary.
2500 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2502 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2503 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2504 // Remove conflicting transactions from the mempool.
2505 list<CTransaction> txConflicted;
2506 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2507 mempool.check(pcoinsTip);
2508 // Update chainActive & related variables.
2509 UpdateTip(pindexNew);
2510 // Tell wallet about transactions that went from mempool
2512 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2513 SyncWithWallets(tx, NULL);
2515 // ... and about transactions that got confirmed:
2516 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2517 SyncWithWallets(tx, pblock);
2519 // Update cached incremental witnesses
2520 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2522 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2523 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2524 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2529 * Return the tip of the chain with the most work in it, that isn't
2530 * known to be invalid (it's however far from certain to be valid).
2532 static CBlockIndex* FindMostWorkChain() {
2534 CBlockIndex *pindexNew = NULL;
2536 // Find the best candidate header.
2538 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2539 if (it == setBlockIndexCandidates.rend())
2544 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2545 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2546 CBlockIndex *pindexTest = pindexNew;
2547 bool fInvalidAncestor = false;
2548 while (pindexTest && !chainActive.Contains(pindexTest)) {
2549 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2551 // Pruned nodes may have entries in setBlockIndexCandidates for
2552 // which block files have been deleted. Remove those as candidates
2553 // for the most work chain if we come across them; we can't switch
2554 // to a chain unless we have all the non-active-chain parent blocks.
2555 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2556 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2557 if (fFailedChain || fMissingData) {
2558 // Candidate chain is not usable (either invalid or missing data)
2559 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2560 pindexBestInvalid = pindexNew;
2561 CBlockIndex *pindexFailed = pindexNew;
2562 // Remove the entire chain from the set.
2563 while (pindexTest != pindexFailed) {
2565 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2566 } else if (fMissingData) {
2567 // If we're missing data, then add back to mapBlocksUnlinked,
2568 // so that if the block arrives in the future we can try adding
2569 // to setBlockIndexCandidates again.
2570 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2572 setBlockIndexCandidates.erase(pindexFailed);
2573 pindexFailed = pindexFailed->pprev;
2575 setBlockIndexCandidates.erase(pindexTest);
2576 fInvalidAncestor = true;
2579 pindexTest = pindexTest->pprev;
2581 if (!fInvalidAncestor)
2586 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2587 static void PruneBlockIndexCandidates() {
2588 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2589 // reorganization to a better block fails.
2590 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2591 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2592 setBlockIndexCandidates.erase(it++);
2594 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2595 assert(!setBlockIndexCandidates.empty());
2599 * Try to make some progress towards making pindexMostWork the active block.
2600 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2602 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2603 AssertLockHeld(cs_main);
2604 bool fInvalidFound = false;
2605 const CBlockIndex *pindexOldTip = chainActive.Tip();
2606 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2608 // Disconnect active blocks which are no longer in the best chain.
2609 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2610 if (!DisconnectTip(state))
2614 // Build list of new blocks to connect.
2615 std::vector<CBlockIndex*> vpindexToConnect;
2616 bool fContinue = true;
2617 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2618 while (fContinue && nHeight != pindexMostWork->nHeight) {
2619 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2620 // a few blocks along the way.
2621 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2622 vpindexToConnect.clear();
2623 vpindexToConnect.reserve(nTargetHeight - nHeight);
2624 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2625 while (pindexIter && pindexIter->nHeight != nHeight) {
2626 vpindexToConnect.push_back(pindexIter);
2627 pindexIter = pindexIter->pprev;
2629 nHeight = nTargetHeight;
2631 // Connect new blocks.
2632 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2633 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2634 if (state.IsInvalid()) {
2635 // The block violates a consensus rule.
2636 if (!state.CorruptionPossible())
2637 InvalidChainFound(vpindexToConnect.back());
2638 state = CValidationState();
2639 fInvalidFound = true;
2643 // A system error occurred (disk space, database error, ...).
2647 PruneBlockIndexCandidates();
2648 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2649 // We're in a better position than we were. Return temporarily to release the lock.
2657 // Callbacks/notifications for a new best chain.
2659 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2661 CheckForkWarningConditions();
2667 * Make the best chain active, in multiple steps. The result is either failure
2668 * or an activated best chain. pblock is either NULL or a pointer to a block
2669 * that is already loaded (to avoid loading it again from disk).
2671 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2672 CBlockIndex *pindexNewTip = NULL;
2673 CBlockIndex *pindexMostWork = NULL;
2674 const CChainParams& chainParams = Params();
2676 boost::this_thread::interruption_point();
2678 bool fInitialDownload;
2681 pindexMostWork = FindMostWorkChain();
2683 // Whether we have anything to do at all.
2684 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2687 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2690 pindexNewTip = chainActive.Tip();
2691 fInitialDownload = IsInitialBlockDownload();
2693 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2695 // Notifications/callbacks that can run without cs_main
2696 if (!fInitialDownload) {
2697 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2698 // Relay inventory, but don't relay old inventory during initial block download.
2699 int nBlockEstimate = 0;
2700 if (fCheckpointsEnabled)
2701 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2702 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2703 // in a stalled download if the block file is pruned before the request.
2704 if (nLocalServices & NODE_NETWORK) {
2706 BOOST_FOREACH(CNode* pnode, vNodes)
2707 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2708 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2710 // Notify external listeners about the new tip.
2711 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2712 uiInterface.NotifyBlockTip(hashNewTip);
2714 } while(pindexMostWork != chainActive.Tip());
2717 // Write changes periodically to disk, after relay.
2718 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2725 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2726 AssertLockHeld(cs_main);
2728 // Mark the block itself as invalid.
2729 pindex->nStatus |= BLOCK_FAILED_VALID;
2730 setDirtyBlockIndex.insert(pindex);
2731 setBlockIndexCandidates.erase(pindex);
2733 while (chainActive.Contains(pindex)) {
2734 CBlockIndex *pindexWalk = chainActive.Tip();
2735 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2736 setDirtyBlockIndex.insert(pindexWalk);
2737 setBlockIndexCandidates.erase(pindexWalk);
2738 // ActivateBestChain considers blocks already in chainActive
2739 // unconditionally valid already, so force disconnect away from it.
2740 if (!DisconnectTip(state)) {
2745 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2747 BlockMap::iterator it = mapBlockIndex.begin();
2748 while (it != mapBlockIndex.end()) {
2749 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2750 setBlockIndexCandidates.insert(it->second);
2755 InvalidChainFound(pindex);
2759 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2760 AssertLockHeld(cs_main);
2762 int nHeight = pindex->nHeight;
2764 // Remove the invalidity flag from this block and all its descendants.
2765 BlockMap::iterator it = mapBlockIndex.begin();
2766 while (it != mapBlockIndex.end()) {
2767 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2768 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2769 setDirtyBlockIndex.insert(it->second);
2770 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2771 setBlockIndexCandidates.insert(it->second);
2773 if (it->second == pindexBestInvalid) {
2774 // Reset invalid block marker if it was pointing to one of those.
2775 pindexBestInvalid = NULL;
2781 // Remove the invalidity flag from all ancestors too.
2782 while (pindex != NULL) {
2783 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2784 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2785 setDirtyBlockIndex.insert(pindex);
2787 pindex = pindex->pprev;
2792 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2794 // Check for duplicate
2795 uint256 hash = block.GetHash();
2796 BlockMap::iterator it = mapBlockIndex.find(hash);
2797 if (it != mapBlockIndex.end())
2800 // Construct new block index object
2801 CBlockIndex* pindexNew = new CBlockIndex(block);
2803 // We assign the sequence id to blocks only when the full data is available,
2804 // to avoid miners withholding blocks but broadcasting headers, to get a
2805 // competitive advantage.
2806 pindexNew->nSequenceId = 0;
2807 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2808 pindexNew->phashBlock = &((*mi).first);
2809 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2810 if (miPrev != mapBlockIndex.end())
2812 pindexNew->pprev = (*miPrev).second;
2813 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2814 pindexNew->BuildSkip();
2816 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2817 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2818 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2819 pindexBestHeader = pindexNew;
2821 setDirtyBlockIndex.insert(pindexNew);
2826 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2827 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2829 pindexNew->nTx = block.vtx.size();
2830 pindexNew->nChainTx = 0;
2831 pindexNew->nFile = pos.nFile;
2832 pindexNew->nDataPos = pos.nPos;
2833 pindexNew->nUndoPos = 0;
2834 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2835 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2836 setDirtyBlockIndex.insert(pindexNew);
2838 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2839 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2840 deque<CBlockIndex*> queue;
2841 queue.push_back(pindexNew);
2843 // Recursively process any descendant blocks that now may be eligible to be connected.
2844 while (!queue.empty()) {
2845 CBlockIndex *pindex = queue.front();
2847 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2849 LOCK(cs_nBlockSequenceId);
2850 pindex->nSequenceId = nBlockSequenceId++;
2852 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2853 setBlockIndexCandidates.insert(pindex);
2855 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2856 while (range.first != range.second) {
2857 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2858 queue.push_back(it->second);
2860 mapBlocksUnlinked.erase(it);
2864 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2865 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2872 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2874 LOCK(cs_LastBlockFile);
2876 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2877 if (vinfoBlockFile.size() <= nFile) {
2878 vinfoBlockFile.resize(nFile + 1);
2882 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2884 if (vinfoBlockFile.size() <= nFile) {
2885 vinfoBlockFile.resize(nFile + 1);
2889 pos.nPos = vinfoBlockFile[nFile].nSize;
2892 if (nFile != nLastBlockFile) {
2894 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2896 FlushBlockFile(!fKnown);
2897 nLastBlockFile = nFile;
2900 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2902 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2904 vinfoBlockFile[nFile].nSize += nAddSize;
2907 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2908 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2909 if (nNewChunks > nOldChunks) {
2911 fCheckForPruning = true;
2912 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2913 FILE *file = OpenBlockFile(pos);
2915 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2916 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2921 return state.Error("out of disk space");
2925 setDirtyFileInfo.insert(nFile);
2929 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2933 LOCK(cs_LastBlockFile);
2935 unsigned int nNewSize;
2936 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2937 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2938 setDirtyFileInfo.insert(nFile);
2940 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2941 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2942 if (nNewChunks > nOldChunks) {
2944 fCheckForPruning = true;
2945 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2946 FILE *file = OpenUndoFile(pos);
2948 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2949 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2954 return state.Error("out of disk space");
2960 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2962 // Check block version
2963 if (block.nVersion < MIN_BLOCK_VERSION)
2964 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
2965 REJECT_INVALID, "version-too-low");
2967 // Check Equihash solution is valid
2968 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2969 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2970 REJECT_INVALID, "invalid-solution");
2972 // Check proof of work matches claimed amount
2973 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2974 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2975 REJECT_INVALID, "high-hash");
2978 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2979 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2980 REJECT_INVALID, "time-too-new");
2985 bool CheckBlock(const CBlock& block, CValidationState& state,
2986 libzcash::ProofVerifier& verifier,
2987 bool fCheckPOW, bool fCheckMerkleRoot)
2989 // These are checks that are independent of context.
2991 // Check that the header is valid (particularly PoW). This is mostly
2992 // redundant with the call in AcceptBlockHeader.
2993 if (!CheckBlockHeader(block, state, fCheckPOW))
2996 // Check the merkle root.
2997 if (fCheckMerkleRoot) {
2999 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3000 if (block.hashMerkleRoot != hashMerkleRoot2)
3001 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3002 REJECT_INVALID, "bad-txnmrklroot", true);
3004 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3005 // of transactions in a block without affecting the merkle root of a block,
3006 // while still invalidating it.
3008 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3009 REJECT_INVALID, "bad-txns-duplicate", true);
3012 // All potential-corruption validation must be done before we do any
3013 // transaction validation, as otherwise we may mark the header as invalid
3014 // because we receive the wrong transactions for it.
3017 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3018 return state.DoS(100, error("CheckBlock(): size limits failed"),
3019 REJECT_INVALID, "bad-blk-length");
3021 // First transaction must be coinbase, the rest must not be
3022 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3023 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3024 REJECT_INVALID, "bad-cb-missing");
3025 for (unsigned int i = 1; i < block.vtx.size(); i++)
3026 if (block.vtx[i].IsCoinBase())
3027 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3028 REJECT_INVALID, "bad-cb-multiple");
3030 // Check transactions
3031 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3032 if (!CheckTransaction(tx, state, verifier))
3033 return error("CheckBlock(): CheckTransaction failed");
3035 unsigned int nSigOps = 0;
3036 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3038 nSigOps += GetLegacySigOpCount(tx);
3040 if (nSigOps > MAX_BLOCK_SIGOPS)
3041 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3042 REJECT_INVALID, "bad-blk-sigops", true);
3047 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3049 const CChainParams& chainParams = Params();
3050 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3051 uint256 hash = block.GetHash();
3052 if (hash == consensusParams.hashGenesisBlock)
3057 int nHeight = pindexPrev->nHeight+1;
3059 // Check proof of work
3060 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3061 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3062 REJECT_INVALID, "bad-diffbits");
3064 // Check timestamp against prev
3065 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3066 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3067 REJECT_INVALID, "time-too-old");
3069 if(fCheckpointsEnabled)
3071 // Check that the block chain matches the known block chain up to a checkpoint
3072 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3073 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
3074 REJECT_CHECKPOINT, "checkpoint mismatch");
3076 // Don't accept any forks from the main chain prior to last checkpoint
3077 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3078 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3079 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3082 // Reject block.nVersion < 4 blocks
3083 if (block.nVersion < 4)
3084 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3085 REJECT_OBSOLETE, "bad-version");
3090 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3092 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3093 const Consensus::Params& consensusParams = Params().GetConsensus();
3095 // Check that all transactions are finalized
3096 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3097 int nLockTimeFlags = 0;
3098 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3099 ? pindexPrev->GetMedianTimePast()
3100 : block.GetBlockTime();
3101 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3102 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3106 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3107 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3108 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3109 // This rule is not applied to the genesis block, which didn't include the height
3113 CScript expect = CScript() << nHeight;
3114 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3115 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3116 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3120 // Coinbase transaction must include an output sending 20% of
3121 // the block reward to a founders reward script, until the last founders
3122 // reward block is reached, with exception of the genesis block.
3123 // The last founders reward block is defined as the block just before the
3124 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3125 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3128 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3129 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3130 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3138 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3145 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3147 const CChainParams& chainparams = Params();
3148 AssertLockHeld(cs_main);
3149 // Check for duplicate
3150 uint256 hash = block.GetHash();
3151 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3152 CBlockIndex *pindex = NULL;
3153 if (miSelf != mapBlockIndex.end()) {
3154 // Block header is already known.
3155 pindex = miSelf->second;
3158 if (pindex->nStatus & BLOCK_FAILED_MASK)
3159 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3163 if (!CheckBlockHeader(block, state))
3166 // Get prev block index
3167 CBlockIndex* pindexPrev = NULL;
3168 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3169 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3170 if (mi == mapBlockIndex.end())
3171 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3172 pindexPrev = (*mi).second;
3173 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3174 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3177 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3181 pindex = AddToBlockIndex(block);
3189 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3191 const CChainParams& chainparams = Params();
3192 AssertLockHeld(cs_main);
3194 CBlockIndex *&pindex = *ppindex;
3196 if (!AcceptBlockHeader(block, state, &pindex))
3199 // Try to process all requested blocks that we don't have, but only
3200 // process an unrequested block if it's new and has enough work to
3201 // advance our tip, and isn't too many blocks ahead.
3202 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3203 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3204 // Blocks that are too out-of-order needlessly limit the effectiveness of
3205 // pruning, because pruning will not delete block files that contain any
3206 // blocks which are too close in height to the tip. Apply this test
3207 // regardless of whether pruning is enabled; it should generally be safe to
3208 // not process unrequested blocks.
3209 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3211 // TODO: deal better with return value and error conditions for duplicate
3212 // and unrequested blocks.
3213 if (fAlreadyHave) return true;
3214 if (!fRequested) { // If we didn't ask for it:
3215 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3216 if (!fHasMoreWork) return true; // Don't process less-work chains
3217 if (fTooFarAhead) return true; // Block height is too high
3220 // See method docstring for why this is always disabled
3221 auto verifier = libzcash::ProofVerifier::Disabled();
3222 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3223 if (state.IsInvalid() && !state.CorruptionPossible()) {
3224 pindex->nStatus |= BLOCK_FAILED_VALID;
3225 setDirtyBlockIndex.insert(pindex);
3230 int nHeight = pindex->nHeight;
3232 // Write block to history file
3234 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3235 CDiskBlockPos blockPos;
3238 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3239 return error("AcceptBlock(): FindBlockPos failed");
3241 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3242 AbortNode(state, "Failed to write block");
3243 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3244 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3245 } catch (const std::runtime_error& e) {
3246 return AbortNode(state, std::string("System error: ") + e.what());
3249 if (fCheckForPruning)
3250 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3255 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3257 unsigned int nFound = 0;
3258 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3260 if (pstart->nVersion >= minVersion)
3262 pstart = pstart->pprev;
3264 return (nFound >= nRequired);
3268 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3270 // Preliminary checks
3271 auto verifier = libzcash::ProofVerifier::Disabled();
3272 bool checked = CheckBlock(*pblock, state, verifier);
3276 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3277 fRequested |= fForceProcessing;
3279 return error("%s: CheckBlock FAILED", __func__);
3283 CBlockIndex *pindex = NULL;
3284 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3285 if (pindex && pfrom) {
3286 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3290 return error("%s: AcceptBlock FAILED", __func__);
3293 if (!ActivateBestChain(state, pblock))
3294 return error("%s: ActivateBestChain failed", __func__);
3299 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3301 AssertLockHeld(cs_main);
3302 assert(pindexPrev == chainActive.Tip());
3304 CCoinsViewCache viewNew(pcoinsTip);
3305 CBlockIndex indexDummy(block);
3306 indexDummy.pprev = pindexPrev;
3307 indexDummy.nHeight = pindexPrev->nHeight + 1;
3308 // JoinSplit proofs are verified in ConnectBlock
3309 auto verifier = libzcash::ProofVerifier::Disabled();
3311 // NOTE: CheckBlockHeader is called by CheckBlock
3312 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3314 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3316 if (!ContextualCheckBlock(block, state, pindexPrev))
3318 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3320 assert(state.IsValid());
3326 * BLOCK PRUNING CODE
3329 /* Calculate the amount of disk space the block & undo files currently use */
3330 uint64_t CalculateCurrentUsage()
3332 uint64_t retval = 0;
3333 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3334 retval += file.nSize + file.nUndoSize;
3339 /* Prune a block file (modify associated database entries)*/
3340 void PruneOneBlockFile(const int fileNumber)
3342 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3343 CBlockIndex* pindex = it->second;
3344 if (pindex->nFile == fileNumber) {
3345 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3346 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3348 pindex->nDataPos = 0;
3349 pindex->nUndoPos = 0;
3350 setDirtyBlockIndex.insert(pindex);
3352 // Prune from mapBlocksUnlinked -- any block we prune would have
3353 // to be downloaded again in order to consider its chain, at which
3354 // point it would be considered as a candidate for
3355 // mapBlocksUnlinked or setBlockIndexCandidates.
3356 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3357 while (range.first != range.second) {
3358 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3360 if (it->second == pindex) {
3361 mapBlocksUnlinked.erase(it);
3367 vinfoBlockFile[fileNumber].SetNull();
3368 setDirtyFileInfo.insert(fileNumber);
3372 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3374 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3375 CDiskBlockPos pos(*it, 0);
3376 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3377 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3378 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3382 /* Calculate the block/rev files that should be deleted to remain under target*/
3383 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3385 LOCK2(cs_main, cs_LastBlockFile);
3386 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3389 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3393 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3394 uint64_t nCurrentUsage = CalculateCurrentUsage();
3395 // We don't check to prune until after we've allocated new space for files
3396 // So we should leave a buffer under our target to account for another allocation
3397 // before the next pruning.
3398 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3399 uint64_t nBytesToPrune;
3402 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3403 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3404 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3406 if (vinfoBlockFile[fileNumber].nSize == 0)
3409 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3412 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3413 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3416 PruneOneBlockFile(fileNumber);
3417 // Queue up the files for removal
3418 setFilesToPrune.insert(fileNumber);
3419 nCurrentUsage -= nBytesToPrune;
3424 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3425 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3426 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3427 nLastBlockWeCanPrune, count);
3430 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3432 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3434 // Check for nMinDiskSpace bytes (currently 50MB)
3435 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3436 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3441 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3445 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3446 boost::filesystem::create_directories(path.parent_path());
3447 FILE* file = fopen(path.string().c_str(), "rb+");
3448 if (!file && !fReadOnly)
3449 file = fopen(path.string().c_str(), "wb+");
3451 LogPrintf("Unable to open file %s\n", path.string());
3455 if (fseek(file, pos.nPos, SEEK_SET)) {
3456 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3464 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3465 return OpenDiskFile(pos, "blk", fReadOnly);
3468 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3469 return OpenDiskFile(pos, "rev", fReadOnly);
3472 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3474 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3477 CBlockIndex * InsertBlockIndex(uint256 hash)
3483 BlockMap::iterator mi = mapBlockIndex.find(hash);
3484 if (mi != mapBlockIndex.end())
3485 return (*mi).second;
3488 CBlockIndex* pindexNew = new CBlockIndex();
3490 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3491 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3492 pindexNew->phashBlock = &((*mi).first);
3497 bool static LoadBlockIndexDB()
3499 const CChainParams& chainparams = Params();
3500 if (!pblocktree->LoadBlockIndexGuts())
3503 boost::this_thread::interruption_point();
3505 // Calculate nChainWork
3506 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3507 vSortedByHeight.reserve(mapBlockIndex.size());
3508 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3510 CBlockIndex* pindex = item.second;
3511 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3513 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3514 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3516 CBlockIndex* pindex = item.second;
3517 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3518 // We can link the chain of blocks for which we've received transactions at some point.
3519 // Pruned nodes may have deleted the block.
3520 if (pindex->nTx > 0) {
3521 if (pindex->pprev) {
3522 if (pindex->pprev->nChainTx) {
3523 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3525 pindex->nChainTx = 0;
3526 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3529 pindex->nChainTx = pindex->nTx;
3532 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3533 setBlockIndexCandidates.insert(pindex);
3534 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3535 pindexBestInvalid = pindex;
3537 pindex->BuildSkip();
3538 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3539 pindexBestHeader = pindex;
3542 // Load block file info
3543 pblocktree->ReadLastBlockFile(nLastBlockFile);
3544 vinfoBlockFile.resize(nLastBlockFile + 1);
3545 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3546 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3547 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3549 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3550 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3551 CBlockFileInfo info;
3552 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3553 vinfoBlockFile.push_back(info);
3559 // Check presence of blk files
3560 LogPrintf("Checking all blk files are present...\n");
3561 set<int> setBlkDataFiles;
3562 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3564 CBlockIndex* pindex = item.second;
3565 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3566 setBlkDataFiles.insert(pindex->nFile);
3569 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3571 CDiskBlockPos pos(*it, 0);
3572 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3577 // Check whether we have ever pruned block & undo files
3578 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3580 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3582 // Check whether we need to continue reindexing
3583 bool fReindexing = false;
3584 pblocktree->ReadReindexing(fReindexing);
3585 fReindex |= fReindexing;
3587 // Check whether we have a transaction index
3588 pblocktree->ReadFlag("txindex", fTxIndex);
3589 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3591 // Load pointer to end of best chain
3592 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3593 if (it == mapBlockIndex.end())
3595 chainActive.SetTip(it->second);
3597 PruneBlockIndexCandidates();
3599 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3600 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3601 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3602 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3607 CVerifyDB::CVerifyDB()
3609 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3612 CVerifyDB::~CVerifyDB()
3614 uiInterface.ShowProgress("", 100);
3617 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3620 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3623 // Verify blocks in the best chain
3624 if (nCheckDepth <= 0)
3625 nCheckDepth = 1000000000; // suffices until the year 19000
3626 if (nCheckDepth > chainActive.Height())
3627 nCheckDepth = chainActive.Height();
3628 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3629 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3630 CCoinsViewCache coins(coinsview);
3631 CBlockIndex* pindexState = chainActive.Tip();
3632 CBlockIndex* pindexFailure = NULL;
3633 int nGoodTransactions = 0;
3634 CValidationState state;
3635 // No need to verify JoinSplits twice
3636 auto verifier = libzcash::ProofVerifier::Disabled();
3637 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3639 boost::this_thread::interruption_point();
3640 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3641 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3644 // check level 0: read from disk
3645 if (!ReadBlockFromDisk(block, pindex))
3646 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3647 // check level 1: verify block validity
3648 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
3649 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3650 // check level 2: verify undo validity
3651 if (nCheckLevel >= 2 && pindex) {
3653 CDiskBlockPos pos = pindex->GetUndoPos();
3654 if (!pos.IsNull()) {
3655 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3656 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3659 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3660 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3662 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3663 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3664 pindexState = pindex->pprev;
3666 nGoodTransactions = 0;
3667 pindexFailure = pindex;
3669 nGoodTransactions += block.vtx.size();
3671 if (ShutdownRequested())
3675 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3677 // check level 4: try reconnecting blocks
3678 if (nCheckLevel >= 4) {
3679 CBlockIndex *pindex = pindexState;
3680 while (pindex != chainActive.Tip()) {
3681 boost::this_thread::interruption_point();
3682 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3683 pindex = chainActive.Next(pindex);
3685 if (!ReadBlockFromDisk(block, pindex))
3686 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3687 if (!ConnectBlock(block, state, pindex, coins))
3688 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3692 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3697 void UnloadBlockIndex()
3700 setBlockIndexCandidates.clear();
3701 chainActive.SetTip(NULL);
3702 pindexBestInvalid = NULL;
3703 pindexBestHeader = NULL;
3705 mapOrphanTransactions.clear();
3706 mapOrphanTransactionsByPrev.clear();
3708 mapBlocksUnlinked.clear();
3709 vinfoBlockFile.clear();
3711 nBlockSequenceId = 1;
3712 mapBlockSource.clear();
3713 mapBlocksInFlight.clear();
3714 nQueuedValidatedHeaders = 0;
3715 nPreferredDownload = 0;
3716 setDirtyBlockIndex.clear();
3717 setDirtyFileInfo.clear();
3718 mapNodeState.clear();
3719 recentRejects.reset(NULL);
3721 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3722 delete entry.second;
3724 mapBlockIndex.clear();
3725 fHavePruned = false;
3728 bool LoadBlockIndex()
3730 // Load block index from databases
3731 if (!fReindex && !LoadBlockIndexDB())
3737 bool InitBlockIndex() {
3738 const CChainParams& chainparams = Params();
3741 // Initialize global variables that cannot be constructed at startup.
3742 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3744 // Check whether we're already initialized
3745 if (chainActive.Genesis() != NULL)
3748 // Use the provided setting for -txindex in the new database
3749 fTxIndex = GetBoolArg("-txindex", false);
3750 pblocktree->WriteFlag("txindex", fTxIndex);
3751 LogPrintf("Initializing databases...\n");
3753 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3756 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3757 // Start new block file
3758 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3759 CDiskBlockPos blockPos;
3760 CValidationState state;
3761 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3762 return error("LoadBlockIndex(): FindBlockPos failed");
3763 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3764 return error("LoadBlockIndex(): writing genesis block to disk failed");
3765 CBlockIndex *pindex = AddToBlockIndex(block);
3766 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3767 return error("LoadBlockIndex(): genesis block not accepted");
3768 if (!ActivateBestChain(state, &block))
3769 return error("LoadBlockIndex(): genesis block cannot be activated");
3770 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3771 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3772 } catch (const std::runtime_error& e) {
3773 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3782 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3784 const CChainParams& chainparams = Params();
3785 // Map of disk positions for blocks with unknown parent (only used for reindex)
3786 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3787 int64_t nStart = GetTimeMillis();
3791 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3792 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3793 uint64_t nRewind = blkdat.GetPos();
3794 while (!blkdat.eof()) {
3795 boost::this_thread::interruption_point();
3797 blkdat.SetPos(nRewind);
3798 nRewind++; // start one byte further next time, in case of failure
3799 blkdat.SetLimit(); // remove former limit
3800 unsigned int nSize = 0;
3803 unsigned char buf[MESSAGE_START_SIZE];
3804 blkdat.FindByte(Params().MessageStart()[0]);
3805 nRewind = blkdat.GetPos()+1;
3806 blkdat >> FLATDATA(buf);
3807 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3811 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3813 } catch (const std::exception&) {
3814 // no valid block header found; don't complain
3819 uint64_t nBlockPos = blkdat.GetPos();
3821 dbp->nPos = nBlockPos;
3822 blkdat.SetLimit(nBlockPos + nSize);
3823 blkdat.SetPos(nBlockPos);
3826 nRewind = blkdat.GetPos();
3828 // detect out of order blocks, and store them for later
3829 uint256 hash = block.GetHash();
3830 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3831 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3832 block.hashPrevBlock.ToString());
3834 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3838 // process in case the block isn't known yet
3839 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3840 CValidationState state;
3841 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3843 if (state.IsError())
3845 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3846 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3849 // Recursively process earlier encountered successors of this block
3850 deque<uint256> queue;
3851 queue.push_back(hash);
3852 while (!queue.empty()) {
3853 uint256 head = queue.front();
3855 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3856 while (range.first != range.second) {
3857 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3858 if (ReadBlockFromDisk(block, it->second))
3860 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3862 CValidationState dummy;
3863 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3866 queue.push_back(block.GetHash());
3870 mapBlocksUnknownParent.erase(it);
3873 } catch (const std::exception& e) {
3874 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3877 } catch (const std::runtime_error& e) {
3878 AbortNode(std::string("System error: ") + e.what());
3881 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3885 void static CheckBlockIndex()
3887 const Consensus::Params& consensusParams = Params().GetConsensus();
3888 if (!fCheckBlockIndex) {
3894 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3895 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3896 // iterating the block tree require that chainActive has been initialized.)
3897 if (chainActive.Height() < 0) {
3898 assert(mapBlockIndex.size() <= 1);
3902 // Build forward-pointing map of the entire block tree.
3903 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3904 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3905 forward.insert(std::make_pair(it->second->pprev, it->second));
3908 assert(forward.size() == mapBlockIndex.size());
3910 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3911 CBlockIndex *pindex = rangeGenesis.first->second;
3912 rangeGenesis.first++;
3913 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3915 // Iterate over the entire block tree, using depth-first search.
3916 // Along the way, remember whether there are blocks on the path from genesis
3917 // block being explored which are the first to have certain properties.
3920 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3921 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3922 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3923 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3924 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3925 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3926 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3927 while (pindex != NULL) {
3929 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3930 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3931 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3932 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3933 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3934 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3935 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3937 // Begin: actual consistency checks.
3938 if (pindex->pprev == NULL) {
3939 // Genesis block checks.
3940 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3941 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3943 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3944 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3945 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3947 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3948 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3949 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3951 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3952 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3954 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3955 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3956 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3957 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3958 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3959 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3960 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.
3961 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3962 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3963 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3964 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3965 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3966 if (pindexFirstInvalid == NULL) {
3967 // Checks for not-invalid blocks.
3968 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3970 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3971 if (pindexFirstInvalid == NULL) {
3972 // If this block sorts at least as good as the current tip and
3973 // is valid and we have all data for its parents, it must be in
3974 // setBlockIndexCandidates. chainActive.Tip() must also be there
3975 // even if some data has been pruned.
3976 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3977 assert(setBlockIndexCandidates.count(pindex));
3979 // If some parent is missing, then it could be that this block was in
3980 // setBlockIndexCandidates but had to be removed because of the missing data.
3981 // In this case it must be in mapBlocksUnlinked -- see test below.
3983 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3984 assert(setBlockIndexCandidates.count(pindex) == 0);
3986 // Check whether this block is in mapBlocksUnlinked.
3987 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3988 bool foundInUnlinked = false;
3989 while (rangeUnlinked.first != rangeUnlinked.second) {
3990 assert(rangeUnlinked.first->first == pindex->pprev);
3991 if (rangeUnlinked.first->second == pindex) {
3992 foundInUnlinked = true;
3995 rangeUnlinked.first++;
3997 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3998 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3999 assert(foundInUnlinked);
4001 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4002 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4003 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4004 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4005 assert(fHavePruned); // We must have pruned.
4006 // This block may have entered mapBlocksUnlinked if:
4007 // - it has a descendant that at some point had more work than the
4009 // - we tried switching to that descendant but were missing
4010 // data for some intermediate block between chainActive and the
4012 // So if this block is itself better than chainActive.Tip() and it wasn't in
4013 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4014 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4015 if (pindexFirstInvalid == NULL) {
4016 assert(foundInUnlinked);
4020 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4021 // End: actual consistency checks.
4023 // Try descending into the first subnode.
4024 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4025 if (range.first != range.second) {
4026 // A subnode was found.
4027 pindex = range.first->second;
4031 // This is a leaf node.
4032 // Move upwards until we reach a node of which we have not yet visited the last child.
4034 // We are going to either move to a parent or a sibling of pindex.
4035 // If pindex was the first with a certain property, unset the corresponding variable.
4036 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4037 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4038 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4039 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4040 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4041 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4042 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4044 CBlockIndex* pindexPar = pindex->pprev;
4045 // Find which child we just visited.
4046 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4047 while (rangePar.first->second != pindex) {
4048 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4051 // Proceed to the next one.
4053 if (rangePar.first != rangePar.second) {
4054 // Move to the sibling.
4055 pindex = rangePar.first->second;
4066 // Check that we actually traversed the entire map.
4067 assert(nNodes == forward.size());
4070 //////////////////////////////////////////////////////////////////////////////
4075 string GetWarnings(string strFor)
4078 string strStatusBar;
4081 if (!CLIENT_VERSION_IS_RELEASE)
4082 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4084 if (GetBoolArg("-testsafemode", false))
4085 strStatusBar = strRPC = "testsafemode enabled";
4087 // Misc warnings like out of disk space and clock is wrong
4088 if (strMiscWarning != "")
4091 strStatusBar = strMiscWarning;
4094 if (fLargeWorkForkFound)
4097 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4099 else if (fLargeWorkInvalidChainFound)
4102 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.");
4108 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4110 const CAlert& alert = item.second;
4111 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4113 nPriority = alert.nPriority;
4114 strStatusBar = alert.strStatusBar;
4115 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4116 strRPC = alert.strRPCError;
4122 if (strFor == "statusbar")
4123 return strStatusBar;
4124 else if (strFor == "rpc")
4126 assert(!"GetWarnings(): invalid parameter");
4137 //////////////////////////////////////////////////////////////////////////////
4143 bool static AlreadyHave(const CInv& inv)
4149 assert(recentRejects);
4150 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4152 // If the chain tip has changed previously rejected transactions
4153 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4154 // or a double-spend. Reset the rejects filter and give those
4155 // txs a second chance.
4156 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4157 recentRejects->reset();
4160 return recentRejects->contains(inv.hash) ||
4161 mempool.exists(inv.hash) ||
4162 mapOrphanTransactions.count(inv.hash) ||
4163 pcoinsTip->HaveCoins(inv.hash);
4166 return mapBlockIndex.count(inv.hash);
4168 // Don't know what it is, just say we already got one
4172 void static ProcessGetData(CNode* pfrom)
4174 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4176 vector<CInv> vNotFound;
4180 while (it != pfrom->vRecvGetData.end()) {
4181 // Don't bother if send buffer is too full to respond anyway
4182 if (pfrom->nSendSize >= SendBufferSize())
4185 const CInv &inv = *it;
4187 boost::this_thread::interruption_point();
4190 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4193 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4194 if (mi != mapBlockIndex.end())
4196 if (chainActive.Contains(mi->second)) {
4199 static const int nOneMonth = 30 * 24 * 60 * 60;
4200 // To prevent fingerprinting attacks, only send blocks outside of the active
4201 // chain if they are valid, and no more than a month older (both in time, and in
4202 // best equivalent proof of work) than the best header chain we know about.
4203 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4204 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4205 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4207 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4211 // Pruned nodes may have deleted the block, so check whether
4212 // it's available before trying to send.
4213 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4215 // Send block from disk
4217 if (!ReadBlockFromDisk(block, (*mi).second))
4218 assert(!"cannot load block from disk");
4219 if (inv.type == MSG_BLOCK)
4220 pfrom->PushMessage("block", block);
4221 else // MSG_FILTERED_BLOCK)
4223 LOCK(pfrom->cs_filter);
4226 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4227 pfrom->PushMessage("merkleblock", merkleBlock);
4228 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4229 // This avoids hurting performance by pointlessly requiring a round-trip
4230 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4231 // they must either disconnect and retry or request the full block.
4232 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4233 // however we MUST always provide at least what the remote peer needs
4234 typedef std::pair<unsigned int, uint256> PairType;
4235 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4236 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4237 pfrom->PushMessage("tx", block.vtx[pair.first]);
4243 // Trigger the peer node to send a getblocks request for the next batch of inventory
4244 if (inv.hash == pfrom->hashContinue)
4246 // Bypass PushInventory, this must send even if redundant,
4247 // and we want it right after the last block so they don't
4248 // wait for other stuff first.
4250 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4251 pfrom->PushMessage("inv", vInv);
4252 pfrom->hashContinue.SetNull();
4256 else if (inv.IsKnownType())
4258 // Send stream from relay memory
4259 bool pushed = false;
4262 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4263 if (mi != mapRelay.end()) {
4264 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4268 if (!pushed && inv.type == MSG_TX) {
4270 if (mempool.lookup(inv.hash, tx)) {
4271 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4274 pfrom->PushMessage("tx", ss);
4279 vNotFound.push_back(inv);
4283 // Track requests for our stuff.
4284 GetMainSignals().Inventory(inv.hash);
4286 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4291 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4293 if (!vNotFound.empty()) {
4294 // Let the peer know that we didn't find what it asked for, so it doesn't
4295 // have to wait around forever. Currently only SPV clients actually care
4296 // about this message: it's needed when they are recursively walking the
4297 // dependencies of relevant unconfirmed transactions. SPV clients want to
4298 // do that because they want to know about (and store and rebroadcast and
4299 // risk analyze) the dependencies of transactions relevant to them, without
4300 // having to download the entire memory pool.
4301 pfrom->PushMessage("notfound", vNotFound);
4305 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4307 const CChainParams& chainparams = Params();
4308 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4309 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4311 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4318 if (strCommand == "version")
4320 // Each connection can only send one version message
4321 if (pfrom->nVersion != 0)
4323 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4324 Misbehaving(pfrom->GetId(), 1);
4331 uint64_t nNonce = 1;
4332 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4333 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4335 // disconnect from peers older than this proto version
4336 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4337 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4338 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4339 pfrom->fDisconnect = true;
4343 if (pfrom->nVersion == 10300)
4344 pfrom->nVersion = 300;
4346 vRecv >> addrFrom >> nNonce;
4347 if (!vRecv.empty()) {
4348 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4349 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4352 vRecv >> pfrom->nStartingHeight;
4354 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4356 pfrom->fRelayTxes = true;
4358 // Disconnect if we connected to ourself
4359 if (nNonce == nLocalHostNonce && nNonce > 1)
4361 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4362 pfrom->fDisconnect = true;
4366 pfrom->addrLocal = addrMe;
4367 if (pfrom->fInbound && addrMe.IsRoutable())
4372 // Be shy and don't send version until we hear
4373 if (pfrom->fInbound)
4374 pfrom->PushVersion();
4376 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4378 // Potentially mark this peer as a preferred download peer.
4379 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4382 pfrom->PushMessage("verack");
4383 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4385 if (!pfrom->fInbound)
4387 // Advertise our address
4388 if (fListen && !IsInitialBlockDownload())
4390 CAddress addr = GetLocalAddress(&pfrom->addr);
4391 if (addr.IsRoutable())
4393 pfrom->PushAddress(addr);
4394 } else if (IsPeerAddrLocalGood(pfrom)) {
4395 addr.SetIP(pfrom->addrLocal);
4396 pfrom->PushAddress(addr);
4400 // Get recent addresses
4401 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4403 pfrom->PushMessage("getaddr");
4404 pfrom->fGetAddr = true;
4406 addrman.Good(pfrom->addr);
4408 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4410 addrman.Add(addrFrom, addrFrom);
4411 addrman.Good(addrFrom);
4418 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4419 item.second.RelayTo(pfrom);
4422 pfrom->fSuccessfullyConnected = true;
4426 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4428 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4429 pfrom->cleanSubVer, pfrom->nVersion,
4430 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4433 int64_t nTimeOffset = nTime - GetTime();
4434 pfrom->nTimeOffset = nTimeOffset;
4435 AddTimeData(pfrom->addr, nTimeOffset);
4439 else if (pfrom->nVersion == 0)
4441 // Must have a version message before anything else
4442 Misbehaving(pfrom->GetId(), 1);
4447 else if (strCommand == "verack")
4449 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4451 // Mark this node as currently connected, so we update its timestamp later.
4452 if (pfrom->fNetworkNode) {
4454 State(pfrom->GetId())->fCurrentlyConnected = true;
4459 else if (strCommand == "addr")
4461 vector<CAddress> vAddr;
4464 // Don't want addr from older versions unless seeding
4465 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4467 if (vAddr.size() > 1000)
4469 Misbehaving(pfrom->GetId(), 20);
4470 return error("message addr size() = %u", vAddr.size());
4473 // Store the new addresses
4474 vector<CAddress> vAddrOk;
4475 int64_t nNow = GetAdjustedTime();
4476 int64_t nSince = nNow - 10 * 60;
4477 BOOST_FOREACH(CAddress& addr, vAddr)
4479 boost::this_thread::interruption_point();
4481 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4482 addr.nTime = nNow - 5 * 24 * 60 * 60;
4483 pfrom->AddAddressKnown(addr);
4484 bool fReachable = IsReachable(addr);
4485 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4487 // Relay to a limited number of other nodes
4490 // Use deterministic randomness to send to the same nodes for 24 hours
4491 // at a time so the addrKnowns of the chosen nodes prevent repeats
4492 static uint256 hashSalt;
4493 if (hashSalt.IsNull())
4494 hashSalt = GetRandHash();
4495 uint64_t hashAddr = addr.GetHash();
4496 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4497 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4498 multimap<uint256, CNode*> mapMix;
4499 BOOST_FOREACH(CNode* pnode, vNodes)
4501 if (pnode->nVersion < CADDR_TIME_VERSION)
4503 unsigned int nPointer;
4504 memcpy(&nPointer, &pnode, sizeof(nPointer));
4505 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4506 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4507 mapMix.insert(make_pair(hashKey, pnode));
4509 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4510 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4511 ((*mi).second)->PushAddress(addr);
4514 // Do not store addresses outside our network
4516 vAddrOk.push_back(addr);
4518 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4519 if (vAddr.size() < 1000)
4520 pfrom->fGetAddr = false;
4521 if (pfrom->fOneShot)
4522 pfrom->fDisconnect = true;
4526 else if (strCommand == "inv")
4530 if (vInv.size() > MAX_INV_SZ)
4532 Misbehaving(pfrom->GetId(), 20);
4533 return error("message inv size() = %u", vInv.size());
4538 std::vector<CInv> vToFetch;
4540 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4542 const CInv &inv = vInv[nInv];
4544 boost::this_thread::interruption_point();
4545 pfrom->AddInventoryKnown(inv);
4547 bool fAlreadyHave = AlreadyHave(inv);
4548 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4550 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4553 if (inv.type == MSG_BLOCK) {
4554 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4555 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4556 // First request the headers preceding the announced block. In the normal fully-synced
4557 // case where a new block is announced that succeeds the current tip (no reorganization),
4558 // there are no such headers.
4559 // Secondly, and only when we are close to being synced, we request the announced block directly,
4560 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4561 // time the block arrives, the header chain leading up to it is already validated. Not
4562 // doing this will result in the received block being rejected as an orphan in case it is
4563 // not a direct successor.
4564 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4565 CNodeState *nodestate = State(pfrom->GetId());
4566 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4567 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4568 vToFetch.push_back(inv);
4569 // Mark block as in flight already, even though the actual "getdata" message only goes out
4570 // later (within the same cs_main lock, though).
4571 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4573 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4577 // Track requests for our stuff
4578 GetMainSignals().Inventory(inv.hash);
4580 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4581 Misbehaving(pfrom->GetId(), 50);
4582 return error("send buffer size() = %u", pfrom->nSendSize);
4586 if (!vToFetch.empty())
4587 pfrom->PushMessage("getdata", vToFetch);
4591 else if (strCommand == "getdata")
4595 if (vInv.size() > MAX_INV_SZ)
4597 Misbehaving(pfrom->GetId(), 20);
4598 return error("message getdata size() = %u", vInv.size());
4601 if (fDebug || (vInv.size() != 1))
4602 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4604 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4605 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4607 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4608 ProcessGetData(pfrom);
4612 else if (strCommand == "getblocks")
4614 CBlockLocator locator;
4616 vRecv >> locator >> hashStop;
4620 // Find the last block the caller has in the main chain
4621 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4623 // Send the rest of the chain
4625 pindex = chainActive.Next(pindex);
4627 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4628 for (; pindex; pindex = chainActive.Next(pindex))
4630 if (pindex->GetBlockHash() == hashStop)
4632 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4635 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4638 // When this block is requested, we'll send an inv that'll
4639 // trigger the peer to getblocks the next batch of inventory.
4640 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4641 pfrom->hashContinue = pindex->GetBlockHash();
4648 else if (strCommand == "getheaders")
4650 CBlockLocator locator;
4652 vRecv >> locator >> hashStop;
4656 if (IsInitialBlockDownload())
4659 CBlockIndex* pindex = NULL;
4660 if (locator.IsNull())
4662 // If locator is null, return the hashStop block
4663 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4664 if (mi == mapBlockIndex.end())
4666 pindex = (*mi).second;
4670 // Find the last block the caller has in the main chain
4671 pindex = FindForkInGlobalIndex(chainActive, locator);
4673 pindex = chainActive.Next(pindex);
4676 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4677 vector<CBlock> vHeaders;
4678 int nLimit = MAX_HEADERS_RESULTS;
4679 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4680 for (; pindex; pindex = chainActive.Next(pindex))
4682 vHeaders.push_back(pindex->GetBlockHeader());
4683 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4686 pfrom->PushMessage("headers", vHeaders);
4690 else if (strCommand == "tx")
4692 vector<uint256> vWorkQueue;
4693 vector<uint256> vEraseQueue;
4697 CInv inv(MSG_TX, tx.GetHash());
4698 pfrom->AddInventoryKnown(inv);
4702 bool fMissingInputs = false;
4703 CValidationState state;
4705 pfrom->setAskFor.erase(inv.hash);
4706 mapAlreadyAskedFor.erase(inv);
4708 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4710 mempool.check(pcoinsTip);
4711 RelayTransaction(tx);
4712 vWorkQueue.push_back(inv.hash);
4714 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4715 pfrom->id, pfrom->cleanSubVer,
4716 tx.GetHash().ToString(),
4717 mempool.mapTx.size());
4719 // Recursively process any orphan transactions that depended on this one
4720 set<NodeId> setMisbehaving;
4721 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4723 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4724 if (itByPrev == mapOrphanTransactionsByPrev.end())
4726 for (set<uint256>::iterator mi = itByPrev->second.begin();
4727 mi != itByPrev->second.end();
4730 const uint256& orphanHash = *mi;
4731 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4732 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4733 bool fMissingInputs2 = false;
4734 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4735 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4736 // anyone relaying LegitTxX banned)
4737 CValidationState stateDummy;
4740 if (setMisbehaving.count(fromPeer))
4742 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4744 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4745 RelayTransaction(orphanTx);
4746 vWorkQueue.push_back(orphanHash);
4747 vEraseQueue.push_back(orphanHash);
4749 else if (!fMissingInputs2)
4752 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4754 // Punish peer that gave us an invalid orphan tx
4755 Misbehaving(fromPeer, nDos);
4756 setMisbehaving.insert(fromPeer);
4757 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4759 // Has inputs but not accepted to mempool
4760 // Probably non-standard or insufficient fee/priority
4761 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4762 vEraseQueue.push_back(orphanHash);
4763 assert(recentRejects);
4764 recentRejects->insert(orphanHash);
4766 mempool.check(pcoinsTip);
4770 BOOST_FOREACH(uint256 hash, vEraseQueue)
4771 EraseOrphanTx(hash);
4773 // TODO: currently, prohibit joinsplits from entering mapOrphans
4774 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4776 AddOrphanTx(tx, pfrom->GetId());
4778 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4779 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4780 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4782 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4784 assert(recentRejects);
4785 recentRejects->insert(tx.GetHash());
4787 if (pfrom->fWhitelisted) {
4788 // Always relay transactions received from whitelisted peers, even
4789 // if they were already in the mempool or rejected from it due
4790 // to policy, allowing the node to function as a gateway for
4791 // nodes hidden behind it.
4793 // Never relay transactions that we would assign a non-zero DoS
4794 // score for, as we expect peers to do the same with us in that
4797 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4798 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4799 RelayTransaction(tx);
4801 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4802 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4807 if (state.IsInvalid(nDoS))
4809 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4810 pfrom->id, pfrom->cleanSubVer,
4811 state.GetRejectReason());
4812 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4813 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4815 Misbehaving(pfrom->GetId(), nDoS);
4820 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4822 std::vector<CBlockHeader> headers;
4824 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4825 unsigned int nCount = ReadCompactSize(vRecv);
4826 if (nCount > MAX_HEADERS_RESULTS) {
4827 Misbehaving(pfrom->GetId(), 20);
4828 return error("headers message size = %u", nCount);
4830 headers.resize(nCount);
4831 for (unsigned int n = 0; n < nCount; n++) {
4832 vRecv >> headers[n];
4833 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4839 // Nothing interesting. Stop asking this peers for more headers.
4843 CBlockIndex *pindexLast = NULL;
4844 BOOST_FOREACH(const CBlockHeader& header, headers) {
4845 CValidationState state;
4846 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4847 Misbehaving(pfrom->GetId(), 20);
4848 return error("non-continuous headers sequence");
4850 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4852 if (state.IsInvalid(nDoS)) {
4854 Misbehaving(pfrom->GetId(), nDoS);
4855 return error("invalid header received");
4861 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4863 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4864 // Headers message had its maximum size; the peer may have more headers.
4865 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4866 // from there instead.
4867 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4868 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4874 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4879 CInv inv(MSG_BLOCK, block.GetHash());
4880 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4882 pfrom->AddInventoryKnown(inv);
4884 CValidationState state;
4885 // Process all blocks from whitelisted peers, even if not requested,
4886 // unless we're still syncing with the network.
4887 // Such an unrequested block may still be processed, subject to the
4888 // conditions in AcceptBlock().
4889 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4890 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4892 if (state.IsInvalid(nDoS)) {
4893 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4894 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4897 Misbehaving(pfrom->GetId(), nDoS);
4904 // This asymmetric behavior for inbound and outbound connections was introduced
4905 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4906 // to users' AddrMan and later request them by sending getaddr messages.
4907 // Making nodes which are behind NAT and can only make outgoing connections ignore
4908 // the getaddr message mitigates the attack.
4909 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4911 // Only send one GetAddr response per connection to reduce resource waste
4912 // and discourage addr stamping of INV announcements.
4913 if (pfrom->fSentAddr) {
4914 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4917 pfrom->fSentAddr = true;
4919 pfrom->vAddrToSend.clear();
4920 vector<CAddress> vAddr = addrman.GetAddr();
4921 BOOST_FOREACH(const CAddress &addr, vAddr)
4922 pfrom->PushAddress(addr);
4926 else if (strCommand == "mempool")
4928 LOCK2(cs_main, pfrom->cs_filter);
4930 std::vector<uint256> vtxid;
4931 mempool.queryHashes(vtxid);
4933 BOOST_FOREACH(uint256& hash, vtxid) {
4934 CInv inv(MSG_TX, hash);
4936 bool fInMemPool = mempool.lookup(hash, tx);
4937 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4938 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4940 vInv.push_back(inv);
4941 if (vInv.size() == MAX_INV_SZ) {
4942 pfrom->PushMessage("inv", vInv);
4946 if (vInv.size() > 0)
4947 pfrom->PushMessage("inv", vInv);
4951 else if (strCommand == "ping")
4953 if (pfrom->nVersion > BIP0031_VERSION)
4957 // Echo the message back with the nonce. This allows for two useful features:
4959 // 1) A remote node can quickly check if the connection is operational
4960 // 2) Remote nodes can measure the latency of the network thread. If this node
4961 // is overloaded it won't respond to pings quickly and the remote node can
4962 // avoid sending us more work, like chain download requests.
4964 // The nonce stops the remote getting confused between different pings: without
4965 // it, if the remote node sends a ping once per second and this node takes 5
4966 // seconds to respond to each, the 5th ping the remote sends would appear to
4967 // return very quickly.
4968 pfrom->PushMessage("pong", nonce);
4973 else if (strCommand == "pong")
4975 int64_t pingUsecEnd = nTimeReceived;
4977 size_t nAvail = vRecv.in_avail();
4978 bool bPingFinished = false;
4979 std::string sProblem;
4981 if (nAvail >= sizeof(nonce)) {
4984 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4985 if (pfrom->nPingNonceSent != 0) {
4986 if (nonce == pfrom->nPingNonceSent) {
4987 // Matching pong received, this ping is no longer outstanding
4988 bPingFinished = true;
4989 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4990 if (pingUsecTime > 0) {
4991 // Successful ping time measurement, replace previous
4992 pfrom->nPingUsecTime = pingUsecTime;
4993 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4995 // This should never happen
4996 sProblem = "Timing mishap";
4999 // Nonce mismatches are normal when pings are overlapping
5000 sProblem = "Nonce mismatch";
5002 // This is most likely a bug in another implementation somewhere; cancel this ping
5003 bPingFinished = true;
5004 sProblem = "Nonce zero";
5008 sProblem = "Unsolicited pong without ping";
5011 // This is most likely a bug in another implementation somewhere; cancel this ping
5012 bPingFinished = true;
5013 sProblem = "Short payload";
5016 if (!(sProblem.empty())) {
5017 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5021 pfrom->nPingNonceSent,
5025 if (bPingFinished) {
5026 pfrom->nPingNonceSent = 0;
5031 else if (fAlerts && strCommand == "alert")
5036 uint256 alertHash = alert.GetHash();
5037 if (pfrom->setKnown.count(alertHash) == 0)
5039 if (alert.ProcessAlert(Params().AlertKey()))
5042 pfrom->setKnown.insert(alertHash);
5045 BOOST_FOREACH(CNode* pnode, vNodes)
5046 alert.RelayTo(pnode);
5050 // Small DoS penalty so peers that send us lots of
5051 // duplicate/expired/invalid-signature/whatever alerts
5052 // eventually get banned.
5053 // This isn't a Misbehaving(100) (immediate ban) because the
5054 // peer might be an older or different implementation with
5055 // a different signature key, etc.
5056 Misbehaving(pfrom->GetId(), 10);
5062 else if (strCommand == "filterload")
5064 CBloomFilter filter;
5067 if (!filter.IsWithinSizeConstraints())
5068 // There is no excuse for sending a too-large filter
5069 Misbehaving(pfrom->GetId(), 100);
5072 LOCK(pfrom->cs_filter);
5073 delete pfrom->pfilter;
5074 pfrom->pfilter = new CBloomFilter(filter);
5075 pfrom->pfilter->UpdateEmptyFull();
5077 pfrom->fRelayTxes = true;
5081 else if (strCommand == "filteradd")
5083 vector<unsigned char> vData;
5086 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5087 // and thus, the maximum size any matched object can have) in a filteradd message
5088 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5090 Misbehaving(pfrom->GetId(), 100);
5092 LOCK(pfrom->cs_filter);
5094 pfrom->pfilter->insert(vData);
5096 Misbehaving(pfrom->GetId(), 100);
5101 else if (strCommand == "filterclear")
5103 LOCK(pfrom->cs_filter);
5104 delete pfrom->pfilter;
5105 pfrom->pfilter = new CBloomFilter();
5106 pfrom->fRelayTxes = true;
5110 else if (strCommand == "reject")
5114 string strMsg; unsigned char ccode; string strReason;
5115 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5118 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5120 if (strMsg == "block" || strMsg == "tx")
5124 ss << ": hash " << hash.ToString();
5126 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5127 } catch (const std::ios_base::failure&) {
5128 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5129 LogPrint("net", "Unparseable reject message received\n");
5134 else if (strCommand == "notfound") {
5135 // We do not care about the NOTFOUND message, but logging an Unknown Command
5136 // message would be undesirable as we transmit it ourselves.
5140 // Ignore unknown commands for extensibility
5141 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5149 // requires LOCK(cs_vRecvMsg)
5150 bool ProcessMessages(CNode* pfrom)
5153 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5157 // (4) message start
5165 if (!pfrom->vRecvGetData.empty())
5166 ProcessGetData(pfrom);
5168 // this maintains the order of responses
5169 if (!pfrom->vRecvGetData.empty()) return fOk;
5171 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5172 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5173 // Don't bother if send buffer is too full to respond anyway
5174 if (pfrom->nSendSize >= SendBufferSize())
5178 CNetMessage& msg = *it;
5181 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5182 // msg.hdr.nMessageSize, msg.vRecv.size(),
5183 // msg.complete() ? "Y" : "N");
5185 // end, if an incomplete message is found
5186 if (!msg.complete())
5189 // at this point, any failure means we can delete the current message
5192 // Scan for message start
5193 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5194 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5200 CMessageHeader& hdr = msg.hdr;
5201 if (!hdr.IsValid(Params().MessageStart()))
5203 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5206 string strCommand = hdr.GetCommand();
5209 unsigned int nMessageSize = hdr.nMessageSize;
5212 CDataStream& vRecv = msg.vRecv;
5213 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5214 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5215 if (nChecksum != hdr.nChecksum)
5217 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5218 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5226 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5227 boost::this_thread::interruption_point();
5229 catch (const std::ios_base::failure& e)
5231 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5232 if (strstr(e.what(), "end of data"))
5234 // Allow exceptions from under-length message on vRecv
5235 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());
5237 else if (strstr(e.what(), "size too large"))
5239 // Allow exceptions from over-long size
5240 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5244 PrintExceptionContinue(&e, "ProcessMessages()");
5247 catch (const boost::thread_interrupted&) {
5250 catch (const std::exception& e) {
5251 PrintExceptionContinue(&e, "ProcessMessages()");
5253 PrintExceptionContinue(NULL, "ProcessMessages()");
5257 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5262 // In case the connection got shut down, its receive buffer was wiped
5263 if (!pfrom->fDisconnect)
5264 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5270 bool SendMessages(CNode* pto, bool fSendTrickle)
5272 const Consensus::Params& consensusParams = Params().GetConsensus();
5274 // Don't send anything until we get its version message
5275 if (pto->nVersion == 0)
5281 bool pingSend = false;
5282 if (pto->fPingQueued) {
5283 // RPC ping request by user
5286 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5287 // Ping automatically sent as a latency probe & keepalive.
5292 while (nonce == 0) {
5293 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5295 pto->fPingQueued = false;
5296 pto->nPingUsecStart = GetTimeMicros();
5297 if (pto->nVersion > BIP0031_VERSION) {
5298 pto->nPingNonceSent = nonce;
5299 pto->PushMessage("ping", nonce);
5301 // Peer is too old to support ping command with nonce, pong will never arrive.
5302 pto->nPingNonceSent = 0;
5303 pto->PushMessage("ping");
5307 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5311 // Address refresh broadcast
5312 static int64_t nLastRebroadcast;
5313 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5316 BOOST_FOREACH(CNode* pnode, vNodes)
5318 // Periodically clear addrKnown to allow refresh broadcasts
5319 if (nLastRebroadcast)
5320 pnode->addrKnown.reset();
5322 // Rebroadcast our address
5323 AdvertizeLocal(pnode);
5325 if (!vNodes.empty())
5326 nLastRebroadcast = GetTime();
5334 vector<CAddress> vAddr;
5335 vAddr.reserve(pto->vAddrToSend.size());
5336 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5338 if (!pto->addrKnown.contains(addr.GetKey()))
5340 pto->addrKnown.insert(addr.GetKey());
5341 vAddr.push_back(addr);
5342 // receiver rejects addr messages larger than 1000
5343 if (vAddr.size() >= 1000)
5345 pto->PushMessage("addr", vAddr);
5350 pto->vAddrToSend.clear();
5352 pto->PushMessage("addr", vAddr);
5355 CNodeState &state = *State(pto->GetId());
5356 if (state.fShouldBan) {
5357 if (pto->fWhitelisted)
5358 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5360 pto->fDisconnect = true;
5361 if (pto->addr.IsLocal())
5362 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5365 CNode::Ban(pto->addr);
5368 state.fShouldBan = false;
5371 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5372 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5373 state.rejects.clear();
5376 if (pindexBestHeader == NULL)
5377 pindexBestHeader = chainActive.Tip();
5378 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.
5379 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5380 // Only actively request headers from a single peer, unless we're close to today.
5381 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5382 state.fSyncStarted = true;
5384 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5385 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5386 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5390 // Resend wallet transactions that haven't gotten in a block yet
5391 // Except during reindex, importing and IBD, when old wallet
5392 // transactions become unconfirmed and spams other nodes.
5393 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5395 GetMainSignals().Broadcast(nTimeBestReceived);
5399 // Message: inventory
5402 vector<CInv> vInvWait;
5404 LOCK(pto->cs_inventory);
5405 vInv.reserve(pto->vInventoryToSend.size());
5406 vInvWait.reserve(pto->vInventoryToSend.size());
5407 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5409 if (pto->setInventoryKnown.count(inv))
5412 // trickle out tx inv to protect privacy
5413 if (inv.type == MSG_TX && !fSendTrickle)
5415 // 1/4 of tx invs blast to all immediately
5416 static uint256 hashSalt;
5417 if (hashSalt.IsNull())
5418 hashSalt = GetRandHash();
5419 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5420 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5421 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5425 vInvWait.push_back(inv);
5430 // returns true if wasn't already contained in the set
5431 if (pto->setInventoryKnown.insert(inv).second)
5433 vInv.push_back(inv);
5434 if (vInv.size() >= 1000)
5436 pto->PushMessage("inv", vInv);
5441 pto->vInventoryToSend = vInvWait;
5444 pto->PushMessage("inv", vInv);
5446 // Detect whether we're stalling
5447 int64_t nNow = GetTimeMicros();
5448 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5449 // Stalling only triggers when the block download window cannot move. During normal steady state,
5450 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5451 // should only happen during initial block download.
5452 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5453 pto->fDisconnect = true;
5455 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5456 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5457 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5458 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5459 // to unreasonably increase our timeout.
5460 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5461 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5462 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5463 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5464 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5465 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5466 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5467 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5468 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5469 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5470 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5472 if (queuedBlock.nTimeDisconnect < nNow) {
5473 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5474 pto->fDisconnect = true;
5479 // Message: getdata (blocks)
5481 vector<CInv> vGetData;
5482 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5483 vector<CBlockIndex*> vToDownload;
5484 NodeId staller = -1;
5485 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5486 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5487 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5488 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5489 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5490 pindex->nHeight, pto->id);
5492 if (state.nBlocksInFlight == 0 && staller != -1) {
5493 if (State(staller)->nStallingSince == 0) {
5494 State(staller)->nStallingSince = nNow;
5495 LogPrint("net", "Stall started peer=%d\n", staller);
5501 // Message: getdata (non-blocks)
5503 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5505 const CInv& inv = (*pto->mapAskFor.begin()).second;
5506 if (!AlreadyHave(inv))
5509 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5510 vGetData.push_back(inv);
5511 if (vGetData.size() >= 1000)
5513 pto->PushMessage("getdata", vGetData);
5517 //If we're not going to ask, don't expect a response.
5518 pto->setAskFor.erase(inv.hash);
5520 pto->mapAskFor.erase(pto->mapAskFor.begin());
5522 if (!vGetData.empty())
5523 pto->PushMessage("getdata", vGetData);
5529 std::string CBlockFileInfo::ToString() const {
5530 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));
5541 BlockMap::iterator it1 = mapBlockIndex.begin();
5542 for (; it1 != mapBlockIndex.end(); it1++)
5543 delete (*it1).second;
5544 mapBlockIndex.clear();
5546 // orphan transactions
5547 mapOrphanTransactions.clear();
5548 mapOrphanTransactionsByPrev.clear();
5550 } instance_of_cmaincleanup;