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 fImporting = false;
60 bool fReindex = false;
61 bool fTxIndex = false;
62 bool fHavePruned = false;
63 bool fPruneMode = false;
64 bool fIsBareMultisigStd = true;
65 bool fCheckBlockIndex = false;
66 bool fCheckpointsEnabled = true;
67 bool fCoinbaseEnforcedProtectionEnabled = true;
68 size_t nCoinCacheUsage = 5000 * 300;
69 uint64_t nPruneTarget = 0;
70 bool fAlerts = DEFAULT_ALERTS;
72 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
73 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
75 CTxMemPool mempool(::minRelayTxFee);
81 map<uint256, COrphanTx> mapOrphanTransactions;
82 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
83 void EraseOrphansFor(NodeId peer);
86 * Returns true if there are nRequired or more blocks of minVersion or above
87 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
89 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
90 static void CheckBlockIndex();
92 /** Constant stuff for coinbase transactions we create: */
93 CScript COINBASE_FLAGS;
95 const string strMessageMagic = "Zcash Signed Message:\n";
100 struct CBlockIndexWorkComparator
102 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
103 // First sort by most total work, ...
104 if (pa->nChainWork > pb->nChainWork) return false;
105 if (pa->nChainWork < pb->nChainWork) return true;
107 // ... then by earliest time received, ...
108 if (pa->nSequenceId < pb->nSequenceId) return false;
109 if (pa->nSequenceId > pb->nSequenceId) return true;
111 // Use pointer address as tie breaker (should only happen with blocks
112 // loaded from disk, as those all have id 0).
113 if (pa < pb) return false;
114 if (pa > pb) return true;
121 CBlockIndex *pindexBestInvalid;
124 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
125 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
126 * missing the data for the block.
128 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
129 /** Number of nodes with fSyncStarted. */
130 int nSyncStarted = 0;
131 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
132 * Pruned nodes may have entries where B is missing data.
134 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
136 CCriticalSection cs_LastBlockFile;
137 std::vector<CBlockFileInfo> vinfoBlockFile;
138 int nLastBlockFile = 0;
139 /** Global flag to indicate we should check to see if there are
140 * block/undo files that should be deleted. Set on startup
141 * or if we allocate more file space when we're in prune mode
143 bool fCheckForPruning = false;
146 * Every received block is assigned a unique and increasing identifier, so we
147 * know which one to give priority in case of a fork.
149 CCriticalSection cs_nBlockSequenceId;
150 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
151 uint32_t nBlockSequenceId = 1;
154 * Sources of received blocks, saved to be able to send them reject
155 * messages or ban them when processing happens afterwards. Protected by
158 map<uint256, NodeId> mapBlockSource;
161 * Filter for transactions that were recently rejected by
162 * AcceptToMemoryPool. These are not rerequested until the chain tip
163 * changes, at which point the entire filter is reset. Protected by
166 * Without this filter we'd be re-requesting txs from each of our peers,
167 * increasing bandwidth consumption considerably. For instance, with 100
168 * peers, half of which relay a tx we don't accept, that might be a 50x
169 * bandwidth increase. A flooding attacker attempting to roll-over the
170 * filter using minimum-sized, 60byte, transactions might manage to send
171 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
172 * two minute window to send invs to us.
174 * Decreasing the false positive rate is fairly cheap, so we pick one in a
175 * million to make it highly unlikely for users to have issues with this
180 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
181 uint256 hashRecentRejectsChainTip;
183 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
186 CBlockIndex *pindex; //! Optional.
187 int64_t nTime; //! Time of "getdata" request in microseconds.
188 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
189 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
191 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
193 /** Number of blocks in flight with validated headers. */
194 int nQueuedValidatedHeaders = 0;
196 /** Number of preferable block download peers. */
197 int nPreferredDownload = 0;
199 /** Dirty block index entries. */
200 set<CBlockIndex*> setDirtyBlockIndex;
202 /** Dirty block file entries. */
203 set<int> setDirtyFileInfo;
206 //////////////////////////////////////////////////////////////////////////////
208 // Registration of network node signals.
213 struct CBlockReject {
214 unsigned char chRejectCode;
215 string strRejectReason;
220 * Maintain validation-specific state about nodes, protected by cs_main, instead
221 * by CNode's own locks. This simplifies asynchronous operation, where
222 * processing of incoming data is done after the ProcessMessage call returns,
223 * and we're no longer holding the node's locks.
226 //! The peer's address
228 //! Whether we have a fully established connection.
229 bool fCurrentlyConnected;
230 //! Accumulated misbehaviour score for this peer.
232 //! Whether this peer should be disconnected and banned (unless whitelisted).
234 //! String name of this peer (debugging/logging purposes).
236 //! List of asynchronously-determined block rejections to notify this peer about.
237 std::vector<CBlockReject> rejects;
238 //! The best known block we know this peer has announced.
239 CBlockIndex *pindexBestKnownBlock;
240 //! The hash of the last unknown block this peer has announced.
241 uint256 hashLastUnknownBlock;
242 //! The last full block we both have.
243 CBlockIndex *pindexLastCommonBlock;
244 //! Whether we've started headers synchronization with this peer.
246 //! Since when we're stalling block download progress (in microseconds), or 0.
247 int64_t nStallingSince;
248 list<QueuedBlock> vBlocksInFlight;
250 int nBlocksInFlightValidHeaders;
251 //! Whether we consider this a preferred download peer.
252 bool fPreferredDownload;
255 fCurrentlyConnected = false;
258 pindexBestKnownBlock = NULL;
259 hashLastUnknownBlock.SetNull();
260 pindexLastCommonBlock = NULL;
261 fSyncStarted = false;
264 nBlocksInFlightValidHeaders = 0;
265 fPreferredDownload = false;
269 /** Map maintaining per-node state. Requires cs_main. */
270 map<NodeId, CNodeState> mapNodeState;
273 CNodeState *State(NodeId pnode) {
274 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
275 if (it == mapNodeState.end())
283 return chainActive.Height();
286 void UpdatePreferredDownload(CNode* node, CNodeState* state)
288 nPreferredDownload -= state->fPreferredDownload;
290 // Whether this node should be marked as a preferred download node.
291 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
293 nPreferredDownload += state->fPreferredDownload;
296 // Returns time at which to timeout block request (nTime in microseconds)
297 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
299 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
302 void InitializeNode(NodeId nodeid, const CNode *pnode) {
304 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
305 state.name = pnode->addrName;
306 state.address = pnode->addr;
309 void FinalizeNode(NodeId nodeid) {
311 CNodeState *state = State(nodeid);
313 if (state->fSyncStarted)
316 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
317 AddressCurrentlyConnected(state->address);
320 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
321 mapBlocksInFlight.erase(entry.hash);
322 EraseOrphansFor(nodeid);
323 nPreferredDownload -= state->fPreferredDownload;
325 mapNodeState.erase(nodeid);
329 // Returns a bool indicating whether we requested this block.
330 bool MarkBlockAsReceived(const uint256& hash) {
331 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
332 if (itInFlight != mapBlocksInFlight.end()) {
333 CNodeState *state = State(itInFlight->second.first);
334 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
335 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
336 state->vBlocksInFlight.erase(itInFlight->second.second);
337 state->nBlocksInFlight--;
338 state->nStallingSince = 0;
339 mapBlocksInFlight.erase(itInFlight);
346 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
347 CNodeState *state = State(nodeid);
348 assert(state != NULL);
350 // Make sure it's not listed somewhere already.
351 MarkBlockAsReceived(hash);
353 int64_t nNow = GetTimeMicros();
354 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
355 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
356 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
357 state->nBlocksInFlight++;
358 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
359 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
362 /** Check whether the last unknown block a peer advertized is not yet known. */
363 void ProcessBlockAvailability(NodeId nodeid) {
364 CNodeState *state = State(nodeid);
365 assert(state != NULL);
367 if (!state->hashLastUnknownBlock.IsNull()) {
368 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
369 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
370 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
371 state->pindexBestKnownBlock = itOld->second;
372 state->hashLastUnknownBlock.SetNull();
377 /** Update tracking information about which blocks a peer is assumed to have. */
378 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
379 CNodeState *state = State(nodeid);
380 assert(state != NULL);
382 ProcessBlockAvailability(nodeid);
384 BlockMap::iterator it = mapBlockIndex.find(hash);
385 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
386 // An actually better block was announced.
387 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
388 state->pindexBestKnownBlock = it->second;
390 // An unknown block was announced; just assume that the latest one is the best one.
391 state->hashLastUnknownBlock = hash;
395 /** Find the last common ancestor two blocks have.
396 * Both pa and pb must be non-NULL. */
397 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
398 if (pa->nHeight > pb->nHeight) {
399 pa = pa->GetAncestor(pb->nHeight);
400 } else if (pb->nHeight > pa->nHeight) {
401 pb = pb->GetAncestor(pa->nHeight);
404 while (pa != pb && pa && pb) {
409 // Eventually all chain branches meet at the genesis block.
414 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
415 * at most count entries. */
416 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
420 vBlocks.reserve(vBlocks.size() + count);
421 CNodeState *state = State(nodeid);
422 assert(state != NULL);
424 // Make sure pindexBestKnownBlock is up to date, we'll need it.
425 ProcessBlockAvailability(nodeid);
427 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
428 // This peer has nothing interesting.
432 if (state->pindexLastCommonBlock == NULL) {
433 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
434 // Guessing wrong in either direction is not a problem.
435 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
438 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
439 // of its current tip anymore. Go back enough to fix that.
440 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
441 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
444 std::vector<CBlockIndex*> vToFetch;
445 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
446 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
447 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
448 // download that next block if the window were 1 larger.
449 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
450 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
451 NodeId waitingfor = -1;
452 while (pindexWalk->nHeight < nMaxHeight) {
453 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
454 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
455 // as iterating over ~100 CBlockIndex* entries anyway.
456 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
457 vToFetch.resize(nToFetch);
458 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
459 vToFetch[nToFetch - 1] = pindexWalk;
460 for (unsigned int i = nToFetch - 1; i > 0; i--) {
461 vToFetch[i - 1] = vToFetch[i]->pprev;
464 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
465 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
466 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
467 // already part of our chain (and therefore don't need it even if pruned).
468 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
469 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
470 // We consider the chain that this peer is on invalid.
473 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
474 if (pindex->nChainTx)
475 state->pindexLastCommonBlock = pindex;
476 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
477 // The block is not already downloaded, and not yet in flight.
478 if (pindex->nHeight > nWindowEnd) {
479 // We reached the end of the window.
480 if (vBlocks.size() == 0 && waitingfor != nodeid) {
481 // We aren't able to fetch anything, but we would be if the download window was one larger.
482 nodeStaller = waitingfor;
486 vBlocks.push_back(pindex);
487 if (vBlocks.size() == count) {
490 } else if (waitingfor == -1) {
491 // This is the first already-in-flight block.
492 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
500 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
502 CNodeState *state = State(nodeid);
505 stats.nMisbehavior = state->nMisbehavior;
506 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
507 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
508 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
510 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
515 void RegisterNodeSignals(CNodeSignals& nodeSignals)
517 nodeSignals.GetHeight.connect(&GetHeight);
518 nodeSignals.ProcessMessages.connect(&ProcessMessages);
519 nodeSignals.SendMessages.connect(&SendMessages);
520 nodeSignals.InitializeNode.connect(&InitializeNode);
521 nodeSignals.FinalizeNode.connect(&FinalizeNode);
524 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
526 nodeSignals.GetHeight.disconnect(&GetHeight);
527 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
528 nodeSignals.SendMessages.disconnect(&SendMessages);
529 nodeSignals.InitializeNode.disconnect(&InitializeNode);
530 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
533 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
535 // Find the first block the caller has in the main chain
536 BOOST_FOREACH(const uint256& hash, locator.vHave) {
537 BlockMap::iterator mi = mapBlockIndex.find(hash);
538 if (mi != mapBlockIndex.end())
540 CBlockIndex* pindex = (*mi).second;
541 if (chain.Contains(pindex))
545 return chain.Genesis();
548 CCoinsViewCache *pcoinsTip = NULL;
549 CBlockTreeDB *pblocktree = NULL;
551 //////////////////////////////////////////////////////////////////////////////
553 // mapOrphanTransactions
556 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
558 uint256 hash = tx.GetHash();
559 if (mapOrphanTransactions.count(hash))
562 // Ignore big transactions, to avoid a
563 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
564 // large transaction with a missing parent then we assume
565 // it will rebroadcast it later, after the parent transaction(s)
566 // have been mined or received.
567 // 10,000 orphans, each of which is at most 5,000 bytes big is
568 // at most 500 megabytes of orphans:
569 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
572 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
576 mapOrphanTransactions[hash].tx = tx;
577 mapOrphanTransactions[hash].fromPeer = peer;
578 BOOST_FOREACH(const CTxIn& txin, tx.vin)
579 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
581 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
582 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
586 void static EraseOrphanTx(uint256 hash)
588 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
589 if (it == mapOrphanTransactions.end())
591 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
593 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
594 if (itPrev == mapOrphanTransactionsByPrev.end())
596 itPrev->second.erase(hash);
597 if (itPrev->second.empty())
598 mapOrphanTransactionsByPrev.erase(itPrev);
600 mapOrphanTransactions.erase(it);
603 void EraseOrphansFor(NodeId peer)
606 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
607 while (iter != mapOrphanTransactions.end())
609 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
610 if (maybeErase->second.fromPeer == peer)
612 EraseOrphanTx(maybeErase->second.tx.GetHash());
616 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
620 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
622 unsigned int nEvicted = 0;
623 while (mapOrphanTransactions.size() > nMaxOrphans)
625 // Evict a random orphan:
626 uint256 randomhash = GetRandHash();
627 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
628 if (it == mapOrphanTransactions.end())
629 it = mapOrphanTransactions.begin();
630 EraseOrphanTx(it->first);
642 bool IsStandardTx(const CTransaction& tx, string& reason)
644 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
649 BOOST_FOREACH(const CTxIn& txin, tx.vin)
651 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
652 // keys. (remember the 520 byte limit on redeemScript size) That works
653 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
654 // bytes of scriptSig, which we round off to 1650 bytes for some minor
655 // future-proofing. That's also enough to spend a 20-of-20
656 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
657 // considered standard)
658 if (txin.scriptSig.size() > 1650) {
659 reason = "scriptsig-size";
662 if (!txin.scriptSig.IsPushOnly()) {
663 reason = "scriptsig-not-pushonly";
668 unsigned int nDataOut = 0;
669 txnouttype whichType;
670 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
671 if (!::IsStandard(txout.scriptPubKey, whichType)) {
672 reason = "scriptpubkey";
676 if (whichType == TX_NULL_DATA)
678 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
679 reason = "bare-multisig";
681 } else if (txout.IsDust(::minRelayTxFee)) {
687 // only one OP_RETURN txout is permitted
689 reason = "multi-op-return";
696 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
698 if (tx.nLockTime == 0)
700 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
702 BOOST_FOREACH(const CTxIn& txin, tx.vin)
708 bool CheckFinalTx(const CTransaction &tx, int flags)
710 AssertLockHeld(cs_main);
712 // By convention a negative value for flags indicates that the
713 // current network-enforced consensus rules should be used. In
714 // a future soft-fork scenario that would mean checking which
715 // rules would be enforced for the next block and setting the
716 // appropriate flags. At the present time no soft-forks are
717 // scheduled, so no flags are set.
718 flags = std::max(flags, 0);
720 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
721 // nLockTime because when IsFinalTx() is called within
722 // CBlock::AcceptBlock(), the height of the block *being*
723 // evaluated is what is used. Thus if we want to know if a
724 // transaction can be part of the *next* block, we need to call
725 // IsFinalTx() with one more than chainActive.Height().
726 const int nBlockHeight = chainActive.Height() + 1;
728 // Timestamps on the other hand don't get any special treatment,
729 // because we can't know what timestamp the next block will have,
730 // and there aren't timestamp applications where it matters.
731 // However this changes once median past time-locks are enforced:
732 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
733 ? chainActive.Tip()->GetMedianTimePast()
736 return IsFinalTx(tx, nBlockHeight, nBlockTime);
740 * Check transaction inputs to mitigate two
741 * potential denial-of-service attacks:
743 * 1. scriptSigs with extra data stuffed into them,
744 * not consumed by scriptPubKey (or P2SH script)
745 * 2. P2SH scripts with a crazy number of expensive
746 * CHECKSIG/CHECKMULTISIG operations
748 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
751 return true; // Coinbases don't use vin normally
753 for (unsigned int i = 0; i < tx.vin.size(); i++)
755 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
757 vector<vector<unsigned char> > vSolutions;
758 txnouttype whichType;
759 // get the scriptPubKey corresponding to this input:
760 const CScript& prevScript = prev.scriptPubKey;
761 if (!Solver(prevScript, whichType, vSolutions))
763 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
764 if (nArgsExpected < 0)
767 // Transactions with extra stuff in their scriptSigs are
768 // non-standard. Note that this EvalScript() call will
769 // be quick, because if there are any operations
770 // beside "push data" in the scriptSig
771 // IsStandardTx() will have already returned false
772 // and this method isn't called.
773 vector<vector<unsigned char> > stack;
774 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
777 if (whichType == TX_SCRIPTHASH)
781 CScript subscript(stack.back().begin(), stack.back().end());
782 vector<vector<unsigned char> > vSolutions2;
783 txnouttype whichType2;
784 if (Solver(subscript, whichType2, vSolutions2))
786 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
789 nArgsExpected += tmpExpected;
793 // Any other Script with less than 15 sigops OK:
794 unsigned int sigops = subscript.GetSigOpCount(true);
795 // ... extra data left on the stack after execution is OK, too:
796 return (sigops <= MAX_P2SH_SIGOPS);
800 if (stack.size() != (unsigned int)nArgsExpected)
807 unsigned int GetLegacySigOpCount(const CTransaction& tx)
809 unsigned int nSigOps = 0;
810 BOOST_FOREACH(const CTxIn& txin, tx.vin)
812 nSigOps += txin.scriptSig.GetSigOpCount(false);
814 BOOST_FOREACH(const CTxOut& txout, tx.vout)
816 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
821 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
826 unsigned int nSigOps = 0;
827 for (unsigned int i = 0; i < tx.vin.size(); i++)
829 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
830 if (prevout.scriptPubKey.IsPayToScriptHash())
831 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
836 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
837 libzcash::ProofVerifier& verifier)
839 // Don't count coinbase transactions because mining skews the count
840 if (!tx.IsCoinBase()) {
841 transactionsValidated.increment();
844 if (!CheckTransactionWithoutProofVerification(tx, state)) {
847 // Ensure that zk-SNARKs verify
848 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
849 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
850 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
851 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
858 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
860 // Basic checks that don't depend on any context
862 // Check transaction version
863 if (tx.nVersion < MIN_TX_VERSION) {
864 return state.DoS(100, error("CheckTransaction(): version too low"),
865 REJECT_INVALID, "bad-txns-version-too-low");
868 // Transactions can contain empty `vin` and `vout` so long as
869 // `vjoinsplit` is non-empty.
870 if (tx.vin.empty() && tx.vjoinsplit.empty())
871 return state.DoS(10, error("CheckTransaction(): vin empty"),
872 REJECT_INVALID, "bad-txns-vin-empty");
873 if (tx.vout.empty() && tx.vjoinsplit.empty())
874 return state.DoS(10, error("CheckTransaction(): vout empty"),
875 REJECT_INVALID, "bad-txns-vout-empty");
878 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
879 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
880 return state.DoS(100, error("CheckTransaction(): size limits failed"),
881 REJECT_INVALID, "bad-txns-oversize");
883 // Check for negative or overflow output values
884 CAmount nValueOut = 0;
885 BOOST_FOREACH(const CTxOut& txout, tx.vout)
887 if (txout.nValue < 0)
888 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
889 REJECT_INVALID, "bad-txns-vout-negative");
890 if (txout.nValue > MAX_MONEY)
891 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
892 REJECT_INVALID, "bad-txns-vout-toolarge");
893 nValueOut += txout.nValue;
894 if (!MoneyRange(nValueOut))
895 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
896 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
899 // Ensure that joinsplit values are well-formed
900 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
902 if (joinsplit.vpub_old < 0) {
903 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
904 REJECT_INVALID, "bad-txns-vpub_old-negative");
907 if (joinsplit.vpub_new < 0) {
908 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
909 REJECT_INVALID, "bad-txns-vpub_new-negative");
912 if (joinsplit.vpub_old > MAX_MONEY) {
913 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
914 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
917 if (joinsplit.vpub_new > MAX_MONEY) {
918 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
919 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
922 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
923 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
924 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
927 nValueOut += joinsplit.vpub_old;
928 if (!MoneyRange(nValueOut)) {
929 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
930 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
934 // Ensure input values do not exceed MAX_MONEY
935 // We have not resolved the txin values at this stage,
936 // but we do know what the joinsplits claim to add
937 // to the value pool.
939 CAmount nValueIn = 0;
940 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
942 nValueIn += it->vpub_new;
944 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
945 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
946 REJECT_INVALID, "bad-txns-txintotal-toolarge");
952 // Check for duplicate inputs
953 set<COutPoint> vInOutPoints;
954 BOOST_FOREACH(const CTxIn& txin, tx.vin)
956 if (vInOutPoints.count(txin.prevout))
957 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
958 REJECT_INVALID, "bad-txns-inputs-duplicate");
959 vInOutPoints.insert(txin.prevout);
962 // Check for duplicate joinsplit nullifiers in this transaction
963 set<uint256> vJoinSplitNullifiers;
964 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
966 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
968 if (vJoinSplitNullifiers.count(nf))
969 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
970 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
972 vJoinSplitNullifiers.insert(nf);
978 // There should be no joinsplits in a coinbase transaction
979 if (tx.vjoinsplit.size() > 0)
980 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
981 REJECT_INVALID, "bad-cb-has-joinsplits");
983 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
984 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
985 REJECT_INVALID, "bad-cb-length");
989 BOOST_FOREACH(const CTxIn& txin, tx.vin)
990 if (txin.prevout.IsNull())
991 return state.DoS(10, error("CheckTransaction(): prevout is null"),
992 REJECT_INVALID, "bad-txns-prevout-null");
994 if (tx.vjoinsplit.size() > 0) {
995 // Empty output script.
997 uint256 dataToBeSigned;
999 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1000 } catch (std::logic_error ex) {
1001 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1002 REJECT_INVALID, "error-computing-signature-hash");
1005 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1007 // We rely on libsodium to check that the signature is canonical.
1008 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1009 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1010 dataToBeSigned.begin(), 32,
1011 tx.joinSplitPubKey.begin()
1013 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1014 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1022 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1026 uint256 hash = tx.GetHash();
1027 double dPriorityDelta = 0;
1028 CAmount nFeeDelta = 0;
1029 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1030 if (dPriorityDelta > 0 || nFeeDelta > 0)
1034 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1038 // There is a free transaction area in blocks created by most miners,
1039 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1040 // to be considered to fall into this category. We don't want to encourage sending
1041 // multiple transactions instead of one big transaction to avoid fees.
1042 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1046 if (!MoneyRange(nMinFee))
1047 nMinFee = MAX_MONEY;
1052 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1053 bool* pfMissingInputs, bool fRejectAbsurdFee)
1055 AssertLockHeld(cs_main);
1056 if (pfMissingInputs)
1057 *pfMissingInputs = false;
1059 auto verifier = libzcash::ProofVerifier::Strict();
1060 if (!CheckTransaction(tx, state, verifier))
1061 return error("AcceptToMemoryPool: CheckTransaction failed");
1063 // Coinbase is only valid in a block, not as a loose transaction
1064 if (tx.IsCoinBase())
1065 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1066 REJECT_INVALID, "coinbase");
1068 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1070 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1072 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1073 REJECT_NONSTANDARD, reason);
1075 // Only accept nLockTime-using transactions that can be mined in the next
1076 // block; we don't want our mempool filled up with transactions that can't
1078 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1079 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1081 // is it already in the memory pool?
1082 uint256 hash = tx.GetHash();
1083 if (pool.exists(hash))
1086 // Check for conflicts with in-memory transactions
1088 LOCK(pool.cs); // protect pool.mapNextTx
1089 for (unsigned int i = 0; i < tx.vin.size(); i++)
1091 COutPoint outpoint = tx.vin[i].prevout;
1092 if (pool.mapNextTx.count(outpoint))
1094 // Disable replacement feature for now
1098 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1099 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1100 if (pool.mapNullifiers.count(nf))
1110 CCoinsViewCache view(&dummy);
1112 CAmount nValueIn = 0;
1115 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1116 view.SetBackend(viewMemPool);
1118 // do we already have it?
1119 if (view.HaveCoins(hash))
1122 // do all inputs exist?
1123 // Note that this does not check for the presence of actual outputs (see the next check for that),
1124 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1125 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1126 if (!view.HaveCoins(txin.prevout.hash)) {
1127 if (pfMissingInputs)
1128 *pfMissingInputs = true;
1133 // are the actual inputs available?
1134 if (!view.HaveInputs(tx))
1135 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1136 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1138 // are the joinsplit's requirements met?
1139 if (!view.HaveJoinSplitRequirements(tx))
1140 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1141 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1143 // Bring the best block into scope
1144 view.GetBestBlock();
1146 nValueIn = view.GetValueIn(tx);
1148 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1149 view.SetBackend(dummy);
1152 // Check for non-standard pay-to-script-hash in inputs
1153 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1154 return error("AcceptToMemoryPool: nonstandard transaction input");
1156 // Check that the transaction doesn't have an excessive number of
1157 // sigops, making it impossible to mine. Since the coinbase transaction
1158 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1159 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1160 // merely non-standard transaction.
1161 unsigned int nSigOps = GetLegacySigOpCount(tx);
1162 nSigOps += GetP2SHSigOpCount(tx, view);
1163 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1165 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1166 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1167 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1169 CAmount nValueOut = tx.GetValueOut();
1170 CAmount nFees = nValueIn-nValueOut;
1171 double dPriority = view.GetPriority(tx, chainActive.Height());
1173 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1174 unsigned int nSize = entry.GetTxSize();
1176 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1177 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1178 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1180 // Don't accept it if it can't get into a block
1181 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1182 if (fLimitFree && nFees < txMinFee)
1183 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1184 hash.ToString(), nFees, txMinFee),
1185 REJECT_INSUFFICIENTFEE, "insufficient fee");
1188 // Require that free transactions have sufficient priority to be mined in the next block.
1189 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1190 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1193 // Continuously rate-limit free (really, very-low-fee) transactions
1194 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1195 // be annoying or make others' transactions take longer to confirm.
1196 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1198 static CCriticalSection csFreeLimiter;
1199 static double dFreeCount;
1200 static int64_t nLastTime;
1201 int64_t nNow = GetTime();
1203 LOCK(csFreeLimiter);
1205 // Use an exponentially decaying ~10-minute window:
1206 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1208 // -limitfreerelay unit is thousand-bytes-per-minute
1209 // At default rate it would take over a month to fill 1GB
1210 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1211 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1212 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1213 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1214 dFreeCount += nSize;
1217 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1218 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1220 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1222 // Check against previous transactions
1223 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1224 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1226 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1229 // Check again against just the consensus-critical mandatory script
1230 // verification flags, in case of bugs in the standard flags that cause
1231 // transactions to pass as valid when they're actually invalid. For
1232 // instance the STRICTENC flag was incorrectly allowing certain
1233 // CHECKSIG NOT scripts to pass, even though they were invalid.
1235 // There is a similar check in CreateNewBlock() to prevent creating
1236 // invalid blocks, however allowing such transactions into the mempool
1237 // can be exploited as a DoS attack.
1238 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1240 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1243 // Store transaction in memory
1244 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1247 SyncWithWallets(tx, NULL);
1252 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1253 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1255 CBlockIndex *pindexSlow = NULL;
1259 if (mempool.lookup(hash, txOut))
1266 if (pblocktree->ReadTxIndex(hash, postx)) {
1267 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1269 return error("%s: OpenBlockFile failed", __func__);
1270 CBlockHeader header;
1273 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1275 } catch (const std::exception& e) {
1276 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1278 hashBlock = header.GetHash();
1279 if (txOut.GetHash() != hash)
1280 return error("%s: txid mismatch", __func__);
1285 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1288 CCoinsViewCache &view = *pcoinsTip;
1289 const CCoins* coins = view.AccessCoins(hash);
1291 nHeight = coins->nHeight;
1294 pindexSlow = chainActive[nHeight];
1299 if (ReadBlockFromDisk(block, pindexSlow)) {
1300 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1301 if (tx.GetHash() == hash) {
1303 hashBlock = pindexSlow->GetBlockHash();
1318 //////////////////////////////////////////////////////////////////////////////
1320 // CBlock and CBlockIndex
1323 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1325 // Open history file to append
1326 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1327 if (fileout.IsNull())
1328 return error("WriteBlockToDisk: OpenBlockFile failed");
1330 // Write index header
1331 unsigned int nSize = fileout.GetSerializeSize(block);
1332 fileout << FLATDATA(messageStart) << nSize;
1335 long fileOutPos = ftell(fileout.Get());
1337 return error("WriteBlockToDisk: ftell failed");
1338 pos.nPos = (unsigned int)fileOutPos;
1344 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1348 // Open history file to read
1349 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1350 if (filein.IsNull())
1351 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1357 catch (const std::exception& e) {
1358 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1362 if (!(CheckEquihashSolution(&block, Params()) &&
1363 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1364 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1369 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1371 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1373 if (block.GetHash() != pindex->GetBlockHash())
1374 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1375 pindex->ToString(), pindex->GetBlockPos().ToString());
1379 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1381 CAmount nSubsidy = 12.5 * COIN;
1383 // Mining slow start
1384 // The subsidy is ramped up linearly, skipping the middle payout of
1385 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1386 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1387 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1388 nSubsidy *= nHeight;
1390 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1391 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1392 nSubsidy *= (nHeight+1);
1396 assert(nHeight > consensusParams.SubsidySlowStartShift());
1397 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1398 // Force block reward to zero when right shift is undefined.
1402 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1403 nSubsidy >>= halvings;
1407 bool IsInitialBlockDownload()
1409 const CChainParams& chainParams = Params();
1411 if (fImporting || fReindex)
1413 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1415 static bool lockIBDState = false;
1418 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1419 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1421 lockIBDState = true;
1425 bool fLargeWorkForkFound = false;
1426 bool fLargeWorkInvalidChainFound = false;
1427 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1429 void CheckForkWarningConditions()
1431 AssertLockHeld(cs_main);
1432 // Before we get past initial download, we cannot reliably alert about forks
1433 // (we assume we don't get stuck on a fork before the last checkpoint)
1434 if (IsInitialBlockDownload())
1437 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1438 // of our head, drop it
1439 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1440 pindexBestForkTip = NULL;
1442 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1444 if (!fLargeWorkForkFound && pindexBestForkBase)
1446 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1447 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1448 CAlert::Notify(warning, true);
1450 if (pindexBestForkTip && pindexBestForkBase)
1452 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__,
1453 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1454 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1455 fLargeWorkForkFound = true;
1459 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1460 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1461 CAlert::Notify(warning, true);
1462 fLargeWorkInvalidChainFound = true;
1467 fLargeWorkForkFound = false;
1468 fLargeWorkInvalidChainFound = false;
1472 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1474 AssertLockHeld(cs_main);
1475 // If we are on a fork that is sufficiently large, set a warning flag
1476 CBlockIndex* pfork = pindexNewForkTip;
1477 CBlockIndex* plonger = chainActive.Tip();
1478 while (pfork && pfork != plonger)
1480 while (plonger && plonger->nHeight > pfork->nHeight)
1481 plonger = plonger->pprev;
1482 if (pfork == plonger)
1484 pfork = pfork->pprev;
1487 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1488 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1489 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1490 // hash rate operating on the fork.
1491 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1492 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1493 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1494 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1495 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1496 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1498 pindexBestForkTip = pindexNewForkTip;
1499 pindexBestForkBase = pfork;
1502 CheckForkWarningConditions();
1505 // Requires cs_main.
1506 void Misbehaving(NodeId pnode, int howmuch)
1511 CNodeState *state = State(pnode);
1515 state->nMisbehavior += howmuch;
1516 int banscore = GetArg("-banscore", 100);
1517 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1519 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1520 state->fShouldBan = true;
1522 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1525 void static InvalidChainFound(CBlockIndex* pindexNew)
1527 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1528 pindexBestInvalid = pindexNew;
1530 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1531 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1532 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1533 pindexNew->GetBlockTime()));
1534 CBlockIndex *tip = chainActive.Tip();
1536 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1537 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1538 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1539 CheckForkWarningConditions();
1542 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1544 if (state.IsInvalid(nDoS)) {
1545 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1546 if (it != mapBlockSource.end() && State(it->second)) {
1547 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1548 State(it->second)->rejects.push_back(reject);
1550 Misbehaving(it->second, nDoS);
1553 if (!state.CorruptionPossible()) {
1554 pindex->nStatus |= BLOCK_FAILED_VALID;
1555 setDirtyBlockIndex.insert(pindex);
1556 setBlockIndexCandidates.erase(pindex);
1557 InvalidChainFound(pindex);
1561 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1563 // mark inputs spent
1564 if (!tx.IsCoinBase()) {
1565 txundo.vprevout.reserve(tx.vin.size());
1566 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1567 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1568 unsigned nPos = txin.prevout.n;
1570 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1572 // mark an outpoint spent, and construct undo information
1573 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1575 if (coins->vout.size() == 0) {
1576 CTxInUndo& undo = txundo.vprevout.back();
1577 undo.nHeight = coins->nHeight;
1578 undo.fCoinBase = coins->fCoinBase;
1579 undo.nVersion = coins->nVersion;
1585 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1586 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1587 inputs.SetNullifier(nf, true);
1592 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1595 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1598 UpdateCoins(tx, state, inputs, txundo, nHeight);
1601 bool CScriptCheck::operator()() {
1602 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1603 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1604 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1609 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)
1611 if (!tx.IsCoinBase())
1614 pvChecks->reserve(tx.vin.size());
1616 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1617 // for an attacker to attempt to split the network.
1618 if (!inputs.HaveInputs(tx))
1619 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1621 // are the JoinSplit's requirements met?
1622 if (!inputs.HaveJoinSplitRequirements(tx))
1623 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1625 CAmount nValueIn = 0;
1627 for (unsigned int i = 0; i < tx.vin.size(); i++)
1629 const COutPoint &prevout = tx.vin[i].prevout;
1630 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1633 if (coins->IsCoinBase()) {
1634 // Ensure that coinbases cannot be spent to transparent outputs
1635 // Disabled on regtest
1636 if (fCoinbaseEnforcedProtectionEnabled &&
1637 consensusParams.fCoinbaseMustBeProtected &&
1639 return state.Invalid(
1640 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1641 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1645 // Check for negative or overflow input values
1646 nValueIn += coins->vout[prevout.n].nValue;
1647 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1648 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1649 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1653 nValueIn += tx.GetJoinSplitValueIn();
1654 if (!MoneyRange(nValueIn))
1655 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1656 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1658 if (nValueIn < tx.GetValueOut())
1659 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1660 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1661 REJECT_INVALID, "bad-txns-in-belowout");
1663 // Tally transaction fees
1664 CAmount nTxFee = nValueIn - tx.GetValueOut();
1666 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1667 REJECT_INVALID, "bad-txns-fee-negative");
1669 if (!MoneyRange(nFees))
1670 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1671 REJECT_INVALID, "bad-txns-fee-outofrange");
1673 // The first loop above does all the inexpensive checks.
1674 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1675 // Helps prevent CPU exhaustion attacks.
1677 // Skip ECDSA signature verification when connecting blocks
1678 // before the last block chain checkpoint. This is safe because block merkle hashes are
1679 // still computed and checked, and any change will be caught at the next checkpoint.
1680 if (fScriptChecks) {
1681 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1682 const COutPoint &prevout = tx.vin[i].prevout;
1683 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1687 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1689 pvChecks->push_back(CScriptCheck());
1690 check.swap(pvChecks->back());
1691 } else if (!check()) {
1692 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1693 // Check whether the failure was caused by a
1694 // non-mandatory script verification check, such as
1695 // non-standard DER encodings or non-null dummy
1696 // arguments; if so, don't trigger DoS protection to
1697 // avoid splitting the network between upgraded and
1698 // non-upgraded nodes.
1699 CScriptCheck check(*coins, tx, i,
1700 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1702 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1704 // Failures of other flags indicate a transaction that is
1705 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1706 // such nodes as they are not following the protocol. That
1707 // said during an upgrade careful thought should be taken
1708 // as to the correct behavior - we may want to continue
1709 // peering with non-upgraded nodes even after a soft-fork
1710 // super-majority vote has passed.
1711 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1720 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)
1722 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1726 if (!tx.IsCoinBase())
1728 // While checking, GetBestBlock() refers to the parent block.
1729 // This is also true for mempool checks.
1730 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1731 int nSpendHeight = pindexPrev->nHeight + 1;
1732 for (unsigned int i = 0; i < tx.vin.size(); i++)
1734 const COutPoint &prevout = tx.vin[i].prevout;
1735 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1736 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1740 // If prev is coinbase, check that it's matured
1741 if (coins->IsCoinBase()) {
1742 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1743 return state.Invalid(
1744 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1745 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1756 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1758 // Open history file to append
1759 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1760 if (fileout.IsNull())
1761 return error("%s: OpenUndoFile failed", __func__);
1763 // Write index header
1764 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1765 fileout << FLATDATA(messageStart) << nSize;
1768 long fileOutPos = ftell(fileout.Get());
1770 return error("%s: ftell failed", __func__);
1771 pos.nPos = (unsigned int)fileOutPos;
1772 fileout << blockundo;
1774 // calculate & write checksum
1775 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1776 hasher << hashBlock;
1777 hasher << blockundo;
1778 fileout << hasher.GetHash();
1783 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1785 // Open history file to read
1786 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1787 if (filein.IsNull())
1788 return error("%s: OpenBlockFile failed", __func__);
1791 uint256 hashChecksum;
1793 filein >> blockundo;
1794 filein >> hashChecksum;
1796 catch (const std::exception& e) {
1797 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1801 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1802 hasher << hashBlock;
1803 hasher << blockundo;
1804 if (hashChecksum != hasher.GetHash())
1805 return error("%s: Checksum mismatch", __func__);
1810 /** Abort with a message */
1811 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1813 strMiscWarning = strMessage;
1814 LogPrintf("*** %s\n", strMessage);
1815 uiInterface.ThreadSafeMessageBox(
1816 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1817 "", CClientUIInterface::MSG_ERROR);
1822 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1824 AbortNode(strMessage, userMessage);
1825 return state.Error(strMessage);
1831 * Apply the undo operation of a CTxInUndo to the given chain state.
1832 * @param undo The undo object.
1833 * @param view The coins view to which to apply the changes.
1834 * @param out The out point that corresponds to the tx input.
1835 * @return True on success.
1837 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1841 CCoinsModifier coins = view.ModifyCoins(out.hash);
1842 if (undo.nHeight != 0) {
1843 // undo data contains height: this is the last output of the prevout tx being spent
1844 if (!coins->IsPruned())
1845 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1847 coins->fCoinBase = undo.fCoinBase;
1848 coins->nHeight = undo.nHeight;
1849 coins->nVersion = undo.nVersion;
1851 if (coins->IsPruned())
1852 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1854 if (coins->IsAvailable(out.n))
1855 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1856 if (coins->vout.size() < out.n+1)
1857 coins->vout.resize(out.n+1);
1858 coins->vout[out.n] = undo.txout;
1863 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1865 assert(pindex->GetBlockHash() == view.GetBestBlock());
1872 CBlockUndo blockUndo;
1873 CDiskBlockPos pos = pindex->GetUndoPos();
1875 return error("DisconnectBlock(): no undo data available");
1876 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1877 return error("DisconnectBlock(): failure reading undo data");
1879 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1880 return error("DisconnectBlock(): block and undo data inconsistent");
1882 // undo transactions in reverse order
1883 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1884 const CTransaction &tx = block.vtx[i];
1885 uint256 hash = tx.GetHash();
1887 // Check that all outputs are available and match the outputs in the block itself
1890 CCoinsModifier outs = view.ModifyCoins(hash);
1891 outs->ClearUnspendable();
1893 CCoins outsBlock(tx, pindex->nHeight);
1894 // The CCoins serialization does not serialize negative numbers.
1895 // No network rules currently depend on the version here, so an inconsistency is harmless
1896 // but it must be corrected before txout nversion ever influences a network rule.
1897 if (outsBlock.nVersion < 0)
1898 outs->nVersion = outsBlock.nVersion;
1899 if (*outs != outsBlock)
1900 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1906 // unspend nullifiers
1907 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1908 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1909 view.SetNullifier(nf, false);
1914 if (i > 0) { // not coinbases
1915 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1916 if (txundo.vprevout.size() != tx.vin.size())
1917 return error("DisconnectBlock(): transaction and undo data inconsistent");
1918 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1919 const COutPoint &out = tx.vin[j].prevout;
1920 const CTxInUndo &undo = txundo.vprevout[j];
1921 if (!ApplyTxInUndo(undo, view, out))
1927 // set the old best anchor back
1928 view.PopAnchor(blockUndo.old_tree_root);
1930 // move best block pointer to prevout block
1931 view.SetBestBlock(pindex->pprev->GetBlockHash());
1941 void static FlushBlockFile(bool fFinalize = false)
1943 LOCK(cs_LastBlockFile);
1945 CDiskBlockPos posOld(nLastBlockFile, 0);
1947 FILE *fileOld = OpenBlockFile(posOld);
1950 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1951 FileCommit(fileOld);
1955 fileOld = OpenUndoFile(posOld);
1958 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1959 FileCommit(fileOld);
1964 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1966 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1968 void ThreadScriptCheck() {
1969 RenameThread("zcash-scriptch");
1970 scriptcheckqueue.Thread();
1974 // Called periodically asynchronously; alerts if it smells like
1975 // we're being fed a bad chain (blocks being generated much
1976 // too slowly or too quickly).
1978 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1979 int64_t nPowTargetSpacing)
1981 if (bestHeader == NULL || initialDownloadCheck()) return;
1983 static int64_t lastAlertTime = 0;
1984 int64_t now = GetAdjustedTime();
1985 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1987 const int SPAN_HOURS=4;
1988 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1989 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1991 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1993 std::string strWarning;
1994 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1997 const CBlockIndex* i = bestHeader;
1999 while (i->GetBlockTime() >= startTime) {
2002 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2005 // How likely is it to find that many by chance?
2006 double p = boost::math::pdf(poisson, nBlocks);
2008 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2009 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2011 // Aim for one false-positive about every fifty years of normal running:
2012 const int FIFTY_YEARS = 50*365*24*60*60;
2013 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2015 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2017 // Many fewer blocks than expected: alert!
2018 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2019 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2021 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2023 // Many more blocks than expected: alert!
2024 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2025 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2027 if (!strWarning.empty())
2029 strMiscWarning = strWarning;
2030 CAlert::Notify(strWarning, true);
2031 lastAlertTime = now;
2035 static int64_t nTimeVerify = 0;
2036 static int64_t nTimeConnect = 0;
2037 static int64_t nTimeIndex = 0;
2038 static int64_t nTimeCallbacks = 0;
2039 static int64_t nTimeTotal = 0;
2041 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2043 const CChainParams& chainparams = Params();
2044 AssertLockHeld(cs_main);
2046 bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2047 auto verifier = libzcash::ProofVerifier::Strict();
2048 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2050 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2051 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2054 // verify that the view's current state corresponds to the previous block
2055 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2056 assert(hashPrevBlock == view.GetBestBlock());
2058 // Special case for the genesis block, skipping connection of its transactions
2059 // (its coinbase is unspendable)
2060 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2062 view.SetBestBlock(pindex->GetBlockHash());
2063 // Before the genesis block, there was an empty tree
2064 ZCIncrementalMerkleTree tree;
2065 pindex->hashAnchor = tree.root();
2070 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2071 // unless those are already completely spent.
2072 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2073 const CCoins* coins = view.AccessCoins(tx.GetHash());
2074 if (coins && !coins->IsPruned())
2075 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2076 REJECT_INVALID, "bad-txns-BIP30");
2079 unsigned int flags = SCRIPT_VERIFY_P2SH;
2081 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2082 // when 75% of the network has upgraded:
2083 if (block.nVersion >= 3) {
2084 flags |= SCRIPT_VERIFY_DERSIG;
2087 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2088 // blocks, when 75% of the network has upgraded:
2089 if (block.nVersion >= 4) {
2090 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2093 CBlockUndo blockundo;
2095 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2097 int64_t nTimeStart = GetTimeMicros();
2100 unsigned int nSigOps = 0;
2101 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2102 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2103 vPos.reserve(block.vtx.size());
2104 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2106 // Construct the incremental merkle tree at the current
2108 auto old_tree_root = view.GetBestAnchor();
2109 // saving the top anchor in the block index as we go.
2111 pindex->hashAnchor = old_tree_root;
2113 ZCIncrementalMerkleTree tree;
2114 // This should never fail: we should always be able to get the root
2115 // that is on the tip of our chain
2116 assert(view.GetAnchorAt(old_tree_root, tree));
2119 // Consistency check: the root of the tree we're given should
2120 // match what we asked for.
2121 assert(tree.root() == old_tree_root);
2124 for (unsigned int i = 0; i < block.vtx.size(); i++)
2126 const CTransaction &tx = block.vtx[i];
2128 nInputs += tx.vin.size();
2129 nSigOps += GetLegacySigOpCount(tx);
2130 if (nSigOps > MAX_BLOCK_SIGOPS)
2131 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2132 REJECT_INVALID, "bad-blk-sigops");
2134 if (!tx.IsCoinBase())
2136 if (!view.HaveInputs(tx))
2137 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2138 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2140 // are the JoinSplit's requirements met?
2141 if (!view.HaveJoinSplitRequirements(tx))
2142 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2143 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2145 // Add in sigops done by pay-to-script-hash inputs;
2146 // this is to prevent a "rogue miner" from creating
2147 // an incredibly-expensive-to-validate block.
2148 nSigOps += GetP2SHSigOpCount(tx, view);
2149 if (nSigOps > MAX_BLOCK_SIGOPS)
2150 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2151 REJECT_INVALID, "bad-blk-sigops");
2153 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2155 std::vector<CScriptCheck> vChecks;
2156 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2158 control.Add(vChecks);
2163 blockundo.vtxundo.push_back(CTxUndo());
2165 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2167 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2168 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2169 // Insert the note commitments into our temporary tree.
2171 tree.append(note_commitment);
2175 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2176 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2179 view.PushAnchor(tree);
2180 blockundo.old_tree_root = old_tree_root;
2182 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2183 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);
2185 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2186 if (block.vtx[0].GetValueOut() > blockReward)
2187 return state.DoS(100,
2188 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2189 block.vtx[0].GetValueOut(), blockReward),
2190 REJECT_INVALID, "bad-cb-amount");
2192 if (!control.Wait())
2193 return state.DoS(100, false);
2194 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2195 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);
2200 // Write undo information to disk
2201 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2203 if (pindex->GetUndoPos().IsNull()) {
2205 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2206 return error("ConnectBlock(): FindUndoPos failed");
2207 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2208 return AbortNode(state, "Failed to write undo data");
2210 // update nUndoPos in block index
2211 pindex->nUndoPos = pos.nPos;
2212 pindex->nStatus |= BLOCK_HAVE_UNDO;
2215 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2216 setDirtyBlockIndex.insert(pindex);
2220 if (!pblocktree->WriteTxIndex(vPos))
2221 return AbortNode(state, "Failed to write transaction index");
2223 // add this block to the view's block chain
2224 view.SetBestBlock(pindex->GetBlockHash());
2226 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2227 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2229 // Watch for changes to the previous coinbase transaction.
2230 static uint256 hashPrevBestCoinBase;
2231 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2232 hashPrevBestCoinBase = block.vtx[0].GetHash();
2234 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2235 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2240 enum FlushStateMode {
2242 FLUSH_STATE_IF_NEEDED,
2243 FLUSH_STATE_PERIODIC,
2248 * Update the on-disk chain state.
2249 * The caches and indexes are flushed depending on the mode we're called with
2250 * if they're too large, if it's been a while since the last write,
2251 * or always and in all cases if we're in prune mode and are deleting files.
2253 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2254 LOCK2(cs_main, cs_LastBlockFile);
2255 static int64_t nLastWrite = 0;
2256 static int64_t nLastFlush = 0;
2257 static int64_t nLastSetChain = 0;
2258 std::set<int> setFilesToPrune;
2259 bool fFlushForPrune = false;
2261 if (fPruneMode && fCheckForPruning && !fReindex) {
2262 FindFilesToPrune(setFilesToPrune);
2263 fCheckForPruning = false;
2264 if (!setFilesToPrune.empty()) {
2265 fFlushForPrune = true;
2267 pblocktree->WriteFlag("prunedblockfiles", true);
2272 int64_t nNow = GetTimeMicros();
2273 // Avoid writing/flushing immediately after startup.
2274 if (nLastWrite == 0) {
2277 if (nLastFlush == 0) {
2280 if (nLastSetChain == 0) {
2281 nLastSetChain = nNow;
2283 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2284 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2285 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2286 // The cache is over the limit, we have to write now.
2287 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2288 // 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.
2289 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2290 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2291 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2292 // Combine all conditions that result in a full cache flush.
2293 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2294 // Write blocks and block index to disk.
2295 if (fDoFullFlush || fPeriodicWrite) {
2296 // Depend on nMinDiskSpace to ensure we can write block index
2297 if (!CheckDiskSpace(0))
2298 return state.Error("out of disk space");
2299 // First make sure all block and undo data is flushed to disk.
2301 // Then update all block file information (which may refer to block and undo files).
2303 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2304 vFiles.reserve(setDirtyFileInfo.size());
2305 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2306 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2307 setDirtyFileInfo.erase(it++);
2309 std::vector<const CBlockIndex*> vBlocks;
2310 vBlocks.reserve(setDirtyBlockIndex.size());
2311 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2312 vBlocks.push_back(*it);
2313 setDirtyBlockIndex.erase(it++);
2315 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2316 return AbortNode(state, "Files to write to block index database");
2319 // Finally remove any pruned files
2321 UnlinkPrunedFiles(setFilesToPrune);
2324 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2326 // Typical CCoins structures on disk are around 128 bytes in size.
2327 // Pushing a new one to the database can cause it to be written
2328 // twice (once in the log, and once in the tables). This is already
2329 // an overestimation, as most will delete an existing entry or
2330 // overwrite one. Still, use a conservative safety factor of 2.
2331 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2332 return state.Error("out of disk space");
2333 // Flush the chainstate (which may refer to block index entries).
2334 if (!pcoinsTip->Flush())
2335 return AbortNode(state, "Failed to write to coin database");
2338 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2339 // Update best block in wallet (so we can detect restored wallets).
2340 GetMainSignals().SetBestChain(chainActive.GetLocator());
2341 nLastSetChain = nNow;
2343 } catch (const std::runtime_error& e) {
2344 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2349 void FlushStateToDisk() {
2350 CValidationState state;
2351 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2354 void PruneAndFlush() {
2355 CValidationState state;
2356 fCheckForPruning = true;
2357 FlushStateToDisk(state, FLUSH_STATE_NONE);
2360 /** Update chainActive and related internal data structures. */
2361 void static UpdateTip(CBlockIndex *pindexNew) {
2362 const CChainParams& chainParams = Params();
2363 chainActive.SetTip(pindexNew);
2366 nTimeBestReceived = GetTime();
2367 mempool.AddTransactionsUpdated(1);
2369 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2370 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2371 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2372 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2374 cvBlockChange.notify_all();
2376 // Check the version of the last 100 blocks to see if we need to upgrade:
2377 static bool fWarned = false;
2378 if (!IsInitialBlockDownload() && !fWarned)
2381 const CBlockIndex* pindex = chainActive.Tip();
2382 for (int i = 0; i < 100 && pindex != NULL; i++)
2384 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2386 pindex = pindex->pprev;
2389 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2390 if (nUpgraded > 100/2)
2392 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2393 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2394 CAlert::Notify(strMiscWarning, true);
2400 /** Disconnect chainActive's tip. */
2401 bool static DisconnectTip(CValidationState &state) {
2402 CBlockIndex *pindexDelete = chainActive.Tip();
2403 assert(pindexDelete);
2404 mempool.check(pcoinsTip);
2405 // Read block from disk.
2407 if (!ReadBlockFromDisk(block, pindexDelete))
2408 return AbortNode(state, "Failed to read block");
2409 // Apply the block atomically to the chain state.
2410 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2411 int64_t nStart = GetTimeMicros();
2413 CCoinsViewCache view(pcoinsTip);
2414 if (!DisconnectBlock(block, state, pindexDelete, view))
2415 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2416 assert(view.Flush());
2418 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2419 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2420 // Write the chain state to disk, if necessary.
2421 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2423 // Resurrect mempool transactions from the disconnected block.
2424 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2425 // ignore validation errors in resurrected transactions
2426 list<CTransaction> removed;
2427 CValidationState stateDummy;
2428 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2429 mempool.remove(tx, removed, true);
2431 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2432 // The anchor may not change between block disconnects,
2433 // in which case we don't want to evict from the mempool yet!
2434 mempool.removeWithAnchor(anchorBeforeDisconnect);
2436 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2437 mempool.check(pcoinsTip);
2438 // Update chainActive and related variables.
2439 UpdateTip(pindexDelete->pprev);
2440 // Get the current commitment tree
2441 ZCIncrementalMerkleTree newTree;
2442 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2443 // Let wallets know transactions went from 1-confirmed to
2444 // 0-confirmed or conflicted:
2445 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2446 SyncWithWallets(tx, NULL);
2448 // Update cached incremental witnesses
2449 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2453 static int64_t nTimeReadFromDisk = 0;
2454 static int64_t nTimeConnectTotal = 0;
2455 static int64_t nTimeFlush = 0;
2456 static int64_t nTimeChainState = 0;
2457 static int64_t nTimePostConnect = 0;
2460 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2461 * corresponding to pindexNew, to bypass loading it again from disk.
2463 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2464 assert(pindexNew->pprev == chainActive.Tip());
2465 mempool.check(pcoinsTip);
2466 // Read block from disk.
2467 int64_t nTime1 = GetTimeMicros();
2470 if (!ReadBlockFromDisk(block, pindexNew))
2471 return AbortNode(state, "Failed to read block");
2474 // Get the current commitment tree
2475 ZCIncrementalMerkleTree oldTree;
2476 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2477 // Apply the block atomically to the chain state.
2478 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2480 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2482 CCoinsViewCache view(pcoinsTip);
2483 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2484 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2485 GetMainSignals().BlockChecked(*pblock, state);
2487 if (state.IsInvalid())
2488 InvalidBlockFound(pindexNew, state);
2489 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2491 mapBlockSource.erase(inv.hash);
2492 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2493 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2494 assert(view.Flush());
2496 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2497 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2498 // Write the chain state to disk, if necessary.
2499 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2501 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2502 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2503 // Remove conflicting transactions from the mempool.
2504 list<CTransaction> txConflicted;
2505 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2506 mempool.check(pcoinsTip);
2507 // Update chainActive & related variables.
2508 UpdateTip(pindexNew);
2509 // Tell wallet about transactions that went from mempool
2511 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2512 SyncWithWallets(tx, NULL);
2514 // ... and about transactions that got confirmed:
2515 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2516 SyncWithWallets(tx, pblock);
2518 // Update cached incremental witnesses
2519 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2521 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2522 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2523 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2528 * Return the tip of the chain with the most work in it, that isn't
2529 * known to be invalid (it's however far from certain to be valid).
2531 static CBlockIndex* FindMostWorkChain() {
2533 CBlockIndex *pindexNew = NULL;
2535 // Find the best candidate header.
2537 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2538 if (it == setBlockIndexCandidates.rend())
2543 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2544 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2545 CBlockIndex *pindexTest = pindexNew;
2546 bool fInvalidAncestor = false;
2547 while (pindexTest && !chainActive.Contains(pindexTest)) {
2548 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2550 // Pruned nodes may have entries in setBlockIndexCandidates for
2551 // which block files have been deleted. Remove those as candidates
2552 // for the most work chain if we come across them; we can't switch
2553 // to a chain unless we have all the non-active-chain parent blocks.
2554 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2555 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2556 if (fFailedChain || fMissingData) {
2557 // Candidate chain is not usable (either invalid or missing data)
2558 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2559 pindexBestInvalid = pindexNew;
2560 CBlockIndex *pindexFailed = pindexNew;
2561 // Remove the entire chain from the set.
2562 while (pindexTest != pindexFailed) {
2564 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2565 } else if (fMissingData) {
2566 // If we're missing data, then add back to mapBlocksUnlinked,
2567 // so that if the block arrives in the future we can try adding
2568 // to setBlockIndexCandidates again.
2569 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2571 setBlockIndexCandidates.erase(pindexFailed);
2572 pindexFailed = pindexFailed->pprev;
2574 setBlockIndexCandidates.erase(pindexTest);
2575 fInvalidAncestor = true;
2578 pindexTest = pindexTest->pprev;
2580 if (!fInvalidAncestor)
2585 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2586 static void PruneBlockIndexCandidates() {
2587 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2588 // reorganization to a better block fails.
2589 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2590 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2591 setBlockIndexCandidates.erase(it++);
2593 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2594 assert(!setBlockIndexCandidates.empty());
2598 * Try to make some progress towards making pindexMostWork the active block.
2599 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2601 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2602 AssertLockHeld(cs_main);
2603 bool fInvalidFound = false;
2604 const CBlockIndex *pindexOldTip = chainActive.Tip();
2605 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2607 // Disconnect active blocks which are no longer in the best chain.
2608 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2609 if (!DisconnectTip(state))
2613 // Build list of new blocks to connect.
2614 std::vector<CBlockIndex*> vpindexToConnect;
2615 bool fContinue = true;
2616 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2617 while (fContinue && nHeight != pindexMostWork->nHeight) {
2618 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2619 // a few blocks along the way.
2620 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2621 vpindexToConnect.clear();
2622 vpindexToConnect.reserve(nTargetHeight - nHeight);
2623 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2624 while (pindexIter && pindexIter->nHeight != nHeight) {
2625 vpindexToConnect.push_back(pindexIter);
2626 pindexIter = pindexIter->pprev;
2628 nHeight = nTargetHeight;
2630 // Connect new blocks.
2631 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2632 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2633 if (state.IsInvalid()) {
2634 // The block violates a consensus rule.
2635 if (!state.CorruptionPossible())
2636 InvalidChainFound(vpindexToConnect.back());
2637 state = CValidationState();
2638 fInvalidFound = true;
2642 // A system error occurred (disk space, database error, ...).
2646 PruneBlockIndexCandidates();
2647 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2648 // We're in a better position than we were. Return temporarily to release the lock.
2656 // Callbacks/notifications for a new best chain.
2658 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2660 CheckForkWarningConditions();
2666 * Make the best chain active, in multiple steps. The result is either failure
2667 * or an activated best chain. pblock is either NULL or a pointer to a block
2668 * that is already loaded (to avoid loading it again from disk).
2670 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2671 CBlockIndex *pindexNewTip = NULL;
2672 CBlockIndex *pindexMostWork = NULL;
2673 const CChainParams& chainParams = Params();
2675 boost::this_thread::interruption_point();
2677 bool fInitialDownload;
2680 pindexMostWork = FindMostWorkChain();
2682 // Whether we have anything to do at all.
2683 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2686 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2689 pindexNewTip = chainActive.Tip();
2690 fInitialDownload = IsInitialBlockDownload();
2692 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2694 // Notifications/callbacks that can run without cs_main
2695 if (!fInitialDownload) {
2696 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2697 // Relay inventory, but don't relay old inventory during initial block download.
2698 int nBlockEstimate = 0;
2699 if (fCheckpointsEnabled)
2700 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2701 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2702 // in a stalled download if the block file is pruned before the request.
2703 if (nLocalServices & NODE_NETWORK) {
2705 BOOST_FOREACH(CNode* pnode, vNodes)
2706 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2707 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2709 // Notify external listeners about the new tip.
2710 uiInterface.NotifyBlockTip(hashNewTip);
2712 } while(pindexMostWork != chainActive.Tip());
2715 // Write changes periodically to disk, after relay.
2716 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2723 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2724 AssertLockHeld(cs_main);
2726 // Mark the block itself as invalid.
2727 pindex->nStatus |= BLOCK_FAILED_VALID;
2728 setDirtyBlockIndex.insert(pindex);
2729 setBlockIndexCandidates.erase(pindex);
2731 while (chainActive.Contains(pindex)) {
2732 CBlockIndex *pindexWalk = chainActive.Tip();
2733 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2734 setDirtyBlockIndex.insert(pindexWalk);
2735 setBlockIndexCandidates.erase(pindexWalk);
2736 // ActivateBestChain considers blocks already in chainActive
2737 // unconditionally valid already, so force disconnect away from it.
2738 if (!DisconnectTip(state)) {
2743 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2745 BlockMap::iterator it = mapBlockIndex.begin();
2746 while (it != mapBlockIndex.end()) {
2747 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2748 setBlockIndexCandidates.insert(it->second);
2753 InvalidChainFound(pindex);
2757 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2758 AssertLockHeld(cs_main);
2760 int nHeight = pindex->nHeight;
2762 // Remove the invalidity flag from this block and all its descendants.
2763 BlockMap::iterator it = mapBlockIndex.begin();
2764 while (it != mapBlockIndex.end()) {
2765 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2766 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2767 setDirtyBlockIndex.insert(it->second);
2768 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2769 setBlockIndexCandidates.insert(it->second);
2771 if (it->second == pindexBestInvalid) {
2772 // Reset invalid block marker if it was pointing to one of those.
2773 pindexBestInvalid = NULL;
2779 // Remove the invalidity flag from all ancestors too.
2780 while (pindex != NULL) {
2781 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2782 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2783 setDirtyBlockIndex.insert(pindex);
2785 pindex = pindex->pprev;
2790 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2792 // Check for duplicate
2793 uint256 hash = block.GetHash();
2794 BlockMap::iterator it = mapBlockIndex.find(hash);
2795 if (it != mapBlockIndex.end())
2798 // Construct new block index object
2799 CBlockIndex* pindexNew = new CBlockIndex(block);
2801 // We assign the sequence id to blocks only when the full data is available,
2802 // to avoid miners withholding blocks but broadcasting headers, to get a
2803 // competitive advantage.
2804 pindexNew->nSequenceId = 0;
2805 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2806 pindexNew->phashBlock = &((*mi).first);
2807 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2808 if (miPrev != mapBlockIndex.end())
2810 pindexNew->pprev = (*miPrev).second;
2811 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2812 pindexNew->BuildSkip();
2814 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2815 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2816 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2817 pindexBestHeader = pindexNew;
2819 setDirtyBlockIndex.insert(pindexNew);
2824 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2825 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2827 pindexNew->nTx = block.vtx.size();
2828 pindexNew->nChainTx = 0;
2829 pindexNew->nFile = pos.nFile;
2830 pindexNew->nDataPos = pos.nPos;
2831 pindexNew->nUndoPos = 0;
2832 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2833 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2834 setDirtyBlockIndex.insert(pindexNew);
2836 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2837 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2838 deque<CBlockIndex*> queue;
2839 queue.push_back(pindexNew);
2841 // Recursively process any descendant blocks that now may be eligible to be connected.
2842 while (!queue.empty()) {
2843 CBlockIndex *pindex = queue.front();
2845 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2847 LOCK(cs_nBlockSequenceId);
2848 pindex->nSequenceId = nBlockSequenceId++;
2850 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2851 setBlockIndexCandidates.insert(pindex);
2853 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2854 while (range.first != range.second) {
2855 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2856 queue.push_back(it->second);
2858 mapBlocksUnlinked.erase(it);
2862 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2863 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2870 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2872 LOCK(cs_LastBlockFile);
2874 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2875 if (vinfoBlockFile.size() <= nFile) {
2876 vinfoBlockFile.resize(nFile + 1);
2880 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2882 if (vinfoBlockFile.size() <= nFile) {
2883 vinfoBlockFile.resize(nFile + 1);
2887 pos.nPos = vinfoBlockFile[nFile].nSize;
2890 if (nFile != nLastBlockFile) {
2892 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2894 FlushBlockFile(!fKnown);
2895 nLastBlockFile = nFile;
2898 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2900 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2902 vinfoBlockFile[nFile].nSize += nAddSize;
2905 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2906 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2907 if (nNewChunks > nOldChunks) {
2909 fCheckForPruning = true;
2910 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2911 FILE *file = OpenBlockFile(pos);
2913 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2914 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2919 return state.Error("out of disk space");
2923 setDirtyFileInfo.insert(nFile);
2927 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2931 LOCK(cs_LastBlockFile);
2933 unsigned int nNewSize;
2934 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2935 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2936 setDirtyFileInfo.insert(nFile);
2938 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2939 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2940 if (nNewChunks > nOldChunks) {
2942 fCheckForPruning = true;
2943 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2944 FILE *file = OpenUndoFile(pos);
2946 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2947 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2952 return state.Error("out of disk space");
2958 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2960 // Check block version
2961 if (block.nVersion < MIN_BLOCK_VERSION)
2962 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
2963 REJECT_INVALID, "version-too-low");
2965 // Check Equihash solution is valid
2966 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2967 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2968 REJECT_INVALID, "invalid-solution");
2970 // Check proof of work matches claimed amount
2971 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2972 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2973 REJECT_INVALID, "high-hash");
2976 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2977 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2978 REJECT_INVALID, "time-too-new");
2983 bool CheckBlock(const CBlock& block, CValidationState& state,
2984 libzcash::ProofVerifier& verifier,
2985 bool fCheckPOW, bool fCheckMerkleRoot)
2987 // These are checks that are independent of context.
2989 // Check that the header is valid (particularly PoW). This is mostly
2990 // redundant with the call in AcceptBlockHeader.
2991 if (!CheckBlockHeader(block, state, fCheckPOW))
2994 // Check the merkle root.
2995 if (fCheckMerkleRoot) {
2997 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2998 if (block.hashMerkleRoot != hashMerkleRoot2)
2999 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3000 REJECT_INVALID, "bad-txnmrklroot", true);
3002 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3003 // of transactions in a block without affecting the merkle root of a block,
3004 // while still invalidating it.
3006 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3007 REJECT_INVALID, "bad-txns-duplicate", true);
3010 // All potential-corruption validation must be done before we do any
3011 // transaction validation, as otherwise we may mark the header as invalid
3012 // because we receive the wrong transactions for it.
3015 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3016 return state.DoS(100, error("CheckBlock(): size limits failed"),
3017 REJECT_INVALID, "bad-blk-length");
3019 // First transaction must be coinbase, the rest must not be
3020 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3021 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3022 REJECT_INVALID, "bad-cb-missing");
3023 for (unsigned int i = 1; i < block.vtx.size(); i++)
3024 if (block.vtx[i].IsCoinBase())
3025 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3026 REJECT_INVALID, "bad-cb-multiple");
3028 // Check transactions
3029 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3030 if (!CheckTransaction(tx, state, verifier))
3031 return error("CheckBlock(): CheckTransaction failed");
3033 unsigned int nSigOps = 0;
3034 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3036 nSigOps += GetLegacySigOpCount(tx);
3038 if (nSigOps > MAX_BLOCK_SIGOPS)
3039 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3040 REJECT_INVALID, "bad-blk-sigops", true);
3045 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3047 const CChainParams& chainParams = Params();
3048 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3049 uint256 hash = block.GetHash();
3050 if (hash == consensusParams.hashGenesisBlock)
3055 int nHeight = pindexPrev->nHeight+1;
3057 // Check proof of work
3058 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3059 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3060 REJECT_INVALID, "bad-diffbits");
3062 // Check timestamp against prev
3063 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3064 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3065 REJECT_INVALID, "time-too-old");
3067 if(fCheckpointsEnabled)
3069 // Check that the block chain matches the known block chain up to a checkpoint
3070 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3071 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
3072 REJECT_CHECKPOINT, "checkpoint mismatch");
3074 // Don't accept any forks from the main chain prior to last checkpoint
3075 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3076 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3077 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3080 // Reject block.nVersion < 4 blocks
3081 if (block.nVersion < 4)
3082 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3083 REJECT_OBSOLETE, "bad-version");
3088 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3090 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3091 const Consensus::Params& consensusParams = Params().GetConsensus();
3093 // Check that all transactions are finalized
3094 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3095 int nLockTimeFlags = 0;
3096 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3097 ? pindexPrev->GetMedianTimePast()
3098 : block.GetBlockTime();
3099 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3100 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3104 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3105 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3106 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3107 // This rule is not applied to the genesis block, which didn't include the height
3111 CScript expect = CScript() << nHeight;
3112 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3113 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3114 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3118 // Coinbase transaction must include an output sending 20% of
3119 // the block reward to a founders reward script, until the last founders
3120 // reward block is reached, with exception of the genesis block.
3121 // The last founders reward block is defined as the block just before the
3122 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3123 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3126 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3127 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3128 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3136 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3143 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3145 const CChainParams& chainparams = Params();
3146 AssertLockHeld(cs_main);
3147 // Check for duplicate
3148 uint256 hash = block.GetHash();
3149 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3150 CBlockIndex *pindex = NULL;
3151 if (miSelf != mapBlockIndex.end()) {
3152 // Block header is already known.
3153 pindex = miSelf->second;
3156 if (pindex->nStatus & BLOCK_FAILED_MASK)
3157 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3161 if (!CheckBlockHeader(block, state))
3164 // Get prev block index
3165 CBlockIndex* pindexPrev = NULL;
3166 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3167 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3168 if (mi == mapBlockIndex.end())
3169 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3170 pindexPrev = (*mi).second;
3171 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3172 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3175 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3179 pindex = AddToBlockIndex(block);
3187 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3189 const CChainParams& chainparams = Params();
3190 AssertLockHeld(cs_main);
3192 CBlockIndex *&pindex = *ppindex;
3194 if (!AcceptBlockHeader(block, state, &pindex))
3197 // Try to process all requested blocks that we don't have, but only
3198 // process an unrequested block if it's new and has enough work to
3199 // advance our tip, and isn't too many blocks ahead.
3200 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3201 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3202 // Blocks that are too out-of-order needlessly limit the effectiveness of
3203 // pruning, because pruning will not delete block files that contain any
3204 // blocks which are too close in height to the tip. Apply this test
3205 // regardless of whether pruning is enabled; it should generally be safe to
3206 // not process unrequested blocks.
3207 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3209 // TODO: deal better with return value and error conditions for duplicate
3210 // and unrequested blocks.
3211 if (fAlreadyHave) return true;
3212 if (!fRequested) { // If we didn't ask for it:
3213 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3214 if (!fHasMoreWork) return true; // Don't process less-work chains
3215 if (fTooFarAhead) return true; // Block height is too high
3218 // See method docstring for why this is always disabled
3219 auto verifier = libzcash::ProofVerifier::Disabled();
3220 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3221 if (state.IsInvalid() && !state.CorruptionPossible()) {
3222 pindex->nStatus |= BLOCK_FAILED_VALID;
3223 setDirtyBlockIndex.insert(pindex);
3228 int nHeight = pindex->nHeight;
3230 // Write block to history file
3232 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3233 CDiskBlockPos blockPos;
3236 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3237 return error("AcceptBlock(): FindBlockPos failed");
3239 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3240 AbortNode(state, "Failed to write block");
3241 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3242 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3243 } catch (const std::runtime_error& e) {
3244 return AbortNode(state, std::string("System error: ") + e.what());
3247 if (fCheckForPruning)
3248 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3253 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3255 unsigned int nFound = 0;
3256 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3258 if (pstart->nVersion >= minVersion)
3260 pstart = pstart->pprev;
3262 return (nFound >= nRequired);
3266 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3268 // Preliminary checks
3269 auto verifier = libzcash::ProofVerifier::Disabled();
3270 bool checked = CheckBlock(*pblock, state, verifier);
3274 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3275 fRequested |= fForceProcessing;
3277 return error("%s: CheckBlock FAILED", __func__);
3281 CBlockIndex *pindex = NULL;
3282 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3283 if (pindex && pfrom) {
3284 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3288 return error("%s: AcceptBlock FAILED", __func__);
3291 if (!ActivateBestChain(state, pblock))
3292 return error("%s: ActivateBestChain failed", __func__);
3297 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3299 AssertLockHeld(cs_main);
3300 assert(pindexPrev == chainActive.Tip());
3302 CCoinsViewCache viewNew(pcoinsTip);
3303 CBlockIndex indexDummy(block);
3304 indexDummy.pprev = pindexPrev;
3305 indexDummy.nHeight = pindexPrev->nHeight + 1;
3306 // JoinSplit proofs are verified in ConnectBlock
3307 auto verifier = libzcash::ProofVerifier::Disabled();
3309 // NOTE: CheckBlockHeader is called by CheckBlock
3310 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3312 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3314 if (!ContextualCheckBlock(block, state, pindexPrev))
3316 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3318 assert(state.IsValid());
3324 * BLOCK PRUNING CODE
3327 /* Calculate the amount of disk space the block & undo files currently use */
3328 uint64_t CalculateCurrentUsage()
3330 uint64_t retval = 0;
3331 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3332 retval += file.nSize + file.nUndoSize;
3337 /* Prune a block file (modify associated database entries)*/
3338 void PruneOneBlockFile(const int fileNumber)
3340 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3341 CBlockIndex* pindex = it->second;
3342 if (pindex->nFile == fileNumber) {
3343 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3344 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3346 pindex->nDataPos = 0;
3347 pindex->nUndoPos = 0;
3348 setDirtyBlockIndex.insert(pindex);
3350 // Prune from mapBlocksUnlinked -- any block we prune would have
3351 // to be downloaded again in order to consider its chain, at which
3352 // point it would be considered as a candidate for
3353 // mapBlocksUnlinked or setBlockIndexCandidates.
3354 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3355 while (range.first != range.second) {
3356 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3358 if (it->second == pindex) {
3359 mapBlocksUnlinked.erase(it);
3365 vinfoBlockFile[fileNumber].SetNull();
3366 setDirtyFileInfo.insert(fileNumber);
3370 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3372 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3373 CDiskBlockPos pos(*it, 0);
3374 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3375 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3376 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3380 /* Calculate the block/rev files that should be deleted to remain under target*/
3381 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3383 LOCK2(cs_main, cs_LastBlockFile);
3384 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3387 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3391 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3392 uint64_t nCurrentUsage = CalculateCurrentUsage();
3393 // We don't check to prune until after we've allocated new space for files
3394 // So we should leave a buffer under our target to account for another allocation
3395 // before the next pruning.
3396 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3397 uint64_t nBytesToPrune;
3400 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3401 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3402 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3404 if (vinfoBlockFile[fileNumber].nSize == 0)
3407 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3410 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3411 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3414 PruneOneBlockFile(fileNumber);
3415 // Queue up the files for removal
3416 setFilesToPrune.insert(fileNumber);
3417 nCurrentUsage -= nBytesToPrune;
3422 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3423 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3424 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3425 nLastBlockWeCanPrune, count);
3428 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3430 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3432 // Check for nMinDiskSpace bytes (currently 50MB)
3433 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3434 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3439 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3443 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3444 boost::filesystem::create_directories(path.parent_path());
3445 FILE* file = fopen(path.string().c_str(), "rb+");
3446 if (!file && !fReadOnly)
3447 file = fopen(path.string().c_str(), "wb+");
3449 LogPrintf("Unable to open file %s\n", path.string());
3453 if (fseek(file, pos.nPos, SEEK_SET)) {
3454 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3462 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3463 return OpenDiskFile(pos, "blk", fReadOnly);
3466 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3467 return OpenDiskFile(pos, "rev", fReadOnly);
3470 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3472 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3475 CBlockIndex * InsertBlockIndex(uint256 hash)
3481 BlockMap::iterator mi = mapBlockIndex.find(hash);
3482 if (mi != mapBlockIndex.end())
3483 return (*mi).second;
3486 CBlockIndex* pindexNew = new CBlockIndex();
3488 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3489 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3490 pindexNew->phashBlock = &((*mi).first);
3495 bool static LoadBlockIndexDB()
3497 const CChainParams& chainparams = Params();
3498 if (!pblocktree->LoadBlockIndexGuts())
3501 boost::this_thread::interruption_point();
3503 // Calculate nChainWork
3504 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3505 vSortedByHeight.reserve(mapBlockIndex.size());
3506 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3508 CBlockIndex* pindex = item.second;
3509 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3511 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3512 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3514 CBlockIndex* pindex = item.second;
3515 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3516 // We can link the chain of blocks for which we've received transactions at some point.
3517 // Pruned nodes may have deleted the block.
3518 if (pindex->nTx > 0) {
3519 if (pindex->pprev) {
3520 if (pindex->pprev->nChainTx) {
3521 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3523 pindex->nChainTx = 0;
3524 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3527 pindex->nChainTx = pindex->nTx;
3530 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3531 setBlockIndexCandidates.insert(pindex);
3532 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3533 pindexBestInvalid = pindex;
3535 pindex->BuildSkip();
3536 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3537 pindexBestHeader = pindex;
3540 // Load block file info
3541 pblocktree->ReadLastBlockFile(nLastBlockFile);
3542 vinfoBlockFile.resize(nLastBlockFile + 1);
3543 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3544 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3545 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3547 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3548 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3549 CBlockFileInfo info;
3550 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3551 vinfoBlockFile.push_back(info);
3557 // Check presence of blk files
3558 LogPrintf("Checking all blk files are present...\n");
3559 set<int> setBlkDataFiles;
3560 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3562 CBlockIndex* pindex = item.second;
3563 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3564 setBlkDataFiles.insert(pindex->nFile);
3567 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3569 CDiskBlockPos pos(*it, 0);
3570 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3575 // Check whether we have ever pruned block & undo files
3576 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3578 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3580 // Check whether we need to continue reindexing
3581 bool fReindexing = false;
3582 pblocktree->ReadReindexing(fReindexing);
3583 fReindex |= fReindexing;
3585 // Check whether we have a transaction index
3586 pblocktree->ReadFlag("txindex", fTxIndex);
3587 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3589 // Load pointer to end of best chain
3590 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3591 if (it == mapBlockIndex.end())
3593 chainActive.SetTip(it->second);
3595 PruneBlockIndexCandidates();
3597 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3598 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3599 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3600 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3605 CVerifyDB::CVerifyDB()
3607 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3610 CVerifyDB::~CVerifyDB()
3612 uiInterface.ShowProgress("", 100);
3615 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3618 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3621 // Verify blocks in the best chain
3622 if (nCheckDepth <= 0)
3623 nCheckDepth = 1000000000; // suffices until the year 19000
3624 if (nCheckDepth > chainActive.Height())
3625 nCheckDepth = chainActive.Height();
3626 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3627 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3628 CCoinsViewCache coins(coinsview);
3629 CBlockIndex* pindexState = chainActive.Tip();
3630 CBlockIndex* pindexFailure = NULL;
3631 int nGoodTransactions = 0;
3632 CValidationState state;
3633 // No need to verify JoinSplits twice
3634 auto verifier = libzcash::ProofVerifier::Disabled();
3635 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3637 boost::this_thread::interruption_point();
3638 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3639 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3642 // check level 0: read from disk
3643 if (!ReadBlockFromDisk(block, pindex))
3644 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3645 // check level 1: verify block validity
3646 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
3647 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3648 // check level 2: verify undo validity
3649 if (nCheckLevel >= 2 && pindex) {
3651 CDiskBlockPos pos = pindex->GetUndoPos();
3652 if (!pos.IsNull()) {
3653 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3654 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3657 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3658 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3660 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3661 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3662 pindexState = pindex->pprev;
3664 nGoodTransactions = 0;
3665 pindexFailure = pindex;
3667 nGoodTransactions += block.vtx.size();
3669 if (ShutdownRequested())
3673 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3675 // check level 4: try reconnecting blocks
3676 if (nCheckLevel >= 4) {
3677 CBlockIndex *pindex = pindexState;
3678 while (pindex != chainActive.Tip()) {
3679 boost::this_thread::interruption_point();
3680 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3681 pindex = chainActive.Next(pindex);
3683 if (!ReadBlockFromDisk(block, pindex))
3684 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3685 if (!ConnectBlock(block, state, pindex, coins))
3686 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3690 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3695 void UnloadBlockIndex()
3698 setBlockIndexCandidates.clear();
3699 chainActive.SetTip(NULL);
3700 pindexBestInvalid = NULL;
3701 pindexBestHeader = NULL;
3703 mapOrphanTransactions.clear();
3704 mapOrphanTransactionsByPrev.clear();
3706 mapBlocksUnlinked.clear();
3707 vinfoBlockFile.clear();
3709 nBlockSequenceId = 1;
3710 mapBlockSource.clear();
3711 mapBlocksInFlight.clear();
3712 nQueuedValidatedHeaders = 0;
3713 nPreferredDownload = 0;
3714 setDirtyBlockIndex.clear();
3715 setDirtyFileInfo.clear();
3716 mapNodeState.clear();
3717 recentRejects.reset(NULL);
3719 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3720 delete entry.second;
3722 mapBlockIndex.clear();
3723 fHavePruned = false;
3726 bool LoadBlockIndex()
3728 // Load block index from databases
3729 if (!fReindex && !LoadBlockIndexDB())
3735 bool InitBlockIndex() {
3736 const CChainParams& chainparams = Params();
3739 // Initialize global variables that cannot be constructed at startup.
3740 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3742 // Check whether we're already initialized
3743 if (chainActive.Genesis() != NULL)
3746 // Use the provided setting for -txindex in the new database
3747 fTxIndex = GetBoolArg("-txindex", false);
3748 pblocktree->WriteFlag("txindex", fTxIndex);
3749 LogPrintf("Initializing databases...\n");
3751 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3754 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3755 // Start new block file
3756 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3757 CDiskBlockPos blockPos;
3758 CValidationState state;
3759 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3760 return error("LoadBlockIndex(): FindBlockPos failed");
3761 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3762 return error("LoadBlockIndex(): writing genesis block to disk failed");
3763 CBlockIndex *pindex = AddToBlockIndex(block);
3764 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3765 return error("LoadBlockIndex(): genesis block not accepted");
3766 if (!ActivateBestChain(state, &block))
3767 return error("LoadBlockIndex(): genesis block cannot be activated");
3768 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3769 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3770 } catch (const std::runtime_error& e) {
3771 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3780 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3782 const CChainParams& chainparams = Params();
3783 // Map of disk positions for blocks with unknown parent (only used for reindex)
3784 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3785 int64_t nStart = GetTimeMillis();
3789 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3790 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3791 uint64_t nRewind = blkdat.GetPos();
3792 while (!blkdat.eof()) {
3793 boost::this_thread::interruption_point();
3795 blkdat.SetPos(nRewind);
3796 nRewind++; // start one byte further next time, in case of failure
3797 blkdat.SetLimit(); // remove former limit
3798 unsigned int nSize = 0;
3801 unsigned char buf[MESSAGE_START_SIZE];
3802 blkdat.FindByte(Params().MessageStart()[0]);
3803 nRewind = blkdat.GetPos()+1;
3804 blkdat >> FLATDATA(buf);
3805 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3809 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3811 } catch (const std::exception&) {
3812 // no valid block header found; don't complain
3817 uint64_t nBlockPos = blkdat.GetPos();
3819 dbp->nPos = nBlockPos;
3820 blkdat.SetLimit(nBlockPos + nSize);
3821 blkdat.SetPos(nBlockPos);
3824 nRewind = blkdat.GetPos();
3826 // detect out of order blocks, and store them for later
3827 uint256 hash = block.GetHash();
3828 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3829 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3830 block.hashPrevBlock.ToString());
3832 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3836 // process in case the block isn't known yet
3837 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3838 CValidationState state;
3839 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3841 if (state.IsError())
3843 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3844 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3847 // Recursively process earlier encountered successors of this block
3848 deque<uint256> queue;
3849 queue.push_back(hash);
3850 while (!queue.empty()) {
3851 uint256 head = queue.front();
3853 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3854 while (range.first != range.second) {
3855 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3856 if (ReadBlockFromDisk(block, it->second))
3858 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3860 CValidationState dummy;
3861 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3864 queue.push_back(block.GetHash());
3868 mapBlocksUnknownParent.erase(it);
3871 } catch (const std::exception& e) {
3872 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3875 } catch (const std::runtime_error& e) {
3876 AbortNode(std::string("System error: ") + e.what());
3879 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3883 void static CheckBlockIndex()
3885 const Consensus::Params& consensusParams = Params().GetConsensus();
3886 if (!fCheckBlockIndex) {
3892 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3893 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3894 // iterating the block tree require that chainActive has been initialized.)
3895 if (chainActive.Height() < 0) {
3896 assert(mapBlockIndex.size() <= 1);
3900 // Build forward-pointing map of the entire block tree.
3901 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3902 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3903 forward.insert(std::make_pair(it->second->pprev, it->second));
3906 assert(forward.size() == mapBlockIndex.size());
3908 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3909 CBlockIndex *pindex = rangeGenesis.first->second;
3910 rangeGenesis.first++;
3911 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3913 // Iterate over the entire block tree, using depth-first search.
3914 // Along the way, remember whether there are blocks on the path from genesis
3915 // block being explored which are the first to have certain properties.
3918 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3919 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3920 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3921 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3922 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3923 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3924 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3925 while (pindex != NULL) {
3927 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3928 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3929 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3930 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3931 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3932 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3933 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3935 // Begin: actual consistency checks.
3936 if (pindex->pprev == NULL) {
3937 // Genesis block checks.
3938 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3939 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3941 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3942 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3943 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3945 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3946 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3947 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3949 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3950 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3952 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3953 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3954 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3955 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3956 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3957 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3958 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.
3959 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3960 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3961 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3962 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3963 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3964 if (pindexFirstInvalid == NULL) {
3965 // Checks for not-invalid blocks.
3966 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3968 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3969 if (pindexFirstInvalid == NULL) {
3970 // If this block sorts at least as good as the current tip and
3971 // is valid and we have all data for its parents, it must be in
3972 // setBlockIndexCandidates. chainActive.Tip() must also be there
3973 // even if some data has been pruned.
3974 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3975 assert(setBlockIndexCandidates.count(pindex));
3977 // If some parent is missing, then it could be that this block was in
3978 // setBlockIndexCandidates but had to be removed because of the missing data.
3979 // In this case it must be in mapBlocksUnlinked -- see test below.
3981 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3982 assert(setBlockIndexCandidates.count(pindex) == 0);
3984 // Check whether this block is in mapBlocksUnlinked.
3985 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3986 bool foundInUnlinked = false;
3987 while (rangeUnlinked.first != rangeUnlinked.second) {
3988 assert(rangeUnlinked.first->first == pindex->pprev);
3989 if (rangeUnlinked.first->second == pindex) {
3990 foundInUnlinked = true;
3993 rangeUnlinked.first++;
3995 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3996 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3997 assert(foundInUnlinked);
3999 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4000 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4001 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4002 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4003 assert(fHavePruned); // We must have pruned.
4004 // This block may have entered mapBlocksUnlinked if:
4005 // - it has a descendant that at some point had more work than the
4007 // - we tried switching to that descendant but were missing
4008 // data for some intermediate block between chainActive and the
4010 // So if this block is itself better than chainActive.Tip() and it wasn't in
4011 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4012 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4013 if (pindexFirstInvalid == NULL) {
4014 assert(foundInUnlinked);
4018 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4019 // End: actual consistency checks.
4021 // Try descending into the first subnode.
4022 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4023 if (range.first != range.second) {
4024 // A subnode was found.
4025 pindex = range.first->second;
4029 // This is a leaf node.
4030 // Move upwards until we reach a node of which we have not yet visited the last child.
4032 // We are going to either move to a parent or a sibling of pindex.
4033 // If pindex was the first with a certain property, unset the corresponding variable.
4034 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4035 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4036 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4037 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4038 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4039 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4040 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4042 CBlockIndex* pindexPar = pindex->pprev;
4043 // Find which child we just visited.
4044 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4045 while (rangePar.first->second != pindex) {
4046 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4049 // Proceed to the next one.
4051 if (rangePar.first != rangePar.second) {
4052 // Move to the sibling.
4053 pindex = rangePar.first->second;
4064 // Check that we actually traversed the entire map.
4065 assert(nNodes == forward.size());
4068 //////////////////////////////////////////////////////////////////////////////
4073 string GetWarnings(string strFor)
4076 string strStatusBar;
4079 if (!CLIENT_VERSION_IS_RELEASE)
4080 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4082 if (GetBoolArg("-testsafemode", false))
4083 strStatusBar = strRPC = "testsafemode enabled";
4085 // Misc warnings like out of disk space and clock is wrong
4086 if (strMiscWarning != "")
4089 strStatusBar = strMiscWarning;
4092 if (fLargeWorkForkFound)
4095 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4097 else if (fLargeWorkInvalidChainFound)
4100 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.");
4106 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4108 const CAlert& alert = item.second;
4109 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4111 nPriority = alert.nPriority;
4112 strStatusBar = alert.strStatusBar;
4113 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4114 strRPC = alert.strRPCError;
4120 if (strFor == "statusbar")
4121 return strStatusBar;
4122 else if (strFor == "rpc")
4124 assert(!"GetWarnings(): invalid parameter");
4135 //////////////////////////////////////////////////////////////////////////////
4141 bool static AlreadyHave(const CInv& inv)
4147 assert(recentRejects);
4148 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4150 // If the chain tip has changed previously rejected transactions
4151 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4152 // or a double-spend. Reset the rejects filter and give those
4153 // txs a second chance.
4154 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4155 recentRejects->reset();
4158 return recentRejects->contains(inv.hash) ||
4159 mempool.exists(inv.hash) ||
4160 mapOrphanTransactions.count(inv.hash) ||
4161 pcoinsTip->HaveCoins(inv.hash);
4164 return mapBlockIndex.count(inv.hash);
4166 // Don't know what it is, just say we already got one
4170 void static ProcessGetData(CNode* pfrom)
4172 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4174 vector<CInv> vNotFound;
4178 while (it != pfrom->vRecvGetData.end()) {
4179 // Don't bother if send buffer is too full to respond anyway
4180 if (pfrom->nSendSize >= SendBufferSize())
4183 const CInv &inv = *it;
4185 boost::this_thread::interruption_point();
4188 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4191 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4192 if (mi != mapBlockIndex.end())
4194 if (chainActive.Contains(mi->second)) {
4197 static const int nOneMonth = 30 * 24 * 60 * 60;
4198 // To prevent fingerprinting attacks, only send blocks outside of the active
4199 // chain if they are valid, and no more than a month older (both in time, and in
4200 // best equivalent proof of work) than the best header chain we know about.
4201 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4202 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4203 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4205 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4209 // Pruned nodes may have deleted the block, so check whether
4210 // it's available before trying to send.
4211 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4213 // Send block from disk
4215 if (!ReadBlockFromDisk(block, (*mi).second))
4216 assert(!"cannot load block from disk");
4217 if (inv.type == MSG_BLOCK)
4218 pfrom->PushMessage("block", block);
4219 else // MSG_FILTERED_BLOCK)
4221 LOCK(pfrom->cs_filter);
4224 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4225 pfrom->PushMessage("merkleblock", merkleBlock);
4226 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4227 // This avoids hurting performance by pointlessly requiring a round-trip
4228 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4229 // they must either disconnect and retry or request the full block.
4230 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4231 // however we MUST always provide at least what the remote peer needs
4232 typedef std::pair<unsigned int, uint256> PairType;
4233 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4234 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4235 pfrom->PushMessage("tx", block.vtx[pair.first]);
4241 // Trigger the peer node to send a getblocks request for the next batch of inventory
4242 if (inv.hash == pfrom->hashContinue)
4244 // Bypass PushInventory, this must send even if redundant,
4245 // and we want it right after the last block so they don't
4246 // wait for other stuff first.
4248 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4249 pfrom->PushMessage("inv", vInv);
4250 pfrom->hashContinue.SetNull();
4254 else if (inv.IsKnownType())
4256 // Send stream from relay memory
4257 bool pushed = false;
4260 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4261 if (mi != mapRelay.end()) {
4262 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4266 if (!pushed && inv.type == MSG_TX) {
4268 if (mempool.lookup(inv.hash, tx)) {
4269 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4272 pfrom->PushMessage("tx", ss);
4277 vNotFound.push_back(inv);
4281 // Track requests for our stuff.
4282 GetMainSignals().Inventory(inv.hash);
4284 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4289 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4291 if (!vNotFound.empty()) {
4292 // Let the peer know that we didn't find what it asked for, so it doesn't
4293 // have to wait around forever. Currently only SPV clients actually care
4294 // about this message: it's needed when they are recursively walking the
4295 // dependencies of relevant unconfirmed transactions. SPV clients want to
4296 // do that because they want to know about (and store and rebroadcast and
4297 // risk analyze) the dependencies of transactions relevant to them, without
4298 // having to download the entire memory pool.
4299 pfrom->PushMessage("notfound", vNotFound);
4303 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4305 const CChainParams& chainparams = Params();
4306 RandAddSeedPerfmon();
4307 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4308 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4310 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4317 if (strCommand == "version")
4319 // Each connection can only send one version message
4320 if (pfrom->nVersion != 0)
4322 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4323 Misbehaving(pfrom->GetId(), 1);
4330 uint64_t nNonce = 1;
4331 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4332 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4334 // disconnect from peers older than this proto version
4335 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4336 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4337 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4338 pfrom->fDisconnect = true;
4342 if (pfrom->nVersion == 10300)
4343 pfrom->nVersion = 300;
4345 vRecv >> addrFrom >> nNonce;
4346 if (!vRecv.empty()) {
4347 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4348 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4351 vRecv >> pfrom->nStartingHeight;
4353 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4355 pfrom->fRelayTxes = true;
4357 // Disconnect if we connected to ourself
4358 if (nNonce == nLocalHostNonce && nNonce > 1)
4360 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4361 pfrom->fDisconnect = true;
4365 pfrom->addrLocal = addrMe;
4366 if (pfrom->fInbound && addrMe.IsRoutable())
4371 // Be shy and don't send version until we hear
4372 if (pfrom->fInbound)
4373 pfrom->PushVersion();
4375 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4377 // Potentially mark this peer as a preferred download peer.
4378 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4381 pfrom->PushMessage("verack");
4382 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4384 if (!pfrom->fInbound)
4386 // Advertise our address
4387 if (fListen && !IsInitialBlockDownload())
4389 CAddress addr = GetLocalAddress(&pfrom->addr);
4390 if (addr.IsRoutable())
4392 pfrom->PushAddress(addr);
4393 } else if (IsPeerAddrLocalGood(pfrom)) {
4394 addr.SetIP(pfrom->addrLocal);
4395 pfrom->PushAddress(addr);
4399 // Get recent addresses
4400 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4402 pfrom->PushMessage("getaddr");
4403 pfrom->fGetAddr = true;
4405 addrman.Good(pfrom->addr);
4407 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4409 addrman.Add(addrFrom, addrFrom);
4410 addrman.Good(addrFrom);
4417 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4418 item.second.RelayTo(pfrom);
4421 pfrom->fSuccessfullyConnected = true;
4425 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4427 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4428 pfrom->cleanSubVer, pfrom->nVersion,
4429 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4432 int64_t nTimeOffset = nTime - GetTime();
4433 pfrom->nTimeOffset = nTimeOffset;
4434 AddTimeData(pfrom->addr, nTimeOffset);
4438 else if (pfrom->nVersion == 0)
4440 // Must have a version message before anything else
4441 Misbehaving(pfrom->GetId(), 1);
4446 else if (strCommand == "verack")
4448 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4450 // Mark this node as currently connected, so we update its timestamp later.
4451 if (pfrom->fNetworkNode) {
4453 State(pfrom->GetId())->fCurrentlyConnected = true;
4458 else if (strCommand == "addr")
4460 vector<CAddress> vAddr;
4463 // Don't want addr from older versions unless seeding
4464 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4466 if (vAddr.size() > 1000)
4468 Misbehaving(pfrom->GetId(), 20);
4469 return error("message addr size() = %u", vAddr.size());
4472 // Store the new addresses
4473 vector<CAddress> vAddrOk;
4474 int64_t nNow = GetAdjustedTime();
4475 int64_t nSince = nNow - 10 * 60;
4476 BOOST_FOREACH(CAddress& addr, vAddr)
4478 boost::this_thread::interruption_point();
4480 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4481 addr.nTime = nNow - 5 * 24 * 60 * 60;
4482 pfrom->AddAddressKnown(addr);
4483 bool fReachable = IsReachable(addr);
4484 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4486 // Relay to a limited number of other nodes
4489 // Use deterministic randomness to send to the same nodes for 24 hours
4490 // at a time so the addrKnowns of the chosen nodes prevent repeats
4491 static uint256 hashSalt;
4492 if (hashSalt.IsNull())
4493 hashSalt = GetRandHash();
4494 uint64_t hashAddr = addr.GetHash();
4495 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4496 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4497 multimap<uint256, CNode*> mapMix;
4498 BOOST_FOREACH(CNode* pnode, vNodes)
4500 if (pnode->nVersion < CADDR_TIME_VERSION)
4502 unsigned int nPointer;
4503 memcpy(&nPointer, &pnode, sizeof(nPointer));
4504 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4505 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4506 mapMix.insert(make_pair(hashKey, pnode));
4508 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4509 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4510 ((*mi).second)->PushAddress(addr);
4513 // Do not store addresses outside our network
4515 vAddrOk.push_back(addr);
4517 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4518 if (vAddr.size() < 1000)
4519 pfrom->fGetAddr = false;
4520 if (pfrom->fOneShot)
4521 pfrom->fDisconnect = true;
4525 else if (strCommand == "inv")
4529 if (vInv.size() > MAX_INV_SZ)
4531 Misbehaving(pfrom->GetId(), 20);
4532 return error("message inv size() = %u", vInv.size());
4537 std::vector<CInv> vToFetch;
4539 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4541 const CInv &inv = vInv[nInv];
4543 boost::this_thread::interruption_point();
4544 pfrom->AddInventoryKnown(inv);
4546 bool fAlreadyHave = AlreadyHave(inv);
4547 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4549 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4552 if (inv.type == MSG_BLOCK) {
4553 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4554 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4555 // First request the headers preceding the announced block. In the normal fully-synced
4556 // case where a new block is announced that succeeds the current tip (no reorganization),
4557 // there are no such headers.
4558 // Secondly, and only when we are close to being synced, we request the announced block directly,
4559 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4560 // time the block arrives, the header chain leading up to it is already validated. Not
4561 // doing this will result in the received block being rejected as an orphan in case it is
4562 // not a direct successor.
4563 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4564 CNodeState *nodestate = State(pfrom->GetId());
4565 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4566 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4567 vToFetch.push_back(inv);
4568 // Mark block as in flight already, even though the actual "getdata" message only goes out
4569 // later (within the same cs_main lock, though).
4570 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4572 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4576 // Track requests for our stuff
4577 GetMainSignals().Inventory(inv.hash);
4579 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4580 Misbehaving(pfrom->GetId(), 50);
4581 return error("send buffer size() = %u", pfrom->nSendSize);
4585 if (!vToFetch.empty())
4586 pfrom->PushMessage("getdata", vToFetch);
4590 else if (strCommand == "getdata")
4594 if (vInv.size() > MAX_INV_SZ)
4596 Misbehaving(pfrom->GetId(), 20);
4597 return error("message getdata size() = %u", vInv.size());
4600 if (fDebug || (vInv.size() != 1))
4601 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4603 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4604 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4606 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4607 ProcessGetData(pfrom);
4611 else if (strCommand == "getblocks")
4613 CBlockLocator locator;
4615 vRecv >> locator >> hashStop;
4619 // Find the last block the caller has in the main chain
4620 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4622 // Send the rest of the chain
4624 pindex = chainActive.Next(pindex);
4626 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4627 for (; pindex; pindex = chainActive.Next(pindex))
4629 if (pindex->GetBlockHash() == hashStop)
4631 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4634 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4637 // When this block is requested, we'll send an inv that'll
4638 // trigger the peer to getblocks the next batch of inventory.
4639 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4640 pfrom->hashContinue = pindex->GetBlockHash();
4647 else if (strCommand == "getheaders")
4649 CBlockLocator locator;
4651 vRecv >> locator >> hashStop;
4655 if (IsInitialBlockDownload())
4658 CBlockIndex* pindex = NULL;
4659 if (locator.IsNull())
4661 // If locator is null, return the hashStop block
4662 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4663 if (mi == mapBlockIndex.end())
4665 pindex = (*mi).second;
4669 // Find the last block the caller has in the main chain
4670 pindex = FindForkInGlobalIndex(chainActive, locator);
4672 pindex = chainActive.Next(pindex);
4675 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4676 vector<CBlock> vHeaders;
4677 int nLimit = MAX_HEADERS_RESULTS;
4678 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4679 for (; pindex; pindex = chainActive.Next(pindex))
4681 vHeaders.push_back(pindex->GetBlockHeader());
4682 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4685 pfrom->PushMessage("headers", vHeaders);
4689 else if (strCommand == "tx")
4691 vector<uint256> vWorkQueue;
4692 vector<uint256> vEraseQueue;
4696 CInv inv(MSG_TX, tx.GetHash());
4697 pfrom->AddInventoryKnown(inv);
4701 bool fMissingInputs = false;
4702 CValidationState state;
4704 pfrom->setAskFor.erase(inv.hash);
4705 mapAlreadyAskedFor.erase(inv);
4707 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4709 mempool.check(pcoinsTip);
4710 RelayTransaction(tx);
4711 vWorkQueue.push_back(inv.hash);
4713 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4714 pfrom->id, pfrom->cleanSubVer,
4715 tx.GetHash().ToString(),
4716 mempool.mapTx.size());
4718 // Recursively process any orphan transactions that depended on this one
4719 set<NodeId> setMisbehaving;
4720 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4722 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4723 if (itByPrev == mapOrphanTransactionsByPrev.end())
4725 for (set<uint256>::iterator mi = itByPrev->second.begin();
4726 mi != itByPrev->second.end();
4729 const uint256& orphanHash = *mi;
4730 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4731 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4732 bool fMissingInputs2 = false;
4733 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4734 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4735 // anyone relaying LegitTxX banned)
4736 CValidationState stateDummy;
4739 if (setMisbehaving.count(fromPeer))
4741 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4743 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4744 RelayTransaction(orphanTx);
4745 vWorkQueue.push_back(orphanHash);
4746 vEraseQueue.push_back(orphanHash);
4748 else if (!fMissingInputs2)
4751 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4753 // Punish peer that gave us an invalid orphan tx
4754 Misbehaving(fromPeer, nDos);
4755 setMisbehaving.insert(fromPeer);
4756 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4758 // Has inputs but not accepted to mempool
4759 // Probably non-standard or insufficient fee/priority
4760 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4761 vEraseQueue.push_back(orphanHash);
4762 assert(recentRejects);
4763 recentRejects->insert(orphanHash);
4765 mempool.check(pcoinsTip);
4769 BOOST_FOREACH(uint256 hash, vEraseQueue)
4770 EraseOrphanTx(hash);
4772 // TODO: currently, prohibit joinsplits from entering mapOrphans
4773 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4775 AddOrphanTx(tx, pfrom->GetId());
4777 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4778 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4779 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4781 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4783 assert(recentRejects);
4784 recentRejects->insert(tx.GetHash());
4786 if (pfrom->fWhitelisted) {
4787 // Always relay transactions received from whitelisted peers, even
4788 // if they were already in the mempool or rejected from it due
4789 // to policy, allowing the node to function as a gateway for
4790 // nodes hidden behind it.
4792 // Never relay transactions that we would assign a non-zero DoS
4793 // score for, as we expect peers to do the same with us in that
4796 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4797 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4798 RelayTransaction(tx);
4800 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4801 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4806 if (state.IsInvalid(nDoS))
4808 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4809 pfrom->id, pfrom->cleanSubVer,
4810 state.GetRejectReason());
4811 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4812 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4814 Misbehaving(pfrom->GetId(), nDoS);
4819 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4821 std::vector<CBlockHeader> headers;
4823 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4824 unsigned int nCount = ReadCompactSize(vRecv);
4825 if (nCount > MAX_HEADERS_RESULTS) {
4826 Misbehaving(pfrom->GetId(), 20);
4827 return error("headers message size = %u", nCount);
4829 headers.resize(nCount);
4830 for (unsigned int n = 0; n < nCount; n++) {
4831 vRecv >> headers[n];
4832 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4838 // Nothing interesting. Stop asking this peers for more headers.
4842 CBlockIndex *pindexLast = NULL;
4843 BOOST_FOREACH(const CBlockHeader& header, headers) {
4844 CValidationState state;
4845 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4846 Misbehaving(pfrom->GetId(), 20);
4847 return error("non-continuous headers sequence");
4849 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4851 if (state.IsInvalid(nDoS)) {
4853 Misbehaving(pfrom->GetId(), nDoS);
4854 return error("invalid header received");
4860 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4862 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4863 // Headers message had its maximum size; the peer may have more headers.
4864 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4865 // from there instead.
4866 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4867 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4873 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4878 CInv inv(MSG_BLOCK, block.GetHash());
4879 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4881 pfrom->AddInventoryKnown(inv);
4883 CValidationState state;
4884 // Process all blocks from whitelisted peers, even if not requested,
4885 // unless we're still syncing with the network.
4886 // Such an unrequested block may still be processed, subject to the
4887 // conditions in AcceptBlock().
4888 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4889 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4891 if (state.IsInvalid(nDoS)) {
4892 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4893 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4896 Misbehaving(pfrom->GetId(), nDoS);
4903 // This asymmetric behavior for inbound and outbound connections was introduced
4904 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4905 // to users' AddrMan and later request them by sending getaddr messages.
4906 // Making nodes which are behind NAT and can only make outgoing connections ignore
4907 // the getaddr message mitigates the attack.
4908 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4910 // Only send one GetAddr response per connection to reduce resource waste
4911 // and discourage addr stamping of INV announcements.
4912 if (pfrom->fSentAddr) {
4913 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4916 pfrom->fSentAddr = true;
4918 pfrom->vAddrToSend.clear();
4919 vector<CAddress> vAddr = addrman.GetAddr();
4920 BOOST_FOREACH(const CAddress &addr, vAddr)
4921 pfrom->PushAddress(addr);
4925 else if (strCommand == "mempool")
4927 LOCK2(cs_main, pfrom->cs_filter);
4929 std::vector<uint256> vtxid;
4930 mempool.queryHashes(vtxid);
4932 BOOST_FOREACH(uint256& hash, vtxid) {
4933 CInv inv(MSG_TX, hash);
4935 bool fInMemPool = mempool.lookup(hash, tx);
4936 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4937 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4939 vInv.push_back(inv);
4940 if (vInv.size() == MAX_INV_SZ) {
4941 pfrom->PushMessage("inv", vInv);
4945 if (vInv.size() > 0)
4946 pfrom->PushMessage("inv", vInv);
4950 else if (strCommand == "ping")
4952 if (pfrom->nVersion > BIP0031_VERSION)
4956 // Echo the message back with the nonce. This allows for two useful features:
4958 // 1) A remote node can quickly check if the connection is operational
4959 // 2) Remote nodes can measure the latency of the network thread. If this node
4960 // is overloaded it won't respond to pings quickly and the remote node can
4961 // avoid sending us more work, like chain download requests.
4963 // The nonce stops the remote getting confused between different pings: without
4964 // it, if the remote node sends a ping once per second and this node takes 5
4965 // seconds to respond to each, the 5th ping the remote sends would appear to
4966 // return very quickly.
4967 pfrom->PushMessage("pong", nonce);
4972 else if (strCommand == "pong")
4974 int64_t pingUsecEnd = nTimeReceived;
4976 size_t nAvail = vRecv.in_avail();
4977 bool bPingFinished = false;
4978 std::string sProblem;
4980 if (nAvail >= sizeof(nonce)) {
4983 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4984 if (pfrom->nPingNonceSent != 0) {
4985 if (nonce == pfrom->nPingNonceSent) {
4986 // Matching pong received, this ping is no longer outstanding
4987 bPingFinished = true;
4988 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4989 if (pingUsecTime > 0) {
4990 // Successful ping time measurement, replace previous
4991 pfrom->nPingUsecTime = pingUsecTime;
4992 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4994 // This should never happen
4995 sProblem = "Timing mishap";
4998 // Nonce mismatches are normal when pings are overlapping
4999 sProblem = "Nonce mismatch";
5001 // This is most likely a bug in another implementation somewhere; cancel this ping
5002 bPingFinished = true;
5003 sProblem = "Nonce zero";
5007 sProblem = "Unsolicited pong without ping";
5010 // This is most likely a bug in another implementation somewhere; cancel this ping
5011 bPingFinished = true;
5012 sProblem = "Short payload";
5015 if (!(sProblem.empty())) {
5016 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5020 pfrom->nPingNonceSent,
5024 if (bPingFinished) {
5025 pfrom->nPingNonceSent = 0;
5030 else if (fAlerts && strCommand == "alert")
5035 uint256 alertHash = alert.GetHash();
5036 if (pfrom->setKnown.count(alertHash) == 0)
5038 if (alert.ProcessAlert(Params().AlertKey()))
5041 pfrom->setKnown.insert(alertHash);
5044 BOOST_FOREACH(CNode* pnode, vNodes)
5045 alert.RelayTo(pnode);
5049 // Small DoS penalty so peers that send us lots of
5050 // duplicate/expired/invalid-signature/whatever alerts
5051 // eventually get banned.
5052 // This isn't a Misbehaving(100) (immediate ban) because the
5053 // peer might be an older or different implementation with
5054 // a different signature key, etc.
5055 Misbehaving(pfrom->GetId(), 10);
5061 else if (strCommand == "filterload")
5063 CBloomFilter filter;
5066 if (!filter.IsWithinSizeConstraints())
5067 // There is no excuse for sending a too-large filter
5068 Misbehaving(pfrom->GetId(), 100);
5071 LOCK(pfrom->cs_filter);
5072 delete pfrom->pfilter;
5073 pfrom->pfilter = new CBloomFilter(filter);
5074 pfrom->pfilter->UpdateEmptyFull();
5076 pfrom->fRelayTxes = true;
5080 else if (strCommand == "filteradd")
5082 vector<unsigned char> vData;
5085 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5086 // and thus, the maximum size any matched object can have) in a filteradd message
5087 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5089 Misbehaving(pfrom->GetId(), 100);
5091 LOCK(pfrom->cs_filter);
5093 pfrom->pfilter->insert(vData);
5095 Misbehaving(pfrom->GetId(), 100);
5100 else if (strCommand == "filterclear")
5102 LOCK(pfrom->cs_filter);
5103 delete pfrom->pfilter;
5104 pfrom->pfilter = new CBloomFilter();
5105 pfrom->fRelayTxes = true;
5109 else if (strCommand == "reject")
5113 string strMsg; unsigned char ccode; string strReason;
5114 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5117 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5119 if (strMsg == "block" || strMsg == "tx")
5123 ss << ": hash " << hash.ToString();
5125 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5126 } catch (const std::ios_base::failure&) {
5127 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5128 LogPrint("net", "Unparseable reject message received\n");
5133 else if (strCommand == "notfound") {
5134 // We do not care about the NOTFOUND message, but logging an Unknown Command
5135 // message would be undesirable as we transmit it ourselves.
5139 // Ignore unknown commands for extensibility
5140 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5148 // requires LOCK(cs_vRecvMsg)
5149 bool ProcessMessages(CNode* pfrom)
5152 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5156 // (4) message start
5164 if (!pfrom->vRecvGetData.empty())
5165 ProcessGetData(pfrom);
5167 // this maintains the order of responses
5168 if (!pfrom->vRecvGetData.empty()) return fOk;
5170 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5171 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5172 // Don't bother if send buffer is too full to respond anyway
5173 if (pfrom->nSendSize >= SendBufferSize())
5177 CNetMessage& msg = *it;
5180 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5181 // msg.hdr.nMessageSize, msg.vRecv.size(),
5182 // msg.complete() ? "Y" : "N");
5184 // end, if an incomplete message is found
5185 if (!msg.complete())
5188 // at this point, any failure means we can delete the current message
5191 // Scan for message start
5192 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5193 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5199 CMessageHeader& hdr = msg.hdr;
5200 if (!hdr.IsValid(Params().MessageStart()))
5202 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5205 string strCommand = hdr.GetCommand();
5208 unsigned int nMessageSize = hdr.nMessageSize;
5211 CDataStream& vRecv = msg.vRecv;
5212 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5213 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5214 if (nChecksum != hdr.nChecksum)
5216 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5217 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5225 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5226 boost::this_thread::interruption_point();
5228 catch (const std::ios_base::failure& e)
5230 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5231 if (strstr(e.what(), "end of data"))
5233 // Allow exceptions from under-length message on vRecv
5234 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());
5236 else if (strstr(e.what(), "size too large"))
5238 // Allow exceptions from over-long size
5239 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5243 PrintExceptionContinue(&e, "ProcessMessages()");
5246 catch (const boost::thread_interrupted&) {
5249 catch (const std::exception& e) {
5250 PrintExceptionContinue(&e, "ProcessMessages()");
5252 PrintExceptionContinue(NULL, "ProcessMessages()");
5256 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5261 // In case the connection got shut down, its receive buffer was wiped
5262 if (!pfrom->fDisconnect)
5263 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5269 bool SendMessages(CNode* pto, bool fSendTrickle)
5271 const Consensus::Params& consensusParams = Params().GetConsensus();
5273 // Don't send anything until we get its version message
5274 if (pto->nVersion == 0)
5280 bool pingSend = false;
5281 if (pto->fPingQueued) {
5282 // RPC ping request by user
5285 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5286 // Ping automatically sent as a latency probe & keepalive.
5291 while (nonce == 0) {
5292 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5294 pto->fPingQueued = false;
5295 pto->nPingUsecStart = GetTimeMicros();
5296 if (pto->nVersion > BIP0031_VERSION) {
5297 pto->nPingNonceSent = nonce;
5298 pto->PushMessage("ping", nonce);
5300 // Peer is too old to support ping command with nonce, pong will never arrive.
5301 pto->nPingNonceSent = 0;
5302 pto->PushMessage("ping");
5306 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5310 // Address refresh broadcast
5311 static int64_t nLastRebroadcast;
5312 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5315 BOOST_FOREACH(CNode* pnode, vNodes)
5317 // Periodically clear addrKnown to allow refresh broadcasts
5318 if (nLastRebroadcast)
5319 pnode->addrKnown.reset();
5321 // Rebroadcast our address
5322 AdvertizeLocal(pnode);
5324 if (!vNodes.empty())
5325 nLastRebroadcast = GetTime();
5333 vector<CAddress> vAddr;
5334 vAddr.reserve(pto->vAddrToSend.size());
5335 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5337 if (!pto->addrKnown.contains(addr.GetKey()))
5339 pto->addrKnown.insert(addr.GetKey());
5340 vAddr.push_back(addr);
5341 // receiver rejects addr messages larger than 1000
5342 if (vAddr.size() >= 1000)
5344 pto->PushMessage("addr", vAddr);
5349 pto->vAddrToSend.clear();
5351 pto->PushMessage("addr", vAddr);
5354 CNodeState &state = *State(pto->GetId());
5355 if (state.fShouldBan) {
5356 if (pto->fWhitelisted)
5357 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5359 pto->fDisconnect = true;
5360 if (pto->addr.IsLocal())
5361 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5364 CNode::Ban(pto->addr);
5367 state.fShouldBan = false;
5370 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5371 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5372 state.rejects.clear();
5375 if (pindexBestHeader == NULL)
5376 pindexBestHeader = chainActive.Tip();
5377 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.
5378 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5379 // Only actively request headers from a single peer, unless we're close to today.
5380 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5381 state.fSyncStarted = true;
5383 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5384 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5385 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5389 // Resend wallet transactions that haven't gotten in a block yet
5390 // Except during reindex, importing and IBD, when old wallet
5391 // transactions become unconfirmed and spams other nodes.
5392 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5394 GetMainSignals().Broadcast(nTimeBestReceived);
5398 // Message: inventory
5401 vector<CInv> vInvWait;
5403 LOCK(pto->cs_inventory);
5404 vInv.reserve(pto->vInventoryToSend.size());
5405 vInvWait.reserve(pto->vInventoryToSend.size());
5406 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5408 if (pto->setInventoryKnown.count(inv))
5411 // trickle out tx inv to protect privacy
5412 if (inv.type == MSG_TX && !fSendTrickle)
5414 // 1/4 of tx invs blast to all immediately
5415 static uint256 hashSalt;
5416 if (hashSalt.IsNull())
5417 hashSalt = GetRandHash();
5418 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5419 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5420 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5424 vInvWait.push_back(inv);
5429 // returns true if wasn't already contained in the set
5430 if (pto->setInventoryKnown.insert(inv).second)
5432 vInv.push_back(inv);
5433 if (vInv.size() >= 1000)
5435 pto->PushMessage("inv", vInv);
5440 pto->vInventoryToSend = vInvWait;
5443 pto->PushMessage("inv", vInv);
5445 // Detect whether we're stalling
5446 int64_t nNow = GetTimeMicros();
5447 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5448 // Stalling only triggers when the block download window cannot move. During normal steady state,
5449 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5450 // should only happen during initial block download.
5451 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5452 pto->fDisconnect = true;
5454 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5455 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5456 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5457 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5458 // to unreasonably increase our timeout.
5459 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5460 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5461 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5462 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5463 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5464 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5465 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5466 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5467 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5468 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5469 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5471 if (queuedBlock.nTimeDisconnect < nNow) {
5472 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5473 pto->fDisconnect = true;
5478 // Message: getdata (blocks)
5480 vector<CInv> vGetData;
5481 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5482 vector<CBlockIndex*> vToDownload;
5483 NodeId staller = -1;
5484 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5485 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5486 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5487 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5488 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5489 pindex->nHeight, pto->id);
5491 if (state.nBlocksInFlight == 0 && staller != -1) {
5492 if (State(staller)->nStallingSince == 0) {
5493 State(staller)->nStallingSince = nNow;
5494 LogPrint("net", "Stall started peer=%d\n", staller);
5500 // Message: getdata (non-blocks)
5502 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5504 const CInv& inv = (*pto->mapAskFor.begin()).second;
5505 if (!AlreadyHave(inv))
5508 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5509 vGetData.push_back(inv);
5510 if (vGetData.size() >= 1000)
5512 pto->PushMessage("getdata", vGetData);
5516 //If we're not going to ask, don't expect a response.
5517 pto->setAskFor.erase(inv.hash);
5519 pto->mapAskFor.erase(pto->mapAskFor.begin());
5521 if (!vGetData.empty())
5522 pto->PushMessage("getdata", vGetData);
5528 std::string CBlockFileInfo::ToString() const {
5529 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));
5540 BlockMap::iterator it1 = mapBlockIndex.begin();
5541 for (; it1 != mapBlockIndex.end(); it1++)
5542 delete (*it1).second;
5543 mapBlockIndex.clear();
5545 // orphan transactions
5546 mapOrphanTransactions.clear();
5547 mapOrphanTransactionsByPrev.clear();
5549 } instance_of_cmaincleanup;