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"
17 #include "deprecation.h"
19 #include "merkleblock.h"
24 #include "txmempool.h"
25 #include "ui_interface.h"
28 #include "utilmoneystr.h"
29 #include "validationinterface.h"
30 #include "wallet/asyncrpcoperation_sendmany.h"
31 #include "wallet/asyncrpcoperation_shieldcoinbase.h"
35 #include <boost/algorithm/string/replace.hpp>
36 #include <boost/filesystem.hpp>
37 #include <boost/filesystem/fstream.hpp>
38 #include <boost/math/distributions/poisson.hpp>
39 #include <boost/thread.hpp>
40 #include <boost/static_assert.hpp>
45 # error "Zcash cannot be compiled without assertions."
52 CCriticalSection cs_main;
54 BlockMap mapBlockIndex;
56 CBlockIndex *pindexBestHeader = NULL;
57 int64_t nTimeBestReceived = 0;
58 CWaitableCriticalSection csBestBlock;
59 CConditionVariable cvBlockChange;
60 int nScriptCheckThreads = 0;
61 bool fExperimentalMode = false;
62 bool fImporting = false;
63 bool fReindex = false;
64 bool fTxIndex = false;
65 bool fHavePruned = false;
66 bool fPruneMode = false;
67 bool fIsBareMultisigStd = true;
68 bool fCheckBlockIndex = false;
69 bool fCheckpointsEnabled = true;
70 bool fCoinbaseEnforcedProtectionEnabled = true;
71 size_t nCoinCacheUsage = 5000 * 300;
72 uint64_t nPruneTarget = 0;
73 bool fAlerts = DEFAULT_ALERTS;
75 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
76 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
78 CTxMemPool mempool(::minRelayTxFee);
84 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
85 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
86 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
89 * Returns true if there are nRequired or more blocks of minVersion or above
90 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
92 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
93 static void CheckBlockIndex();
95 /** Constant stuff for coinbase transactions we create: */
96 CScript COINBASE_FLAGS;
98 const string strMessageMagic = "Zcash Signed Message:\n";
103 struct CBlockIndexWorkComparator
105 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
106 // First sort by most total work, ...
107 if (pa->nChainWork > pb->nChainWork) return false;
108 if (pa->nChainWork < pb->nChainWork) return true;
110 // ... then by earliest time received, ...
111 if (pa->nSequenceId < pb->nSequenceId) return false;
112 if (pa->nSequenceId > pb->nSequenceId) return true;
114 // Use pointer address as tie breaker (should only happen with blocks
115 // loaded from disk, as those all have id 0).
116 if (pa < pb) return false;
117 if (pa > pb) return true;
124 CBlockIndex *pindexBestInvalid;
127 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
128 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
129 * missing the data for the block.
131 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
132 /** Number of nodes with fSyncStarted. */
133 int nSyncStarted = 0;
134 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
135 * Pruned nodes may have entries where B is missing data.
137 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
139 CCriticalSection cs_LastBlockFile;
140 std::vector<CBlockFileInfo> vinfoBlockFile;
141 int nLastBlockFile = 0;
142 /** Global flag to indicate we should check to see if there are
143 * block/undo files that should be deleted. Set on startup
144 * or if we allocate more file space when we're in prune mode
146 bool fCheckForPruning = false;
149 * Every received block is assigned a unique and increasing identifier, so we
150 * know which one to give priority in case of a fork.
152 CCriticalSection cs_nBlockSequenceId;
153 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
154 uint32_t nBlockSequenceId = 1;
157 * Sources of received blocks, saved to be able to send them reject
158 * messages or ban them when processing happens afterwards. Protected by
161 map<uint256, NodeId> mapBlockSource;
164 * Filter for transactions that were recently rejected by
165 * AcceptToMemoryPool. These are not rerequested until the chain tip
166 * changes, at which point the entire filter is reset. Protected by
169 * Without this filter we'd be re-requesting txs from each of our peers,
170 * increasing bandwidth consumption considerably. For instance, with 100
171 * peers, half of which relay a tx we don't accept, that might be a 50x
172 * bandwidth increase. A flooding attacker attempting to roll-over the
173 * filter using minimum-sized, 60byte, transactions might manage to send
174 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
175 * two minute window to send invs to us.
177 * Decreasing the false positive rate is fairly cheap, so we pick one in a
178 * million to make it highly unlikely for users to have issues with this
183 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
184 uint256 hashRecentRejectsChainTip;
186 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
189 CBlockIndex *pindex; //! Optional.
190 int64_t nTime; //! Time of "getdata" request in microseconds.
191 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
192 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
194 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
196 /** Number of blocks in flight with validated headers. */
197 int nQueuedValidatedHeaders = 0;
199 /** Number of preferable block download peers. */
200 int nPreferredDownload = 0;
202 /** Dirty block index entries. */
203 set<CBlockIndex*> setDirtyBlockIndex;
205 /** Dirty block file entries. */
206 set<int> setDirtyFileInfo;
209 //////////////////////////////////////////////////////////////////////////////
211 // Registration of network node signals.
216 struct CBlockReject {
217 unsigned char chRejectCode;
218 string strRejectReason;
223 * Maintain validation-specific state about nodes, protected by cs_main, instead
224 * by CNode's own locks. This simplifies asynchronous operation, where
225 * processing of incoming data is done after the ProcessMessage call returns,
226 * and we're no longer holding the node's locks.
229 //! The peer's address
231 //! Whether we have a fully established connection.
232 bool fCurrentlyConnected;
233 //! Accumulated misbehaviour score for this peer.
235 //! Whether this peer should be disconnected and banned (unless whitelisted).
237 //! String name of this peer (debugging/logging purposes).
239 //! List of asynchronously-determined block rejections to notify this peer about.
240 std::vector<CBlockReject> rejects;
241 //! The best known block we know this peer has announced.
242 CBlockIndex *pindexBestKnownBlock;
243 //! The hash of the last unknown block this peer has announced.
244 uint256 hashLastUnknownBlock;
245 //! The last full block we both have.
246 CBlockIndex *pindexLastCommonBlock;
247 //! Whether we've started headers synchronization with this peer.
249 //! Since when we're stalling block download progress (in microseconds), or 0.
250 int64_t nStallingSince;
251 list<QueuedBlock> vBlocksInFlight;
253 int nBlocksInFlightValidHeaders;
254 //! Whether we consider this a preferred download peer.
255 bool fPreferredDownload;
258 fCurrentlyConnected = false;
261 pindexBestKnownBlock = NULL;
262 hashLastUnknownBlock.SetNull();
263 pindexLastCommonBlock = NULL;
264 fSyncStarted = false;
267 nBlocksInFlightValidHeaders = 0;
268 fPreferredDownload = false;
272 /** Map maintaining per-node state. Requires cs_main. */
273 map<NodeId, CNodeState> mapNodeState;
276 CNodeState *State(NodeId pnode) {
277 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
278 if (it == mapNodeState.end())
286 return chainActive.Height();
289 void UpdatePreferredDownload(CNode* node, CNodeState* state)
291 nPreferredDownload -= state->fPreferredDownload;
293 // Whether this node should be marked as a preferred download node.
294 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
296 nPreferredDownload += state->fPreferredDownload;
299 // Returns time at which to timeout block request (nTime in microseconds)
300 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
302 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
305 void InitializeNode(NodeId nodeid, const CNode *pnode) {
307 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
308 state.name = pnode->addrName;
309 state.address = pnode->addr;
312 void FinalizeNode(NodeId nodeid) {
314 CNodeState *state = State(nodeid);
316 if (state->fSyncStarted)
319 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
320 AddressCurrentlyConnected(state->address);
323 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
324 mapBlocksInFlight.erase(entry.hash);
325 EraseOrphansFor(nodeid);
326 nPreferredDownload -= state->fPreferredDownload;
328 mapNodeState.erase(nodeid);
332 // Returns a bool indicating whether we requested this block.
333 bool MarkBlockAsReceived(const uint256& hash) {
334 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
335 if (itInFlight != mapBlocksInFlight.end()) {
336 CNodeState *state = State(itInFlight->second.first);
337 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
338 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
339 state->vBlocksInFlight.erase(itInFlight->second.second);
340 state->nBlocksInFlight--;
341 state->nStallingSince = 0;
342 mapBlocksInFlight.erase(itInFlight);
349 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
350 CNodeState *state = State(nodeid);
351 assert(state != NULL);
353 // Make sure it's not listed somewhere already.
354 MarkBlockAsReceived(hash);
356 int64_t nNow = GetTimeMicros();
357 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
358 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
359 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
360 state->nBlocksInFlight++;
361 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
362 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
365 /** Check whether the last unknown block a peer advertized is not yet known. */
366 void ProcessBlockAvailability(NodeId nodeid) {
367 CNodeState *state = State(nodeid);
368 assert(state != NULL);
370 if (!state->hashLastUnknownBlock.IsNull()) {
371 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
372 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
373 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
374 state->pindexBestKnownBlock = itOld->second;
375 state->hashLastUnknownBlock.SetNull();
380 /** Update tracking information about which blocks a peer is assumed to have. */
381 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
382 CNodeState *state = State(nodeid);
383 assert(state != NULL);
385 ProcessBlockAvailability(nodeid);
387 BlockMap::iterator it = mapBlockIndex.find(hash);
388 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
389 // An actually better block was announced.
390 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
391 state->pindexBestKnownBlock = it->second;
393 // An unknown block was announced; just assume that the latest one is the best one.
394 state->hashLastUnknownBlock = hash;
398 /** Find the last common ancestor two blocks have.
399 * Both pa and pb must be non-NULL. */
400 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
401 if (pa->nHeight > pb->nHeight) {
402 pa = pa->GetAncestor(pb->nHeight);
403 } else if (pb->nHeight > pa->nHeight) {
404 pb = pb->GetAncestor(pa->nHeight);
407 while (pa != pb && pa && pb) {
412 // Eventually all chain branches meet at the genesis block.
417 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
418 * at most count entries. */
419 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
423 vBlocks.reserve(vBlocks.size() + count);
424 CNodeState *state = State(nodeid);
425 assert(state != NULL);
427 // Make sure pindexBestKnownBlock is up to date, we'll need it.
428 ProcessBlockAvailability(nodeid);
430 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
431 // This peer has nothing interesting.
435 if (state->pindexLastCommonBlock == NULL) {
436 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
437 // Guessing wrong in either direction is not a problem.
438 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
441 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
442 // of its current tip anymore. Go back enough to fix that.
443 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
444 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
447 std::vector<CBlockIndex*> vToFetch;
448 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
449 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
450 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
451 // download that next block if the window were 1 larger.
452 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
453 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
454 NodeId waitingfor = -1;
455 while (pindexWalk->nHeight < nMaxHeight) {
456 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
457 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
458 // as iterating over ~100 CBlockIndex* entries anyway.
459 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
460 vToFetch.resize(nToFetch);
461 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
462 vToFetch[nToFetch - 1] = pindexWalk;
463 for (unsigned int i = nToFetch - 1; i > 0; i--) {
464 vToFetch[i - 1] = vToFetch[i]->pprev;
467 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
468 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
469 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
470 // already part of our chain (and therefore don't need it even if pruned).
471 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
472 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
473 // We consider the chain that this peer is on invalid.
476 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
477 if (pindex->nChainTx)
478 state->pindexLastCommonBlock = pindex;
479 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
480 // The block is not already downloaded, and not yet in flight.
481 if (pindex->nHeight > nWindowEnd) {
482 // We reached the end of the window.
483 if (vBlocks.size() == 0 && waitingfor != nodeid) {
484 // We aren't able to fetch anything, but we would be if the download window was one larger.
485 nodeStaller = waitingfor;
489 vBlocks.push_back(pindex);
490 if (vBlocks.size() == count) {
493 } else if (waitingfor == -1) {
494 // This is the first already-in-flight block.
495 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
503 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
505 CNodeState *state = State(nodeid);
508 stats.nMisbehavior = state->nMisbehavior;
509 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
510 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
511 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
513 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
518 void RegisterNodeSignals(CNodeSignals& nodeSignals)
520 nodeSignals.GetHeight.connect(&GetHeight);
521 nodeSignals.ProcessMessages.connect(&ProcessMessages);
522 nodeSignals.SendMessages.connect(&SendMessages);
523 nodeSignals.InitializeNode.connect(&InitializeNode);
524 nodeSignals.FinalizeNode.connect(&FinalizeNode);
527 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
529 nodeSignals.GetHeight.disconnect(&GetHeight);
530 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
531 nodeSignals.SendMessages.disconnect(&SendMessages);
532 nodeSignals.InitializeNode.disconnect(&InitializeNode);
533 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
536 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
538 // Find the first block the caller has in the main chain
539 BOOST_FOREACH(const uint256& hash, locator.vHave) {
540 BlockMap::iterator mi = mapBlockIndex.find(hash);
541 if (mi != mapBlockIndex.end())
543 CBlockIndex* pindex = (*mi).second;
544 if (chain.Contains(pindex))
548 return chain.Genesis();
551 CCoinsViewCache *pcoinsTip = NULL;
552 CBlockTreeDB *pblocktree = NULL;
554 //////////////////////////////////////////////////////////////////////////////
556 // mapOrphanTransactions
559 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
561 uint256 hash = tx.GetHash();
562 if (mapOrphanTransactions.count(hash))
565 // Ignore big transactions, to avoid a
566 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
567 // large transaction with a missing parent then we assume
568 // it will rebroadcast it later, after the parent transaction(s)
569 // have been mined or received.
570 // 10,000 orphans, each of which is at most 5,000 bytes big is
571 // at most 500 megabytes of orphans:
572 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
575 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
579 mapOrphanTransactions[hash].tx = tx;
580 mapOrphanTransactions[hash].fromPeer = peer;
581 BOOST_FOREACH(const CTxIn& txin, tx.vin)
582 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
584 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
585 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
589 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
591 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
592 if (it == mapOrphanTransactions.end())
594 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
596 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
597 if (itPrev == mapOrphanTransactionsByPrev.end())
599 itPrev->second.erase(hash);
600 if (itPrev->second.empty())
601 mapOrphanTransactionsByPrev.erase(itPrev);
603 mapOrphanTransactions.erase(it);
606 void EraseOrphansFor(NodeId peer)
609 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
610 while (iter != mapOrphanTransactions.end())
612 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
613 if (maybeErase->second.fromPeer == peer)
615 EraseOrphanTx(maybeErase->second.tx.GetHash());
619 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
623 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
625 unsigned int nEvicted = 0;
626 while (mapOrphanTransactions.size() > nMaxOrphans)
628 // Evict a random orphan:
629 uint256 randomhash = GetRandHash();
630 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
631 if (it == mapOrphanTransactions.end())
632 it = mapOrphanTransactions.begin();
633 EraseOrphanTx(it->first);
645 bool IsStandardTx(const CTransaction& tx, string& reason)
647 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
652 BOOST_FOREACH(const CTxIn& txin, tx.vin)
654 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
655 // keys. (remember the 520 byte limit on redeemScript size) That works
656 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
657 // bytes of scriptSig, which we round off to 1650 bytes for some minor
658 // future-proofing. That's also enough to spend a 20-of-20
659 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
660 // considered standard)
661 if (txin.scriptSig.size() > 1650) {
662 reason = "scriptsig-size";
665 if (!txin.scriptSig.IsPushOnly()) {
666 reason = "scriptsig-not-pushonly";
671 unsigned int nDataOut = 0;
672 txnouttype whichType;
673 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
674 if (!::IsStandard(txout.scriptPubKey, whichType)) {
675 reason = "scriptpubkey";
679 if (whichType == TX_NULL_DATA)
681 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
682 reason = "bare-multisig";
684 } else if (txout.IsDust(::minRelayTxFee)) {
690 // only one OP_RETURN txout is permitted
692 reason = "multi-op-return";
699 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
701 if (tx.nLockTime == 0)
703 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
705 BOOST_FOREACH(const CTxIn& txin, tx.vin)
711 bool CheckFinalTx(const CTransaction &tx, int flags)
713 AssertLockHeld(cs_main);
715 // By convention a negative value for flags indicates that the
716 // current network-enforced consensus rules should be used. In
717 // a future soft-fork scenario that would mean checking which
718 // rules would be enforced for the next block and setting the
719 // appropriate flags. At the present time no soft-forks are
720 // scheduled, so no flags are set.
721 flags = std::max(flags, 0);
723 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
724 // nLockTime because when IsFinalTx() is called within
725 // CBlock::AcceptBlock(), the height of the block *being*
726 // evaluated is what is used. Thus if we want to know if a
727 // transaction can be part of the *next* block, we need to call
728 // IsFinalTx() with one more than chainActive.Height().
729 const int nBlockHeight = chainActive.Height() + 1;
731 // Timestamps on the other hand don't get any special treatment,
732 // because we can't know what timestamp the next block will have,
733 // and there aren't timestamp applications where it matters.
734 // However this changes once median past time-locks are enforced:
735 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
736 ? chainActive.Tip()->GetMedianTimePast()
739 return IsFinalTx(tx, nBlockHeight, nBlockTime);
743 * Check transaction inputs to mitigate two
744 * potential denial-of-service attacks:
746 * 1. scriptSigs with extra data stuffed into them,
747 * not consumed by scriptPubKey (or P2SH script)
748 * 2. P2SH scripts with a crazy number of expensive
749 * CHECKSIG/CHECKMULTISIG operations
751 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
754 return true; // Coinbases don't use vin normally
756 for (unsigned int i = 0; i < tx.vin.size(); i++)
758 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
760 vector<vector<unsigned char> > vSolutions;
761 txnouttype whichType;
762 // get the scriptPubKey corresponding to this input:
763 const CScript& prevScript = prev.scriptPubKey;
764 if (!Solver(prevScript, whichType, vSolutions))
766 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
767 if (nArgsExpected < 0)
770 // Transactions with extra stuff in their scriptSigs are
771 // non-standard. Note that this EvalScript() call will
772 // be quick, because if there are any operations
773 // beside "push data" in the scriptSig
774 // IsStandardTx() will have already returned false
775 // and this method isn't called.
776 vector<vector<unsigned char> > stack;
777 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
780 if (whichType == TX_SCRIPTHASH)
784 CScript subscript(stack.back().begin(), stack.back().end());
785 vector<vector<unsigned char> > vSolutions2;
786 txnouttype whichType2;
787 if (Solver(subscript, whichType2, vSolutions2))
789 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
792 nArgsExpected += tmpExpected;
796 // Any other Script with less than 15 sigops OK:
797 unsigned int sigops = subscript.GetSigOpCount(true);
798 // ... extra data left on the stack after execution is OK, too:
799 return (sigops <= MAX_P2SH_SIGOPS);
803 if (stack.size() != (unsigned int)nArgsExpected)
810 unsigned int GetLegacySigOpCount(const CTransaction& tx)
812 unsigned int nSigOps = 0;
813 BOOST_FOREACH(const CTxIn& txin, tx.vin)
815 nSigOps += txin.scriptSig.GetSigOpCount(false);
817 BOOST_FOREACH(const CTxOut& txout, tx.vout)
819 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
824 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
829 unsigned int nSigOps = 0;
830 for (unsigned int i = 0; i < tx.vin.size(); i++)
832 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
833 if (prevout.scriptPubKey.IsPayToScriptHash())
834 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
839 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
840 libzcash::ProofVerifier& verifier)
842 // Don't count coinbase transactions because mining skews the count
843 if (!tx.IsCoinBase()) {
844 transactionsValidated.increment();
847 if (!CheckTransactionWithoutProofVerification(tx, state)) {
850 // Ensure that zk-SNARKs verify
851 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
852 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
853 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
854 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
861 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
863 // Basic checks that don't depend on any context
865 // Check transaction version
866 if (tx.nVersion < MIN_TX_VERSION) {
867 return state.DoS(100, error("CheckTransaction(): version too low"),
868 REJECT_INVALID, "bad-txns-version-too-low");
871 // Transactions can contain empty `vin` and `vout` so long as
872 // `vjoinsplit` is non-empty.
873 if (tx.vin.empty() && tx.vjoinsplit.empty())
874 return state.DoS(10, error("CheckTransaction(): vin empty"),
875 REJECT_INVALID, "bad-txns-vin-empty");
876 if (tx.vout.empty() && tx.vjoinsplit.empty())
877 return state.DoS(10, error("CheckTransaction(): vout empty"),
878 REJECT_INVALID, "bad-txns-vout-empty");
881 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
882 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
883 return state.DoS(100, error("CheckTransaction(): size limits failed"),
884 REJECT_INVALID, "bad-txns-oversize");
886 // Check for negative or overflow output values
887 CAmount nValueOut = 0;
888 BOOST_FOREACH(const CTxOut& txout, tx.vout)
890 if (txout.nValue < 0)
891 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
892 REJECT_INVALID, "bad-txns-vout-negative");
893 if (txout.nValue > MAX_MONEY)
894 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
895 REJECT_INVALID, "bad-txns-vout-toolarge");
896 nValueOut += txout.nValue;
897 if (!MoneyRange(nValueOut))
898 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
899 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
902 // Ensure that joinsplit values are well-formed
903 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
905 if (joinsplit.vpub_old < 0) {
906 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
907 REJECT_INVALID, "bad-txns-vpub_old-negative");
910 if (joinsplit.vpub_new < 0) {
911 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
912 REJECT_INVALID, "bad-txns-vpub_new-negative");
915 if (joinsplit.vpub_old > MAX_MONEY) {
916 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
917 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
920 if (joinsplit.vpub_new > MAX_MONEY) {
921 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
922 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
925 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
926 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
927 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
930 nValueOut += joinsplit.vpub_old;
931 if (!MoneyRange(nValueOut)) {
932 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
933 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
937 // Ensure input values do not exceed MAX_MONEY
938 // We have not resolved the txin values at this stage,
939 // but we do know what the joinsplits claim to add
940 // to the value pool.
942 CAmount nValueIn = 0;
943 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
945 nValueIn += it->vpub_new;
947 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
948 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
949 REJECT_INVALID, "bad-txns-txintotal-toolarge");
955 // Check for duplicate inputs
956 set<COutPoint> vInOutPoints;
957 BOOST_FOREACH(const CTxIn& txin, tx.vin)
959 if (vInOutPoints.count(txin.prevout))
960 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
961 REJECT_INVALID, "bad-txns-inputs-duplicate");
962 vInOutPoints.insert(txin.prevout);
965 // Check for duplicate joinsplit nullifiers in this transaction
966 set<uint256> vJoinSplitNullifiers;
967 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
969 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
971 if (vJoinSplitNullifiers.count(nf))
972 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
973 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
975 vJoinSplitNullifiers.insert(nf);
981 // There should be no joinsplits in a coinbase transaction
982 if (tx.vjoinsplit.size() > 0)
983 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
984 REJECT_INVALID, "bad-cb-has-joinsplits");
986 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
987 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
988 REJECT_INVALID, "bad-cb-length");
992 BOOST_FOREACH(const CTxIn& txin, tx.vin)
993 if (txin.prevout.IsNull())
994 return state.DoS(10, error("CheckTransaction(): prevout is null"),
995 REJECT_INVALID, "bad-txns-prevout-null");
997 if (tx.vjoinsplit.size() > 0) {
998 // Empty output script.
1000 uint256 dataToBeSigned;
1002 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1003 } catch (std::logic_error ex) {
1004 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1005 REJECT_INVALID, "error-computing-signature-hash");
1008 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1010 // We rely on libsodium to check that the signature is canonical.
1011 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1012 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1013 dataToBeSigned.begin(), 32,
1014 tx.joinSplitPubKey.begin()
1016 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1017 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1025 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1029 uint256 hash = tx.GetHash();
1030 double dPriorityDelta = 0;
1031 CAmount nFeeDelta = 0;
1032 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1033 if (dPriorityDelta > 0 || nFeeDelta > 0)
1037 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1041 // There is a free transaction area in blocks created by most miners,
1042 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1043 // to be considered to fall into this category. We don't want to encourage sending
1044 // multiple transactions instead of one big transaction to avoid fees.
1045 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1049 if (!MoneyRange(nMinFee))
1050 nMinFee = MAX_MONEY;
1055 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1056 bool* pfMissingInputs, bool fRejectAbsurdFee)
1058 AssertLockHeld(cs_main);
1059 if (pfMissingInputs)
1060 *pfMissingInputs = false;
1062 // Node operator can choose to reject tx by number of transparent inputs
1063 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1064 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1066 size_t n = tx.vin.size();
1068 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1073 auto verifier = libzcash::ProofVerifier::Strict();
1074 if (!CheckTransaction(tx, state, verifier))
1075 return error("AcceptToMemoryPool: CheckTransaction failed");
1077 // Coinbase is only valid in a block, not as a loose transaction
1078 if (tx.IsCoinBase())
1079 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1080 REJECT_INVALID, "coinbase");
1082 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1084 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1086 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1087 REJECT_NONSTANDARD, reason);
1089 // Only accept nLockTime-using transactions that can be mined in the next
1090 // block; we don't want our mempool filled up with transactions that can't
1092 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1093 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1095 // is it already in the memory pool?
1096 uint256 hash = tx.GetHash();
1097 if (pool.exists(hash))
1100 // Check for conflicts with in-memory transactions
1102 LOCK(pool.cs); // protect pool.mapNextTx
1103 for (unsigned int i = 0; i < tx.vin.size(); i++)
1105 COutPoint outpoint = tx.vin[i].prevout;
1106 if (pool.mapNextTx.count(outpoint))
1108 // Disable replacement feature for now
1112 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1113 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1114 if (pool.mapNullifiers.count(nf))
1124 CCoinsViewCache view(&dummy);
1126 CAmount nValueIn = 0;
1129 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1130 view.SetBackend(viewMemPool);
1132 // do we already have it?
1133 if (view.HaveCoins(hash))
1136 // do all inputs exist?
1137 // Note that this does not check for the presence of actual outputs (see the next check for that),
1138 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1139 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1140 if (!view.HaveCoins(txin.prevout.hash)) {
1141 if (pfMissingInputs)
1142 *pfMissingInputs = true;
1147 // are the actual inputs available?
1148 if (!view.HaveInputs(tx))
1149 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1150 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1152 // are the joinsplit's requirements met?
1153 if (!view.HaveJoinSplitRequirements(tx))
1154 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1155 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1157 // Bring the best block into scope
1158 view.GetBestBlock();
1160 nValueIn = view.GetValueIn(tx);
1162 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1163 view.SetBackend(dummy);
1166 // Check for non-standard pay-to-script-hash in inputs
1167 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1168 return error("AcceptToMemoryPool: nonstandard transaction input");
1170 // Check that the transaction doesn't have an excessive number of
1171 // sigops, making it impossible to mine. Since the coinbase transaction
1172 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1173 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1174 // merely non-standard transaction.
1175 unsigned int nSigOps = GetLegacySigOpCount(tx);
1176 nSigOps += GetP2SHSigOpCount(tx, view);
1177 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1179 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1180 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1181 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1183 CAmount nValueOut = tx.GetValueOut();
1184 CAmount nFees = nValueIn-nValueOut;
1185 double dPriority = view.GetPriority(tx, chainActive.Height());
1187 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1188 unsigned int nSize = entry.GetTxSize();
1190 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1191 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1192 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1194 // Don't accept it if it can't get into a block
1195 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1196 if (fLimitFree && nFees < txMinFee)
1197 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1198 hash.ToString(), nFees, txMinFee),
1199 REJECT_INSUFFICIENTFEE, "insufficient fee");
1202 // Require that free transactions have sufficient priority to be mined in the next block.
1203 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1204 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1207 // Continuously rate-limit free (really, very-low-fee) transactions
1208 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1209 // be annoying or make others' transactions take longer to confirm.
1210 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1212 static CCriticalSection csFreeLimiter;
1213 static double dFreeCount;
1214 static int64_t nLastTime;
1215 int64_t nNow = GetTime();
1217 LOCK(csFreeLimiter);
1219 // Use an exponentially decaying ~10-minute window:
1220 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1222 // -limitfreerelay unit is thousand-bytes-per-minute
1223 // At default rate it would take over a month to fill 1GB
1224 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1225 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1226 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1227 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1228 dFreeCount += nSize;
1231 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1232 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1234 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1236 // Check against previous transactions
1237 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1238 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1240 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1243 // Check again against just the consensus-critical mandatory script
1244 // verification flags, in case of bugs in the standard flags that cause
1245 // transactions to pass as valid when they're actually invalid. For
1246 // instance the STRICTENC flag was incorrectly allowing certain
1247 // CHECKSIG NOT scripts to pass, even though they were invalid.
1249 // There is a similar check in CreateNewBlock() to prevent creating
1250 // invalid blocks, however allowing such transactions into the mempool
1251 // can be exploited as a DoS attack.
1252 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1254 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1257 // Store transaction in memory
1258 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1261 SyncWithWallets(tx, NULL);
1266 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1267 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1269 CBlockIndex *pindexSlow = NULL;
1273 if (mempool.lookup(hash, txOut))
1280 if (pblocktree->ReadTxIndex(hash, postx)) {
1281 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1283 return error("%s: OpenBlockFile failed", __func__);
1284 CBlockHeader header;
1287 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1289 } catch (const std::exception& e) {
1290 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1292 hashBlock = header.GetHash();
1293 if (txOut.GetHash() != hash)
1294 return error("%s: txid mismatch", __func__);
1299 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1302 CCoinsViewCache &view = *pcoinsTip;
1303 const CCoins* coins = view.AccessCoins(hash);
1305 nHeight = coins->nHeight;
1308 pindexSlow = chainActive[nHeight];
1313 if (ReadBlockFromDisk(block, pindexSlow)) {
1314 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1315 if (tx.GetHash() == hash) {
1317 hashBlock = pindexSlow->GetBlockHash();
1332 //////////////////////////////////////////////////////////////////////////////
1334 // CBlock and CBlockIndex
1337 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1339 // Open history file to append
1340 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1341 if (fileout.IsNull())
1342 return error("WriteBlockToDisk: OpenBlockFile failed");
1344 // Write index header
1345 unsigned int nSize = fileout.GetSerializeSize(block);
1346 fileout << FLATDATA(messageStart) << nSize;
1349 long fileOutPos = ftell(fileout.Get());
1351 return error("WriteBlockToDisk: ftell failed");
1352 pos.nPos = (unsigned int)fileOutPos;
1358 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1362 // Open history file to read
1363 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1364 if (filein.IsNull())
1365 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1371 catch (const std::exception& e) {
1372 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1376 if (!(CheckEquihashSolution(&block, Params()) &&
1377 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1378 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1383 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1385 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1387 if (block.GetHash() != pindex->GetBlockHash())
1388 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1389 pindex->ToString(), pindex->GetBlockPos().ToString());
1393 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1395 CAmount nSubsidy = 12.5 * COIN;
1397 // Mining slow start
1398 // The subsidy is ramped up linearly, skipping the middle payout of
1399 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1400 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1401 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1402 nSubsidy *= nHeight;
1404 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1405 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1406 nSubsidy *= (nHeight+1);
1410 assert(nHeight > consensusParams.SubsidySlowStartShift());
1411 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1412 // Force block reward to zero when right shift is undefined.
1416 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1417 nSubsidy >>= halvings;
1421 bool IsInitialBlockDownload()
1423 const CChainParams& chainParams = Params();
1425 if (fImporting || fReindex)
1427 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1429 static bool lockIBDState = false;
1432 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1433 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1435 lockIBDState = true;
1439 bool fLargeWorkForkFound = false;
1440 bool fLargeWorkInvalidChainFound = false;
1441 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1443 void CheckForkWarningConditions()
1445 AssertLockHeld(cs_main);
1446 // Before we get past initial download, we cannot reliably alert about forks
1447 // (we assume we don't get stuck on a fork before the last checkpoint)
1448 if (IsInitialBlockDownload())
1451 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1452 // of our head, drop it
1453 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1454 pindexBestForkTip = NULL;
1456 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1458 if (!fLargeWorkForkFound && pindexBestForkBase)
1460 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1461 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1462 CAlert::Notify(warning, true);
1464 if (pindexBestForkTip && pindexBestForkBase)
1466 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__,
1467 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1468 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1469 fLargeWorkForkFound = true;
1473 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1474 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1475 CAlert::Notify(warning, true);
1476 fLargeWorkInvalidChainFound = true;
1481 fLargeWorkForkFound = false;
1482 fLargeWorkInvalidChainFound = false;
1486 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1488 AssertLockHeld(cs_main);
1489 // If we are on a fork that is sufficiently large, set a warning flag
1490 CBlockIndex* pfork = pindexNewForkTip;
1491 CBlockIndex* plonger = chainActive.Tip();
1492 while (pfork && pfork != plonger)
1494 while (plonger && plonger->nHeight > pfork->nHeight)
1495 plonger = plonger->pprev;
1496 if (pfork == plonger)
1498 pfork = pfork->pprev;
1501 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1502 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1503 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1504 // hash rate operating on the fork.
1505 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1506 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1507 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1508 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1509 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1510 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1512 pindexBestForkTip = pindexNewForkTip;
1513 pindexBestForkBase = pfork;
1516 CheckForkWarningConditions();
1519 // Requires cs_main.
1520 void Misbehaving(NodeId pnode, int howmuch)
1525 CNodeState *state = State(pnode);
1529 state->nMisbehavior += howmuch;
1530 int banscore = GetArg("-banscore", 100);
1531 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1533 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1534 state->fShouldBan = true;
1536 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1539 void static InvalidChainFound(CBlockIndex* pindexNew)
1541 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1542 pindexBestInvalid = pindexNew;
1544 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1545 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1546 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1547 pindexNew->GetBlockTime()));
1548 CBlockIndex *tip = chainActive.Tip();
1550 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1551 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1552 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1553 CheckForkWarningConditions();
1556 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1558 if (state.IsInvalid(nDoS)) {
1559 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1560 if (it != mapBlockSource.end() && State(it->second)) {
1561 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1562 State(it->second)->rejects.push_back(reject);
1564 Misbehaving(it->second, nDoS);
1567 if (!state.CorruptionPossible()) {
1568 pindex->nStatus |= BLOCK_FAILED_VALID;
1569 setDirtyBlockIndex.insert(pindex);
1570 setBlockIndexCandidates.erase(pindex);
1571 InvalidChainFound(pindex);
1575 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1577 // mark inputs spent
1578 if (!tx.IsCoinBase()) {
1579 txundo.vprevout.reserve(tx.vin.size());
1580 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1581 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1582 unsigned nPos = txin.prevout.n;
1584 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1586 // mark an outpoint spent, and construct undo information
1587 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1589 if (coins->vout.size() == 0) {
1590 CTxInUndo& undo = txundo.vprevout.back();
1591 undo.nHeight = coins->nHeight;
1592 undo.fCoinBase = coins->fCoinBase;
1593 undo.nVersion = coins->nVersion;
1599 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1600 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1601 inputs.SetNullifier(nf, true);
1606 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1609 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1612 UpdateCoins(tx, state, inputs, txundo, nHeight);
1615 bool CScriptCheck::operator()() {
1616 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1617 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1618 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1623 int GetSpendHeight(const CCoinsViewCache& inputs)
1626 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1627 return pindexPrev->nHeight + 1;
1630 namespace Consensus {
1631 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1633 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1634 // for an attacker to attempt to split the network.
1635 if (!inputs.HaveInputs(tx))
1636 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1638 // are the JoinSplit's requirements met?
1639 if (!inputs.HaveJoinSplitRequirements(tx))
1640 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1642 CAmount nValueIn = 0;
1644 for (unsigned int i = 0; i < tx.vin.size(); i++)
1646 const COutPoint &prevout = tx.vin[i].prevout;
1647 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1650 if (coins->IsCoinBase()) {
1651 // Ensure that coinbases are matured
1652 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1653 return state.Invalid(
1654 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1655 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1658 // Ensure that coinbases cannot be spent to transparent outputs
1659 // Disabled on regtest
1660 if (fCoinbaseEnforcedProtectionEnabled &&
1661 consensusParams.fCoinbaseMustBeProtected &&
1663 return state.Invalid(
1664 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1665 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1669 // Check for negative or overflow input values
1670 nValueIn += coins->vout[prevout.n].nValue;
1671 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1672 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1673 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1677 nValueIn += tx.GetJoinSplitValueIn();
1678 if (!MoneyRange(nValueIn))
1679 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1680 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1682 if (nValueIn < tx.GetValueOut())
1683 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1684 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1685 REJECT_INVALID, "bad-txns-in-belowout");
1687 // Tally transaction fees
1688 CAmount nTxFee = nValueIn - tx.GetValueOut();
1690 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1691 REJECT_INVALID, "bad-txns-fee-negative");
1693 if (!MoneyRange(nFees))
1694 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1695 REJECT_INVALID, "bad-txns-fee-outofrange");
1698 }// namespace Consensus
1700 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)
1702 if (!tx.IsCoinBase())
1704 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
1709 pvChecks->reserve(tx.vin.size());
1711 // The first loop above does all the inexpensive checks.
1712 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1713 // Helps prevent CPU exhaustion attacks.
1715 // Skip ECDSA signature verification when connecting blocks
1716 // before the last block chain checkpoint. This is safe because block merkle hashes are
1717 // still computed and checked, and any change will be caught at the next checkpoint.
1718 if (fScriptChecks) {
1719 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1720 const COutPoint &prevout = tx.vin[i].prevout;
1721 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1725 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1727 pvChecks->push_back(CScriptCheck());
1728 check.swap(pvChecks->back());
1729 } else if (!check()) {
1730 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1731 // Check whether the failure was caused by a
1732 // non-mandatory script verification check, such as
1733 // non-standard DER encodings or non-null dummy
1734 // arguments; if so, don't trigger DoS protection to
1735 // avoid splitting the network between upgraded and
1736 // non-upgraded nodes.
1737 CScriptCheck check(*coins, tx, i,
1738 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1740 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1742 // Failures of other flags indicate a transaction that is
1743 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1744 // such nodes as they are not following the protocol. That
1745 // said during an upgrade careful thought should be taken
1746 // as to the correct behavior - we may want to continue
1747 // peering with non-upgraded nodes even after a soft-fork
1748 // super-majority vote has passed.
1749 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1760 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1762 // Open history file to append
1763 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1764 if (fileout.IsNull())
1765 return error("%s: OpenUndoFile failed", __func__);
1767 // Write index header
1768 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1769 fileout << FLATDATA(messageStart) << nSize;
1772 long fileOutPos = ftell(fileout.Get());
1774 return error("%s: ftell failed", __func__);
1775 pos.nPos = (unsigned int)fileOutPos;
1776 fileout << blockundo;
1778 // calculate & write checksum
1779 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1780 hasher << hashBlock;
1781 hasher << blockundo;
1782 fileout << hasher.GetHash();
1787 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1789 // Open history file to read
1790 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1791 if (filein.IsNull())
1792 return error("%s: OpenBlockFile failed", __func__);
1795 uint256 hashChecksum;
1797 filein >> blockundo;
1798 filein >> hashChecksum;
1800 catch (const std::exception& e) {
1801 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1805 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1806 hasher << hashBlock;
1807 hasher << blockundo;
1808 if (hashChecksum != hasher.GetHash())
1809 return error("%s: Checksum mismatch", __func__);
1814 /** Abort with a message */
1815 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1817 strMiscWarning = strMessage;
1818 LogPrintf("*** %s\n", strMessage);
1819 uiInterface.ThreadSafeMessageBox(
1820 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1821 "", CClientUIInterface::MSG_ERROR);
1826 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1828 AbortNode(strMessage, userMessage);
1829 return state.Error(strMessage);
1835 * Apply the undo operation of a CTxInUndo to the given chain state.
1836 * @param undo The undo object.
1837 * @param view The coins view to which to apply the changes.
1838 * @param out The out point that corresponds to the tx input.
1839 * @return True on success.
1841 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1845 CCoinsModifier coins = view.ModifyCoins(out.hash);
1846 if (undo.nHeight != 0) {
1847 // undo data contains height: this is the last output of the prevout tx being spent
1848 if (!coins->IsPruned())
1849 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1851 coins->fCoinBase = undo.fCoinBase;
1852 coins->nHeight = undo.nHeight;
1853 coins->nVersion = undo.nVersion;
1855 if (coins->IsPruned())
1856 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1858 if (coins->IsAvailable(out.n))
1859 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1860 if (coins->vout.size() < out.n+1)
1861 coins->vout.resize(out.n+1);
1862 coins->vout[out.n] = undo.txout;
1867 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1869 assert(pindex->GetBlockHash() == view.GetBestBlock());
1876 CBlockUndo blockUndo;
1877 CDiskBlockPos pos = pindex->GetUndoPos();
1879 return error("DisconnectBlock(): no undo data available");
1880 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1881 return error("DisconnectBlock(): failure reading undo data");
1883 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1884 return error("DisconnectBlock(): block and undo data inconsistent");
1886 // undo transactions in reverse order
1887 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1888 const CTransaction &tx = block.vtx[i];
1889 uint256 hash = tx.GetHash();
1891 // Check that all outputs are available and match the outputs in the block itself
1894 CCoinsModifier outs = view.ModifyCoins(hash);
1895 outs->ClearUnspendable();
1897 CCoins outsBlock(tx, pindex->nHeight);
1898 // The CCoins serialization does not serialize negative numbers.
1899 // No network rules currently depend on the version here, so an inconsistency is harmless
1900 // but it must be corrected before txout nversion ever influences a network rule.
1901 if (outsBlock.nVersion < 0)
1902 outs->nVersion = outsBlock.nVersion;
1903 if (*outs != outsBlock)
1904 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1910 // unspend nullifiers
1911 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1912 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1913 view.SetNullifier(nf, false);
1918 if (i > 0) { // not coinbases
1919 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1920 if (txundo.vprevout.size() != tx.vin.size())
1921 return error("DisconnectBlock(): transaction and undo data inconsistent");
1922 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1923 const COutPoint &out = tx.vin[j].prevout;
1924 const CTxInUndo &undo = txundo.vprevout[j];
1925 if (!ApplyTxInUndo(undo, view, out))
1931 // set the old best anchor back
1932 view.PopAnchor(blockUndo.old_tree_root);
1934 // move best block pointer to prevout block
1935 view.SetBestBlock(pindex->pprev->GetBlockHash());
1945 void static FlushBlockFile(bool fFinalize = false)
1947 LOCK(cs_LastBlockFile);
1949 CDiskBlockPos posOld(nLastBlockFile, 0);
1951 FILE *fileOld = OpenBlockFile(posOld);
1954 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1955 FileCommit(fileOld);
1959 fileOld = OpenUndoFile(posOld);
1962 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1963 FileCommit(fileOld);
1968 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1970 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1972 void ThreadScriptCheck() {
1973 RenameThread("zcash-scriptch");
1974 scriptcheckqueue.Thread();
1978 // Called periodically asynchronously; alerts if it smells like
1979 // we're being fed a bad chain (blocks being generated much
1980 // too slowly or too quickly).
1982 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1983 int64_t nPowTargetSpacing)
1985 if (bestHeader == NULL || initialDownloadCheck()) return;
1987 static int64_t lastAlertTime = 0;
1988 int64_t now = GetAdjustedTime();
1989 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1991 const int SPAN_HOURS=4;
1992 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1993 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1995 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1997 std::string strWarning;
1998 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2001 const CBlockIndex* i = bestHeader;
2003 while (i->GetBlockTime() >= startTime) {
2006 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2009 // How likely is it to find that many by chance?
2010 double p = boost::math::pdf(poisson, nBlocks);
2012 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2013 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2015 // Aim for one false-positive about every fifty years of normal running:
2016 const int FIFTY_YEARS = 50*365*24*60*60;
2017 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2019 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2021 // Many fewer blocks than expected: alert!
2022 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2023 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2025 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2027 // Many more blocks than expected: alert!
2028 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2029 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2031 if (!strWarning.empty())
2033 strMiscWarning = strWarning;
2034 CAlert::Notify(strWarning, true);
2035 lastAlertTime = now;
2039 static int64_t nTimeVerify = 0;
2040 static int64_t nTimeConnect = 0;
2041 static int64_t nTimeIndex = 0;
2042 static int64_t nTimeCallbacks = 0;
2043 static int64_t nTimeTotal = 0;
2045 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2047 const CChainParams& chainparams = Params();
2048 AssertLockHeld(cs_main);
2050 bool fExpensiveChecks = true;
2051 if (fCheckpointsEnabled) {
2052 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2053 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2054 // This block is an ancestor of a checkpoint: disable script checks
2055 fExpensiveChecks = false;
2059 auto verifier = libzcash::ProofVerifier::Strict();
2060 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2062 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2063 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2066 // verify that the view's current state corresponds to the previous block
2067 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2068 assert(hashPrevBlock == view.GetBestBlock());
2070 // Special case for the genesis block, skipping connection of its transactions
2071 // (its coinbase is unspendable)
2072 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2074 view.SetBestBlock(pindex->GetBlockHash());
2075 // Before the genesis block, there was an empty tree
2076 ZCIncrementalMerkleTree tree;
2077 pindex->hashAnchor = tree.root();
2078 // The genesis block contained no JoinSplits
2079 pindex->hashAnchorEnd = pindex->hashAnchor;
2084 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2085 // unless those are already completely spent.
2086 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2087 const CCoins* coins = view.AccessCoins(tx.GetHash());
2088 if (coins && !coins->IsPruned())
2089 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2090 REJECT_INVALID, "bad-txns-BIP30");
2093 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2095 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2097 CBlockUndo blockundo;
2099 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2101 int64_t nTimeStart = GetTimeMicros();
2104 unsigned int nSigOps = 0;
2105 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2106 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2107 vPos.reserve(block.vtx.size());
2108 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2110 // Construct the incremental merkle tree at the current
2112 auto old_tree_root = view.GetBestAnchor();
2113 // saving the top anchor in the block index as we go.
2115 pindex->hashAnchor = old_tree_root;
2117 ZCIncrementalMerkleTree tree;
2118 // This should never fail: we should always be able to get the root
2119 // that is on the tip of our chain
2120 assert(view.GetAnchorAt(old_tree_root, tree));
2123 // Consistency check: the root of the tree we're given should
2124 // match what we asked for.
2125 assert(tree.root() == old_tree_root);
2128 for (unsigned int i = 0; i < block.vtx.size(); i++)
2130 const CTransaction &tx = block.vtx[i];
2132 nInputs += tx.vin.size();
2133 nSigOps += GetLegacySigOpCount(tx);
2134 if (nSigOps > MAX_BLOCK_SIGOPS)
2135 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2136 REJECT_INVALID, "bad-blk-sigops");
2138 if (!tx.IsCoinBase())
2140 if (!view.HaveInputs(tx))
2141 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2142 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2144 // are the JoinSplit's requirements met?
2145 if (!view.HaveJoinSplitRequirements(tx))
2146 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2147 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2149 // Add in sigops done by pay-to-script-hash inputs;
2150 // this is to prevent a "rogue miner" from creating
2151 // an incredibly-expensive-to-validate block.
2152 nSigOps += GetP2SHSigOpCount(tx, view);
2153 if (nSigOps > MAX_BLOCK_SIGOPS)
2154 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2155 REJECT_INVALID, "bad-blk-sigops");
2157 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2159 std::vector<CScriptCheck> vChecks;
2160 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2162 control.Add(vChecks);
2167 blockundo.vtxundo.push_back(CTxUndo());
2169 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2171 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2172 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2173 // Insert the note commitments into our temporary tree.
2175 tree.append(note_commitment);
2179 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2180 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2183 view.PushAnchor(tree);
2185 pindex->hashAnchorEnd = tree.root();
2187 blockundo.old_tree_root = old_tree_root;
2189 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2190 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);
2192 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2193 if (block.vtx[0].GetValueOut() > blockReward)
2194 return state.DoS(100,
2195 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2196 block.vtx[0].GetValueOut(), blockReward),
2197 REJECT_INVALID, "bad-cb-amount");
2199 if (!control.Wait())
2200 return state.DoS(100, false);
2201 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2202 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);
2207 // Write undo information to disk
2208 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2210 if (pindex->GetUndoPos().IsNull()) {
2212 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2213 return error("ConnectBlock(): FindUndoPos failed");
2214 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2215 return AbortNode(state, "Failed to write undo data");
2217 // update nUndoPos in block index
2218 pindex->nUndoPos = pos.nPos;
2219 pindex->nStatus |= BLOCK_HAVE_UNDO;
2222 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2223 setDirtyBlockIndex.insert(pindex);
2227 if (!pblocktree->WriteTxIndex(vPos))
2228 return AbortNode(state, "Failed to write transaction index");
2230 // add this block to the view's block chain
2231 view.SetBestBlock(pindex->GetBlockHash());
2233 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2234 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2236 // Watch for changes to the previous coinbase transaction.
2237 static uint256 hashPrevBestCoinBase;
2238 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2239 hashPrevBestCoinBase = block.vtx[0].GetHash();
2241 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2242 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2247 enum FlushStateMode {
2249 FLUSH_STATE_IF_NEEDED,
2250 FLUSH_STATE_PERIODIC,
2255 * Update the on-disk chain state.
2256 * The caches and indexes are flushed depending on the mode we're called with
2257 * if they're too large, if it's been a while since the last write,
2258 * or always and in all cases if we're in prune mode and are deleting files.
2260 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2261 LOCK2(cs_main, cs_LastBlockFile);
2262 static int64_t nLastWrite = 0;
2263 static int64_t nLastFlush = 0;
2264 static int64_t nLastSetChain = 0;
2265 std::set<int> setFilesToPrune;
2266 bool fFlushForPrune = false;
2268 if (fPruneMode && fCheckForPruning && !fReindex) {
2269 FindFilesToPrune(setFilesToPrune);
2270 fCheckForPruning = false;
2271 if (!setFilesToPrune.empty()) {
2272 fFlushForPrune = true;
2274 pblocktree->WriteFlag("prunedblockfiles", true);
2279 int64_t nNow = GetTimeMicros();
2280 // Avoid writing/flushing immediately after startup.
2281 if (nLastWrite == 0) {
2284 if (nLastFlush == 0) {
2287 if (nLastSetChain == 0) {
2288 nLastSetChain = nNow;
2290 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2291 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2292 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2293 // The cache is over the limit, we have to write now.
2294 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2295 // 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.
2296 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2297 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2298 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2299 // Combine all conditions that result in a full cache flush.
2300 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2301 // Write blocks and block index to disk.
2302 if (fDoFullFlush || fPeriodicWrite) {
2303 // Depend on nMinDiskSpace to ensure we can write block index
2304 if (!CheckDiskSpace(0))
2305 return state.Error("out of disk space");
2306 // First make sure all block and undo data is flushed to disk.
2308 // Then update all block file information (which may refer to block and undo files).
2310 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2311 vFiles.reserve(setDirtyFileInfo.size());
2312 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2313 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2314 setDirtyFileInfo.erase(it++);
2316 std::vector<const CBlockIndex*> vBlocks;
2317 vBlocks.reserve(setDirtyBlockIndex.size());
2318 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2319 vBlocks.push_back(*it);
2320 setDirtyBlockIndex.erase(it++);
2322 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2323 return AbortNode(state, "Files to write to block index database");
2326 // Finally remove any pruned files
2328 UnlinkPrunedFiles(setFilesToPrune);
2331 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2333 // Typical CCoins structures on disk are around 128 bytes in size.
2334 // Pushing a new one to the database can cause it to be written
2335 // twice (once in the log, and once in the tables). This is already
2336 // an overestimation, as most will delete an existing entry or
2337 // overwrite one. Still, use a conservative safety factor of 2.
2338 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2339 return state.Error("out of disk space");
2340 // Flush the chainstate (which may refer to block index entries).
2341 if (!pcoinsTip->Flush())
2342 return AbortNode(state, "Failed to write to coin database");
2345 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2346 // Update best block in wallet (so we can detect restored wallets).
2347 GetMainSignals().SetBestChain(chainActive.GetLocator());
2348 nLastSetChain = nNow;
2350 } catch (const std::runtime_error& e) {
2351 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2356 void FlushStateToDisk() {
2357 CValidationState state;
2358 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2361 void PruneAndFlush() {
2362 CValidationState state;
2363 fCheckForPruning = true;
2364 FlushStateToDisk(state, FLUSH_STATE_NONE);
2367 /** Update chainActive and related internal data structures. */
2368 void static UpdateTip(CBlockIndex *pindexNew) {
2369 const CChainParams& chainParams = Params();
2370 chainActive.SetTip(pindexNew);
2373 nTimeBestReceived = GetTime();
2374 mempool.AddTransactionsUpdated(1);
2376 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2377 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2378 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2379 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2381 cvBlockChange.notify_all();
2383 // Check the version of the last 100 blocks to see if we need to upgrade:
2384 static bool fWarned = false;
2385 if (!IsInitialBlockDownload() && !fWarned)
2388 const CBlockIndex* pindex = chainActive.Tip();
2389 for (int i = 0; i < 100 && pindex != NULL; i++)
2391 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2393 pindex = pindex->pprev;
2396 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2397 if (nUpgraded > 100/2)
2399 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2400 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2401 CAlert::Notify(strMiscWarning, true);
2407 /** Disconnect chainActive's tip. */
2408 bool static DisconnectTip(CValidationState &state) {
2409 CBlockIndex *pindexDelete = chainActive.Tip();
2410 assert(pindexDelete);
2411 mempool.check(pcoinsTip);
2412 // Read block from disk.
2414 if (!ReadBlockFromDisk(block, pindexDelete))
2415 return AbortNode(state, "Failed to read block");
2416 // Apply the block atomically to the chain state.
2417 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2418 int64_t nStart = GetTimeMicros();
2420 CCoinsViewCache view(pcoinsTip);
2421 if (!DisconnectBlock(block, state, pindexDelete, view))
2422 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2423 assert(view.Flush());
2425 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2426 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2427 // Write the chain state to disk, if necessary.
2428 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2430 // Resurrect mempool transactions from the disconnected block.
2431 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2432 // ignore validation errors in resurrected transactions
2433 list<CTransaction> removed;
2434 CValidationState stateDummy;
2435 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2436 mempool.remove(tx, removed, true);
2438 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2439 // The anchor may not change between block disconnects,
2440 // in which case we don't want to evict from the mempool yet!
2441 mempool.removeWithAnchor(anchorBeforeDisconnect);
2443 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2444 mempool.check(pcoinsTip);
2445 // Update chainActive and related variables.
2446 UpdateTip(pindexDelete->pprev);
2447 // Get the current commitment tree
2448 ZCIncrementalMerkleTree newTree;
2449 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2450 // Let wallets know transactions went from 1-confirmed to
2451 // 0-confirmed or conflicted:
2452 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2453 SyncWithWallets(tx, NULL);
2455 // Update cached incremental witnesses
2456 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2460 static int64_t nTimeReadFromDisk = 0;
2461 static int64_t nTimeConnectTotal = 0;
2462 static int64_t nTimeFlush = 0;
2463 static int64_t nTimeChainState = 0;
2464 static int64_t nTimePostConnect = 0;
2467 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2468 * corresponding to pindexNew, to bypass loading it again from disk.
2470 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2471 assert(pindexNew->pprev == chainActive.Tip());
2472 mempool.check(pcoinsTip);
2473 // Read block from disk.
2474 int64_t nTime1 = GetTimeMicros();
2477 if (!ReadBlockFromDisk(block, pindexNew))
2478 return AbortNode(state, "Failed to read block");
2481 // Get the current commitment tree
2482 ZCIncrementalMerkleTree oldTree;
2483 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2484 // Apply the block atomically to the chain state.
2485 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2487 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2489 CCoinsViewCache view(pcoinsTip);
2490 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2491 GetMainSignals().BlockChecked(*pblock, state);
2493 if (state.IsInvalid())
2494 InvalidBlockFound(pindexNew, state);
2495 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2497 mapBlockSource.erase(pindexNew->GetBlockHash());
2498 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2499 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2500 assert(view.Flush());
2502 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2503 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2504 // Write the chain state to disk, if necessary.
2505 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2507 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2508 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2509 // Remove conflicting transactions from the mempool.
2510 list<CTransaction> txConflicted;
2511 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2512 mempool.check(pcoinsTip);
2513 // Update chainActive & related variables.
2514 UpdateTip(pindexNew);
2515 // Tell wallet about transactions that went from mempool
2517 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2518 SyncWithWallets(tx, NULL);
2520 // ... and about transactions that got confirmed:
2521 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2522 SyncWithWallets(tx, pblock);
2524 // Update cached incremental witnesses
2525 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2527 EnforceNodeDeprecation(pindexNew->nHeight);
2529 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2530 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2531 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2536 * Return the tip of the chain with the most work in it, that isn't
2537 * known to be invalid (it's however far from certain to be valid).
2539 static CBlockIndex* FindMostWorkChain() {
2541 CBlockIndex *pindexNew = NULL;
2543 // Find the best candidate header.
2545 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2546 if (it == setBlockIndexCandidates.rend())
2551 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2552 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2553 CBlockIndex *pindexTest = pindexNew;
2554 bool fInvalidAncestor = false;
2555 while (pindexTest && !chainActive.Contains(pindexTest)) {
2556 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2558 // Pruned nodes may have entries in setBlockIndexCandidates for
2559 // which block files have been deleted. Remove those as candidates
2560 // for the most work chain if we come across them; we can't switch
2561 // to a chain unless we have all the non-active-chain parent blocks.
2562 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2563 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2564 if (fFailedChain || fMissingData) {
2565 // Candidate chain is not usable (either invalid or missing data)
2566 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2567 pindexBestInvalid = pindexNew;
2568 CBlockIndex *pindexFailed = pindexNew;
2569 // Remove the entire chain from the set.
2570 while (pindexTest != pindexFailed) {
2572 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2573 } else if (fMissingData) {
2574 // If we're missing data, then add back to mapBlocksUnlinked,
2575 // so that if the block arrives in the future we can try adding
2576 // to setBlockIndexCandidates again.
2577 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2579 setBlockIndexCandidates.erase(pindexFailed);
2580 pindexFailed = pindexFailed->pprev;
2582 setBlockIndexCandidates.erase(pindexTest);
2583 fInvalidAncestor = true;
2586 pindexTest = pindexTest->pprev;
2588 if (!fInvalidAncestor)
2593 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2594 static void PruneBlockIndexCandidates() {
2595 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2596 // reorganization to a better block fails.
2597 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2598 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2599 setBlockIndexCandidates.erase(it++);
2601 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2602 assert(!setBlockIndexCandidates.empty());
2606 * Try to make some progress towards making pindexMostWork the active block.
2607 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2609 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2610 AssertLockHeld(cs_main);
2611 bool fInvalidFound = false;
2612 const CBlockIndex *pindexOldTip = chainActive.Tip();
2613 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2615 // Disconnect active blocks which are no longer in the best chain.
2616 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2617 if (!DisconnectTip(state))
2621 // Build list of new blocks to connect.
2622 std::vector<CBlockIndex*> vpindexToConnect;
2623 bool fContinue = true;
2624 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2625 while (fContinue && nHeight != pindexMostWork->nHeight) {
2626 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2627 // a few blocks along the way.
2628 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2629 vpindexToConnect.clear();
2630 vpindexToConnect.reserve(nTargetHeight - nHeight);
2631 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2632 while (pindexIter && pindexIter->nHeight != nHeight) {
2633 vpindexToConnect.push_back(pindexIter);
2634 pindexIter = pindexIter->pprev;
2636 nHeight = nTargetHeight;
2638 // Connect new blocks.
2639 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2640 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2641 if (state.IsInvalid()) {
2642 // The block violates a consensus rule.
2643 if (!state.CorruptionPossible())
2644 InvalidChainFound(vpindexToConnect.back());
2645 state = CValidationState();
2646 fInvalidFound = true;
2650 // A system error occurred (disk space, database error, ...).
2654 PruneBlockIndexCandidates();
2655 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2656 // We're in a better position than we were. Return temporarily to release the lock.
2664 // Callbacks/notifications for a new best chain.
2666 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2668 CheckForkWarningConditions();
2674 * Make the best chain active, in multiple steps. The result is either failure
2675 * or an activated best chain. pblock is either NULL or a pointer to a block
2676 * that is already loaded (to avoid loading it again from disk).
2678 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2679 CBlockIndex *pindexNewTip = NULL;
2680 CBlockIndex *pindexMostWork = NULL;
2681 const CChainParams& chainParams = Params();
2683 boost::this_thread::interruption_point();
2685 bool fInitialDownload;
2688 pindexMostWork = FindMostWorkChain();
2690 // Whether we have anything to do at all.
2691 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2694 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2697 pindexNewTip = chainActive.Tip();
2698 fInitialDownload = IsInitialBlockDownload();
2700 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2702 // Notifications/callbacks that can run without cs_main
2703 if (!fInitialDownload) {
2704 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2705 // Relay inventory, but don't relay old inventory during initial block download.
2706 int nBlockEstimate = 0;
2707 if (fCheckpointsEnabled)
2708 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2709 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2710 // in a stalled download if the block file is pruned before the request.
2711 if (nLocalServices & NODE_NETWORK) {
2713 BOOST_FOREACH(CNode* pnode, vNodes)
2714 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2715 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2717 // Notify external listeners about the new tip.
2718 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2719 uiInterface.NotifyBlockTip(hashNewTip);
2721 } while(pindexMostWork != chainActive.Tip());
2724 // Write changes periodically to disk, after relay.
2725 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2732 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2733 AssertLockHeld(cs_main);
2735 // Mark the block itself as invalid.
2736 pindex->nStatus |= BLOCK_FAILED_VALID;
2737 setDirtyBlockIndex.insert(pindex);
2738 setBlockIndexCandidates.erase(pindex);
2740 while (chainActive.Contains(pindex)) {
2741 CBlockIndex *pindexWalk = chainActive.Tip();
2742 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2743 setDirtyBlockIndex.insert(pindexWalk);
2744 setBlockIndexCandidates.erase(pindexWalk);
2745 // ActivateBestChain considers blocks already in chainActive
2746 // unconditionally valid already, so force disconnect away from it.
2747 if (!DisconnectTip(state)) {
2752 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2754 BlockMap::iterator it = mapBlockIndex.begin();
2755 while (it != mapBlockIndex.end()) {
2756 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2757 setBlockIndexCandidates.insert(it->second);
2762 InvalidChainFound(pindex);
2766 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2767 AssertLockHeld(cs_main);
2769 int nHeight = pindex->nHeight;
2771 // Remove the invalidity flag from this block and all its descendants.
2772 BlockMap::iterator it = mapBlockIndex.begin();
2773 while (it != mapBlockIndex.end()) {
2774 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2775 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2776 setDirtyBlockIndex.insert(it->second);
2777 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2778 setBlockIndexCandidates.insert(it->second);
2780 if (it->second == pindexBestInvalid) {
2781 // Reset invalid block marker if it was pointing to one of those.
2782 pindexBestInvalid = NULL;
2788 // Remove the invalidity flag from all ancestors too.
2789 while (pindex != NULL) {
2790 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2791 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2792 setDirtyBlockIndex.insert(pindex);
2794 pindex = pindex->pprev;
2799 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2801 // Check for duplicate
2802 uint256 hash = block.GetHash();
2803 BlockMap::iterator it = mapBlockIndex.find(hash);
2804 if (it != mapBlockIndex.end())
2807 // Construct new block index object
2808 CBlockIndex* pindexNew = new CBlockIndex(block);
2810 // We assign the sequence id to blocks only when the full data is available,
2811 // to avoid miners withholding blocks but broadcasting headers, to get a
2812 // competitive advantage.
2813 pindexNew->nSequenceId = 0;
2814 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2815 pindexNew->phashBlock = &((*mi).first);
2816 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2817 if (miPrev != mapBlockIndex.end())
2819 pindexNew->pprev = (*miPrev).second;
2820 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2821 pindexNew->BuildSkip();
2823 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2824 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2825 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2826 pindexBestHeader = pindexNew;
2828 setDirtyBlockIndex.insert(pindexNew);
2833 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2834 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2836 pindexNew->nTx = block.vtx.size();
2837 pindexNew->nChainTx = 0;
2838 pindexNew->nFile = pos.nFile;
2839 pindexNew->nDataPos = pos.nPos;
2840 pindexNew->nUndoPos = 0;
2841 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2842 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2843 setDirtyBlockIndex.insert(pindexNew);
2845 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2846 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2847 deque<CBlockIndex*> queue;
2848 queue.push_back(pindexNew);
2850 // Recursively process any descendant blocks that now may be eligible to be connected.
2851 while (!queue.empty()) {
2852 CBlockIndex *pindex = queue.front();
2854 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2856 LOCK(cs_nBlockSequenceId);
2857 pindex->nSequenceId = nBlockSequenceId++;
2859 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2860 setBlockIndexCandidates.insert(pindex);
2862 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2863 while (range.first != range.second) {
2864 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2865 queue.push_back(it->second);
2867 mapBlocksUnlinked.erase(it);
2871 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2872 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2879 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2881 LOCK(cs_LastBlockFile);
2883 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2884 if (vinfoBlockFile.size() <= nFile) {
2885 vinfoBlockFile.resize(nFile + 1);
2889 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2891 if (vinfoBlockFile.size() <= nFile) {
2892 vinfoBlockFile.resize(nFile + 1);
2896 pos.nPos = vinfoBlockFile[nFile].nSize;
2899 if (nFile != nLastBlockFile) {
2901 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2903 FlushBlockFile(!fKnown);
2904 nLastBlockFile = nFile;
2907 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2909 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2911 vinfoBlockFile[nFile].nSize += nAddSize;
2914 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2915 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2916 if (nNewChunks > nOldChunks) {
2918 fCheckForPruning = true;
2919 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2920 FILE *file = OpenBlockFile(pos);
2922 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2923 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2928 return state.Error("out of disk space");
2932 setDirtyFileInfo.insert(nFile);
2936 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2940 LOCK(cs_LastBlockFile);
2942 unsigned int nNewSize;
2943 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2944 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2945 setDirtyFileInfo.insert(nFile);
2947 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2948 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2949 if (nNewChunks > nOldChunks) {
2951 fCheckForPruning = true;
2952 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2953 FILE *file = OpenUndoFile(pos);
2955 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2956 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2961 return state.Error("out of disk space");
2967 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2969 // Check block version
2970 if (block.nVersion < MIN_BLOCK_VERSION)
2971 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
2972 REJECT_INVALID, "version-too-low");
2974 // Check Equihash solution is valid
2975 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2976 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2977 REJECT_INVALID, "invalid-solution");
2979 // Check proof of work matches claimed amount
2980 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2981 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2982 REJECT_INVALID, "high-hash");
2985 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2986 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2987 REJECT_INVALID, "time-too-new");
2992 bool CheckBlock(const CBlock& block, CValidationState& state,
2993 libzcash::ProofVerifier& verifier,
2994 bool fCheckPOW, bool fCheckMerkleRoot)
2996 // These are checks that are independent of context.
2998 // Check that the header is valid (particularly PoW). This is mostly
2999 // redundant with the call in AcceptBlockHeader.
3000 if (!CheckBlockHeader(block, state, fCheckPOW))
3003 // Check the merkle root.
3004 if (fCheckMerkleRoot) {
3006 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3007 if (block.hashMerkleRoot != hashMerkleRoot2)
3008 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3009 REJECT_INVALID, "bad-txnmrklroot", true);
3011 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3012 // of transactions in a block without affecting the merkle root of a block,
3013 // while still invalidating it.
3015 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3016 REJECT_INVALID, "bad-txns-duplicate", true);
3019 // All potential-corruption validation must be done before we do any
3020 // transaction validation, as otherwise we may mark the header as invalid
3021 // because we receive the wrong transactions for it.
3024 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3025 return state.DoS(100, error("CheckBlock(): size limits failed"),
3026 REJECT_INVALID, "bad-blk-length");
3028 // First transaction must be coinbase, the rest must not be
3029 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3030 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3031 REJECT_INVALID, "bad-cb-missing");
3032 for (unsigned int i = 1; i < block.vtx.size(); i++)
3033 if (block.vtx[i].IsCoinBase())
3034 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3035 REJECT_INVALID, "bad-cb-multiple");
3037 // Check transactions
3038 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3039 if (!CheckTransaction(tx, state, verifier))
3040 return error("CheckBlock(): CheckTransaction failed");
3042 unsigned int nSigOps = 0;
3043 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3045 nSigOps += GetLegacySigOpCount(tx);
3047 if (nSigOps > MAX_BLOCK_SIGOPS)
3048 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3049 REJECT_INVALID, "bad-blk-sigops", true);
3054 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3056 const CChainParams& chainParams = Params();
3057 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3058 uint256 hash = block.GetHash();
3059 if (hash == consensusParams.hashGenesisBlock)
3064 int nHeight = pindexPrev->nHeight+1;
3066 // Check proof of work
3067 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3068 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3069 REJECT_INVALID, "bad-diffbits");
3071 // Check timestamp against prev
3072 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3073 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3074 REJECT_INVALID, "time-too-old");
3076 if (fCheckpointsEnabled)
3078 // Don't accept any forks from the main chain prior to last checkpoint
3079 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3080 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3081 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3084 // Reject block.nVersion < 4 blocks
3085 if (block.nVersion < 4)
3086 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3087 REJECT_OBSOLETE, "bad-version");
3092 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3094 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3095 const Consensus::Params& consensusParams = Params().GetConsensus();
3097 // Check that all transactions are finalized
3098 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3099 int nLockTimeFlags = 0;
3100 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3101 ? pindexPrev->GetMedianTimePast()
3102 : block.GetBlockTime();
3103 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3104 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3108 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3109 // In Zcash this has been enforced since launch, except that the genesis
3110 // block didn't include the height in the coinbase (see Zcash protocol spec
3111 // section '6.8 Bitcoin Improvement Proposals').
3114 CScript expect = CScript() << nHeight;
3115 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3116 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3117 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3121 // Coinbase transaction must include an output sending 20% of
3122 // the block reward to a founders reward script, until the last founders
3123 // reward block is reached, with exception of the genesis block.
3124 // The last founders reward block is defined as the block just before the
3125 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3126 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3129 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3130 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3131 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3139 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3146 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3148 const CChainParams& chainparams = Params();
3149 AssertLockHeld(cs_main);
3150 // Check for duplicate
3151 uint256 hash = block.GetHash();
3152 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3153 CBlockIndex *pindex = NULL;
3154 if (miSelf != mapBlockIndex.end()) {
3155 // Block header is already known.
3156 pindex = miSelf->second;
3159 if (pindex->nStatus & BLOCK_FAILED_MASK)
3160 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3164 if (!CheckBlockHeader(block, state))
3167 // Get prev block index
3168 CBlockIndex* pindexPrev = NULL;
3169 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3170 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3171 if (mi == mapBlockIndex.end())
3172 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3173 pindexPrev = (*mi).second;
3174 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3175 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3178 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3182 pindex = AddToBlockIndex(block);
3190 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3192 const CChainParams& chainparams = Params();
3193 AssertLockHeld(cs_main);
3195 CBlockIndex *&pindex = *ppindex;
3197 if (!AcceptBlockHeader(block, state, &pindex))
3200 // Try to process all requested blocks that we don't have, but only
3201 // process an unrequested block if it's new and has enough work to
3202 // advance our tip, and isn't too many blocks ahead.
3203 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3204 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3205 // Blocks that are too out-of-order needlessly limit the effectiveness of
3206 // pruning, because pruning will not delete block files that contain any
3207 // blocks which are too close in height to the tip. Apply this test
3208 // regardless of whether pruning is enabled; it should generally be safe to
3209 // not process unrequested blocks.
3210 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3212 // TODO: deal better with return value and error conditions for duplicate
3213 // and unrequested blocks.
3214 if (fAlreadyHave) return true;
3215 if (!fRequested) { // If we didn't ask for it:
3216 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3217 if (!fHasMoreWork) return true; // Don't process less-work chains
3218 if (fTooFarAhead) return true; // Block height is too high
3221 // See method docstring for why this is always disabled
3222 auto verifier = libzcash::ProofVerifier::Disabled();
3223 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3224 if (state.IsInvalid() && !state.CorruptionPossible()) {
3225 pindex->nStatus |= BLOCK_FAILED_VALID;
3226 setDirtyBlockIndex.insert(pindex);
3231 int nHeight = pindex->nHeight;
3233 // Write block to history file
3235 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3236 CDiskBlockPos blockPos;
3239 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3240 return error("AcceptBlock(): FindBlockPos failed");
3242 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3243 AbortNode(state, "Failed to write block");
3244 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3245 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3246 } catch (const std::runtime_error& e) {
3247 return AbortNode(state, std::string("System error: ") + e.what());
3250 if (fCheckForPruning)
3251 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3256 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3258 unsigned int nFound = 0;
3259 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3261 if (pstart->nVersion >= minVersion)
3263 pstart = pstart->pprev;
3265 return (nFound >= nRequired);
3269 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3271 // Preliminary checks
3272 auto verifier = libzcash::ProofVerifier::Disabled();
3273 bool checked = CheckBlock(*pblock, state, verifier);
3277 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3278 fRequested |= fForceProcessing;
3280 return error("%s: CheckBlock FAILED", __func__);
3284 CBlockIndex *pindex = NULL;
3285 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3286 if (pindex && pfrom) {
3287 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3291 return error("%s: AcceptBlock FAILED", __func__);
3294 if (!ActivateBestChain(state, pblock))
3295 return error("%s: ActivateBestChain failed", __func__);
3300 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3302 AssertLockHeld(cs_main);
3303 assert(pindexPrev == chainActive.Tip());
3305 CCoinsViewCache viewNew(pcoinsTip);
3306 CBlockIndex indexDummy(block);
3307 indexDummy.pprev = pindexPrev;
3308 indexDummy.nHeight = pindexPrev->nHeight + 1;
3309 // JoinSplit proofs are verified in ConnectBlock
3310 auto verifier = libzcash::ProofVerifier::Disabled();
3312 // NOTE: CheckBlockHeader is called by CheckBlock
3313 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3315 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3317 if (!ContextualCheckBlock(block, state, pindexPrev))
3319 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3321 assert(state.IsValid());
3327 * BLOCK PRUNING CODE
3330 /* Calculate the amount of disk space the block & undo files currently use */
3331 uint64_t CalculateCurrentUsage()
3333 uint64_t retval = 0;
3334 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3335 retval += file.nSize + file.nUndoSize;
3340 /* Prune a block file (modify associated database entries)*/
3341 void PruneOneBlockFile(const int fileNumber)
3343 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3344 CBlockIndex* pindex = it->second;
3345 if (pindex->nFile == fileNumber) {
3346 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3347 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3349 pindex->nDataPos = 0;
3350 pindex->nUndoPos = 0;
3351 setDirtyBlockIndex.insert(pindex);
3353 // Prune from mapBlocksUnlinked -- any block we prune would have
3354 // to be downloaded again in order to consider its chain, at which
3355 // point it would be considered as a candidate for
3356 // mapBlocksUnlinked or setBlockIndexCandidates.
3357 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3358 while (range.first != range.second) {
3359 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3361 if (it->second == pindex) {
3362 mapBlocksUnlinked.erase(it);
3368 vinfoBlockFile[fileNumber].SetNull();
3369 setDirtyFileInfo.insert(fileNumber);
3373 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3375 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3376 CDiskBlockPos pos(*it, 0);
3377 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3378 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3379 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3383 /* Calculate the block/rev files that should be deleted to remain under target*/
3384 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3386 LOCK2(cs_main, cs_LastBlockFile);
3387 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3390 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3394 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3395 uint64_t nCurrentUsage = CalculateCurrentUsage();
3396 // We don't check to prune until after we've allocated new space for files
3397 // So we should leave a buffer under our target to account for another allocation
3398 // before the next pruning.
3399 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3400 uint64_t nBytesToPrune;
3403 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3404 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3405 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3407 if (vinfoBlockFile[fileNumber].nSize == 0)
3410 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3413 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3414 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3417 PruneOneBlockFile(fileNumber);
3418 // Queue up the files for removal
3419 setFilesToPrune.insert(fileNumber);
3420 nCurrentUsage -= nBytesToPrune;
3425 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3426 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3427 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3428 nLastBlockWeCanPrune, count);
3431 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3433 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3435 // Check for nMinDiskSpace bytes (currently 50MB)
3436 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3437 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3442 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3446 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3447 boost::filesystem::create_directories(path.parent_path());
3448 FILE* file = fopen(path.string().c_str(), "rb+");
3449 if (!file && !fReadOnly)
3450 file = fopen(path.string().c_str(), "wb+");
3452 LogPrintf("Unable to open file %s\n", path.string());
3456 if (fseek(file, pos.nPos, SEEK_SET)) {
3457 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3465 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3466 return OpenDiskFile(pos, "blk", fReadOnly);
3469 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3470 return OpenDiskFile(pos, "rev", fReadOnly);
3473 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3475 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3478 CBlockIndex * InsertBlockIndex(uint256 hash)
3484 BlockMap::iterator mi = mapBlockIndex.find(hash);
3485 if (mi != mapBlockIndex.end())
3486 return (*mi).second;
3489 CBlockIndex* pindexNew = new CBlockIndex();
3491 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3492 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3493 pindexNew->phashBlock = &((*mi).first);
3498 bool static LoadBlockIndexDB()
3500 const CChainParams& chainparams = Params();
3501 if (!pblocktree->LoadBlockIndexGuts())
3504 boost::this_thread::interruption_point();
3506 // Calculate nChainWork
3507 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3508 vSortedByHeight.reserve(mapBlockIndex.size());
3509 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3511 CBlockIndex* pindex = item.second;
3512 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3514 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3515 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3517 CBlockIndex* pindex = item.second;
3518 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3519 // We can link the chain of blocks for which we've received transactions at some point.
3520 // Pruned nodes may have deleted the block.
3521 if (pindex->nTx > 0) {
3522 if (pindex->pprev) {
3523 if (pindex->pprev->nChainTx) {
3524 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3526 pindex->nChainTx = 0;
3527 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3530 pindex->nChainTx = pindex->nTx;
3533 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3534 setBlockIndexCandidates.insert(pindex);
3535 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3536 pindexBestInvalid = pindex;
3538 pindex->BuildSkip();
3539 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3540 pindexBestHeader = pindex;
3543 // Load block file info
3544 pblocktree->ReadLastBlockFile(nLastBlockFile);
3545 vinfoBlockFile.resize(nLastBlockFile + 1);
3546 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3547 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3548 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3550 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3551 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3552 CBlockFileInfo info;
3553 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3554 vinfoBlockFile.push_back(info);
3560 // Check presence of blk files
3561 LogPrintf("Checking all blk files are present...\n");
3562 set<int> setBlkDataFiles;
3563 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3565 CBlockIndex* pindex = item.second;
3566 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3567 setBlkDataFiles.insert(pindex->nFile);
3570 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3572 CDiskBlockPos pos(*it, 0);
3573 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3578 // Check whether we have ever pruned block & undo files
3579 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3581 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3583 // Check whether we need to continue reindexing
3584 bool fReindexing = false;
3585 pblocktree->ReadReindexing(fReindexing);
3586 fReindex |= fReindexing;
3588 // Check whether we have a transaction index
3589 pblocktree->ReadFlag("txindex", fTxIndex);
3590 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3592 // Fill in-memory data
3593 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3595 CBlockIndex* pindex = item.second;
3596 // - This relationship will always be true even if pprev has multiple
3597 // children, because hashAnchor is technically a property of pprev,
3598 // not its children.
3599 // - This will miss chain tips; we handle the best tip below, and other
3600 // tips will be handled by ConnectTip during a re-org.
3601 if (pindex->pprev) {
3602 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3606 // Load pointer to end of best chain
3607 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3608 if (it == mapBlockIndex.end())
3610 chainActive.SetTip(it->second);
3611 // Set hashAnchorEnd for the end of best chain
3612 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3614 PruneBlockIndexCandidates();
3616 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3617 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3618 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3619 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3621 EnforceNodeDeprecation(chainActive.Height(), true);
3626 CVerifyDB::CVerifyDB()
3628 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3631 CVerifyDB::~CVerifyDB()
3633 uiInterface.ShowProgress("", 100);
3636 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3639 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3642 // Verify blocks in the best chain
3643 if (nCheckDepth <= 0)
3644 nCheckDepth = 1000000000; // suffices until the year 19000
3645 if (nCheckDepth > chainActive.Height())
3646 nCheckDepth = chainActive.Height();
3647 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3648 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3649 CCoinsViewCache coins(coinsview);
3650 CBlockIndex* pindexState = chainActive.Tip();
3651 CBlockIndex* pindexFailure = NULL;
3652 int nGoodTransactions = 0;
3653 CValidationState state;
3654 // No need to verify JoinSplits twice
3655 auto verifier = libzcash::ProofVerifier::Disabled();
3656 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3658 boost::this_thread::interruption_point();
3659 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3660 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3663 // check level 0: read from disk
3664 if (!ReadBlockFromDisk(block, pindex))
3665 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3666 // check level 1: verify block validity
3667 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
3668 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3669 // check level 2: verify undo validity
3670 if (nCheckLevel >= 2 && pindex) {
3672 CDiskBlockPos pos = pindex->GetUndoPos();
3673 if (!pos.IsNull()) {
3674 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3675 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3678 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3679 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3681 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3682 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3683 pindexState = pindex->pprev;
3685 nGoodTransactions = 0;
3686 pindexFailure = pindex;
3688 nGoodTransactions += block.vtx.size();
3690 if (ShutdownRequested())
3694 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3696 // check level 4: try reconnecting blocks
3697 if (nCheckLevel >= 4) {
3698 CBlockIndex *pindex = pindexState;
3699 while (pindex != chainActive.Tip()) {
3700 boost::this_thread::interruption_point();
3701 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3702 pindex = chainActive.Next(pindex);
3704 if (!ReadBlockFromDisk(block, pindex))
3705 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3706 if (!ConnectBlock(block, state, pindex, coins))
3707 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3711 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3716 void UnloadBlockIndex()
3719 setBlockIndexCandidates.clear();
3720 chainActive.SetTip(NULL);
3721 pindexBestInvalid = NULL;
3722 pindexBestHeader = NULL;
3724 mapOrphanTransactions.clear();
3725 mapOrphanTransactionsByPrev.clear();
3727 mapBlocksUnlinked.clear();
3728 vinfoBlockFile.clear();
3730 nBlockSequenceId = 1;
3731 mapBlockSource.clear();
3732 mapBlocksInFlight.clear();
3733 nQueuedValidatedHeaders = 0;
3734 nPreferredDownload = 0;
3735 setDirtyBlockIndex.clear();
3736 setDirtyFileInfo.clear();
3737 mapNodeState.clear();
3738 recentRejects.reset(NULL);
3740 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3741 delete entry.second;
3743 mapBlockIndex.clear();
3744 fHavePruned = false;
3747 bool LoadBlockIndex()
3749 // Load block index from databases
3750 if (!fReindex && !LoadBlockIndexDB())
3756 bool InitBlockIndex() {
3757 const CChainParams& chainparams = Params();
3760 // Initialize global variables that cannot be constructed at startup.
3761 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3763 // Check whether we're already initialized
3764 if (chainActive.Genesis() != NULL)
3767 // Use the provided setting for -txindex in the new database
3768 fTxIndex = GetBoolArg("-txindex", false);
3769 pblocktree->WriteFlag("txindex", fTxIndex);
3770 LogPrintf("Initializing databases...\n");
3772 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3775 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3776 // Start new block file
3777 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3778 CDiskBlockPos blockPos;
3779 CValidationState state;
3780 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3781 return error("LoadBlockIndex(): FindBlockPos failed");
3782 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3783 return error("LoadBlockIndex(): writing genesis block to disk failed");
3784 CBlockIndex *pindex = AddToBlockIndex(block);
3785 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3786 return error("LoadBlockIndex(): genesis block not accepted");
3787 if (!ActivateBestChain(state, &block))
3788 return error("LoadBlockIndex(): genesis block cannot be activated");
3789 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3790 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3791 } catch (const std::runtime_error& e) {
3792 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3801 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3803 const CChainParams& chainparams = Params();
3804 // Map of disk positions for blocks with unknown parent (only used for reindex)
3805 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3806 int64_t nStart = GetTimeMillis();
3810 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3811 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3812 uint64_t nRewind = blkdat.GetPos();
3813 while (!blkdat.eof()) {
3814 boost::this_thread::interruption_point();
3816 blkdat.SetPos(nRewind);
3817 nRewind++; // start one byte further next time, in case of failure
3818 blkdat.SetLimit(); // remove former limit
3819 unsigned int nSize = 0;
3822 unsigned char buf[MESSAGE_START_SIZE];
3823 blkdat.FindByte(Params().MessageStart()[0]);
3824 nRewind = blkdat.GetPos()+1;
3825 blkdat >> FLATDATA(buf);
3826 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3830 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3832 } catch (const std::exception&) {
3833 // no valid block header found; don't complain
3838 uint64_t nBlockPos = blkdat.GetPos();
3840 dbp->nPos = nBlockPos;
3841 blkdat.SetLimit(nBlockPos + nSize);
3842 blkdat.SetPos(nBlockPos);
3845 nRewind = blkdat.GetPos();
3847 // detect out of order blocks, and store them for later
3848 uint256 hash = block.GetHash();
3849 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3850 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3851 block.hashPrevBlock.ToString());
3853 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3857 // process in case the block isn't known yet
3858 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3859 CValidationState state;
3860 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3862 if (state.IsError())
3864 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3865 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3868 // Recursively process earlier encountered successors of this block
3869 deque<uint256> queue;
3870 queue.push_back(hash);
3871 while (!queue.empty()) {
3872 uint256 head = queue.front();
3874 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3875 while (range.first != range.second) {
3876 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3877 if (ReadBlockFromDisk(block, it->second))
3879 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3881 CValidationState dummy;
3882 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3885 queue.push_back(block.GetHash());
3889 mapBlocksUnknownParent.erase(it);
3892 } catch (const std::exception& e) {
3893 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3896 } catch (const std::runtime_error& e) {
3897 AbortNode(std::string("System error: ") + e.what());
3900 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3904 void static CheckBlockIndex()
3906 const Consensus::Params& consensusParams = Params().GetConsensus();
3907 if (!fCheckBlockIndex) {
3913 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3914 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3915 // iterating the block tree require that chainActive has been initialized.)
3916 if (chainActive.Height() < 0) {
3917 assert(mapBlockIndex.size() <= 1);
3921 // Build forward-pointing map of the entire block tree.
3922 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3923 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3924 forward.insert(std::make_pair(it->second->pprev, it->second));
3927 assert(forward.size() == mapBlockIndex.size());
3929 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3930 CBlockIndex *pindex = rangeGenesis.first->second;
3931 rangeGenesis.first++;
3932 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3934 // Iterate over the entire block tree, using depth-first search.
3935 // Along the way, remember whether there are blocks on the path from genesis
3936 // block being explored which are the first to have certain properties.
3939 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3940 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3941 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3942 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3943 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3944 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3945 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3946 while (pindex != NULL) {
3948 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3949 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3950 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3951 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3952 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3953 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3954 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3956 // Begin: actual consistency checks.
3957 if (pindex->pprev == NULL) {
3958 // Genesis block checks.
3959 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3960 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3962 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3963 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3964 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3966 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3967 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3968 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3970 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3971 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3973 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3974 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3975 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3976 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3977 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3978 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3979 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.
3980 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3981 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3982 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3983 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3984 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3985 if (pindexFirstInvalid == NULL) {
3986 // Checks for not-invalid blocks.
3987 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3989 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3990 if (pindexFirstInvalid == NULL) {
3991 // If this block sorts at least as good as the current tip and
3992 // is valid and we have all data for its parents, it must be in
3993 // setBlockIndexCandidates. chainActive.Tip() must also be there
3994 // even if some data has been pruned.
3995 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3996 assert(setBlockIndexCandidates.count(pindex));
3998 // If some parent is missing, then it could be that this block was in
3999 // setBlockIndexCandidates but had to be removed because of the missing data.
4000 // In this case it must be in mapBlocksUnlinked -- see test below.
4002 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4003 assert(setBlockIndexCandidates.count(pindex) == 0);
4005 // Check whether this block is in mapBlocksUnlinked.
4006 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4007 bool foundInUnlinked = false;
4008 while (rangeUnlinked.first != rangeUnlinked.second) {
4009 assert(rangeUnlinked.first->first == pindex->pprev);
4010 if (rangeUnlinked.first->second == pindex) {
4011 foundInUnlinked = true;
4014 rangeUnlinked.first++;
4016 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4017 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4018 assert(foundInUnlinked);
4020 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4021 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4022 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4023 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4024 assert(fHavePruned); // We must have pruned.
4025 // This block may have entered mapBlocksUnlinked if:
4026 // - it has a descendant that at some point had more work than the
4028 // - we tried switching to that descendant but were missing
4029 // data for some intermediate block between chainActive and the
4031 // So if this block is itself better than chainActive.Tip() and it wasn't in
4032 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4033 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4034 if (pindexFirstInvalid == NULL) {
4035 assert(foundInUnlinked);
4039 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4040 // End: actual consistency checks.
4042 // Try descending into the first subnode.
4043 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4044 if (range.first != range.second) {
4045 // A subnode was found.
4046 pindex = range.first->second;
4050 // This is a leaf node.
4051 // Move upwards until we reach a node of which we have not yet visited the last child.
4053 // We are going to either move to a parent or a sibling of pindex.
4054 // If pindex was the first with a certain property, unset the corresponding variable.
4055 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4056 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4057 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4058 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4059 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4060 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4061 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4063 CBlockIndex* pindexPar = pindex->pprev;
4064 // Find which child we just visited.
4065 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4066 while (rangePar.first->second != pindex) {
4067 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4070 // Proceed to the next one.
4072 if (rangePar.first != rangePar.second) {
4073 // Move to the sibling.
4074 pindex = rangePar.first->second;
4085 // Check that we actually traversed the entire map.
4086 assert(nNodes == forward.size());
4089 //////////////////////////////////////////////////////////////////////////////
4094 std::string GetWarnings(const std::string& strFor)
4097 string strStatusBar;
4100 if (!CLIENT_VERSION_IS_RELEASE)
4101 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4103 if (GetBoolArg("-testsafemode", false))
4104 strStatusBar = strRPC = "testsafemode enabled";
4106 // Misc warnings like out of disk space and clock is wrong
4107 if (strMiscWarning != "")
4110 strStatusBar = strMiscWarning;
4113 if (fLargeWorkForkFound)
4116 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4118 else if (fLargeWorkInvalidChainFound)
4121 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.");
4127 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4129 const CAlert& alert = item.second;
4130 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4132 nPriority = alert.nPriority;
4133 strStatusBar = alert.strStatusBar;
4134 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4135 strRPC = alert.strRPCError;
4141 if (strFor == "statusbar")
4142 return strStatusBar;
4143 else if (strFor == "rpc")
4145 assert(!"GetWarnings(): invalid parameter");
4156 //////////////////////////////////////////////////////////////////////////////
4162 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4168 assert(recentRejects);
4169 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4171 // If the chain tip has changed previously rejected transactions
4172 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4173 // or a double-spend. Reset the rejects filter and give those
4174 // txs a second chance.
4175 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4176 recentRejects->reset();
4179 return recentRejects->contains(inv.hash) ||
4180 mempool.exists(inv.hash) ||
4181 mapOrphanTransactions.count(inv.hash) ||
4182 pcoinsTip->HaveCoins(inv.hash);
4185 return mapBlockIndex.count(inv.hash);
4187 // Don't know what it is, just say we already got one
4191 void static ProcessGetData(CNode* pfrom)
4193 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4195 vector<CInv> vNotFound;
4199 while (it != pfrom->vRecvGetData.end()) {
4200 // Don't bother if send buffer is too full to respond anyway
4201 if (pfrom->nSendSize >= SendBufferSize())
4204 const CInv &inv = *it;
4206 boost::this_thread::interruption_point();
4209 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4212 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4213 if (mi != mapBlockIndex.end())
4215 if (chainActive.Contains(mi->second)) {
4218 static const int nOneMonth = 30 * 24 * 60 * 60;
4219 // To prevent fingerprinting attacks, only send blocks outside of the active
4220 // chain if they are valid, and no more than a month older (both in time, and in
4221 // best equivalent proof of work) than the best header chain we know about.
4222 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4223 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4224 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4226 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4230 // Pruned nodes may have deleted the block, so check whether
4231 // it's available before trying to send.
4232 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4234 // Send block from disk
4236 if (!ReadBlockFromDisk(block, (*mi).second))
4237 assert(!"cannot load block from disk");
4238 if (inv.type == MSG_BLOCK)
4239 pfrom->PushMessage("block", block);
4240 else // MSG_FILTERED_BLOCK)
4242 LOCK(pfrom->cs_filter);
4245 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4246 pfrom->PushMessage("merkleblock", merkleBlock);
4247 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4248 // This avoids hurting performance by pointlessly requiring a round-trip
4249 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4250 // they must either disconnect and retry or request the full block.
4251 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4252 // however we MUST always provide at least what the remote peer needs
4253 typedef std::pair<unsigned int, uint256> PairType;
4254 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4255 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4256 pfrom->PushMessage("tx", block.vtx[pair.first]);
4262 // Trigger the peer node to send a getblocks request for the next batch of inventory
4263 if (inv.hash == pfrom->hashContinue)
4265 // Bypass PushInventory, this must send even if redundant,
4266 // and we want it right after the last block so they don't
4267 // wait for other stuff first.
4269 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4270 pfrom->PushMessage("inv", vInv);
4271 pfrom->hashContinue.SetNull();
4275 else if (inv.IsKnownType())
4277 // Send stream from relay memory
4278 bool pushed = false;
4281 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4282 if (mi != mapRelay.end()) {
4283 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4287 if (!pushed && inv.type == MSG_TX) {
4289 if (mempool.lookup(inv.hash, tx)) {
4290 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4293 pfrom->PushMessage("tx", ss);
4298 vNotFound.push_back(inv);
4302 // Track requests for our stuff.
4303 GetMainSignals().Inventory(inv.hash);
4305 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4310 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4312 if (!vNotFound.empty()) {
4313 // Let the peer know that we didn't find what it asked for, so it doesn't
4314 // have to wait around forever. Currently only SPV clients actually care
4315 // about this message: it's needed when they are recursively walking the
4316 // dependencies of relevant unconfirmed transactions. SPV clients want to
4317 // do that because they want to know about (and store and rebroadcast and
4318 // risk analyze) the dependencies of transactions relevant to them, without
4319 // having to download the entire memory pool.
4320 pfrom->PushMessage("notfound", vNotFound);
4324 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4326 const CChainParams& chainparams = Params();
4327 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4328 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4330 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4337 if (strCommand == "version")
4339 // Each connection can only send one version message
4340 if (pfrom->nVersion != 0)
4342 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4343 Misbehaving(pfrom->GetId(), 1);
4350 uint64_t nNonce = 1;
4351 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4352 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4354 // disconnect from peers older than this proto version
4355 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4356 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4357 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4358 pfrom->fDisconnect = true;
4362 if (pfrom->nVersion == 10300)
4363 pfrom->nVersion = 300;
4365 vRecv >> addrFrom >> nNonce;
4366 if (!vRecv.empty()) {
4367 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4368 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4371 vRecv >> pfrom->nStartingHeight;
4373 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4375 pfrom->fRelayTxes = true;
4377 // Disconnect if we connected to ourself
4378 if (nNonce == nLocalHostNonce && nNonce > 1)
4380 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4381 pfrom->fDisconnect = true;
4385 pfrom->addrLocal = addrMe;
4386 if (pfrom->fInbound && addrMe.IsRoutable())
4391 // Be shy and don't send version until we hear
4392 if (pfrom->fInbound)
4393 pfrom->PushVersion();
4395 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4397 // Potentially mark this peer as a preferred download peer.
4398 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4401 pfrom->PushMessage("verack");
4402 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4404 if (!pfrom->fInbound)
4406 // Advertise our address
4407 if (fListen && !IsInitialBlockDownload())
4409 CAddress addr = GetLocalAddress(&pfrom->addr);
4410 if (addr.IsRoutable())
4412 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4413 pfrom->PushAddress(addr);
4414 } else if (IsPeerAddrLocalGood(pfrom)) {
4415 addr.SetIP(pfrom->addrLocal);
4416 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4417 pfrom->PushAddress(addr);
4421 // Get recent addresses
4422 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4424 pfrom->PushMessage("getaddr");
4425 pfrom->fGetAddr = true;
4427 addrman.Good(pfrom->addr);
4429 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4431 addrman.Add(addrFrom, addrFrom);
4432 addrman.Good(addrFrom);
4439 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4440 item.second.RelayTo(pfrom);
4443 pfrom->fSuccessfullyConnected = true;
4447 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4449 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4450 pfrom->cleanSubVer, pfrom->nVersion,
4451 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4454 int64_t nTimeOffset = nTime - GetTime();
4455 pfrom->nTimeOffset = nTimeOffset;
4456 AddTimeData(pfrom->addr, nTimeOffset);
4460 else if (pfrom->nVersion == 0)
4462 // Must have a version message before anything else
4463 Misbehaving(pfrom->GetId(), 1);
4468 else if (strCommand == "verack")
4470 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4472 // Mark this node as currently connected, so we update its timestamp later.
4473 if (pfrom->fNetworkNode) {
4475 State(pfrom->GetId())->fCurrentlyConnected = true;
4480 else if (strCommand == "addr")
4482 vector<CAddress> vAddr;
4485 // Don't want addr from older versions unless seeding
4486 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4488 if (vAddr.size() > 1000)
4490 Misbehaving(pfrom->GetId(), 20);
4491 return error("message addr size() = %u", vAddr.size());
4494 // Store the new addresses
4495 vector<CAddress> vAddrOk;
4496 int64_t nNow = GetAdjustedTime();
4497 int64_t nSince = nNow - 10 * 60;
4498 BOOST_FOREACH(CAddress& addr, vAddr)
4500 boost::this_thread::interruption_point();
4502 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4503 addr.nTime = nNow - 5 * 24 * 60 * 60;
4504 pfrom->AddAddressKnown(addr);
4505 bool fReachable = IsReachable(addr);
4506 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4508 // Relay to a limited number of other nodes
4511 // Use deterministic randomness to send to the same nodes for 24 hours
4512 // at a time so the addrKnowns of the chosen nodes prevent repeats
4513 static uint256 hashSalt;
4514 if (hashSalt.IsNull())
4515 hashSalt = GetRandHash();
4516 uint64_t hashAddr = addr.GetHash();
4517 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4518 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4519 multimap<uint256, CNode*> mapMix;
4520 BOOST_FOREACH(CNode* pnode, vNodes)
4522 if (pnode->nVersion < CADDR_TIME_VERSION)
4524 unsigned int nPointer;
4525 memcpy(&nPointer, &pnode, sizeof(nPointer));
4526 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4527 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4528 mapMix.insert(make_pair(hashKey, pnode));
4530 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4531 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4532 ((*mi).second)->PushAddress(addr);
4535 // Do not store addresses outside our network
4537 vAddrOk.push_back(addr);
4539 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4540 if (vAddr.size() < 1000)
4541 pfrom->fGetAddr = false;
4542 if (pfrom->fOneShot)
4543 pfrom->fDisconnect = true;
4547 else if (strCommand == "inv")
4551 if (vInv.size() > MAX_INV_SZ)
4553 Misbehaving(pfrom->GetId(), 20);
4554 return error("message inv size() = %u", vInv.size());
4559 std::vector<CInv> vToFetch;
4561 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4563 const CInv &inv = vInv[nInv];
4565 boost::this_thread::interruption_point();
4566 pfrom->AddInventoryKnown(inv);
4568 bool fAlreadyHave = AlreadyHave(inv);
4569 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4571 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4574 if (inv.type == MSG_BLOCK) {
4575 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4576 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4577 // First request the headers preceding the announced block. In the normal fully-synced
4578 // case where a new block is announced that succeeds the current tip (no reorganization),
4579 // there are no such headers.
4580 // Secondly, and only when we are close to being synced, we request the announced block directly,
4581 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4582 // time the block arrives, the header chain leading up to it is already validated. Not
4583 // doing this will result in the received block being rejected as an orphan in case it is
4584 // not a direct successor.
4585 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4586 CNodeState *nodestate = State(pfrom->GetId());
4587 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4588 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4589 vToFetch.push_back(inv);
4590 // Mark block as in flight already, even though the actual "getdata" message only goes out
4591 // later (within the same cs_main lock, though).
4592 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4594 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4598 // Track requests for our stuff
4599 GetMainSignals().Inventory(inv.hash);
4601 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4602 Misbehaving(pfrom->GetId(), 50);
4603 return error("send buffer size() = %u", pfrom->nSendSize);
4607 if (!vToFetch.empty())
4608 pfrom->PushMessage("getdata", vToFetch);
4612 else if (strCommand == "getdata")
4616 if (vInv.size() > MAX_INV_SZ)
4618 Misbehaving(pfrom->GetId(), 20);
4619 return error("message getdata size() = %u", vInv.size());
4622 if (fDebug || (vInv.size() != 1))
4623 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4625 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4626 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4628 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4629 ProcessGetData(pfrom);
4633 else if (strCommand == "getblocks")
4635 CBlockLocator locator;
4637 vRecv >> locator >> hashStop;
4641 // Find the last block the caller has in the main chain
4642 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4644 // Send the rest of the chain
4646 pindex = chainActive.Next(pindex);
4648 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4649 for (; pindex; pindex = chainActive.Next(pindex))
4651 if (pindex->GetBlockHash() == hashStop)
4653 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4656 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4659 // When this block is requested, we'll send an inv that'll
4660 // trigger the peer to getblocks the next batch of inventory.
4661 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4662 pfrom->hashContinue = pindex->GetBlockHash();
4669 else if (strCommand == "getheaders")
4671 CBlockLocator locator;
4673 vRecv >> locator >> hashStop;
4677 if (IsInitialBlockDownload())
4680 CBlockIndex* pindex = NULL;
4681 if (locator.IsNull())
4683 // If locator is null, return the hashStop block
4684 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4685 if (mi == mapBlockIndex.end())
4687 pindex = (*mi).second;
4691 // Find the last block the caller has in the main chain
4692 pindex = FindForkInGlobalIndex(chainActive, locator);
4694 pindex = chainActive.Next(pindex);
4697 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4698 vector<CBlock> vHeaders;
4699 int nLimit = MAX_HEADERS_RESULTS;
4700 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4701 for (; pindex; pindex = chainActive.Next(pindex))
4703 vHeaders.push_back(pindex->GetBlockHeader());
4704 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4707 pfrom->PushMessage("headers", vHeaders);
4711 else if (strCommand == "tx")
4713 vector<uint256> vWorkQueue;
4714 vector<uint256> vEraseQueue;
4718 CInv inv(MSG_TX, tx.GetHash());
4719 pfrom->AddInventoryKnown(inv);
4723 bool fMissingInputs = false;
4724 CValidationState state;
4726 pfrom->setAskFor.erase(inv.hash);
4727 mapAlreadyAskedFor.erase(inv);
4729 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4731 mempool.check(pcoinsTip);
4732 RelayTransaction(tx);
4733 vWorkQueue.push_back(inv.hash);
4735 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4736 pfrom->id, pfrom->cleanSubVer,
4737 tx.GetHash().ToString(),
4738 mempool.mapTx.size());
4740 // Recursively process any orphan transactions that depended on this one
4741 set<NodeId> setMisbehaving;
4742 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4744 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4745 if (itByPrev == mapOrphanTransactionsByPrev.end())
4747 for (set<uint256>::iterator mi = itByPrev->second.begin();
4748 mi != itByPrev->second.end();
4751 const uint256& orphanHash = *mi;
4752 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4753 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4754 bool fMissingInputs2 = false;
4755 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4756 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4757 // anyone relaying LegitTxX banned)
4758 CValidationState stateDummy;
4761 if (setMisbehaving.count(fromPeer))
4763 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4765 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4766 RelayTransaction(orphanTx);
4767 vWorkQueue.push_back(orphanHash);
4768 vEraseQueue.push_back(orphanHash);
4770 else if (!fMissingInputs2)
4773 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4775 // Punish peer that gave us an invalid orphan tx
4776 Misbehaving(fromPeer, nDos);
4777 setMisbehaving.insert(fromPeer);
4778 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4780 // Has inputs but not accepted to mempool
4781 // Probably non-standard or insufficient fee/priority
4782 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4783 vEraseQueue.push_back(orphanHash);
4784 assert(recentRejects);
4785 recentRejects->insert(orphanHash);
4787 mempool.check(pcoinsTip);
4791 BOOST_FOREACH(uint256 hash, vEraseQueue)
4792 EraseOrphanTx(hash);
4794 // TODO: currently, prohibit joinsplits from entering mapOrphans
4795 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4797 AddOrphanTx(tx, pfrom->GetId());
4799 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4800 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4801 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4803 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4805 assert(recentRejects);
4806 recentRejects->insert(tx.GetHash());
4808 if (pfrom->fWhitelisted) {
4809 // Always relay transactions received from whitelisted peers, even
4810 // if they were already in the mempool or rejected from it due
4811 // to policy, allowing the node to function as a gateway for
4812 // nodes hidden behind it.
4814 // Never relay transactions that we would assign a non-zero DoS
4815 // score for, as we expect peers to do the same with us in that
4818 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4819 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4820 RelayTransaction(tx);
4822 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4823 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4828 if (state.IsInvalid(nDoS))
4830 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4831 pfrom->id, pfrom->cleanSubVer,
4832 state.GetRejectReason());
4833 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4834 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4836 Misbehaving(pfrom->GetId(), nDoS);
4841 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4843 std::vector<CBlockHeader> headers;
4845 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4846 unsigned int nCount = ReadCompactSize(vRecv);
4847 if (nCount > MAX_HEADERS_RESULTS) {
4848 Misbehaving(pfrom->GetId(), 20);
4849 return error("headers message size = %u", nCount);
4851 headers.resize(nCount);
4852 for (unsigned int n = 0; n < nCount; n++) {
4853 vRecv >> headers[n];
4854 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4860 // Nothing interesting. Stop asking this peers for more headers.
4864 CBlockIndex *pindexLast = NULL;
4865 BOOST_FOREACH(const CBlockHeader& header, headers) {
4866 CValidationState state;
4867 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4868 Misbehaving(pfrom->GetId(), 20);
4869 return error("non-continuous headers sequence");
4871 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4873 if (state.IsInvalid(nDoS)) {
4875 Misbehaving(pfrom->GetId(), nDoS);
4876 return error("invalid header received");
4882 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4884 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4885 // Headers message had its maximum size; the peer may have more headers.
4886 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4887 // from there instead.
4888 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4889 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4895 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4900 CInv inv(MSG_BLOCK, block.GetHash());
4901 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4903 pfrom->AddInventoryKnown(inv);
4905 CValidationState state;
4906 // Process all blocks from whitelisted peers, even if not requested,
4907 // unless we're still syncing with the network.
4908 // Such an unrequested block may still be processed, subject to the
4909 // conditions in AcceptBlock().
4910 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4911 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4913 if (state.IsInvalid(nDoS)) {
4914 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4915 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4918 Misbehaving(pfrom->GetId(), nDoS);
4925 // This asymmetric behavior for inbound and outbound connections was introduced
4926 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4927 // to users' AddrMan and later request them by sending getaddr messages.
4928 // Making nodes which are behind NAT and can only make outgoing connections ignore
4929 // the getaddr message mitigates the attack.
4930 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4932 // Only send one GetAddr response per connection to reduce resource waste
4933 // and discourage addr stamping of INV announcements.
4934 if (pfrom->fSentAddr) {
4935 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4938 pfrom->fSentAddr = true;
4940 pfrom->vAddrToSend.clear();
4941 vector<CAddress> vAddr = addrman.GetAddr();
4942 BOOST_FOREACH(const CAddress &addr, vAddr)
4943 pfrom->PushAddress(addr);
4947 else if (strCommand == "mempool")
4949 LOCK2(cs_main, pfrom->cs_filter);
4951 std::vector<uint256> vtxid;
4952 mempool.queryHashes(vtxid);
4954 BOOST_FOREACH(uint256& hash, vtxid) {
4955 CInv inv(MSG_TX, hash);
4957 bool fInMemPool = mempool.lookup(hash, tx);
4958 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4959 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4961 vInv.push_back(inv);
4962 if (vInv.size() == MAX_INV_SZ) {
4963 pfrom->PushMessage("inv", vInv);
4967 if (vInv.size() > 0)
4968 pfrom->PushMessage("inv", vInv);
4972 else if (strCommand == "ping")
4974 if (pfrom->nVersion > BIP0031_VERSION)
4978 // Echo the message back with the nonce. This allows for two useful features:
4980 // 1) A remote node can quickly check if the connection is operational
4981 // 2) Remote nodes can measure the latency of the network thread. If this node
4982 // is overloaded it won't respond to pings quickly and the remote node can
4983 // avoid sending us more work, like chain download requests.
4985 // The nonce stops the remote getting confused between different pings: without
4986 // it, if the remote node sends a ping once per second and this node takes 5
4987 // seconds to respond to each, the 5th ping the remote sends would appear to
4988 // return very quickly.
4989 pfrom->PushMessage("pong", nonce);
4994 else if (strCommand == "pong")
4996 int64_t pingUsecEnd = nTimeReceived;
4998 size_t nAvail = vRecv.in_avail();
4999 bool bPingFinished = false;
5000 std::string sProblem;
5002 if (nAvail >= sizeof(nonce)) {
5005 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5006 if (pfrom->nPingNonceSent != 0) {
5007 if (nonce == pfrom->nPingNonceSent) {
5008 // Matching pong received, this ping is no longer outstanding
5009 bPingFinished = true;
5010 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5011 if (pingUsecTime > 0) {
5012 // Successful ping time measurement, replace previous
5013 pfrom->nPingUsecTime = pingUsecTime;
5014 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5016 // This should never happen
5017 sProblem = "Timing mishap";
5020 // Nonce mismatches are normal when pings are overlapping
5021 sProblem = "Nonce mismatch";
5023 // This is most likely a bug in another implementation somewhere; cancel this ping
5024 bPingFinished = true;
5025 sProblem = "Nonce zero";
5029 sProblem = "Unsolicited pong without ping";
5032 // This is most likely a bug in another implementation somewhere; cancel this ping
5033 bPingFinished = true;
5034 sProblem = "Short payload";
5037 if (!(sProblem.empty())) {
5038 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5042 pfrom->nPingNonceSent,
5046 if (bPingFinished) {
5047 pfrom->nPingNonceSent = 0;
5052 else if (fAlerts && strCommand == "alert")
5057 uint256 alertHash = alert.GetHash();
5058 if (pfrom->setKnown.count(alertHash) == 0)
5060 if (alert.ProcessAlert(Params().AlertKey()))
5063 pfrom->setKnown.insert(alertHash);
5066 BOOST_FOREACH(CNode* pnode, vNodes)
5067 alert.RelayTo(pnode);
5071 // Small DoS penalty so peers that send us lots of
5072 // duplicate/expired/invalid-signature/whatever alerts
5073 // eventually get banned.
5074 // This isn't a Misbehaving(100) (immediate ban) because the
5075 // peer might be an older or different implementation with
5076 // a different signature key, etc.
5077 Misbehaving(pfrom->GetId(), 10);
5083 else if (strCommand == "filterload")
5085 CBloomFilter filter;
5088 if (!filter.IsWithinSizeConstraints())
5089 // There is no excuse for sending a too-large filter
5090 Misbehaving(pfrom->GetId(), 100);
5093 LOCK(pfrom->cs_filter);
5094 delete pfrom->pfilter;
5095 pfrom->pfilter = new CBloomFilter(filter);
5096 pfrom->pfilter->UpdateEmptyFull();
5098 pfrom->fRelayTxes = true;
5102 else if (strCommand == "filteradd")
5104 vector<unsigned char> vData;
5107 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5108 // and thus, the maximum size any matched object can have) in a filteradd message
5109 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5111 Misbehaving(pfrom->GetId(), 100);
5113 LOCK(pfrom->cs_filter);
5115 pfrom->pfilter->insert(vData);
5117 Misbehaving(pfrom->GetId(), 100);
5122 else if (strCommand == "filterclear")
5124 LOCK(pfrom->cs_filter);
5125 delete pfrom->pfilter;
5126 pfrom->pfilter = new CBloomFilter();
5127 pfrom->fRelayTxes = true;
5131 else if (strCommand == "reject")
5135 string strMsg; unsigned char ccode; string strReason;
5136 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5139 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5141 if (strMsg == "block" || strMsg == "tx")
5145 ss << ": hash " << hash.ToString();
5147 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5148 } catch (const std::ios_base::failure&) {
5149 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5150 LogPrint("net", "Unparseable reject message received\n");
5155 else if (strCommand == "notfound") {
5156 // We do not care about the NOTFOUND message, but logging an Unknown Command
5157 // message would be undesirable as we transmit it ourselves.
5161 // Ignore unknown commands for extensibility
5162 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5170 // requires LOCK(cs_vRecvMsg)
5171 bool ProcessMessages(CNode* pfrom)
5174 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5178 // (4) message start
5186 if (!pfrom->vRecvGetData.empty())
5187 ProcessGetData(pfrom);
5189 // this maintains the order of responses
5190 if (!pfrom->vRecvGetData.empty()) return fOk;
5192 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5193 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5194 // Don't bother if send buffer is too full to respond anyway
5195 if (pfrom->nSendSize >= SendBufferSize())
5199 CNetMessage& msg = *it;
5202 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5203 // msg.hdr.nMessageSize, msg.vRecv.size(),
5204 // msg.complete() ? "Y" : "N");
5206 // end, if an incomplete message is found
5207 if (!msg.complete())
5210 // at this point, any failure means we can delete the current message
5213 // Scan for message start
5214 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5215 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5221 CMessageHeader& hdr = msg.hdr;
5222 if (!hdr.IsValid(Params().MessageStart()))
5224 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5227 string strCommand = hdr.GetCommand();
5230 unsigned int nMessageSize = hdr.nMessageSize;
5233 CDataStream& vRecv = msg.vRecv;
5234 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5235 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5236 if (nChecksum != hdr.nChecksum)
5238 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5239 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5247 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5248 boost::this_thread::interruption_point();
5250 catch (const std::ios_base::failure& e)
5252 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5253 if (strstr(e.what(), "end of data"))
5255 // Allow exceptions from under-length message on vRecv
5256 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());
5258 else if (strstr(e.what(), "size too large"))
5260 // Allow exceptions from over-long size
5261 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5265 PrintExceptionContinue(&e, "ProcessMessages()");
5268 catch (const boost::thread_interrupted&) {
5271 catch (const std::exception& e) {
5272 PrintExceptionContinue(&e, "ProcessMessages()");
5274 PrintExceptionContinue(NULL, "ProcessMessages()");
5278 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5283 // In case the connection got shut down, its receive buffer was wiped
5284 if (!pfrom->fDisconnect)
5285 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5291 bool SendMessages(CNode* pto, bool fSendTrickle)
5293 const Consensus::Params& consensusParams = Params().GetConsensus();
5295 // Don't send anything until we get its version message
5296 if (pto->nVersion == 0)
5302 bool pingSend = false;
5303 if (pto->fPingQueued) {
5304 // RPC ping request by user
5307 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5308 // Ping automatically sent as a latency probe & keepalive.
5313 while (nonce == 0) {
5314 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5316 pto->fPingQueued = false;
5317 pto->nPingUsecStart = GetTimeMicros();
5318 if (pto->nVersion > BIP0031_VERSION) {
5319 pto->nPingNonceSent = nonce;
5320 pto->PushMessage("ping", nonce);
5322 // Peer is too old to support ping command with nonce, pong will never arrive.
5323 pto->nPingNonceSent = 0;
5324 pto->PushMessage("ping");
5328 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5332 // Address refresh broadcast
5333 static int64_t nLastRebroadcast;
5334 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5337 BOOST_FOREACH(CNode* pnode, vNodes)
5339 // Periodically clear addrKnown to allow refresh broadcasts
5340 if (nLastRebroadcast)
5341 pnode->addrKnown.reset();
5343 // Rebroadcast our address
5344 AdvertizeLocal(pnode);
5346 if (!vNodes.empty())
5347 nLastRebroadcast = GetTime();
5355 vector<CAddress> vAddr;
5356 vAddr.reserve(pto->vAddrToSend.size());
5357 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5359 if (!pto->addrKnown.contains(addr.GetKey()))
5361 pto->addrKnown.insert(addr.GetKey());
5362 vAddr.push_back(addr);
5363 // receiver rejects addr messages larger than 1000
5364 if (vAddr.size() >= 1000)
5366 pto->PushMessage("addr", vAddr);
5371 pto->vAddrToSend.clear();
5373 pto->PushMessage("addr", vAddr);
5376 CNodeState &state = *State(pto->GetId());
5377 if (state.fShouldBan) {
5378 if (pto->fWhitelisted)
5379 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5381 pto->fDisconnect = true;
5382 if (pto->addr.IsLocal())
5383 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5386 CNode::Ban(pto->addr);
5389 state.fShouldBan = false;
5392 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5393 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5394 state.rejects.clear();
5397 if (pindexBestHeader == NULL)
5398 pindexBestHeader = chainActive.Tip();
5399 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.
5400 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5401 // Only actively request headers from a single peer, unless we're close to today.
5402 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5403 state.fSyncStarted = true;
5405 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5406 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5407 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5411 // Resend wallet transactions that haven't gotten in a block yet
5412 // Except during reindex, importing and IBD, when old wallet
5413 // transactions become unconfirmed and spams other nodes.
5414 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5416 GetMainSignals().Broadcast(nTimeBestReceived);
5420 // Message: inventory
5423 vector<CInv> vInvWait;
5425 LOCK(pto->cs_inventory);
5426 vInv.reserve(pto->vInventoryToSend.size());
5427 vInvWait.reserve(pto->vInventoryToSend.size());
5428 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5430 if (pto->setInventoryKnown.count(inv))
5433 // trickle out tx inv to protect privacy
5434 if (inv.type == MSG_TX && !fSendTrickle)
5436 // 1/4 of tx invs blast to all immediately
5437 static uint256 hashSalt;
5438 if (hashSalt.IsNull())
5439 hashSalt = GetRandHash();
5440 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5441 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5442 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5446 vInvWait.push_back(inv);
5451 // returns true if wasn't already contained in the set
5452 if (pto->setInventoryKnown.insert(inv).second)
5454 vInv.push_back(inv);
5455 if (vInv.size() >= 1000)
5457 pto->PushMessage("inv", vInv);
5462 pto->vInventoryToSend = vInvWait;
5465 pto->PushMessage("inv", vInv);
5467 // Detect whether we're stalling
5468 int64_t nNow = GetTimeMicros();
5469 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5470 // Stalling only triggers when the block download window cannot move. During normal steady state,
5471 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5472 // should only happen during initial block download.
5473 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5474 pto->fDisconnect = true;
5476 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5477 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5478 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5479 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5480 // to unreasonably increase our timeout.
5481 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5482 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5483 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5484 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5485 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5486 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5487 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5488 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5489 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5490 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5491 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5493 if (queuedBlock.nTimeDisconnect < nNow) {
5494 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5495 pto->fDisconnect = true;
5500 // Message: getdata (blocks)
5502 vector<CInv> vGetData;
5503 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5504 vector<CBlockIndex*> vToDownload;
5505 NodeId staller = -1;
5506 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5507 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5508 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5509 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5510 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5511 pindex->nHeight, pto->id);
5513 if (state.nBlocksInFlight == 0 && staller != -1) {
5514 if (State(staller)->nStallingSince == 0) {
5515 State(staller)->nStallingSince = nNow;
5516 LogPrint("net", "Stall started peer=%d\n", staller);
5522 // Message: getdata (non-blocks)
5524 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5526 const CInv& inv = (*pto->mapAskFor.begin()).second;
5527 if (!AlreadyHave(inv))
5530 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5531 vGetData.push_back(inv);
5532 if (vGetData.size() >= 1000)
5534 pto->PushMessage("getdata", vGetData);
5538 //If we're not going to ask, don't expect a response.
5539 pto->setAskFor.erase(inv.hash);
5541 pto->mapAskFor.erase(pto->mapAskFor.begin());
5543 if (!vGetData.empty())
5544 pto->PushMessage("getdata", vGetData);
5550 std::string CBlockFileInfo::ToString() const {
5551 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));
5562 BlockMap::iterator it1 = mapBlockIndex.begin();
5563 for (; it1 != mapBlockIndex.end(); it1++)
5564 delete (*it1).second;
5565 mapBlockIndex.clear();
5567 // orphan transactions
5568 mapOrphanTransactions.clear();
5569 mapOrphanTransactionsByPrev.clear();
5571 } instance_of_cmaincleanup;