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/upgrades.h"
17 #include "consensus/validation.h"
18 #include "deprecation.h"
20 #include "merkleblock.h"
25 #include "txmempool.h"
26 #include "ui_interface.h"
29 #include "utilmoneystr.h"
30 #include "validationinterface.h"
31 #include "wallet/asyncrpcoperation_sendmany.h"
32 #include "wallet/asyncrpcoperation_shieldcoinbase.h"
38 #include <boost/algorithm/string/replace.hpp>
39 #include <boost/filesystem.hpp>
40 #include <boost/filesystem/fstream.hpp>
41 #include <boost/math/distributions/poisson.hpp>
42 #include <boost/thread.hpp>
43 #include <boost/static_assert.hpp>
48 # error "Zcash cannot be compiled without assertions."
51 #include "librustzcash.h"
57 CCriticalSection cs_main;
59 BlockMap mapBlockIndex;
61 CBlockIndex *pindexBestHeader = NULL;
62 static int64_t nTimeBestReceived = 0;
63 CWaitableCriticalSection csBestBlock;
64 CConditionVariable cvBlockChange;
65 int nScriptCheckThreads = 0;
66 bool fExperimentalMode = false;
67 bool fImporting = false;
68 bool fReindex = false;
69 bool fTxIndex = false;
70 bool fHavePruned = false;
71 bool fPruneMode = false;
72 bool fIsBareMultisigStd = true;
73 bool fCheckBlockIndex = false;
74 bool fCheckpointsEnabled = true;
75 bool fCoinbaseEnforcedProtectionEnabled = true;
76 size_t nCoinCacheUsage = 5000 * 300;
77 uint64_t nPruneTarget = 0;
78 bool fAlerts = DEFAULT_ALERTS;
79 /* If the tip is older than this (in seconds), the node is considered to be in initial block download.
81 int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
83 unsigned int expiryDelta = DEFAULT_TX_EXPIRY_DELTA;
85 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
86 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
88 CTxMemPool mempool(::minRelayTxFee);
94 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
95 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
96 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
99 * Returns true if there are nRequired or more blocks of minVersion or above
100 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
102 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
103 static void CheckBlockIndex();
105 /** Constant stuff for coinbase transactions we create: */
106 CScript COINBASE_FLAGS;
108 const string strMessageMagic = "Zcash Signed Message:\n";
113 struct CBlockIndexWorkComparator
115 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
116 // First sort by most total work, ...
117 if (pa->nChainWork > pb->nChainWork) return false;
118 if (pa->nChainWork < pb->nChainWork) return true;
120 // ... then by earliest time received, ...
121 if (pa->nSequenceId < pb->nSequenceId) return false;
122 if (pa->nSequenceId > pb->nSequenceId) return true;
124 // Use pointer address as tie breaker (should only happen with blocks
125 // loaded from disk, as those all have id 0).
126 if (pa < pb) return false;
127 if (pa > pb) return true;
134 CBlockIndex *pindexBestInvalid;
137 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
138 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
139 * missing the data for the block.
141 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
142 /** Number of nodes with fSyncStarted. */
143 int nSyncStarted = 0;
144 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
145 * Pruned nodes may have entries where B is missing data.
147 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
149 CCriticalSection cs_LastBlockFile;
150 std::vector<CBlockFileInfo> vinfoBlockFile;
151 int nLastBlockFile = 0;
152 /** Global flag to indicate we should check to see if there are
153 * block/undo files that should be deleted. Set on startup
154 * or if we allocate more file space when we're in prune mode
156 bool fCheckForPruning = false;
159 * Every received block is assigned a unique and increasing identifier, so we
160 * know which one to give priority in case of a fork.
162 CCriticalSection cs_nBlockSequenceId;
163 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
164 uint32_t nBlockSequenceId = 1;
167 * Sources of received blocks, saved to be able to send them reject
168 * messages or ban them when processing happens afterwards. Protected by
171 map<uint256, NodeId> mapBlockSource;
174 * Filter for transactions that were recently rejected by
175 * AcceptToMemoryPool. These are not rerequested until the chain tip
176 * changes, at which point the entire filter is reset. Protected by
179 * Without this filter we'd be re-requesting txs from each of our peers,
180 * increasing bandwidth consumption considerably. For instance, with 100
181 * peers, half of which relay a tx we don't accept, that might be a 50x
182 * bandwidth increase. A flooding attacker attempting to roll-over the
183 * filter using minimum-sized, 60byte, transactions might manage to send
184 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
185 * two minute window to send invs to us.
187 * Decreasing the false positive rate is fairly cheap, so we pick one in a
188 * million to make it highly unlikely for users to have issues with this
193 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
194 uint256 hashRecentRejectsChainTip;
196 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
199 CBlockIndex *pindex; //! Optional.
200 int64_t nTime; //! Time of "getdata" request in microseconds.
201 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
202 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
204 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
206 /** Number of blocks in flight with validated headers. */
207 int nQueuedValidatedHeaders = 0;
209 /** Number of preferable block download peers. */
210 int nPreferredDownload = 0;
212 /** Dirty block index entries. */
213 set<CBlockIndex*> setDirtyBlockIndex;
215 /** Dirty block file entries. */
216 set<int> setDirtyFileInfo;
219 //////////////////////////////////////////////////////////////////////////////
221 // Registration of network node signals.
226 struct CBlockReject {
227 unsigned char chRejectCode;
228 string strRejectReason;
233 * Maintain validation-specific state about nodes, protected by cs_main, instead
234 * by CNode's own locks. This simplifies asynchronous operation, where
235 * processing of incoming data is done after the ProcessMessage call returns,
236 * and we're no longer holding the node's locks.
239 //! The peer's address
241 //! Whether we have a fully established connection.
242 bool fCurrentlyConnected;
243 //! Accumulated misbehaviour score for this peer.
245 //! Whether this peer should be disconnected and banned (unless whitelisted).
247 //! String name of this peer (debugging/logging purposes).
249 //! List of asynchronously-determined block rejections to notify this peer about.
250 std::vector<CBlockReject> rejects;
251 //! The best known block we know this peer has announced.
252 CBlockIndex *pindexBestKnownBlock;
253 //! The hash of the last unknown block this peer has announced.
254 uint256 hashLastUnknownBlock;
255 //! The last full block we both have.
256 CBlockIndex *pindexLastCommonBlock;
257 //! Whether we've started headers synchronization with this peer.
259 //! Since when we're stalling block download progress (in microseconds), or 0.
260 int64_t nStallingSince;
261 list<QueuedBlock> vBlocksInFlight;
263 int nBlocksInFlightValidHeaders;
264 //! Whether we consider this a preferred download peer.
265 bool fPreferredDownload;
268 fCurrentlyConnected = false;
271 pindexBestKnownBlock = NULL;
272 hashLastUnknownBlock.SetNull();
273 pindexLastCommonBlock = NULL;
274 fSyncStarted = false;
277 nBlocksInFlightValidHeaders = 0;
278 fPreferredDownload = false;
282 /** Map maintaining per-node state. Requires cs_main. */
283 map<NodeId, CNodeState> mapNodeState;
286 CNodeState *State(NodeId pnode) {
287 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
288 if (it == mapNodeState.end())
296 return chainActive.Height();
299 void UpdatePreferredDownload(CNode* node, CNodeState* state)
301 nPreferredDownload -= state->fPreferredDownload;
303 // Whether this node should be marked as a preferred download node.
304 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
306 nPreferredDownload += state->fPreferredDownload;
309 // Returns time at which to timeout block request (nTime in microseconds)
310 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
312 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
315 void InitializeNode(NodeId nodeid, const CNode *pnode) {
317 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
318 state.name = pnode->addrName;
319 state.address = pnode->addr;
322 void FinalizeNode(NodeId nodeid) {
324 CNodeState *state = State(nodeid);
326 if (state->fSyncStarted)
329 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
330 AddressCurrentlyConnected(state->address);
333 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
334 mapBlocksInFlight.erase(entry.hash);
335 EraseOrphansFor(nodeid);
336 nPreferredDownload -= state->fPreferredDownload;
338 mapNodeState.erase(nodeid);
342 // Returns a bool indicating whether we requested this block.
343 bool MarkBlockAsReceived(const uint256& hash) {
344 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
345 if (itInFlight != mapBlocksInFlight.end()) {
346 CNodeState *state = State(itInFlight->second.first);
347 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
348 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
349 state->vBlocksInFlight.erase(itInFlight->second.second);
350 state->nBlocksInFlight--;
351 state->nStallingSince = 0;
352 mapBlocksInFlight.erase(itInFlight);
359 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
360 CNodeState *state = State(nodeid);
361 assert(state != NULL);
363 // Make sure it's not listed somewhere already.
364 MarkBlockAsReceived(hash);
366 int64_t nNow = GetTimeMicros();
367 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
368 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
369 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
370 state->nBlocksInFlight++;
371 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
372 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
375 /** Check whether the last unknown block a peer advertized is not yet known. */
376 void ProcessBlockAvailability(NodeId nodeid) {
377 CNodeState *state = State(nodeid);
378 assert(state != NULL);
380 if (!state->hashLastUnknownBlock.IsNull()) {
381 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
382 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
383 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
384 state->pindexBestKnownBlock = itOld->second;
385 state->hashLastUnknownBlock.SetNull();
390 /** Update tracking information about which blocks a peer is assumed to have. */
391 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
392 CNodeState *state = State(nodeid);
393 assert(state != NULL);
395 ProcessBlockAvailability(nodeid);
397 BlockMap::iterator it = mapBlockIndex.find(hash);
398 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
399 // An actually better block was announced.
400 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
401 state->pindexBestKnownBlock = it->second;
403 // An unknown block was announced; just assume that the latest one is the best one.
404 state->hashLastUnknownBlock = hash;
408 /** Find the last common ancestor two blocks have.
409 * Both pa and pb must be non-NULL. */
410 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
411 if (pa->nHeight > pb->nHeight) {
412 pa = pa->GetAncestor(pb->nHeight);
413 } else if (pb->nHeight > pa->nHeight) {
414 pb = pb->GetAncestor(pa->nHeight);
417 while (pa != pb && pa && pb) {
422 // Eventually all chain branches meet at the genesis block.
427 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
428 * at most count entries. */
429 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
433 vBlocks.reserve(vBlocks.size() + count);
434 CNodeState *state = State(nodeid);
435 assert(state != NULL);
437 // Make sure pindexBestKnownBlock is up to date, we'll need it.
438 ProcessBlockAvailability(nodeid);
440 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
441 // This peer has nothing interesting.
445 if (state->pindexLastCommonBlock == NULL) {
446 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
447 // Guessing wrong in either direction is not a problem.
448 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
451 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
452 // of its current tip anymore. Go back enough to fix that.
453 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
454 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
457 std::vector<CBlockIndex*> vToFetch;
458 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
459 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
460 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
461 // download that next block if the window were 1 larger.
462 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
463 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
464 NodeId waitingfor = -1;
465 while (pindexWalk->nHeight < nMaxHeight) {
466 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
467 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
468 // as iterating over ~100 CBlockIndex* entries anyway.
469 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
470 vToFetch.resize(nToFetch);
471 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
472 vToFetch[nToFetch - 1] = pindexWalk;
473 for (unsigned int i = nToFetch - 1; i > 0; i--) {
474 vToFetch[i - 1] = vToFetch[i]->pprev;
477 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
478 // are not yet downloaded and not in flight to vBlocks. In the meantime, update
479 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
480 // already part of our chain (and therefore don't need it even if pruned).
481 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
482 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
483 // We consider the chain that this peer is on invalid.
486 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
487 if (pindex->nChainTx)
488 state->pindexLastCommonBlock = pindex;
489 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
490 // The block is not already downloaded, and not yet in flight.
491 if (pindex->nHeight > nWindowEnd) {
492 // We reached the end of the window.
493 if (vBlocks.size() == 0 && waitingfor != nodeid) {
494 // We aren't able to fetch anything, but we would be if the download window was one larger.
495 nodeStaller = waitingfor;
499 vBlocks.push_back(pindex);
500 if (vBlocks.size() == count) {
503 } else if (waitingfor == -1) {
504 // This is the first already-in-flight block.
505 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
513 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
515 CNodeState *state = State(nodeid);
518 stats.nMisbehavior = state->nMisbehavior;
519 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
520 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
521 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
523 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
528 void RegisterNodeSignals(CNodeSignals& nodeSignals)
530 nodeSignals.GetHeight.connect(&GetHeight);
531 nodeSignals.ProcessMessages.connect(&ProcessMessages);
532 nodeSignals.SendMessages.connect(&SendMessages);
533 nodeSignals.InitializeNode.connect(&InitializeNode);
534 nodeSignals.FinalizeNode.connect(&FinalizeNode);
537 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
539 nodeSignals.GetHeight.disconnect(&GetHeight);
540 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
541 nodeSignals.SendMessages.disconnect(&SendMessages);
542 nodeSignals.InitializeNode.disconnect(&InitializeNode);
543 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
546 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
548 // Find the first block the caller has in the main chain
549 BOOST_FOREACH(const uint256& hash, locator.vHave) {
550 BlockMap::iterator mi = mapBlockIndex.find(hash);
551 if (mi != mapBlockIndex.end())
553 CBlockIndex* pindex = (*mi).second;
554 if (chain.Contains(pindex))
556 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
561 return chain.Genesis();
564 CCoinsViewCache *pcoinsTip = NULL;
565 CBlockTreeDB *pblocktree = NULL;
567 //////////////////////////////////////////////////////////////////////////////
569 // mapOrphanTransactions
572 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
574 uint256 hash = tx.GetHash();
575 if (mapOrphanTransactions.count(hash))
578 // Ignore big transactions, to avoid a
579 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
580 // large transaction with a missing parent then we assume
581 // it will rebroadcast it later, after the parent transaction(s)
582 // have been mined or received.
583 // 10,000 orphans, each of which is at most 5,000 bytes big is
584 // at most 500 megabytes of orphans:
585 unsigned int sz = GetSerializeSize(tx, SER_NETWORK, tx.nVersion);
588 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
592 mapOrphanTransactions[hash].tx = tx;
593 mapOrphanTransactions[hash].fromPeer = peer;
594 BOOST_FOREACH(const CTxIn& txin, tx.vin)
595 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
597 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
598 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
602 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
604 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
605 if (it == mapOrphanTransactions.end())
607 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
609 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
610 if (itPrev == mapOrphanTransactionsByPrev.end())
612 itPrev->second.erase(hash);
613 if (itPrev->second.empty())
614 mapOrphanTransactionsByPrev.erase(itPrev);
616 mapOrphanTransactions.erase(it);
619 void EraseOrphansFor(NodeId peer)
622 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
623 while (iter != mapOrphanTransactions.end())
625 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
626 if (maybeErase->second.fromPeer == peer)
628 EraseOrphanTx(maybeErase->second.tx.GetHash());
632 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
636 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
638 unsigned int nEvicted = 0;
639 while (mapOrphanTransactions.size() > nMaxOrphans)
641 // Evict a random orphan:
642 uint256 randomhash = GetRandHash();
643 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
644 if (it == mapOrphanTransactions.end())
645 it = mapOrphanTransactions.begin();
646 EraseOrphanTx(it->first);
653 bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight)
655 bool overwinterActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
656 bool saplingActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING);
659 // Sapling standard rules apply
660 if (tx.nVersion > CTransaction::SAPLING_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SAPLING_MIN_CURRENT_VERSION) {
661 reason = "sapling-version";
664 } else if (overwinterActive) {
665 // Overwinter standard rules apply
666 if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) {
667 reason = "overwinter-version";
671 // Sprout standard rules apply
672 if (tx.nVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION) {
678 BOOST_FOREACH(const CTxIn& txin, tx.vin)
680 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
681 // keys. (remember the 520 byte limit on redeemScript size) That works
682 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
683 // bytes of scriptSig, which we round off to 1650 bytes for some minor
684 // future-proofing. That's also enough to spend a 20-of-20
685 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
686 // considered standard)
687 if (txin.scriptSig.size() > 1650) {
688 reason = "scriptsig-size";
691 if (!txin.scriptSig.IsPushOnly()) {
692 reason = "scriptsig-not-pushonly";
697 unsigned int nDataOut = 0;
698 txnouttype whichType;
699 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
700 if (!::IsStandard(txout.scriptPubKey, whichType)) {
701 reason = "scriptpubkey";
705 if (whichType == TX_NULL_DATA)
707 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
708 reason = "bare-multisig";
710 } else if (txout.IsDust(::minRelayTxFee)) {
716 // only one OP_RETURN txout is permitted
718 reason = "multi-op-return";
725 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
727 if (tx.nLockTime == 0)
729 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
731 BOOST_FOREACH(const CTxIn& txin, tx.vin)
737 bool IsExpiredTx(const CTransaction &tx, int nBlockHeight)
739 if (tx.nExpiryHeight == 0 || tx.IsCoinBase()) {
742 return static_cast<uint32_t>(nBlockHeight) > tx.nExpiryHeight;
745 bool CheckFinalTx(const CTransaction &tx, int flags)
747 AssertLockHeld(cs_main);
749 // By convention a negative value for flags indicates that the
750 // current network-enforced consensus rules should be used. In
751 // a future soft-fork scenario that would mean checking which
752 // rules would be enforced for the next block and setting the
753 // appropriate flags. At the present time no soft-forks are
754 // scheduled, so no flags are set.
755 flags = std::max(flags, 0);
757 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
758 // nLockTime because when IsFinalTx() is called within
759 // CBlock::AcceptBlock(), the height of the block *being*
760 // evaluated is what is used. Thus if we want to know if a
761 // transaction can be part of the *next* block, we need to call
762 // IsFinalTx() with one more than chainActive.Height().
763 const int nBlockHeight = chainActive.Height() + 1;
765 // Timestamps on the other hand don't get any special treatment,
766 // because we can't know what timestamp the next block will have,
767 // and there aren't timestamp applications where it matters.
768 // However this changes once median past time-locks are enforced:
769 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
770 ? chainActive.Tip()->GetMedianTimePast()
773 return IsFinalTx(tx, nBlockHeight, nBlockTime);
777 * Check transaction inputs to mitigate two
778 * potential denial-of-service attacks:
780 * 1. scriptSigs with extra data stuffed into them,
781 * not consumed by scriptPubKey (or P2SH script)
782 * 2. P2SH scripts with a crazy number of expensive
783 * CHECKSIG/CHECKMULTISIG operations
785 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId)
788 return true; // Coinbases don't use vin normally
790 for (unsigned int i = 0; i < tx.vin.size(); i++)
792 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
794 vector<vector<unsigned char> > vSolutions;
795 txnouttype whichType;
796 // get the scriptPubKey corresponding to this input:
797 const CScript& prevScript = prev.scriptPubKey;
798 if (!Solver(prevScript, whichType, vSolutions))
800 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
801 if (nArgsExpected < 0)
804 // Transactions with extra stuff in their scriptSigs are
805 // non-standard. Note that this EvalScript() call will
806 // be quick, because if there are any operations
807 // beside "push data" in the scriptSig
808 // IsStandardTx() will have already returned false
809 // and this method isn't called.
810 vector<vector<unsigned char> > stack;
811 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), consensusBranchId))
814 if (whichType == TX_SCRIPTHASH)
818 CScript subscript(stack.back().begin(), stack.back().end());
819 vector<vector<unsigned char> > vSolutions2;
820 txnouttype whichType2;
821 if (Solver(subscript, whichType2, vSolutions2))
823 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
826 nArgsExpected += tmpExpected;
830 // Any other Script with less than 15 sigops OK:
831 unsigned int sigops = subscript.GetSigOpCount(true);
832 // ... extra data left on the stack after execution is OK, too:
833 return (sigops <= MAX_P2SH_SIGOPS);
837 if (stack.size() != (unsigned int)nArgsExpected)
844 unsigned int GetLegacySigOpCount(const CTransaction& tx)
846 unsigned int nSigOps = 0;
847 BOOST_FOREACH(const CTxIn& txin, tx.vin)
849 nSigOps += txin.scriptSig.GetSigOpCount(false);
851 BOOST_FOREACH(const CTxOut& txout, tx.vout)
853 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
858 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
863 unsigned int nSigOps = 0;
864 for (unsigned int i = 0; i < tx.vin.size(); i++)
866 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
867 if (prevout.scriptPubKey.IsPayToScriptHash())
868 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
874 * Check a transaction contextually against a set of consensus rules valid at a given block height.
877 * 1. AcceptToMemoryPool calls CheckTransaction and this function.
878 * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction)
879 * and ContextualCheckBlock (which calls this function).
880 * 3. The isInitBlockDownload argument is only to assist with testing.
882 bool ContextualCheckTransaction(
883 const CTransaction& tx,
884 CValidationState &state,
887 bool (*isInitBlockDownload)())
889 bool overwinterActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
890 bool saplingActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING);
891 bool isSprout = !overwinterActive;
893 // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond
894 if (isSprout && tx.fOverwintered) {
895 return state.DoS(isInitBlockDownload() ? 0 : dosLevel,
896 error("ContextualCheckTransaction(): overwinter is not active yet"),
897 REJECT_INVALID, "tx-overwinter-not-active");
901 // Reject transactions with valid version but missing overwintered flag
902 if (tx.nVersion >= SAPLING_MIN_TX_VERSION && !tx.fOverwintered) {
903 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwintered flag must be set"),
904 REJECT_INVALID, "tx-overwintered-flag-not-set");
907 // Reject transactions with non-Sapling version group ID
908 if (tx.fOverwintered && tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
909 return state.DoS(dosLevel, error("CheckTransaction(): invalid Sapling tx version"),
910 REJECT_INVALID, "bad-sapling-tx-version-group-id");
913 // Reject transactions with invalid version
914 if (tx.fOverwintered && tx.nVersion < SAPLING_MIN_TX_VERSION ) {
915 return state.DoS(100, error("CheckTransaction(): Sapling version too low"),
916 REJECT_INVALID, "bad-tx-sapling-version-too-low");
919 // Reject transactions with invalid version
920 if (tx.fOverwintered && tx.nVersion > SAPLING_MAX_TX_VERSION ) {
921 return state.DoS(100, error("CheckTransaction(): Sapling version too high"),
922 REJECT_INVALID, "bad-tx-sapling-version-too-high");
924 } else if (overwinterActive) {
925 // Reject transactions with valid version but missing overwinter flag
926 if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) {
927 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"),
928 REJECT_INVALID, "tx-overwinter-flag-not-set");
931 // Reject transactions with non-Overwinter version group ID
932 if (tx.fOverwintered && tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
933 return state.DoS(dosLevel, error("CheckTransaction(): invalid Overwinter tx version"),
934 REJECT_INVALID, "bad-overwinter-tx-version-group-id");
937 // Reject transactions with invalid version
938 if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) {
939 return state.DoS(100, error("CheckTransaction(): overwinter version too high"),
940 REJECT_INVALID, "bad-tx-overwinter-version-too-high");
944 // Rules that apply to Overwinter or later:
945 if (overwinterActive) {
946 // Reject transactions intended for Sprout
947 if (!tx.fOverwintered) {
948 return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"),
949 REJECT_INVALID, "tx-overwinter-active");
952 // Check that all transactions are unexpired
953 if (IsExpiredTx(tx, nHeight)) {
954 // Don't increase banscore if the transaction only just expired
955 int expiredDosLevel = IsExpiredTx(tx, nHeight - 1) ? dosLevel : 0;
956 return state.DoS(expiredDosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired");
960 // Rules that apply before Sapling:
961 if (!saplingActive) {
963 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
964 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_BEFORE_SAPLING)
965 return state.DoS(100, error("ContextualCheckTransaction(): size limits failed"),
966 REJECT_INVALID, "bad-txns-oversize");
969 uint256 dataToBeSigned;
971 if (!tx.vjoinsplit.empty() ||
972 !tx.vShieldedSpend.empty() ||
973 !tx.vShieldedOutput.empty())
975 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
976 // Empty output script.
979 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId);
980 } catch (std::logic_error ex) {
981 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
982 REJECT_INVALID, "error-computing-signature-hash");
986 if (!tx.vjoinsplit.empty())
988 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
990 // We rely on libsodium to check that the signature is canonical.
991 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
992 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
993 dataToBeSigned.begin(), 32,
994 tx.joinSplitPubKey.begin()
996 return state.DoS(isInitBlockDownload() ? 0 : 100,
997 error("CheckTransaction(): invalid joinsplit signature"),
998 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1002 if (!tx.vShieldedSpend.empty() ||
1003 !tx.vShieldedOutput.empty())
1005 auto ctx = librustzcash_sapling_verification_ctx_init();
1007 for (const SpendDescription &spend : tx.vShieldedSpend) {
1008 if (!librustzcash_sapling_check_spend(
1011 spend.anchor.begin(),
1012 spend.nullifier.begin(),
1014 spend.zkproof.begin(),
1015 spend.spendAuthSig.begin(),
1016 dataToBeSigned.begin()
1019 librustzcash_sapling_verification_ctx_free(ctx);
1020 return state.DoS(100, error("ContextualCheckTransaction(): Sapling spend description invalid"),
1021 REJECT_INVALID, "bad-txns-sapling-spend-description-invalid");
1025 for (const OutputDescription &output : tx.vShieldedOutput) {
1026 if (!librustzcash_sapling_check_output(
1030 output.ephemeralKey.begin(),
1031 output.zkproof.begin()
1034 librustzcash_sapling_verification_ctx_free(ctx);
1035 return state.DoS(100, error("ContextualCheckTransaction(): Sapling output description invalid"),
1036 REJECT_INVALID, "bad-txns-sapling-output-description-invalid");
1040 if (!librustzcash_sapling_final_check(
1043 tx.bindingSig.begin(),
1044 dataToBeSigned.begin()
1047 librustzcash_sapling_verification_ctx_free(ctx);
1048 return state.DoS(100, error("ContextualCheckTransaction(): Sapling binding signature invalid"),
1049 REJECT_INVALID, "bad-txns-sapling-binding-signature-invalid");
1052 librustzcash_sapling_verification_ctx_free(ctx);
1058 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
1059 libzcash::ProofVerifier& verifier)
1061 // Don't count coinbase transactions because mining skews the count
1062 if (!tx.IsCoinBase()) {
1063 transactionsValidated.increment();
1066 if (!CheckTransactionWithoutProofVerification(tx, state)) {
1069 // Ensure that zk-SNARKs verify
1070 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1071 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
1072 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
1073 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
1080 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
1082 // Basic checks that don't depend on any context
1086 * 1. The consensus rule below was:
1087 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
1088 * which checked if tx.nVersion fell within the range:
1089 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
1090 * 2. The parser allowed tx.nVersion to be negative
1093 * 1. The consensus rule checks to see if tx.Version falls within the range:
1094 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
1095 * 2. The previous consensus rule checked for negative values within the range:
1096 * INT32_MIN <= tx.nVersion < 0
1097 * This is unnecessary for Overwinter transactions since the parser now
1098 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
1099 * and when Overwinter is not active ContextualCheckTransaction rejects
1100 * transactions with fOverwintered set. When fOverwintered is set,
1101 * this function and ContextualCheckTransaction will together check to
1102 * ensure tx.nVersion avoids the following ranges:
1103 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
1104 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
1106 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
1107 return state.DoS(100, error("CheckTransaction(): version too low"),
1108 REJECT_INVALID, "bad-txns-version-too-low");
1110 else if (tx.fOverwintered) {
1111 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
1112 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
1113 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
1115 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID &&
1116 tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
1117 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
1118 REJECT_INVALID, "bad-tx-version-group-id");
1120 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
1121 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
1122 REJECT_INVALID, "bad-tx-expiry-height-too-high");
1126 // Transactions containing empty `vin` must have either non-empty
1127 // `vjoinsplit` or non-empty `vShieldedSpend`.
1128 if (tx.vin.empty() && tx.vjoinsplit.empty() && tx.vShieldedSpend.empty())
1129 return state.DoS(10, error("CheckTransaction(): vin empty"),
1130 REJECT_INVALID, "bad-txns-vin-empty");
1131 // Transactions containing empty `vout` must have either non-empty
1132 // `vjoinsplit` or non-empty `vShieldedOutput`.
1133 if (tx.vout.empty() && tx.vjoinsplit.empty() && tx.vShieldedOutput.empty())
1134 return state.DoS(10, error("CheckTransaction(): vout empty"),
1135 REJECT_INVALID, "bad-txns-vout-empty");
1138 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE >= MAX_TX_SIZE_AFTER_SAPLING); // sanity
1139 BOOST_STATIC_ASSERT(MAX_TX_SIZE_AFTER_SAPLING > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
1140 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_AFTER_SAPLING)
1141 return state.DoS(100, error("CheckTransaction(): size limits failed"),
1142 REJECT_INVALID, "bad-txns-oversize");
1144 // Check for negative or overflow output values
1145 CAmount nValueOut = 0;
1146 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1148 if (txout.nValue < 0)
1149 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
1150 REJECT_INVALID, "bad-txns-vout-negative");
1151 if (txout.nValue > MAX_MONEY)
1152 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
1153 REJECT_INVALID, "bad-txns-vout-toolarge");
1154 nValueOut += txout.nValue;
1155 if (!MoneyRange(nValueOut))
1156 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1157 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1160 // Check for non-zero valueBalance when there are no Sapling inputs or outputs
1161 if (tx.vShieldedSpend.empty() && tx.vShieldedOutput.empty() && tx.valueBalance != 0) {
1162 return state.DoS(100, error("CheckTransaction(): tx.valueBalance has no sources or sinks"),
1163 REJECT_INVALID, "bad-txns-valuebalance-nonzero");
1166 // Check for overflow valueBalance
1167 if (tx.valueBalance > MAX_MONEY || tx.valueBalance < -MAX_MONEY) {
1168 return state.DoS(100, error("CheckTransaction(): abs(tx.valueBalance) too large"),
1169 REJECT_INVALID, "bad-txns-valuebalance-toolarge");
1172 if (tx.valueBalance <= 0) {
1173 // NB: negative valueBalance "takes" money from the transparent value pool just as outputs do
1174 nValueOut += -tx.valueBalance;
1176 if (!MoneyRange(nValueOut)) {
1177 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1178 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1182 // Ensure that joinsplit values are well-formed
1183 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1185 if (joinsplit.vpub_old < 0) {
1186 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
1187 REJECT_INVALID, "bad-txns-vpub_old-negative");
1190 if (joinsplit.vpub_new < 0) {
1191 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
1192 REJECT_INVALID, "bad-txns-vpub_new-negative");
1195 if (joinsplit.vpub_old > MAX_MONEY) {
1196 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
1197 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
1200 if (joinsplit.vpub_new > MAX_MONEY) {
1201 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
1202 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
1205 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1206 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
1207 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1210 nValueOut += joinsplit.vpub_old;
1211 if (!MoneyRange(nValueOut)) {
1212 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1213 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1217 // Ensure input values do not exceed MAX_MONEY
1218 // We have not resolved the txin values at this stage,
1219 // but we do know what the joinsplits claim to add
1220 // to the value pool.
1222 CAmount nValueIn = 0;
1223 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1225 nValueIn += it->vpub_new;
1227 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1228 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1229 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1233 // Also check for Sapling
1234 if (tx.valueBalance >= 0) {
1235 // NB: positive valueBalance "adds" money to the transparent value pool, just as inputs do
1236 nValueIn += tx.valueBalance;
1238 if (!MoneyRange(nValueIn)) {
1239 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1240 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1245 // Check for duplicate inputs
1246 set<COutPoint> vInOutPoints;
1247 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1249 if (vInOutPoints.count(txin.prevout))
1250 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1251 REJECT_INVALID, "bad-txns-inputs-duplicate");
1252 vInOutPoints.insert(txin.prevout);
1255 // Check for duplicate joinsplit nullifiers in this transaction
1257 set<uint256> vJoinSplitNullifiers;
1258 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1260 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1262 if (vJoinSplitNullifiers.count(nf))
1263 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1264 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1266 vJoinSplitNullifiers.insert(nf);
1271 // Check for duplicate sapling nullifiers in this transaction
1273 set<uint256> vSaplingNullifiers;
1274 BOOST_FOREACH(const SpendDescription& spend_desc, tx.vShieldedSpend)
1276 if (vSaplingNullifiers.count(spend_desc.nullifier))
1277 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1278 REJECT_INVALID, "bad-spend-description-nullifiers-duplicate");
1280 vSaplingNullifiers.insert(spend_desc.nullifier);
1284 if (tx.IsCoinBase())
1286 // There should be no joinsplits in a coinbase transaction
1287 if (tx.vjoinsplit.size() > 0)
1288 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1289 REJECT_INVALID, "bad-cb-has-joinsplits");
1291 // A coinbase transaction cannot have spend descriptions or output descriptions
1292 if (tx.vShieldedSpend.size() > 0)
1293 return state.DoS(100, error("CheckTransaction(): coinbase has spend descriptions"),
1294 REJECT_INVALID, "bad-cb-has-spend-description");
1295 if (tx.vShieldedOutput.size() > 0)
1296 return state.DoS(100, error("CheckTransaction(): coinbase has output descriptions"),
1297 REJECT_INVALID, "bad-cb-has-output-description");
1299 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1300 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1301 REJECT_INVALID, "bad-cb-length");
1305 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1306 if (txin.prevout.IsNull())
1307 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1308 REJECT_INVALID, "bad-txns-prevout-null");
1314 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1318 uint256 hash = tx.GetHash();
1319 double dPriorityDelta = 0;
1320 CAmount nFeeDelta = 0;
1321 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1322 if (dPriorityDelta > 0 || nFeeDelta > 0)
1326 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1330 // There is a free transaction area in blocks created by most miners,
1331 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1332 // to be considered to fall into this category. We don't want to encourage sending
1333 // multiple transactions instead of one big transaction to avoid fees.
1334 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1338 if (!MoneyRange(nMinFee))
1339 nMinFee = MAX_MONEY;
1344 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1345 bool* pfMissingInputs, bool fRejectAbsurdFee)
1347 AssertLockHeld(cs_main);
1348 if (pfMissingInputs)
1349 *pfMissingInputs = false;
1351 int nextBlockHeight = chainActive.Height() + 1;
1352 auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus());
1354 // Node operator can choose to reject tx by number of transparent inputs
1355 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1356 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1357 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
1361 size_t n = tx.vin.size();
1363 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1368 auto verifier = libzcash::ProofVerifier::Strict();
1369 if (!CheckTransaction(tx, state, verifier))
1370 return error("AcceptToMemoryPool: CheckTransaction failed");
1372 // DoS level set to 10 to be more forgiving.
1373 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
1374 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1375 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1378 // Coinbase is only valid in a block, not as a loose transaction
1379 if (tx.IsCoinBase())
1380 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1381 REJECT_INVALID, "coinbase");
1383 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1385 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
1387 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1388 REJECT_NONSTANDARD, reason);
1390 // Only accept nLockTime-using transactions that can be mined in the next
1391 // block; we don't want our mempool filled up with transactions that can't
1393 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1394 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1396 // is it already in the memory pool?
1397 uint256 hash = tx.GetHash();
1398 if (pool.exists(hash))
1401 // Check for conflicts with in-memory transactions
1403 LOCK(pool.cs); // protect pool.mapNextTx
1404 for (unsigned int i = 0; i < tx.vin.size(); i++)
1406 COutPoint outpoint = tx.vin[i].prevout;
1407 if (pool.mapNextTx.count(outpoint))
1409 // Disable replacement feature for now
1413 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1414 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1415 if (pool.nullifierExists(nf, SPROUT)) {
1420 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
1421 if (pool.nullifierExists(spendDescription.nullifier, SAPLING)) {
1429 CCoinsViewCache view(&dummy);
1431 CAmount nValueIn = 0;
1434 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1435 view.SetBackend(viewMemPool);
1437 // do we already have it?
1438 if (view.HaveCoins(hash))
1441 // do all inputs exist?
1442 // Note that this does not check for the presence of actual outputs (see the next check for that),
1443 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1444 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1445 if (!view.HaveCoins(txin.prevout.hash)) {
1446 if (pfMissingInputs)
1447 *pfMissingInputs = true;
1452 // are the actual inputs available?
1453 if (!view.HaveInputs(tx))
1454 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1455 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1457 // are the joinsplit's requirements met?
1458 if (!view.HaveJoinSplitRequirements(tx))
1459 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1460 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1462 // Bring the best block into scope
1463 view.GetBestBlock();
1465 nValueIn = view.GetValueIn(tx);
1467 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1468 view.SetBackend(dummy);
1471 // Check for non-standard pay-to-script-hash in inputs
1472 if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId))
1473 return error("AcceptToMemoryPool: nonstandard transaction input");
1475 // Check that the transaction doesn't have an excessive number of
1476 // sigops, making it impossible to mine. Since the coinbase transaction
1477 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1478 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1479 // merely non-standard transaction.
1480 unsigned int nSigOps = GetLegacySigOpCount(tx);
1481 nSigOps += GetP2SHSigOpCount(tx, view);
1482 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1484 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1485 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1486 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1488 CAmount nValueOut = tx.GetValueOut();
1489 CAmount nFees = nValueIn-nValueOut;
1490 double dPriority = view.GetPriority(tx, chainActive.Height());
1492 // Keep track of transactions that spend a coinbase, which we re-scan
1493 // during reorgs to ensure COINBASE_MATURITY is still met.
1494 bool fSpendsCoinbase = false;
1495 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1496 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1497 if (coins->IsCoinBase()) {
1498 fSpendsCoinbase = true;
1503 // Grab the branch ID we expect this transaction to commit to. We don't
1504 // yet know if it does, but if the entry gets added to the mempool, then
1505 // it has passed ContextualCheckInputs and therefore this is correct.
1506 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1508 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
1509 unsigned int nSize = entry.GetTxSize();
1511 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1512 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1513 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1515 // Don't accept it if it can't get into a block
1516 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1517 if (fLimitFree && nFees < txMinFee)
1518 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1519 hash.ToString(), nFees, txMinFee),
1520 REJECT_INSUFFICIENTFEE, "insufficient fee");
1523 // Require that free transactions have sufficient priority to be mined in the next block.
1524 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1525 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1528 // Continuously rate-limit free (really, very-low-fee) transactions
1529 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1530 // be annoying or make others' transactions take longer to confirm.
1531 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1533 static CCriticalSection csFreeLimiter;
1534 static double dFreeCount;
1535 static int64_t nLastTime;
1536 int64_t nNow = GetTime();
1538 LOCK(csFreeLimiter);
1540 // Use an exponentially decaying ~10-minute window:
1541 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1543 // -limitfreerelay unit is thousand-bytes-per-minute
1544 // At default rate it would take over a month to fill 1GB
1545 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1546 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1547 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1548 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1549 dFreeCount += nSize;
1552 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) {
1553 string errmsg = strprintf("absurdly high fees %s, %d > %d",
1555 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1556 LogPrint("mempool", errmsg.c_str());
1557 return state.Error("AcceptToMemoryPool: " + errmsg);
1560 // Check against previous transactions
1561 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1562 PrecomputedTransactionData txdata(tx);
1563 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1565 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1568 // Check again against just the consensus-critical mandatory script
1569 // verification flags, in case of bugs in the standard flags that cause
1570 // transactions to pass as valid when they're actually invalid. For
1571 // instance the STRICTENC flag was incorrectly allowing certain
1572 // CHECKSIG NOT scripts to pass, even though they were invalid.
1574 // There is a similar check in CreateNewBlock() to prevent creating
1575 // invalid blocks, however allowing such transactions into the mempool
1576 // can be exploited as a DoS attack.
1577 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1579 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1582 // Store transaction in memory
1583 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1586 SyncWithWallets(tx, NULL);
1591 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1592 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1594 CBlockIndex *pindexSlow = NULL;
1598 if (mempool.lookup(hash, txOut))
1605 if (pblocktree->ReadTxIndex(hash, postx)) {
1606 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1608 return error("%s: OpenBlockFile failed", __func__);
1609 CBlockHeader header;
1612 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1614 } catch (const std::exception& e) {
1615 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1617 hashBlock = header.GetHash();
1618 if (txOut.GetHash() != hash)
1619 return error("%s: txid mismatch", __func__);
1624 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1627 CCoinsViewCache &view = *pcoinsTip;
1628 const CCoins* coins = view.AccessCoins(hash);
1630 nHeight = coins->nHeight;
1633 pindexSlow = chainActive[nHeight];
1638 if (ReadBlockFromDisk(block, pindexSlow)) {
1639 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1640 if (tx.GetHash() == hash) {
1642 hashBlock = pindexSlow->GetBlockHash();
1657 //////////////////////////////////////////////////////////////////////////////
1659 // CBlock and CBlockIndex
1662 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1664 // Open history file to append
1665 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1666 if (fileout.IsNull())
1667 return error("WriteBlockToDisk: OpenBlockFile failed");
1669 // Write index header
1670 unsigned int nSize = GetSerializeSize(fileout, block);
1671 fileout << FLATDATA(messageStart) << nSize;
1674 long fileOutPos = ftell(fileout.Get());
1676 return error("WriteBlockToDisk: ftell failed");
1677 pos.nPos = (unsigned int)fileOutPos;
1683 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1687 // Open history file to read
1688 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1689 if (filein.IsNull())
1690 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1696 catch (const std::exception& e) {
1697 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1701 if (!(CheckEquihashSolution(&block, Params()) &&
1702 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1703 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1708 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1710 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1712 if (block.GetHash() != pindex->GetBlockHash())
1713 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1714 pindex->ToString(), pindex->GetBlockPos().ToString());
1718 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1720 CAmount nSubsidy = 12.5 * COIN;
1722 // Mining slow start
1723 // The subsidy is ramped up linearly, skipping the middle payout of
1724 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1725 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1726 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1727 nSubsidy *= nHeight;
1729 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1730 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1731 nSubsidy *= (nHeight+1);
1735 assert(nHeight > consensusParams.SubsidySlowStartShift());
1736 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1737 // Force block reward to zero when right shift is undefined.
1741 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1742 nSubsidy >>= halvings;
1746 bool IsInitialBlockDownload()
1748 const CChainParams& chainParams = Params();
1750 // Once this function has returned false, it must remain false.
1751 static std::atomic<bool> latchToFalse{false};
1752 // Optimization: pre-test latch before taking the lock.
1753 if (latchToFalse.load(std::memory_order_relaxed))
1757 if (latchToFalse.load(std::memory_order_relaxed))
1759 if (fImporting || fReindex)
1761 if (chainActive.Tip() == NULL)
1763 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1765 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1767 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1768 latchToFalse.store(true, std::memory_order_relaxed);
1772 static bool fLargeWorkForkFound = false;
1773 static bool fLargeWorkInvalidChainFound = false;
1774 static CBlockIndex *pindexBestForkTip = NULL;
1775 static CBlockIndex *pindexBestForkBase = NULL;
1777 void CheckForkWarningConditions()
1779 AssertLockHeld(cs_main);
1780 // Before we get past initial download, we cannot reliably alert about forks
1781 // (we assume we don't get stuck on a fork before finishing our initial sync)
1782 if (IsInitialBlockDownload())
1785 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1786 // of our head, drop it
1787 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1788 pindexBestForkTip = NULL;
1790 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1792 if (!fLargeWorkForkFound && pindexBestForkBase)
1794 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1795 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1796 CAlert::Notify(warning, true);
1798 if (pindexBestForkTip && pindexBestForkBase)
1800 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__,
1801 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1802 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1803 fLargeWorkForkFound = true;
1807 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1808 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1809 CAlert::Notify(warning, true);
1810 fLargeWorkInvalidChainFound = true;
1815 fLargeWorkForkFound = false;
1816 fLargeWorkInvalidChainFound = false;
1820 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1822 AssertLockHeld(cs_main);
1823 // If we are on a fork that is sufficiently large, set a warning flag
1824 CBlockIndex* pfork = pindexNewForkTip;
1825 CBlockIndex* plonger = chainActive.Tip();
1826 while (pfork && pfork != plonger)
1828 while (plonger && plonger->nHeight > pfork->nHeight)
1829 plonger = plonger->pprev;
1830 if (pfork == plonger)
1832 pfork = pfork->pprev;
1835 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1836 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1837 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1838 // hash rate operating on the fork.
1839 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1840 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1841 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1842 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1843 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1844 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1846 pindexBestForkTip = pindexNewForkTip;
1847 pindexBestForkBase = pfork;
1850 CheckForkWarningConditions();
1853 // Requires cs_main.
1854 void Misbehaving(NodeId pnode, int howmuch)
1859 CNodeState *state = State(pnode);
1863 state->nMisbehavior += howmuch;
1864 int banscore = GetArg("-banscore", 100);
1865 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1867 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1868 state->fShouldBan = true;
1870 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1873 void static InvalidChainFound(CBlockIndex* pindexNew)
1875 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1876 pindexBestInvalid = pindexNew;
1878 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1879 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1880 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1881 pindexNew->GetBlockTime()));
1882 CBlockIndex *tip = chainActive.Tip();
1884 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1885 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1886 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1887 CheckForkWarningConditions();
1890 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1892 if (state.IsInvalid(nDoS)) {
1893 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1894 if (it != mapBlockSource.end() && State(it->second)) {
1895 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1896 State(it->second)->rejects.push_back(reject);
1898 Misbehaving(it->second, nDoS);
1901 if (!state.CorruptionPossible()) {
1902 pindex->nStatus |= BLOCK_FAILED_VALID;
1903 setDirtyBlockIndex.insert(pindex);
1904 setBlockIndexCandidates.erase(pindex);
1905 InvalidChainFound(pindex);
1909 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1911 // mark inputs spent
1912 if (!tx.IsCoinBase()) {
1913 txundo.vprevout.reserve(tx.vin.size());
1914 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1915 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1916 unsigned nPos = txin.prevout.n;
1918 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1920 // mark an outpoint spent, and construct undo information
1921 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1923 if (coins->vout.size() == 0) {
1924 CTxInUndo& undo = txundo.vprevout.back();
1925 undo.nHeight = coins->nHeight;
1926 undo.fCoinBase = coins->fCoinBase;
1927 undo.nVersion = coins->nVersion;
1933 inputs.SetNullifiers(tx, true);
1936 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1939 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1942 UpdateCoins(tx, inputs, txundo, nHeight);
1945 bool CScriptCheck::operator()() {
1946 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1947 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) {
1948 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1953 int GetSpendHeight(const CCoinsViewCache& inputs)
1956 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1957 return pindexPrev->nHeight + 1;
1960 namespace Consensus {
1961 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1963 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1964 // for an attacker to attempt to split the network.
1965 if (!inputs.HaveInputs(tx))
1966 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1968 // are the JoinSplit's requirements met?
1969 if (!inputs.HaveJoinSplitRequirements(tx))
1970 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1972 CAmount nValueIn = 0;
1974 for (unsigned int i = 0; i < tx.vin.size(); i++)
1976 const COutPoint &prevout = tx.vin[i].prevout;
1977 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1980 if (coins->IsCoinBase()) {
1981 // Ensure that coinbases are matured
1982 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1983 return state.Invalid(
1984 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1985 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1988 // Ensure that coinbases cannot be spent to transparent outputs
1989 // Disabled on regtest
1990 if (fCoinbaseEnforcedProtectionEnabled &&
1991 consensusParams.fCoinbaseMustBeProtected &&
1993 return state.Invalid(
1994 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1995 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1999 // Check for negative or overflow input values
2000 nValueIn += coins->vout[prevout.n].nValue;
2001 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
2002 return state.DoS(100, error("CheckInputs(): txin values out of range"),
2003 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2007 nValueIn += tx.GetShieldedValueIn();
2008 if (!MoneyRange(nValueIn))
2009 return state.DoS(100, error("CheckInputs(): shielded input to transparent value pool out of range"),
2010 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2012 if (nValueIn < tx.GetValueOut())
2013 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
2014 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
2015 REJECT_INVALID, "bad-txns-in-belowout");
2017 // Tally transaction fees
2018 CAmount nTxFee = nValueIn - tx.GetValueOut();
2020 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
2021 REJECT_INVALID, "bad-txns-fee-negative");
2023 if (!MoneyRange(nFees))
2024 return state.DoS(100, error("CheckInputs(): nFees out of range"),
2025 REJECT_INVALID, "bad-txns-fee-outofrange");
2028 }// namespace Consensus
2030 bool ContextualCheckInputs(
2031 const CTransaction& tx,
2032 CValidationState &state,
2033 const CCoinsViewCache &inputs,
2037 PrecomputedTransactionData& txdata,
2038 const Consensus::Params& consensusParams,
2039 uint32_t consensusBranchId,
2040 std::vector<CScriptCheck> *pvChecks)
2042 if (!tx.IsCoinBase())
2044 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
2049 pvChecks->reserve(tx.vin.size());
2051 // The first loop above does all the inexpensive checks.
2052 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
2053 // Helps prevent CPU exhaustion attacks.
2055 // Skip ECDSA signature verification when connecting blocks
2056 // before the last block chain checkpoint. This is safe because block merkle hashes are
2057 // still computed and checked, and any change will be caught at the next checkpoint.
2058 if (fScriptChecks) {
2059 for (unsigned int i = 0; i < tx.vin.size(); i++) {
2060 const COutPoint &prevout = tx.vin[i].prevout;
2061 const CCoins* coins = inputs.AccessCoins(prevout.hash);
2065 CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata);
2067 pvChecks->push_back(CScriptCheck());
2068 check.swap(pvChecks->back());
2069 } else if (!check()) {
2070 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2071 // Check whether the failure was caused by a
2072 // non-mandatory script verification check, such as
2073 // non-standard DER encodings or non-null dummy
2074 // arguments; if so, don't trigger DoS protection to
2075 // avoid splitting the network between upgraded and
2076 // non-upgraded nodes.
2077 CScriptCheck check2(*coins, tx, i,
2078 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata);
2080 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
2082 // Failures of other flags indicate a transaction that is
2083 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
2084 // such nodes as they are not following the protocol. That
2085 // said during an upgrade careful thought should be taken
2086 // as to the correct behavior - we may want to continue
2087 // peering with non-upgraded nodes even after a soft-fork
2088 // super-majority vote has passed.
2089 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
2100 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
2102 // Open history file to append
2103 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
2104 if (fileout.IsNull())
2105 return error("%s: OpenUndoFile failed", __func__);
2107 // Write index header
2108 unsigned int nSize = GetSerializeSize(fileout, blockundo);
2109 fileout << FLATDATA(messageStart) << nSize;
2112 long fileOutPos = ftell(fileout.Get());
2114 return error("%s: ftell failed", __func__);
2115 pos.nPos = (unsigned int)fileOutPos;
2116 fileout << blockundo;
2118 // calculate & write checksum
2119 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2120 hasher << hashBlock;
2121 hasher << blockundo;
2122 fileout << hasher.GetHash();
2127 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
2129 // Open history file to read
2130 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
2131 if (filein.IsNull())
2132 return error("%s: OpenBlockFile failed", __func__);
2135 uint256 hashChecksum;
2137 filein >> blockundo;
2138 filein >> hashChecksum;
2140 catch (const std::exception& e) {
2141 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2145 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2146 hasher << hashBlock;
2147 hasher << blockundo;
2148 if (hashChecksum != hasher.GetHash())
2149 return error("%s: Checksum mismatch", __func__);
2154 /** Abort with a message */
2155 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2157 strMiscWarning = strMessage;
2158 LogPrintf("*** %s\n", strMessage);
2159 uiInterface.ThreadSafeMessageBox(
2160 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2161 "", CClientUIInterface::MSG_ERROR);
2166 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2168 AbortNode(strMessage, userMessage);
2169 return state.Error(strMessage);
2175 * Apply the undo operation of a CTxInUndo to the given chain state.
2176 * @param undo The undo object.
2177 * @param view The coins view to which to apply the changes.
2178 * @param out The out point that corresponds to the tx input.
2179 * @return True on success.
2181 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2185 CCoinsModifier coins = view.ModifyCoins(out.hash);
2186 if (undo.nHeight != 0) {
2187 // undo data contains height: this is the last output of the prevout tx being spent
2188 if (!coins->IsPruned())
2189 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2191 coins->fCoinBase = undo.fCoinBase;
2192 coins->nHeight = undo.nHeight;
2193 coins->nVersion = undo.nVersion;
2195 if (coins->IsPruned())
2196 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2198 if (coins->IsAvailable(out.n))
2199 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2200 if (coins->vout.size() < out.n+1)
2201 coins->vout.resize(out.n+1);
2202 coins->vout[out.n] = undo.txout;
2207 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2209 assert(pindex->GetBlockHash() == view.GetBestBlock());
2216 CBlockUndo blockUndo;
2217 CDiskBlockPos pos = pindex->GetUndoPos();
2219 return error("DisconnectBlock(): no undo data available");
2220 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2221 return error("DisconnectBlock(): failure reading undo data");
2223 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2224 return error("DisconnectBlock(): block and undo data inconsistent");
2226 // undo transactions in reverse order
2227 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2228 const CTransaction &tx = block.vtx[i];
2229 uint256 hash = tx.GetHash();
2231 // Check that all outputs are available and match the outputs in the block itself
2234 CCoinsModifier outs = view.ModifyCoins(hash);
2235 outs->ClearUnspendable();
2237 CCoins outsBlock(tx, pindex->nHeight);
2238 // The CCoins serialization does not serialize negative numbers.
2239 // No network rules currently depend on the version here, so an inconsistency is harmless
2240 // but it must be corrected before txout nversion ever influences a network rule.
2241 if (outsBlock.nVersion < 0)
2242 outs->nVersion = outsBlock.nVersion;
2243 if (*outs != outsBlock)
2244 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2250 // unspend nullifiers
2251 view.SetNullifiers(tx, false);
2254 if (i > 0) { // not coinbases
2255 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2256 if (txundo.vprevout.size() != tx.vin.size())
2257 return error("DisconnectBlock(): transaction and undo data inconsistent");
2258 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2259 const COutPoint &out = tx.vin[j].prevout;
2260 const CTxInUndo &undo = txundo.vprevout[j];
2261 if (!ApplyTxInUndo(undo, view, out))
2267 // set the old best Sprout anchor back
2268 view.PopAnchor(blockUndo.old_sprout_tree_root, SPROUT);
2270 // set the old best Sapling anchor back
2271 // We can get this from the `hashFinalSaplingRoot` of the last block
2272 // However, this is only reliable if the last block was on or after
2273 // the Sapling activation height. Otherwise, the last anchor was the
2275 if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2276 view.PopAnchor(pindex->pprev->hashFinalSaplingRoot, SAPLING);
2278 view.PopAnchor(SaplingMerkleTree::empty_root(), SAPLING);
2281 // move best block pointer to prevout block
2282 view.SetBestBlock(pindex->pprev->GetBlockHash());
2292 void static FlushBlockFile(bool fFinalize = false)
2294 LOCK(cs_LastBlockFile);
2296 CDiskBlockPos posOld(nLastBlockFile, 0);
2298 FILE *fileOld = OpenBlockFile(posOld);
2301 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2302 FileCommit(fileOld);
2306 fileOld = OpenUndoFile(posOld);
2309 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2310 FileCommit(fileOld);
2315 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2317 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2319 void ThreadScriptCheck() {
2320 RenameThread("zcash-scriptch");
2321 scriptcheckqueue.Thread();
2325 // Called periodically asynchronously; alerts if it smells like
2326 // we're being fed a bad chain (blocks being generated much
2327 // too slowly or too quickly).
2329 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2330 int64_t nPowTargetSpacing)
2332 if (bestHeader == NULL || initialDownloadCheck()) return;
2334 static int64_t lastAlertTime = 0;
2335 int64_t now = GetAdjustedTime();
2336 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2338 const int SPAN_HOURS=4;
2339 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2340 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2342 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2344 std::string strWarning;
2345 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2348 const CBlockIndex* i = bestHeader;
2350 while (i->GetBlockTime() >= startTime) {
2353 if (i == NULL) return; // Ran out of chain, we must not be fully synced
2356 // How likely is it to find that many by chance?
2357 double p = boost::math::pdf(poisson, nBlocks);
2359 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2360 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2362 // Aim for one false-positive about every fifty years of normal running:
2363 const int FIFTY_YEARS = 50*365*24*60*60;
2364 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2366 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2368 // Many fewer blocks than expected: alert!
2369 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2370 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2372 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2374 // Many more blocks than expected: alert!
2375 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2376 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2378 if (!strWarning.empty())
2380 strMiscWarning = strWarning;
2381 CAlert::Notify(strWarning, true);
2382 lastAlertTime = now;
2386 static int64_t nTimeVerify = 0;
2387 static int64_t nTimeConnect = 0;
2388 static int64_t nTimeIndex = 0;
2389 static int64_t nTimeCallbacks = 0;
2390 static int64_t nTimeTotal = 0;
2392 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2394 const CChainParams& chainparams = Params();
2395 AssertLockHeld(cs_main);
2397 bool fExpensiveChecks = true;
2398 if (fCheckpointsEnabled) {
2399 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2400 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2401 // This block is an ancestor of a checkpoint: disable script checks
2402 fExpensiveChecks = false;
2406 auto verifier = libzcash::ProofVerifier::Strict();
2407 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2409 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2410 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2413 // verify that the view's current state corresponds to the previous block
2414 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2415 assert(hashPrevBlock == view.GetBestBlock());
2417 // Special case for the genesis block, skipping connection of its transactions
2418 // (its coinbase is unspendable)
2419 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2421 view.SetBestBlock(pindex->GetBlockHash());
2422 // Before the genesis block, there was an empty tree
2423 SproutMerkleTree tree;
2424 pindex->hashSproutAnchor = tree.root();
2425 // The genesis block contained no JoinSplits
2426 pindex->hashFinalSproutRoot = pindex->hashSproutAnchor;
2431 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2432 // unless those are already completely spent.
2433 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2434 const CCoins* coins = view.AccessCoins(tx.GetHash());
2435 if (coins && !coins->IsPruned())
2436 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2437 REJECT_INVALID, "bad-txns-BIP30");
2440 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2442 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2444 CBlockUndo blockundo;
2446 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2448 int64_t nTimeStart = GetTimeMicros();
2451 unsigned int nSigOps = 0;
2452 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2453 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2454 vPos.reserve(block.vtx.size());
2455 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2457 // Construct the incremental merkle tree at the current
2459 auto old_sprout_tree_root = view.GetBestAnchor(SPROUT);
2460 // saving the top anchor in the block index as we go.
2462 pindex->hashSproutAnchor = old_sprout_tree_root;
2464 SproutMerkleTree sprout_tree;
2465 // This should never fail: we should always be able to get the root
2466 // that is on the tip of our chain
2467 assert(view.GetSproutAnchorAt(old_sprout_tree_root, sprout_tree));
2470 // Consistency check: the root of the tree we're given should
2471 // match what we asked for.
2472 assert(sprout_tree.root() == old_sprout_tree_root);
2475 SaplingMerkleTree sapling_tree;
2476 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
2478 // Grab the consensus branch ID for the block's height
2479 auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus());
2481 std::vector<PrecomputedTransactionData> txdata;
2482 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2483 for (unsigned int i = 0; i < block.vtx.size(); i++)
2485 const CTransaction &tx = block.vtx[i];
2487 nInputs += tx.vin.size();
2488 nSigOps += GetLegacySigOpCount(tx);
2489 if (nSigOps > MAX_BLOCK_SIGOPS)
2490 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2491 REJECT_INVALID, "bad-blk-sigops");
2493 if (!tx.IsCoinBase())
2495 if (!view.HaveInputs(tx))
2496 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2497 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2499 // are the JoinSplit's requirements met?
2500 if (!view.HaveJoinSplitRequirements(tx))
2501 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2502 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2504 // Add in sigops done by pay-to-script-hash inputs;
2505 // this is to prevent a "rogue miner" from creating
2506 // an incredibly-expensive-to-validate block.
2507 nSigOps += GetP2SHSigOpCount(tx, view);
2508 if (nSigOps > MAX_BLOCK_SIGOPS)
2509 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2510 REJECT_INVALID, "bad-blk-sigops");
2513 txdata.emplace_back(tx);
2515 if (!tx.IsCoinBase())
2517 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2519 std::vector<CScriptCheck> vChecks;
2520 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL))
2522 control.Add(vChecks);
2527 blockundo.vtxundo.push_back(CTxUndo());
2529 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2531 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2532 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2533 // Insert the note commitments into our temporary tree.
2535 sprout_tree.append(note_commitment);
2539 BOOST_FOREACH(const OutputDescription &outputDescription, tx.vShieldedOutput) {
2540 sapling_tree.append(outputDescription.cm);
2543 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2544 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2547 view.PushAnchor(sprout_tree);
2548 view.PushAnchor(sapling_tree);
2550 pindex->hashFinalSproutRoot = sprout_tree.root();
2552 blockundo.old_sprout_tree_root = old_sprout_tree_root;
2554 // If Sapling is active, block.hashFinalSaplingRoot must be the
2555 // same as the root of the Sapling tree
2556 if (NetworkUpgradeActive(pindex->nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2557 if (block.hashFinalSaplingRoot != sapling_tree.root()) {
2558 return state.DoS(100,
2559 error("ConnectBlock(): block's hashFinalSaplingRoot is incorrect"),
2560 REJECT_INVALID, "bad-sapling-root-in-block");
2564 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2565 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);
2567 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2568 if (block.vtx[0].GetValueOut() > blockReward)
2569 return state.DoS(100,
2570 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2571 block.vtx[0].GetValueOut(), blockReward),
2572 REJECT_INVALID, "bad-cb-amount");
2574 if (!control.Wait())
2575 return state.DoS(100, false);
2576 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2577 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);
2582 // Write undo information to disk
2583 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2585 if (pindex->GetUndoPos().IsNull()) {
2587 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2588 return error("ConnectBlock(): FindUndoPos failed");
2589 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2590 return AbortNode(state, "Failed to write undo data");
2592 // update nUndoPos in block index
2593 pindex->nUndoPos = pos.nPos;
2594 pindex->nStatus |= BLOCK_HAVE_UNDO;
2597 // Now that all consensus rules have been validated, set nCachedBranchId.
2598 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2599 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
2600 "nCachedBranchId must be set after all consensus rules have been validated.");
2601 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2602 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
2603 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
2604 } else if (pindex->pprev) {
2605 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
2608 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2609 setDirtyBlockIndex.insert(pindex);
2613 if (!pblocktree->WriteTxIndex(vPos))
2614 return AbortNode(state, "Failed to write transaction index");
2616 // add this block to the view's block chain
2617 view.SetBestBlock(pindex->GetBlockHash());
2619 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2620 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2622 // Watch for changes to the previous coinbase transaction.
2623 static uint256 hashPrevBestCoinBase;
2624 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2625 hashPrevBestCoinBase = block.vtx[0].GetHash();
2627 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2628 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2633 enum FlushStateMode {
2635 FLUSH_STATE_IF_NEEDED,
2636 FLUSH_STATE_PERIODIC,
2641 * Update the on-disk chain state.
2642 * The caches and indexes are flushed depending on the mode we're called with
2643 * if they're too large, if it's been a while since the last write,
2644 * or always and in all cases if we're in prune mode and are deleting files.
2646 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2647 LOCK2(cs_main, cs_LastBlockFile);
2648 static int64_t nLastWrite = 0;
2649 static int64_t nLastFlush = 0;
2650 static int64_t nLastSetChain = 0;
2651 std::set<int> setFilesToPrune;
2652 bool fFlushForPrune = false;
2654 if (fPruneMode && fCheckForPruning && !fReindex) {
2655 FindFilesToPrune(setFilesToPrune);
2656 fCheckForPruning = false;
2657 if (!setFilesToPrune.empty()) {
2658 fFlushForPrune = true;
2660 pblocktree->WriteFlag("prunedblockfiles", true);
2665 int64_t nNow = GetTimeMicros();
2666 // Avoid writing/flushing immediately after startup.
2667 if (nLastWrite == 0) {
2670 if (nLastFlush == 0) {
2673 if (nLastSetChain == 0) {
2674 nLastSetChain = nNow;
2676 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2677 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2678 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2679 // The cache is over the limit, we have to write now.
2680 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2681 // 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.
2682 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2683 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2684 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2685 // Combine all conditions that result in a full cache flush.
2686 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2687 // Write blocks and block index to disk.
2688 if (fDoFullFlush || fPeriodicWrite) {
2689 // Depend on nMinDiskSpace to ensure we can write block index
2690 if (!CheckDiskSpace(0))
2691 return state.Error("out of disk space");
2692 // First make sure all block and undo data is flushed to disk.
2694 // Then update all block file information (which may refer to block and undo files).
2696 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2697 vFiles.reserve(setDirtyFileInfo.size());
2698 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2699 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2700 setDirtyFileInfo.erase(it++);
2702 std::vector<const CBlockIndex*> vBlocks;
2703 vBlocks.reserve(setDirtyBlockIndex.size());
2704 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2705 vBlocks.push_back(*it);
2706 setDirtyBlockIndex.erase(it++);
2708 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2709 return AbortNode(state, "Files to write to block index database");
2712 // Finally remove any pruned files
2714 UnlinkPrunedFiles(setFilesToPrune);
2717 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2719 // Typical CCoins structures on disk are around 128 bytes in size.
2720 // Pushing a new one to the database can cause it to be written
2721 // twice (once in the log, and once in the tables). This is already
2722 // an overestimation, as most will delete an existing entry or
2723 // overwrite one. Still, use a conservative safety factor of 2.
2724 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2725 return state.Error("out of disk space");
2726 // Flush the chainstate (which may refer to block index entries).
2727 if (!pcoinsTip->Flush())
2728 return AbortNode(state, "Failed to write to coin database");
2731 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2732 // Update best block in wallet (so we can detect restored wallets).
2733 GetMainSignals().SetBestChain(chainActive.GetLocator());
2734 nLastSetChain = nNow;
2736 } catch (const std::runtime_error& e) {
2737 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2742 void FlushStateToDisk() {
2743 CValidationState state;
2744 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2747 void PruneAndFlush() {
2748 CValidationState state;
2749 fCheckForPruning = true;
2750 FlushStateToDisk(state, FLUSH_STATE_NONE);
2753 /** Update chainActive and related internal data structures. */
2754 void static UpdateTip(CBlockIndex *pindexNew) {
2755 const CChainParams& chainParams = Params();
2756 chainActive.SetTip(pindexNew);
2759 nTimeBestReceived = GetTime();
2760 mempool.AddTransactionsUpdated(1);
2762 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2763 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2764 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2765 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2767 cvBlockChange.notify_all();
2769 // Check the version of the last 100 blocks to see if we need to upgrade:
2770 static bool fWarned = false;
2771 if (!IsInitialBlockDownload() && !fWarned)
2774 const CBlockIndex* pindex = chainActive.Tip();
2775 for (int i = 0; i < 100 && pindex != NULL; i++)
2777 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2779 pindex = pindex->pprev;
2782 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2783 if (nUpgraded > 100/2)
2785 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2786 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2787 CAlert::Notify(strMiscWarning, true);
2794 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2795 * mempool.removeWithoutBranchId after this, with cs_main held.
2797 bool static DisconnectTip(CValidationState &state, bool fBare = false) {
2798 CBlockIndex *pindexDelete = chainActive.Tip();
2799 assert(pindexDelete);
2800 // Read block from disk.
2802 if (!ReadBlockFromDisk(block, pindexDelete))
2803 return AbortNode(state, "Failed to read block");
2804 // Apply the block atomically to the chain state.
2805 uint256 sproutAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2806 uint256 saplingAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
2807 int64_t nStart = GetTimeMicros();
2809 CCoinsViewCache view(pcoinsTip);
2810 if (!DisconnectBlock(block, state, pindexDelete, view))
2811 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2812 assert(view.Flush());
2814 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2815 uint256 sproutAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2816 uint256 saplingAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
2817 // Write the chain state to disk, if necessary.
2818 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2822 // Resurrect mempool transactions from the disconnected block.
2823 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2824 // ignore validation errors in resurrected transactions
2825 list<CTransaction> removed;
2826 CValidationState stateDummy;
2827 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2828 mempool.remove(tx, removed, true);
2830 if (sproutAnchorBeforeDisconnect != sproutAnchorAfterDisconnect) {
2831 // The anchor may not change between block disconnects,
2832 // in which case we don't want to evict from the mempool yet!
2833 mempool.removeWithAnchor(sproutAnchorBeforeDisconnect, SPROUT);
2835 if (saplingAnchorBeforeDisconnect != saplingAnchorAfterDisconnect) {
2836 // The anchor may not change between block disconnects,
2837 // in which case we don't want to evict from the mempool yet!
2838 mempool.removeWithAnchor(saplingAnchorBeforeDisconnect, SAPLING);
2842 // Update chainActive and related variables.
2843 UpdateTip(pindexDelete->pprev);
2844 // Get the current commitment tree
2845 SproutMerkleTree newSproutTree;
2846 SaplingMerkleTree newSaplingTree;
2847 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), newSproutTree));
2848 assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(SAPLING), newSaplingTree));
2849 // Let wallets know transactions went from 1-confirmed to
2850 // 0-confirmed or conflicted:
2851 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2852 SyncWithWallets(tx, NULL);
2854 // Update cached incremental witnesses
2855 GetMainSignals().ChainTip(pindexDelete, &block, newSproutTree, newSaplingTree, false);
2859 static int64_t nTimeReadFromDisk = 0;
2860 static int64_t nTimeConnectTotal = 0;
2861 static int64_t nTimeFlush = 0;
2862 static int64_t nTimeChainState = 0;
2863 static int64_t nTimePostConnect = 0;
2866 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2867 * corresponding to pindexNew, to bypass loading it again from disk.
2868 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
2870 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2871 assert(pindexNew->pprev == chainActive.Tip());
2872 // Read block from disk.
2873 int64_t nTime1 = GetTimeMicros();
2876 if (!ReadBlockFromDisk(block, pindexNew))
2877 return AbortNode(state, "Failed to read block");
2880 // Get the current commitment tree
2881 SproutMerkleTree oldSproutTree;
2882 SaplingMerkleTree oldSaplingTree;
2883 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), oldSproutTree));
2884 assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(SAPLING), oldSaplingTree));
2885 // Apply the block atomically to the chain state.
2886 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2888 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2890 CCoinsViewCache view(pcoinsTip);
2891 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2892 GetMainSignals().BlockChecked(*pblock, state);
2894 if (state.IsInvalid())
2895 InvalidBlockFound(pindexNew, state);
2896 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2898 mapBlockSource.erase(pindexNew->GetBlockHash());
2899 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2900 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2901 assert(view.Flush());
2903 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2904 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2905 // Write the chain state to disk, if necessary.
2906 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2908 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2909 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2910 // Remove conflicting transactions from the mempool.
2911 list<CTransaction> txConflicted;
2912 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2914 // Remove transactions that expire at new block height from mempool
2915 mempool.removeExpired(pindexNew->nHeight);
2917 // Update chainActive & related variables.
2918 UpdateTip(pindexNew);
2919 // Tell wallet about transactions that went from mempool
2921 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2922 SyncWithWallets(tx, NULL);
2924 // ... and about transactions that got confirmed:
2925 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2926 SyncWithWallets(tx, pblock);
2928 // Update cached incremental witnesses
2929 GetMainSignals().ChainTip(pindexNew, pblock, oldSproutTree, oldSaplingTree, true);
2931 EnforceNodeDeprecation(pindexNew->nHeight);
2933 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2934 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2935 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2940 * Return the tip of the chain with the most work in it, that isn't
2941 * known to be invalid (it's however far from certain to be valid).
2943 static CBlockIndex* FindMostWorkChain() {
2945 CBlockIndex *pindexNew = NULL;
2947 // Find the best candidate header.
2949 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2950 if (it == setBlockIndexCandidates.rend())
2955 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2956 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2957 CBlockIndex *pindexTest = pindexNew;
2958 bool fInvalidAncestor = false;
2959 while (pindexTest && !chainActive.Contains(pindexTest)) {
2960 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2962 // Pruned nodes may have entries in setBlockIndexCandidates for
2963 // which block files have been deleted. Remove those as candidates
2964 // for the most work chain if we come across them; we can't switch
2965 // to a chain unless we have all the non-active-chain parent blocks.
2966 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2967 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2968 if (fFailedChain || fMissingData) {
2969 // Candidate chain is not usable (either invalid or missing data)
2970 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2971 pindexBestInvalid = pindexNew;
2972 CBlockIndex *pindexFailed = pindexNew;
2973 // Remove the entire chain from the set.
2974 while (pindexTest != pindexFailed) {
2976 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2977 } else if (fMissingData) {
2978 // If we're missing data, then add back to mapBlocksUnlinked,
2979 // so that if the block arrives in the future we can try adding
2980 // to setBlockIndexCandidates again.
2981 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2983 setBlockIndexCandidates.erase(pindexFailed);
2984 pindexFailed = pindexFailed->pprev;
2986 setBlockIndexCandidates.erase(pindexTest);
2987 fInvalidAncestor = true;
2990 pindexTest = pindexTest->pprev;
2992 if (!fInvalidAncestor)
2997 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2998 static void PruneBlockIndexCandidates() {
2999 // Note that we can't delete the current block itself, as we may need to return to it later in case a
3000 // reorganization to a better block fails.
3001 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
3002 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
3003 setBlockIndexCandidates.erase(it++);
3005 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3006 assert(!setBlockIndexCandidates.empty());
3010 * Try to make some progress towards making pindexMostWork the active block.
3011 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
3013 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
3014 AssertLockHeld(cs_main);
3015 bool fInvalidFound = false;
3016 const CBlockIndex *pindexOldTip = chainActive.Tip();
3017 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
3019 // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks.
3020 // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain,
3021 // then pindexFork will be null, and we would need to remove the entire chain including
3022 // our genesis block. In practice this (probably) won't happen because of checks elsewhere.
3023 auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0;
3024 static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance");
3025 if (reorgLength > MAX_REORG_LENGTH) {
3026 auto msg = strprintf(_(
3027 "A block chain reorganization has been detected that would roll back %d blocks! "
3028 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
3029 ), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
3030 _("Reorganization details") + ":\n" +
3031 "- " + strprintf(_("Current tip: %s, height %d, work %s"),
3032 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" +
3033 "- " + strprintf(_("New tip: %s, height %d, work %s"),
3034 pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" +
3035 "- " + strprintf(_("Fork point: %s, height %d"),
3036 pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" +
3037 _("Please help, human!");
3038 LogPrintf("*** %s\n", msg);
3039 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
3044 // Disconnect active blocks which are no longer in the best chain.
3045 bool fBlocksDisconnected = false;
3046 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
3047 if (!DisconnectTip(state))
3049 fBlocksDisconnected = true;
3052 // Build list of new blocks to connect.
3053 std::vector<CBlockIndex*> vpindexToConnect;
3054 bool fContinue = true;
3055 int nHeight = pindexFork ? pindexFork->nHeight : -1;
3056 while (fContinue && nHeight != pindexMostWork->nHeight) {
3057 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3058 // a few blocks along the way.
3059 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3060 vpindexToConnect.clear();
3061 vpindexToConnect.reserve(nTargetHeight - nHeight);
3062 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3063 while (pindexIter && pindexIter->nHeight != nHeight) {
3064 vpindexToConnect.push_back(pindexIter);
3065 pindexIter = pindexIter->pprev;
3067 nHeight = nTargetHeight;
3069 // Connect new blocks.
3070 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
3071 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
3072 if (state.IsInvalid()) {
3073 // The block violates a consensus rule.
3074 if (!state.CorruptionPossible())
3075 InvalidChainFound(vpindexToConnect.back());
3076 state = CValidationState();
3077 fInvalidFound = true;
3081 // A system error occurred (disk space, database error, ...).
3085 PruneBlockIndexCandidates();
3086 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
3087 // We're in a better position than we were. Return temporarily to release the lock.
3095 if (fBlocksDisconnected) {
3096 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3098 mempool.removeWithoutBranchId(
3099 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3100 mempool.check(pcoinsTip);
3102 // Callbacks/notifications for a new best chain.
3104 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
3106 CheckForkWarningConditions();
3112 * Make the best chain active, in multiple steps. The result is either failure
3113 * or an activated best chain. pblock is either NULL or a pointer to a block
3114 * that is already loaded (to avoid loading it again from disk).
3116 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
3117 CBlockIndex *pindexNewTip = NULL;
3118 CBlockIndex *pindexMostWork = NULL;
3119 const CChainParams& chainParams = Params();
3121 boost::this_thread::interruption_point();
3123 bool fInitialDownload;
3126 pindexMostWork = FindMostWorkChain();
3128 // Whether we have anything to do at all.
3129 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
3132 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
3135 pindexNewTip = chainActive.Tip();
3136 fInitialDownload = IsInitialBlockDownload();
3138 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3140 // Notifications/callbacks that can run without cs_main
3141 if (!fInitialDownload) {
3142 uint256 hashNewTip = pindexNewTip->GetBlockHash();
3143 // Relay inventory, but don't relay old inventory during initial block download.
3144 int nBlockEstimate = 0;
3145 if (fCheckpointsEnabled)
3146 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
3147 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
3148 // in a stalled download if the block file is pruned before the request.
3149 if (nLocalServices & NODE_NETWORK) {
3151 BOOST_FOREACH(CNode* pnode, vNodes)
3152 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
3153 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
3155 // Notify external listeners about the new tip.
3156 GetMainSignals().UpdatedBlockTip(pindexNewTip);
3157 uiInterface.NotifyBlockTip(hashNewTip);
3159 } while(pindexMostWork != chainActive.Tip());
3162 // Write changes periodically to disk, after relay.
3163 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
3170 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
3171 AssertLockHeld(cs_main);
3173 // Mark the block itself as invalid.
3174 pindex->nStatus |= BLOCK_FAILED_VALID;
3175 setDirtyBlockIndex.insert(pindex);
3176 setBlockIndexCandidates.erase(pindex);
3178 while (chainActive.Contains(pindex)) {
3179 CBlockIndex *pindexWalk = chainActive.Tip();
3180 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3181 setDirtyBlockIndex.insert(pindexWalk);
3182 setBlockIndexCandidates.erase(pindexWalk);
3183 // ActivateBestChain considers blocks already in chainActive
3184 // unconditionally valid already, so force disconnect away from it.
3185 if (!DisconnectTip(state)) {
3186 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3187 mempool.removeWithoutBranchId(
3188 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3193 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3195 BlockMap::iterator it = mapBlockIndex.begin();
3196 while (it != mapBlockIndex.end()) {
3197 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3198 setBlockIndexCandidates.insert(it->second);
3203 InvalidChainFound(pindex);
3204 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3205 mempool.removeWithoutBranchId(
3206 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3210 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
3211 AssertLockHeld(cs_main);
3213 int nHeight = pindex->nHeight;
3215 // Remove the invalidity flag from this block and all its descendants.
3216 BlockMap::iterator it = mapBlockIndex.begin();
3217 while (it != mapBlockIndex.end()) {
3218 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3219 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3220 setDirtyBlockIndex.insert(it->second);
3221 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3222 setBlockIndexCandidates.insert(it->second);
3224 if (it->second == pindexBestInvalid) {
3225 // Reset invalid block marker if it was pointing to one of those.
3226 pindexBestInvalid = NULL;
3232 // Remove the invalidity flag from all ancestors too.
3233 while (pindex != NULL) {
3234 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3235 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3236 setDirtyBlockIndex.insert(pindex);
3238 pindex = pindex->pprev;
3243 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3245 // Check for duplicate
3246 uint256 hash = block.GetHash();
3247 BlockMap::iterator it = mapBlockIndex.find(hash);
3248 if (it != mapBlockIndex.end())
3251 // Construct new block index object
3252 CBlockIndex* pindexNew = new CBlockIndex(block);
3254 // We assign the sequence id to blocks only when the full data is available,
3255 // to avoid miners withholding blocks but broadcasting headers, to get a
3256 // competitive advantage.
3257 pindexNew->nSequenceId = 0;
3258 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3259 pindexNew->phashBlock = &((*mi).first);
3260 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3261 if (miPrev != mapBlockIndex.end())
3263 pindexNew->pprev = (*miPrev).second;
3264 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3265 pindexNew->BuildSkip();
3267 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3268 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3269 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3270 pindexBestHeader = pindexNew;
3272 setDirtyBlockIndex.insert(pindexNew);
3277 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3278 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3280 pindexNew->nTx = block.vtx.size();
3281 pindexNew->nChainTx = 0;
3282 CAmount sproutValue = 0;
3283 CAmount saplingValue = 0;
3284 for (auto tx : block.vtx) {
3285 // Negative valueBalance "takes" money from the transparent value pool
3286 // and adds it to the Sapling value pool. Positive valueBalance "gives"
3287 // money to the transparent value pool, removing from the Sapling value
3288 // pool. So we invert the sign here.
3289 saplingValue += -tx.valueBalance;
3291 for (auto js : tx.vjoinsplit) {
3292 sproutValue += js.vpub_old;
3293 sproutValue -= js.vpub_new;
3296 pindexNew->nSproutValue = sproutValue;
3297 pindexNew->nChainSproutValue = boost::none;
3298 pindexNew->nSaplingValue = saplingValue;
3299 pindexNew->nChainSaplingValue = boost::none;
3300 pindexNew->nFile = pos.nFile;
3301 pindexNew->nDataPos = pos.nPos;
3302 pindexNew->nUndoPos = 0;
3303 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3304 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3305 setDirtyBlockIndex.insert(pindexNew);
3307 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3308 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3309 deque<CBlockIndex*> queue;
3310 queue.push_back(pindexNew);
3312 // Recursively process any descendant blocks that now may be eligible to be connected.
3313 while (!queue.empty()) {
3314 CBlockIndex *pindex = queue.front();
3316 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3317 if (pindex->pprev) {
3318 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3319 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3321 pindex->nChainSproutValue = boost::none;
3323 if (pindex->pprev->nChainSaplingValue) {
3324 pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue;
3326 pindex->nChainSaplingValue = boost::none;
3329 pindex->nChainSproutValue = pindex->nSproutValue;
3330 pindex->nChainSaplingValue = pindex->nSaplingValue;
3333 LOCK(cs_nBlockSequenceId);
3334 pindex->nSequenceId = nBlockSequenceId++;
3336 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3337 setBlockIndexCandidates.insert(pindex);
3339 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3340 while (range.first != range.second) {
3341 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3342 queue.push_back(it->second);
3344 mapBlocksUnlinked.erase(it);
3348 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3349 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3356 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3358 LOCK(cs_LastBlockFile);
3360 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3361 if (vinfoBlockFile.size() <= nFile) {
3362 vinfoBlockFile.resize(nFile + 1);
3366 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3368 if (vinfoBlockFile.size() <= nFile) {
3369 vinfoBlockFile.resize(nFile + 1);
3373 pos.nPos = vinfoBlockFile[nFile].nSize;
3376 if (nFile != nLastBlockFile) {
3378 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3380 FlushBlockFile(!fKnown);
3381 nLastBlockFile = nFile;
3384 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3386 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3388 vinfoBlockFile[nFile].nSize += nAddSize;
3391 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3392 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3393 if (nNewChunks > nOldChunks) {
3395 fCheckForPruning = true;
3396 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3397 FILE *file = OpenBlockFile(pos);
3399 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3400 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3405 return state.Error("out of disk space");
3409 setDirtyFileInfo.insert(nFile);
3413 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3417 LOCK(cs_LastBlockFile);
3419 unsigned int nNewSize;
3420 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3421 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3422 setDirtyFileInfo.insert(nFile);
3424 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3425 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3426 if (nNewChunks > nOldChunks) {
3428 fCheckForPruning = true;
3429 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3430 FILE *file = OpenUndoFile(pos);
3432 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3433 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3438 return state.Error("out of disk space");
3444 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
3446 // Check block version
3447 if (block.nVersion < MIN_BLOCK_VERSION)
3448 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
3449 REJECT_INVALID, "version-too-low");
3451 // Check Equihash solution is valid
3452 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
3453 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3454 REJECT_INVALID, "invalid-solution");
3456 // Check proof of work matches claimed amount
3457 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
3458 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
3459 REJECT_INVALID, "high-hash");
3462 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
3463 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
3464 REJECT_INVALID, "time-too-new");
3469 bool CheckBlock(const CBlock& block, CValidationState& state,
3470 libzcash::ProofVerifier& verifier,
3471 bool fCheckPOW, bool fCheckMerkleRoot)
3473 // These are checks that are independent of context.
3475 // Check that the header is valid (particularly PoW). This is mostly
3476 // redundant with the call in AcceptBlockHeader.
3477 if (!CheckBlockHeader(block, state, fCheckPOW))
3480 // Check the merkle root.
3481 if (fCheckMerkleRoot) {
3483 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3484 if (block.hashMerkleRoot != hashMerkleRoot2)
3485 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3486 REJECT_INVALID, "bad-txnmrklroot", true);
3488 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3489 // of transactions in a block without affecting the merkle root of a block,
3490 // while still invalidating it.
3492 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3493 REJECT_INVALID, "bad-txns-duplicate", true);
3496 // All potential-corruption validation must be done before we do any
3497 // transaction validation, as otherwise we may mark the header as invalid
3498 // because we receive the wrong transactions for it.
3501 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3502 return state.DoS(100, error("CheckBlock(): size limits failed"),
3503 REJECT_INVALID, "bad-blk-length");
3505 // First transaction must be coinbase, the rest must not be
3506 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3507 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3508 REJECT_INVALID, "bad-cb-missing");
3509 for (unsigned int i = 1; i < block.vtx.size(); i++)
3510 if (block.vtx[i].IsCoinBase())
3511 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3512 REJECT_INVALID, "bad-cb-multiple");
3514 // Check transactions
3515 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3516 if (!CheckTransaction(tx, state, verifier))
3517 return error("CheckBlock(): CheckTransaction failed");
3519 unsigned int nSigOps = 0;
3520 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3522 nSigOps += GetLegacySigOpCount(tx);
3524 if (nSigOps > MAX_BLOCK_SIGOPS)
3525 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3526 REJECT_INVALID, "bad-blk-sigops", true);
3531 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3533 const CChainParams& chainParams = Params();
3534 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3535 uint256 hash = block.GetHash();
3536 if (hash == consensusParams.hashGenesisBlock)
3541 int nHeight = pindexPrev->nHeight+1;
3543 // Check proof of work
3544 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3545 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3546 REJECT_INVALID, "bad-diffbits");
3548 // Check timestamp against prev
3549 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3550 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3551 REJECT_INVALID, "time-too-old");
3553 if (fCheckpointsEnabled)
3555 // Don't accept any forks from the main chain prior to last checkpoint
3556 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3557 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3558 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3561 // Reject block.nVersion < 4 blocks
3562 if (block.nVersion < 4)
3563 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3564 REJECT_OBSOLETE, "bad-version");
3569 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3571 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3572 const Consensus::Params& consensusParams = Params().GetConsensus();
3574 // Check that all transactions are finalized
3575 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3577 // Check transaction contextually against consensus rules at block height
3578 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3579 return false; // Failure reason has been set in validation state object
3582 int nLockTimeFlags = 0;
3583 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3584 ? pindexPrev->GetMedianTimePast()
3585 : block.GetBlockTime();
3586 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3587 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3591 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3592 // In Zcash this has been enforced since launch, except that the genesis
3593 // block didn't include the height in the coinbase (see Zcash protocol spec
3594 // section '6.8 Bitcoin Improvement Proposals').
3597 CScript expect = CScript() << nHeight;
3598 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3599 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3600 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3604 // Coinbase transaction must include an output sending 20% of
3605 // the block reward to a founders reward script, until the last founders
3606 // reward block is reached, with exception of the genesis block.
3607 // The last founders reward block is defined as the block just before the
3608 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3609 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3612 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3613 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3614 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3622 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3629 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3631 const CChainParams& chainparams = Params();
3632 AssertLockHeld(cs_main);
3633 // Check for duplicate
3634 uint256 hash = block.GetHash();
3635 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3636 CBlockIndex *pindex = NULL;
3637 if (miSelf != mapBlockIndex.end()) {
3638 // Block header is already known.
3639 pindex = miSelf->second;
3642 if (pindex->nStatus & BLOCK_FAILED_MASK)
3643 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3647 if (!CheckBlockHeader(block, state))
3650 // Get prev block index
3651 CBlockIndex* pindexPrev = NULL;
3652 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3653 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3654 if (mi == mapBlockIndex.end())
3655 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3656 pindexPrev = (*mi).second;
3657 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3658 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3661 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3665 pindex = AddToBlockIndex(block);
3673 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3675 const CChainParams& chainparams = Params();
3676 AssertLockHeld(cs_main);
3678 CBlockIndex *&pindex = *ppindex;
3680 if (!AcceptBlockHeader(block, state, &pindex))
3683 // Try to process all requested blocks that we don't have, but only
3684 // process an unrequested block if it's new and has enough work to
3685 // advance our tip, and isn't too many blocks ahead.
3686 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3687 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3688 // Blocks that are too out-of-order needlessly limit the effectiveness of
3689 // pruning, because pruning will not delete block files that contain any
3690 // blocks which are too close in height to the tip. Apply this test
3691 // regardless of whether pruning is enabled; it should generally be safe to
3692 // not process unrequested blocks.
3693 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3695 // TODO: deal better with return value and error conditions for duplicate
3696 // and unrequested blocks.
3697 if (fAlreadyHave) return true;
3698 if (!fRequested) { // If we didn't ask for it:
3699 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3700 if (!fHasMoreWork) return true; // Don't process less-work chains
3701 if (fTooFarAhead) return true; // Block height is too high
3704 // See method docstring for why this is always disabled
3705 auto verifier = libzcash::ProofVerifier::Disabled();
3706 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3707 if (state.IsInvalid() && !state.CorruptionPossible()) {
3708 pindex->nStatus |= BLOCK_FAILED_VALID;
3709 setDirtyBlockIndex.insert(pindex);
3714 int nHeight = pindex->nHeight;
3716 // Write block to history file
3718 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3719 CDiskBlockPos blockPos;
3722 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3723 return error("AcceptBlock(): FindBlockPos failed");
3725 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3726 AbortNode(state, "Failed to write block");
3727 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3728 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3729 } catch (const std::runtime_error& e) {
3730 return AbortNode(state, std::string("System error: ") + e.what());
3733 if (fCheckForPruning)
3734 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3739 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3741 unsigned int nFound = 0;
3742 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3744 if (pstart->nVersion >= minVersion)
3746 pstart = pstart->pprev;
3748 return (nFound >= nRequired);
3752 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3754 // Preliminary checks
3755 auto verifier = libzcash::ProofVerifier::Disabled();
3756 bool checked = CheckBlock(*pblock, state, verifier);
3760 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3761 fRequested |= fForceProcessing;
3763 return error("%s: CheckBlock FAILED", __func__);
3767 CBlockIndex *pindex = NULL;
3768 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3769 if (pindex && pfrom) {
3770 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3774 return error("%s: AcceptBlock FAILED", __func__);
3777 if (!ActivateBestChain(state, pblock))
3778 return error("%s: ActivateBestChain failed", __func__);
3783 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3785 AssertLockHeld(cs_main);
3786 assert(pindexPrev == chainActive.Tip());
3788 CCoinsViewCache viewNew(pcoinsTip);
3789 CBlockIndex indexDummy(block);
3790 indexDummy.pprev = pindexPrev;
3791 indexDummy.nHeight = pindexPrev->nHeight + 1;
3792 // JoinSplit proofs are verified in ConnectBlock
3793 auto verifier = libzcash::ProofVerifier::Disabled();
3795 // NOTE: CheckBlockHeader is called by CheckBlock
3796 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3798 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3800 if (!ContextualCheckBlock(block, state, pindexPrev))
3802 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3804 assert(state.IsValid());
3810 * BLOCK PRUNING CODE
3813 /* Calculate the amount of disk space the block & undo files currently use */
3814 uint64_t CalculateCurrentUsage()
3816 uint64_t retval = 0;
3817 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3818 retval += file.nSize + file.nUndoSize;
3823 /* Prune a block file (modify associated database entries)*/
3824 void PruneOneBlockFile(const int fileNumber)
3826 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3827 CBlockIndex* pindex = it->second;
3828 if (pindex->nFile == fileNumber) {
3829 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3830 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3832 pindex->nDataPos = 0;
3833 pindex->nUndoPos = 0;
3834 setDirtyBlockIndex.insert(pindex);
3836 // Prune from mapBlocksUnlinked -- any block we prune would have
3837 // to be downloaded again in order to consider its chain, at which
3838 // point it would be considered as a candidate for
3839 // mapBlocksUnlinked or setBlockIndexCandidates.
3840 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3841 while (range.first != range.second) {
3842 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3844 if (it->second == pindex) {
3845 mapBlocksUnlinked.erase(it);
3851 vinfoBlockFile[fileNumber].SetNull();
3852 setDirtyFileInfo.insert(fileNumber);
3856 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3858 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3859 CDiskBlockPos pos(*it, 0);
3860 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3861 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3862 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3866 /* Calculate the block/rev files that should be deleted to remain under target*/
3867 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3869 LOCK2(cs_main, cs_LastBlockFile);
3870 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3873 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3877 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3878 uint64_t nCurrentUsage = CalculateCurrentUsage();
3879 // We don't check to prune until after we've allocated new space for files
3880 // So we should leave a buffer under our target to account for another allocation
3881 // before the next pruning.
3882 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3883 uint64_t nBytesToPrune;
3886 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3887 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3888 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3890 if (vinfoBlockFile[fileNumber].nSize == 0)
3893 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3896 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3897 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3900 PruneOneBlockFile(fileNumber);
3901 // Queue up the files for removal
3902 setFilesToPrune.insert(fileNumber);
3903 nCurrentUsage -= nBytesToPrune;
3908 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3909 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3910 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3911 nLastBlockWeCanPrune, count);
3914 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3916 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3918 // Check for nMinDiskSpace bytes (currently 50MB)
3919 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3920 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3925 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3929 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3930 boost::filesystem::create_directories(path.parent_path());
3931 FILE* file = fopen(path.string().c_str(), "rb+");
3932 if (!file && !fReadOnly)
3933 file = fopen(path.string().c_str(), "wb+");
3935 LogPrintf("Unable to open file %s\n", path.string());
3939 if (fseek(file, pos.nPos, SEEK_SET)) {
3940 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3948 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3949 return OpenDiskFile(pos, "blk", fReadOnly);
3952 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3953 return OpenDiskFile(pos, "rev", fReadOnly);
3956 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3958 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3961 CBlockIndex * InsertBlockIndex(uint256 hash)
3967 BlockMap::iterator mi = mapBlockIndex.find(hash);
3968 if (mi != mapBlockIndex.end())
3969 return (*mi).second;
3972 CBlockIndex* pindexNew = new CBlockIndex();
3974 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3975 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3976 pindexNew->phashBlock = &((*mi).first);
3981 bool static LoadBlockIndexDB()
3983 const CChainParams& chainparams = Params();
3984 if (!pblocktree->LoadBlockIndexGuts())
3987 boost::this_thread::interruption_point();
3989 // Calculate nChainWork
3990 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3991 vSortedByHeight.reserve(mapBlockIndex.size());
3992 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3994 CBlockIndex* pindex = item.second;
3995 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3997 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3998 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
4000 CBlockIndex* pindex = item.second;
4001 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
4002 // We can link the chain of blocks for which we've received transactions at some point.
4003 // Pruned nodes may have deleted the block.
4004 if (pindex->nTx > 0) {
4005 if (pindex->pprev) {
4006 if (pindex->pprev->nChainTx) {
4007 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4008 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
4009 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
4011 pindex->nChainSproutValue = boost::none;
4013 if (pindex->pprev->nChainSaplingValue) {
4014 pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue;
4016 pindex->nChainSaplingValue = boost::none;
4019 pindex->nChainTx = 0;
4020 pindex->nChainSproutValue = boost::none;
4021 pindex->nChainSaplingValue = boost::none;
4022 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
4025 pindex->nChainTx = pindex->nTx;
4026 pindex->nChainSproutValue = pindex->nSproutValue;
4027 pindex->nChainSaplingValue = pindex->nSaplingValue;
4030 // Construct in-memory chain of branch IDs.
4031 // Relies on invariant: a block that does not activate a network upgrade
4032 // will always be valid under the same consensus rules as its parent.
4033 // Genesis block has a branch ID of zero by definition, but has no
4034 // validity status because it is side-loaded into a fresh chain.
4035 // Activation blocks will have branch IDs set (read from disk).
4036 if (pindex->pprev) {
4037 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
4038 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
4041 pindex->nCachedBranchId = SPROUT_BRANCH_ID;
4043 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
4044 setBlockIndexCandidates.insert(pindex);
4045 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
4046 pindexBestInvalid = pindex;
4048 pindex->BuildSkip();
4049 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4050 pindexBestHeader = pindex;
4053 // Load block file info
4054 pblocktree->ReadLastBlockFile(nLastBlockFile);
4055 vinfoBlockFile.resize(nLastBlockFile + 1);
4056 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4057 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4058 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4060 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4061 for (int nFile = nLastBlockFile + 1; true; nFile++) {
4062 CBlockFileInfo info;
4063 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4064 vinfoBlockFile.push_back(info);
4070 // Check presence of blk files
4071 LogPrintf("Checking all blk files are present...\n");
4072 set<int> setBlkDataFiles;
4073 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4075 CBlockIndex* pindex = item.second;
4076 if (pindex->nStatus & BLOCK_HAVE_DATA) {
4077 setBlkDataFiles.insert(pindex->nFile);
4080 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4082 CDiskBlockPos pos(*it, 0);
4083 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4088 // Check whether we have ever pruned block & undo files
4089 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4091 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4093 // Check whether we need to continue reindexing
4094 bool fReindexing = false;
4095 pblocktree->ReadReindexing(fReindexing);
4096 fReindex |= fReindexing;
4098 // Check whether we have a transaction index
4099 pblocktree->ReadFlag("txindex", fTxIndex);
4100 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
4102 // Fill in-memory data
4103 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4105 CBlockIndex* pindex = item.second;
4106 // - This relationship will always be true even if pprev has multiple
4107 // children, because hashSproutAnchor is technically a property of pprev,
4108 // not its children.
4109 // - This will miss chain tips; we handle the best tip below, and other
4110 // tips will be handled by ConnectTip during a re-org.
4111 if (pindex->pprev) {
4112 pindex->pprev->hashFinalSproutRoot = pindex->hashSproutAnchor;
4116 // Load pointer to end of best chain
4117 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4118 if (it == mapBlockIndex.end())
4120 chainActive.SetTip(it->second);
4121 // Set hashFinalSproutRoot for the end of best chain
4122 it->second->hashFinalSproutRoot = pcoinsTip->GetBestAnchor(SPROUT);
4124 PruneBlockIndexCandidates();
4126 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
4127 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
4128 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4129 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
4131 EnforceNodeDeprecation(chainActive.Height(), true);
4136 CVerifyDB::CVerifyDB()
4138 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
4141 CVerifyDB::~CVerifyDB()
4143 uiInterface.ShowProgress("", 100);
4146 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4149 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
4152 // Verify blocks in the best chain
4153 if (nCheckDepth <= 0)
4154 nCheckDepth = 1000000000; // suffices until the year 19000
4155 if (nCheckDepth > chainActive.Height())
4156 nCheckDepth = chainActive.Height();
4157 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4158 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4159 CCoinsViewCache coins(coinsview);
4160 CBlockIndex* pindexState = chainActive.Tip();
4161 CBlockIndex* pindexFailure = NULL;
4162 int nGoodTransactions = 0;
4163 CValidationState state;
4164 // No need to verify JoinSplits twice
4165 auto verifier = libzcash::ProofVerifier::Disabled();
4166 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
4168 boost::this_thread::interruption_point();
4169 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
4170 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
4173 // check level 0: read from disk
4174 if (!ReadBlockFromDisk(block, pindex))
4175 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4176 // check level 1: verify block validity
4177 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
4178 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4179 // check level 2: verify undo validity
4180 if (nCheckLevel >= 2 && pindex) {
4182 CDiskBlockPos pos = pindex->GetUndoPos();
4183 if (!pos.IsNull()) {
4184 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
4185 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4188 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4189 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
4191 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
4192 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4193 pindexState = pindex->pprev;
4195 nGoodTransactions = 0;
4196 pindexFailure = pindex;
4198 nGoodTransactions += block.vtx.size();
4200 if (ShutdownRequested())
4204 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4206 // check level 4: try reconnecting blocks
4207 if (nCheckLevel >= 4) {
4208 CBlockIndex *pindex = pindexState;
4209 while (pindex != chainActive.Tip()) {
4210 boost::this_thread::interruption_point();
4211 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
4212 pindex = chainActive.Next(pindex);
4214 if (!ReadBlockFromDisk(block, pindex))
4215 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4216 if (!ConnectBlock(block, state, pindex, coins))
4217 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4221 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4226 bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches)
4230 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
4231 // index will have nCachedBranchId set based on the values previously persisted
4232 // to disk. By definition, a set nCachedBranchId means that the block was
4233 // fully-validated under the corresponding consensus rules. Thus we can quickly
4234 // identify whether the current active chain matches our expected sequence of
4235 // consensus rule changes, with two checks:
4237 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
4238 // - nCachedBranchId for each block matches what we expect.
4239 auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) {
4240 auto consensus = params.GetConsensus();
4241 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
4242 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
4243 return fFlagSet == fFlagExpected &&
4244 pindex->nCachedBranchId &&
4245 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
4249 while (nHeight <= chainActive.Height()) {
4250 if (!sufficientlyValidated(chainActive[nHeight])) {
4256 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4257 auto rewindLength = chainActive.Height() - nHeight;
4258 clearWitnessCaches = false;
4260 if (rewindLength > 0) {
4261 LogPrintf("*** First insufficiently validated block at height %d, rewind length %d\n", nHeight, rewindLength);
4262 const uint256 *phashFirstInsufValidated = chainActive[nHeight]->phashBlock;
4263 auto networkID = params.NetworkIDString();
4265 // This is true when we intend to do a long rewind.
4266 bool intendedRewind =
4267 (networkID == "test" && nHeight == 252500 && *phashFirstInsufValidated ==
4268 uint256S("0018bd16a9c6f15795a754c498d2b2083ab78f14dae44a66a8d0e90ba8464d9c"));
4270 clearWitnessCaches = (rewindLength > MAX_REORG_LENGTH && intendedRewind);
4272 if (clearWitnessCaches) {
4273 auto msg = strprintf(_(
4274 "An intended block chain rewind has been detected: network %s, hash %s, height %d"
4275 ), networkID, phashFirstInsufValidated->GetHex(), nHeight);
4276 LogPrintf("*** %s\n", msg);
4279 if (rewindLength > MAX_REORG_LENGTH && !intendedRewind) {
4280 auto pindexOldTip = chainActive.Tip();
4281 auto pindexRewind = chainActive[nHeight - 1];
4282 auto msg = strprintf(_(
4283 "A block chain rewind has been detected that would roll back %d blocks! "
4284 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
4285 ), rewindLength, MAX_REORG_LENGTH) + "\n\n" +
4286 _("Rewind details") + ":\n" +
4287 "- " + strprintf(_("Current tip: %s, height %d"),
4288 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" +
4289 "- " + strprintf(_("Rewinding to: %s, height %d"),
4290 pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" +
4291 _("Please help, human!");
4292 LogPrintf("*** %s\n", msg);
4293 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
4299 CValidationState state;
4300 CBlockIndex* pindex = chainActive.Tip();
4301 while (chainActive.Height() >= nHeight) {
4302 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4303 // If pruning, don't try rewinding past the HAVE_DATA point;
4304 // since older blocks can't be served anyway, there's
4305 // no need to walk further, and trying to DisconnectTip()
4306 // will fail (and require a needless reindex/redownload
4307 // of the blockchain).
4310 if (!DisconnectTip(state, true)) {
4311 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4313 // Occasionally flush state to disk.
4314 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
4318 // Collect blocks to be removed (blocks in mapBlockIndex must be at least BLOCK_VALID_TREE).
4319 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4320 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4321 std::vector<const CBlockIndex*> vBlocks;
4322 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4323 CBlockIndex* pindexIter = it->second;
4325 // Note: If we encounter an insufficiently validated block that
4326 // is on chainActive, it must be because we are a pruning node, and
4327 // this block or some successor doesn't HAVE_DATA, so we were unable to
4328 // rewind all the way. Blocks remaining on chainActive at this point
4329 // must not have their validity reduced.
4330 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
4331 // Add to the list of blocks to remove
4332 vBlocks.push_back(pindexIter);
4333 if (pindexIter == pindexBestInvalid) {
4334 // Reset invalid block marker if it was pointing to this block
4335 pindexBestInvalid = NULL;
4338 setBlockIndexCandidates.erase(pindexIter);
4339 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4340 while (ret.first != ret.second) {
4341 if (ret.first->second == pindexIter) {
4342 mapBlocksUnlinked.erase(ret.first++);
4347 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4348 setBlockIndexCandidates.insert(pindexIter);
4352 // Set pindexBestHeader to the current chain tip
4353 // (since we are about to delete the block it is pointing to)
4354 pindexBestHeader = chainActive.Tip();
4356 // Erase block indices on-disk
4357 if (!pblocktree->EraseBatchSync(vBlocks)) {
4358 return AbortNode(state, "Failed to erase from block index database");
4361 // Erase block indices in-memory
4362 for (auto pindex : vBlocks) {
4363 auto ret = mapBlockIndex.find(*pindex->phashBlock);
4364 if (ret != mapBlockIndex.end()) {
4365 mapBlockIndex.erase(ret);
4370 PruneBlockIndexCandidates();
4374 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4381 void UnloadBlockIndex()
4384 setBlockIndexCandidates.clear();
4385 chainActive.SetTip(NULL);
4386 pindexBestInvalid = NULL;
4387 pindexBestHeader = NULL;
4389 mapOrphanTransactions.clear();
4390 mapOrphanTransactionsByPrev.clear();
4392 mapBlocksUnlinked.clear();
4393 vinfoBlockFile.clear();
4395 nBlockSequenceId = 1;
4396 mapBlockSource.clear();
4397 mapBlocksInFlight.clear();
4398 nQueuedValidatedHeaders = 0;
4399 nPreferredDownload = 0;
4400 setDirtyBlockIndex.clear();
4401 setDirtyFileInfo.clear();
4402 mapNodeState.clear();
4403 recentRejects.reset(NULL);
4405 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4406 delete entry.second;
4408 mapBlockIndex.clear();
4409 fHavePruned = false;
4412 bool LoadBlockIndex()
4414 // Load block index from databases
4415 if (!fReindex && !LoadBlockIndexDB())
4421 bool InitBlockIndex() {
4422 const CChainParams& chainparams = Params();
4425 // Initialize global variables that cannot be constructed at startup.
4426 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4428 // Check whether we're already initialized
4429 if (chainActive.Genesis() != NULL)
4432 // Use the provided setting for -txindex in the new database
4433 fTxIndex = GetBoolArg("-txindex", false);
4434 pblocktree->WriteFlag("txindex", fTxIndex);
4435 LogPrintf("Initializing databases...\n");
4437 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4440 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4441 // Start new block file
4442 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4443 CDiskBlockPos blockPos;
4444 CValidationState state;
4445 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4446 return error("LoadBlockIndex(): FindBlockPos failed");
4447 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4448 return error("LoadBlockIndex(): writing genesis block to disk failed");
4449 CBlockIndex *pindex = AddToBlockIndex(block);
4450 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4451 return error("LoadBlockIndex(): genesis block not accepted");
4452 if (!ActivateBestChain(state, &block))
4453 return error("LoadBlockIndex(): genesis block cannot be activated");
4454 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4455 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4456 } catch (const std::runtime_error& e) {
4457 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4466 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4468 const CChainParams& chainparams = Params();
4469 // Map of disk positions for blocks with unknown parent (only used for reindex)
4470 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4471 int64_t nStart = GetTimeMillis();
4475 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4476 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4477 uint64_t nRewind = blkdat.GetPos();
4478 while (!blkdat.eof()) {
4479 boost::this_thread::interruption_point();
4481 blkdat.SetPos(nRewind);
4482 nRewind++; // start one byte further next time, in case of failure
4483 blkdat.SetLimit(); // remove former limit
4484 unsigned int nSize = 0;
4487 unsigned char buf[MESSAGE_START_SIZE];
4488 blkdat.FindByte(Params().MessageStart()[0]);
4489 nRewind = blkdat.GetPos()+1;
4490 blkdat >> FLATDATA(buf);
4491 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4495 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4497 } catch (const std::exception&) {
4498 // no valid block header found; don't complain
4503 uint64_t nBlockPos = blkdat.GetPos();
4505 dbp->nPos = nBlockPos;
4506 blkdat.SetLimit(nBlockPos + nSize);
4507 blkdat.SetPos(nBlockPos);
4510 nRewind = blkdat.GetPos();
4512 // detect out of order blocks, and store them for later
4513 uint256 hash = block.GetHash();
4514 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4515 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4516 block.hashPrevBlock.ToString());
4518 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4522 // process in case the block isn't known yet
4523 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4524 CValidationState state;
4525 if (ProcessNewBlock(state, NULL, &block, true, dbp))
4527 if (state.IsError())
4529 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4530 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4533 // Recursively process earlier encountered successors of this block
4534 deque<uint256> queue;
4535 queue.push_back(hash);
4536 while (!queue.empty()) {
4537 uint256 head = queue.front();
4539 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4540 while (range.first != range.second) {
4541 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4542 if (ReadBlockFromDisk(block, it->second))
4544 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4546 CValidationState dummy;
4547 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
4550 queue.push_back(block.GetHash());
4554 mapBlocksUnknownParent.erase(it);
4557 } catch (const std::exception& e) {
4558 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4561 } catch (const std::runtime_error& e) {
4562 AbortNode(std::string("System error: ") + e.what());
4565 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4569 void static CheckBlockIndex()
4571 const Consensus::Params& consensusParams = Params().GetConsensus();
4572 if (!fCheckBlockIndex) {
4578 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4579 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4580 // iterating the block tree require that chainActive has been initialized.)
4581 if (chainActive.Height() < 0) {
4582 assert(mapBlockIndex.size() <= 1);
4586 // Build forward-pointing map of the entire block tree.
4587 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4588 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4589 forward.insert(std::make_pair(it->second->pprev, it->second));
4592 assert(forward.size() == mapBlockIndex.size());
4594 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4595 CBlockIndex *pindex = rangeGenesis.first->second;
4596 rangeGenesis.first++;
4597 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4599 // Iterate over the entire block tree, using depth-first search.
4600 // Along the way, remember whether there are blocks on the path from genesis
4601 // block being explored which are the first to have certain properties.
4604 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4605 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4606 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4607 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4608 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4609 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4610 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4611 while (pindex != NULL) {
4613 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4614 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4615 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4616 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4617 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4618 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4619 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4621 // Begin: actual consistency checks.
4622 if (pindex->pprev == NULL) {
4623 // Genesis block checks.
4624 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4625 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4627 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4628 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4629 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4631 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4632 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4633 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4635 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4636 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4638 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4639 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4640 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4641 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4642 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4643 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4644 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.
4645 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4646 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4647 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4648 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4649 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4650 if (pindexFirstInvalid == NULL) {
4651 // Checks for not-invalid blocks.
4652 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4654 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4655 if (pindexFirstInvalid == NULL) {
4656 // If this block sorts at least as good as the current tip and
4657 // is valid and we have all data for its parents, it must be in
4658 // setBlockIndexCandidates. chainActive.Tip() must also be there
4659 // even if some data has been pruned.
4660 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4661 assert(setBlockIndexCandidates.count(pindex));
4663 // If some parent is missing, then it could be that this block was in
4664 // setBlockIndexCandidates but had to be removed because of the missing data.
4665 // In this case it must be in mapBlocksUnlinked -- see test below.
4667 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4668 assert(setBlockIndexCandidates.count(pindex) == 0);
4670 // Check whether this block is in mapBlocksUnlinked.
4671 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4672 bool foundInUnlinked = false;
4673 while (rangeUnlinked.first != rangeUnlinked.second) {
4674 assert(rangeUnlinked.first->first == pindex->pprev);
4675 if (rangeUnlinked.first->second == pindex) {
4676 foundInUnlinked = true;
4679 rangeUnlinked.first++;
4681 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4682 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4683 assert(foundInUnlinked);
4685 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4686 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4687 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4688 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4689 assert(fHavePruned); // We must have pruned.
4690 // This block may have entered mapBlocksUnlinked if:
4691 // - it has a descendant that at some point had more work than the
4693 // - we tried switching to that descendant but were missing
4694 // data for some intermediate block between chainActive and the
4696 // So if this block is itself better than chainActive.Tip() and it wasn't in
4697 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4698 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4699 if (pindexFirstInvalid == NULL) {
4700 assert(foundInUnlinked);
4704 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4705 // End: actual consistency checks.
4707 // Try descending into the first subnode.
4708 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4709 if (range.first != range.second) {
4710 // A subnode was found.
4711 pindex = range.first->second;
4715 // This is a leaf node.
4716 // Move upwards until we reach a node of which we have not yet visited the last child.
4718 // We are going to either move to a parent or a sibling of pindex.
4719 // If pindex was the first with a certain property, unset the corresponding variable.
4720 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4721 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4722 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4723 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4724 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4725 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4726 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4728 CBlockIndex* pindexPar = pindex->pprev;
4729 // Find which child we just visited.
4730 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4731 while (rangePar.first->second != pindex) {
4732 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4735 // Proceed to the next one.
4737 if (rangePar.first != rangePar.second) {
4738 // Move to the sibling.
4739 pindex = rangePar.first->second;
4750 // Check that we actually traversed the entire map.
4751 assert(nNodes == forward.size());
4754 //////////////////////////////////////////////////////////////////////////////
4759 std::string GetWarnings(const std::string& strFor)
4762 string strStatusBar;
4765 if (!CLIENT_VERSION_IS_RELEASE)
4766 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4768 if (GetBoolArg("-testsafemode", false))
4769 strStatusBar = strRPC = "testsafemode enabled";
4771 // Misc warnings like out of disk space and clock is wrong
4772 if (strMiscWarning != "")
4775 strStatusBar = strMiscWarning;
4778 if (fLargeWorkForkFound)
4781 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4783 else if (fLargeWorkInvalidChainFound)
4786 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.");
4792 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4794 const CAlert& alert = item.second;
4795 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4797 nPriority = alert.nPriority;
4798 strStatusBar = alert.strStatusBar;
4799 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4800 strRPC = alert.strRPCError;
4806 if (strFor == "statusbar")
4807 return strStatusBar;
4808 else if (strFor == "rpc")
4810 assert(!"GetWarnings(): invalid parameter");
4821 //////////////////////////////////////////////////////////////////////////////
4827 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4833 assert(recentRejects);
4834 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4836 // If the chain tip has changed previously rejected transactions
4837 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4838 // or a double-spend. Reset the rejects filter and give those
4839 // txs a second chance.
4840 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4841 recentRejects->reset();
4844 return recentRejects->contains(inv.hash) ||
4845 mempool.exists(inv.hash) ||
4846 mapOrphanTransactions.count(inv.hash) ||
4847 pcoinsTip->HaveCoins(inv.hash);
4850 return mapBlockIndex.count(inv.hash);
4852 // Don't know what it is, just say we already got one
4856 void static ProcessGetData(CNode* pfrom)
4858 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4860 vector<CInv> vNotFound;
4864 while (it != pfrom->vRecvGetData.end()) {
4865 // Don't bother if send buffer is too full to respond anyway
4866 if (pfrom->nSendSize >= SendBufferSize())
4869 const CInv &inv = *it;
4871 boost::this_thread::interruption_point();
4874 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4877 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4878 if (mi != mapBlockIndex.end())
4880 if (chainActive.Contains(mi->second)) {
4883 static const int nOneMonth = 30 * 24 * 60 * 60;
4884 // To prevent fingerprinting attacks, only send blocks outside of the active
4885 // chain if they are valid, and no more than a month older (both in time, and in
4886 // best equivalent proof of work) than the best header chain we know about.
4887 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4888 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4889 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4891 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4895 // Pruned nodes may have deleted the block, so check whether
4896 // it's available before trying to send.
4897 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4899 // Send block from disk
4901 if (!ReadBlockFromDisk(block, (*mi).second))
4902 assert(!"cannot load block from disk");
4903 if (inv.type == MSG_BLOCK)
4904 pfrom->PushMessage("block", block);
4905 else // MSG_FILTERED_BLOCK)
4907 LOCK(pfrom->cs_filter);
4910 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4911 pfrom->PushMessage("merkleblock", merkleBlock);
4912 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4913 // This avoids hurting performance by pointlessly requiring a round-trip
4914 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4915 // they must either disconnect and retry or request the full block.
4916 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4917 // however we MUST always provide at least what the remote peer needs
4918 typedef std::pair<unsigned int, uint256> PairType;
4919 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4920 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4921 pfrom->PushMessage("tx", block.vtx[pair.first]);
4927 // Trigger the peer node to send a getblocks request for the next batch of inventory
4928 if (inv.hash == pfrom->hashContinue)
4930 // Bypass PushInventory, this must send even if redundant,
4931 // and we want it right after the last block so they don't
4932 // wait for other stuff first.
4934 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4935 pfrom->PushMessage("inv", vInv);
4936 pfrom->hashContinue.SetNull();
4940 else if (inv.IsKnownType())
4942 // Send stream from relay memory
4943 bool pushed = false;
4946 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4947 if (mi != mapRelay.end()) {
4948 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4952 if (!pushed && inv.type == MSG_TX) {
4954 if (mempool.lookup(inv.hash, tx)) {
4955 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4958 pfrom->PushMessage("tx", ss);
4963 vNotFound.push_back(inv);
4967 // Track requests for our stuff.
4968 GetMainSignals().Inventory(inv.hash);
4970 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4975 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4977 if (!vNotFound.empty()) {
4978 // Let the peer know that we didn't find what it asked for, so it doesn't
4979 // have to wait around forever. Currently only SPV clients actually care
4980 // about this message: it's needed when they are recursively walking the
4981 // dependencies of relevant unconfirmed transactions. SPV clients want to
4982 // do that because they want to know about (and store and rebroadcast and
4983 // risk analyze) the dependencies of transactions relevant to them, without
4984 // having to download the entire memory pool.
4985 pfrom->PushMessage("notfound", vNotFound);
4989 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4991 const CChainParams& chainparams = Params();
4992 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4993 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4995 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
5000 if (strCommand == "version")
5002 // Each connection can only send one version message
5003 if (pfrom->nVersion != 0)
5005 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
5006 Misbehaving(pfrom->GetId(), 1);
5013 uint64_t nNonce = 1;
5014 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
5015 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
5017 // disconnect from peers older than this proto version
5018 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5019 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5020 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
5021 pfrom->fDisconnect = true;
5025 // Reject incoming connections from nodes that don't know about the current epoch
5026 const Consensus::Params& params = Params().GetConsensus();
5027 auto currentEpoch = CurrentEpoch(GetHeight(), params);
5028 if (pfrom->nVersion < params.vUpgrades[currentEpoch].nProtocolVersion)
5030 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5031 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5032 strprintf("Version must be %d or greater",
5033 params.vUpgrades[currentEpoch].nProtocolVersion));
5034 pfrom->fDisconnect = true;
5038 if (pfrom->nVersion == 10300)
5039 pfrom->nVersion = 300;
5041 vRecv >> addrFrom >> nNonce;
5042 if (!vRecv.empty()) {
5043 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
5044 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
5047 vRecv >> pfrom->nStartingHeight;
5049 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
5051 pfrom->fRelayTxes = true;
5053 // Disconnect if we connected to ourself
5054 if (nNonce == nLocalHostNonce && nNonce > 1)
5056 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
5057 pfrom->fDisconnect = true;
5061 pfrom->addrLocal = addrMe;
5062 if (pfrom->fInbound && addrMe.IsRoutable())
5067 // Be shy and don't send version until we hear
5068 if (pfrom->fInbound)
5069 pfrom->PushVersion();
5071 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
5073 // Potentially mark this peer as a preferred download peer.
5074 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
5077 pfrom->PushMessage("verack");
5078 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5080 if (!pfrom->fInbound)
5082 // Advertise our address
5083 if (fListen && !IsInitialBlockDownload())
5085 CAddress addr = GetLocalAddress(&pfrom->addr);
5086 if (addr.IsRoutable())
5088 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5089 pfrom->PushAddress(addr);
5090 } else if (IsPeerAddrLocalGood(pfrom)) {
5091 addr.SetIP(pfrom->addrLocal);
5092 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5093 pfrom->PushAddress(addr);
5097 // Get recent addresses
5098 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
5100 pfrom->PushMessage("getaddr");
5101 pfrom->fGetAddr = true;
5103 addrman.Good(pfrom->addr);
5105 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
5107 addrman.Add(addrFrom, addrFrom);
5108 addrman.Good(addrFrom);
5115 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
5116 item.second.RelayTo(pfrom);
5119 pfrom->fSuccessfullyConnected = true;
5123 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
5125 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
5126 pfrom->cleanSubVer, pfrom->nVersion,
5127 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
5130 int64_t nTimeOffset = nTime - GetTime();
5131 pfrom->nTimeOffset = nTimeOffset;
5132 AddTimeData(pfrom->addr, nTimeOffset);
5136 else if (pfrom->nVersion == 0)
5138 // Must have a version message before anything else
5139 Misbehaving(pfrom->GetId(), 1);
5144 else if (strCommand == "verack")
5146 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5148 // Mark this node as currently connected, so we update its timestamp later.
5149 if (pfrom->fNetworkNode) {
5151 State(pfrom->GetId())->fCurrentlyConnected = true;
5156 // Disconnect existing peer connection when:
5157 // 1. The version message has been received
5158 // 2. Peer version is below the minimum version for the current epoch
5159 else if (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[
5160 CurrentEpoch(GetHeight(), chainparams.GetConsensus())].nProtocolVersion)
5162 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5163 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5164 strprintf("Version must be %d or greater",
5165 chainparams.GetConsensus().vUpgrades[
5166 CurrentEpoch(GetHeight(), chainparams.GetConsensus())].nProtocolVersion));
5167 pfrom->fDisconnect = true;
5172 else if (strCommand == "addr")
5174 vector<CAddress> vAddr;
5177 // Don't want addr from older versions unless seeding
5178 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
5180 if (vAddr.size() > 1000)
5182 Misbehaving(pfrom->GetId(), 20);
5183 return error("message addr size() = %u", vAddr.size());
5186 // Store the new addresses
5187 vector<CAddress> vAddrOk;
5188 int64_t nNow = GetAdjustedTime();
5189 int64_t nSince = nNow - 10 * 60;
5190 BOOST_FOREACH(CAddress& addr, vAddr)
5192 boost::this_thread::interruption_point();
5194 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
5195 addr.nTime = nNow - 5 * 24 * 60 * 60;
5196 pfrom->AddAddressKnown(addr);
5197 bool fReachable = IsReachable(addr);
5198 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
5200 // Relay to a limited number of other nodes
5203 // Use deterministic randomness to send to the same nodes for 24 hours
5204 // at a time so the addrKnowns of the chosen nodes prevent repeats
5205 static uint256 hashSalt;
5206 if (hashSalt.IsNull())
5207 hashSalt = GetRandHash();
5208 uint64_t hashAddr = addr.GetHash();
5209 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
5210 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5211 multimap<uint256, CNode*> mapMix;
5212 BOOST_FOREACH(CNode* pnode, vNodes)
5214 if (pnode->nVersion < CADDR_TIME_VERSION)
5216 unsigned int nPointer;
5217 memcpy(&nPointer, &pnode, sizeof(nPointer));
5218 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
5219 hashKey = Hash(BEGIN(hashKey), END(hashKey));
5220 mapMix.insert(make_pair(hashKey, pnode));
5222 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
5223 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
5224 ((*mi).second)->PushAddress(addr);
5227 // Do not store addresses outside our network
5229 vAddrOk.push_back(addr);
5231 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
5232 if (vAddr.size() < 1000)
5233 pfrom->fGetAddr = false;
5234 if (pfrom->fOneShot)
5235 pfrom->fDisconnect = true;
5239 else if (strCommand == "inv")
5243 if (vInv.size() > MAX_INV_SZ)
5245 Misbehaving(pfrom->GetId(), 20);
5246 return error("message inv size() = %u", vInv.size());
5251 std::vector<CInv> vToFetch;
5253 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
5255 const CInv &inv = vInv[nInv];
5257 boost::this_thread::interruption_point();
5258 pfrom->AddInventoryKnown(inv);
5260 bool fAlreadyHave = AlreadyHave(inv);
5261 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
5263 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
5266 if (inv.type == MSG_BLOCK) {
5267 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
5268 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
5269 // First request the headers preceding the announced block. In the normal fully-synced
5270 // case where a new block is announced that succeeds the current tip (no reorganization),
5271 // there are no such headers.
5272 // Secondly, and only when we are close to being synced, we request the announced block directly,
5273 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
5274 // time the block arrives, the header chain leading up to it is already validated. Not
5275 // doing this will result in the received block being rejected as an orphan in case it is
5276 // not a direct successor.
5277 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
5278 CNodeState *nodestate = State(pfrom->GetId());
5279 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
5280 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5281 vToFetch.push_back(inv);
5282 // Mark block as in flight already, even though the actual "getdata" message only goes out
5283 // later (within the same cs_main lock, though).
5284 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
5286 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
5290 // Track requests for our stuff
5291 GetMainSignals().Inventory(inv.hash);
5293 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
5294 Misbehaving(pfrom->GetId(), 50);
5295 return error("send buffer size() = %u", pfrom->nSendSize);
5299 if (!vToFetch.empty())
5300 pfrom->PushMessage("getdata", vToFetch);
5304 else if (strCommand == "getdata")
5308 if (vInv.size() > MAX_INV_SZ)
5310 Misbehaving(pfrom->GetId(), 20);
5311 return error("message getdata size() = %u", vInv.size());
5314 if (fDebug || (vInv.size() != 1))
5315 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
5317 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
5318 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
5320 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
5321 ProcessGetData(pfrom);
5325 else if (strCommand == "getblocks")
5327 CBlockLocator locator;
5329 vRecv >> locator >> hashStop;
5333 // Find the last block the caller has in the main chain
5334 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
5336 // Send the rest of the chain
5338 pindex = chainActive.Next(pindex);
5340 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
5341 for (; pindex; pindex = chainActive.Next(pindex))
5343 if (pindex->GetBlockHash() == hashStop)
5345 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5348 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5351 // When this block is requested, we'll send an inv that'll
5352 // trigger the peer to getblocks the next batch of inventory.
5353 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5354 pfrom->hashContinue = pindex->GetBlockHash();
5361 else if (strCommand == "getheaders")
5363 CBlockLocator locator;
5365 vRecv >> locator >> hashStop;
5369 if (IsInitialBlockDownload())
5372 CBlockIndex* pindex = NULL;
5373 if (locator.IsNull())
5375 // If locator is null, return the hashStop block
5376 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
5377 if (mi == mapBlockIndex.end())
5379 pindex = (*mi).second;
5383 // Find the last block the caller has in the main chain
5384 pindex = FindForkInGlobalIndex(chainActive, locator);
5386 pindex = chainActive.Next(pindex);
5389 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5390 vector<CBlock> vHeaders;
5391 int nLimit = MAX_HEADERS_RESULTS;
5392 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5393 for (; pindex; pindex = chainActive.Next(pindex))
5395 vHeaders.push_back(pindex->GetBlockHeader());
5396 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5399 pfrom->PushMessage("headers", vHeaders);
5403 else if (strCommand == "tx")
5405 vector<uint256> vWorkQueue;
5406 vector<uint256> vEraseQueue;
5410 CInv inv(MSG_TX, tx.GetHash());
5411 pfrom->AddInventoryKnown(inv);
5415 bool fMissingInputs = false;
5416 CValidationState state;
5418 pfrom->setAskFor.erase(inv.hash);
5419 mapAlreadyAskedFor.erase(inv);
5421 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5423 mempool.check(pcoinsTip);
5424 RelayTransaction(tx);
5425 vWorkQueue.push_back(inv.hash);
5427 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5428 pfrom->id, pfrom->cleanSubVer,
5429 tx.GetHash().ToString(),
5430 mempool.mapTx.size());
5432 // Recursively process any orphan transactions that depended on this one
5433 set<NodeId> setMisbehaving;
5434 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5436 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5437 if (itByPrev == mapOrphanTransactionsByPrev.end())
5439 for (set<uint256>::iterator mi = itByPrev->second.begin();
5440 mi != itByPrev->second.end();
5443 const uint256& orphanHash = *mi;
5444 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5445 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5446 bool fMissingInputs2 = false;
5447 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5448 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5449 // anyone relaying LegitTxX banned)
5450 CValidationState stateDummy;
5453 if (setMisbehaving.count(fromPeer))
5455 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5457 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5458 RelayTransaction(orphanTx);
5459 vWorkQueue.push_back(orphanHash);
5460 vEraseQueue.push_back(orphanHash);
5462 else if (!fMissingInputs2)
5465 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5467 // Punish peer that gave us an invalid orphan tx
5468 Misbehaving(fromPeer, nDos);
5469 setMisbehaving.insert(fromPeer);
5470 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5472 // Has inputs but not accepted to mempool
5473 // Probably non-standard or insufficient fee/priority
5474 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5475 vEraseQueue.push_back(orphanHash);
5476 assert(recentRejects);
5477 recentRejects->insert(orphanHash);
5479 mempool.check(pcoinsTip);
5483 BOOST_FOREACH(uint256 hash, vEraseQueue)
5484 EraseOrphanTx(hash);
5486 // TODO: currently, prohibit joinsplits and shielded spends/outputs from entering mapOrphans
5487 else if (fMissingInputs &&
5488 tx.vjoinsplit.empty() &&
5489 tx.vShieldedSpend.empty() &&
5490 tx.vShieldedOutput.empty())
5492 AddOrphanTx(tx, pfrom->GetId());
5494 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5495 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5496 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5498 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5500 assert(recentRejects);
5501 recentRejects->insert(tx.GetHash());
5503 if (pfrom->fWhitelisted) {
5504 // Always relay transactions received from whitelisted peers, even
5505 // if they were already in the mempool or rejected from it due
5506 // to policy, allowing the node to function as a gateway for
5507 // nodes hidden behind it.
5509 // Never relay transactions that we would assign a non-zero DoS
5510 // score for, as we expect peers to do the same with us in that
5513 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5514 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5515 RelayTransaction(tx);
5517 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5518 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5523 if (state.IsInvalid(nDoS))
5525 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5526 pfrom->id, pfrom->cleanSubVer,
5527 state.GetRejectReason());
5528 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5529 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5531 Misbehaving(pfrom->GetId(), nDoS);
5536 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5538 std::vector<CBlockHeader> headers;
5540 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5541 unsigned int nCount = ReadCompactSize(vRecv);
5542 if (nCount > MAX_HEADERS_RESULTS) {
5543 Misbehaving(pfrom->GetId(), 20);
5544 return error("headers message size = %u", nCount);
5546 headers.resize(nCount);
5547 for (unsigned int n = 0; n < nCount; n++) {
5548 vRecv >> headers[n];
5549 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5555 // Nothing interesting. Stop asking this peers for more headers.
5559 CBlockIndex *pindexLast = NULL;
5560 BOOST_FOREACH(const CBlockHeader& header, headers) {
5561 CValidationState state;
5562 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5563 Misbehaving(pfrom->GetId(), 20);
5564 return error("non-continuous headers sequence");
5566 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5568 if (state.IsInvalid(nDoS)) {
5570 Misbehaving(pfrom->GetId(), nDoS);
5571 return error("invalid header received");
5577 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5579 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5580 // Headers message had its maximum size; the peer may have more headers.
5581 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5582 // from there instead.
5583 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5584 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5590 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5595 CInv inv(MSG_BLOCK, block.GetHash());
5596 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5598 pfrom->AddInventoryKnown(inv);
5600 CValidationState state;
5601 // Process all blocks from whitelisted peers, even if not requested,
5602 // unless we're still syncing with the network.
5603 // Such an unrequested block may still be processed, subject to the
5604 // conditions in AcceptBlock().
5605 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5606 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
5608 if (state.IsInvalid(nDoS)) {
5609 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5610 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5613 Misbehaving(pfrom->GetId(), nDoS);
5620 // This asymmetric behavior for inbound and outbound connections was introduced
5621 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5622 // to users' AddrMan and later request them by sending getaddr messages.
5623 // Making nodes which are behind NAT and can only make outgoing connections ignore
5624 // the getaddr message mitigates the attack.
5625 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5627 // Only send one GetAddr response per connection to reduce resource waste
5628 // and discourage addr stamping of INV announcements.
5629 if (pfrom->fSentAddr) {
5630 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5633 pfrom->fSentAddr = true;
5635 pfrom->vAddrToSend.clear();
5636 vector<CAddress> vAddr = addrman.GetAddr();
5637 BOOST_FOREACH(const CAddress &addr, vAddr)
5638 pfrom->PushAddress(addr);
5642 else if (strCommand == "mempool")
5644 LOCK2(cs_main, pfrom->cs_filter);
5646 std::vector<uint256> vtxid;
5647 mempool.queryHashes(vtxid);
5649 BOOST_FOREACH(uint256& hash, vtxid) {
5650 CInv inv(MSG_TX, hash);
5651 if (pfrom->pfilter) {
5653 bool fInMemPool = mempool.lookup(hash, tx);
5654 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5655 if (!pfrom->pfilter->IsRelevantAndUpdate(tx)) continue;
5657 vInv.push_back(inv);
5658 if (vInv.size() == MAX_INV_SZ) {
5659 pfrom->PushMessage("inv", vInv);
5663 if (vInv.size() > 0)
5664 pfrom->PushMessage("inv", vInv);
5668 else if (strCommand == "ping")
5670 if (pfrom->nVersion > BIP0031_VERSION)
5674 // Echo the message back with the nonce. This allows for two useful features:
5676 // 1) A remote node can quickly check if the connection is operational
5677 // 2) Remote nodes can measure the latency of the network thread. If this node
5678 // is overloaded it won't respond to pings quickly and the remote node can
5679 // avoid sending us more work, like chain download requests.
5681 // The nonce stops the remote getting confused between different pings: without
5682 // it, if the remote node sends a ping once per second and this node takes 5
5683 // seconds to respond to each, the 5th ping the remote sends would appear to
5684 // return very quickly.
5685 pfrom->PushMessage("pong", nonce);
5690 else if (strCommand == "pong")
5692 int64_t pingUsecEnd = nTimeReceived;
5694 size_t nAvail = vRecv.in_avail();
5695 bool bPingFinished = false;
5696 std::string sProblem;
5698 if (nAvail >= sizeof(nonce)) {
5701 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5702 if (pfrom->nPingNonceSent != 0) {
5703 if (nonce == pfrom->nPingNonceSent) {
5704 // Matching pong received, this ping is no longer outstanding
5705 bPingFinished = true;
5706 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5707 if (pingUsecTime > 0) {
5708 // Successful ping time measurement, replace previous
5709 pfrom->nPingUsecTime = pingUsecTime;
5710 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5712 // This should never happen
5713 sProblem = "Timing mishap";
5716 // Nonce mismatches are normal when pings are overlapping
5717 sProblem = "Nonce mismatch";
5719 // This is most likely a bug in another implementation somewhere; cancel this ping
5720 bPingFinished = true;
5721 sProblem = "Nonce zero";
5725 sProblem = "Unsolicited pong without ping";
5728 // This is most likely a bug in another implementation somewhere; cancel this ping
5729 bPingFinished = true;
5730 sProblem = "Short payload";
5733 if (!(sProblem.empty())) {
5734 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5738 pfrom->nPingNonceSent,
5742 if (bPingFinished) {
5743 pfrom->nPingNonceSent = 0;
5748 else if (fAlerts && strCommand == "alert")
5753 uint256 alertHash = alert.GetHash();
5754 if (pfrom->setKnown.count(alertHash) == 0)
5756 if (alert.ProcessAlert(Params().AlertKey()))
5759 pfrom->setKnown.insert(alertHash);
5762 BOOST_FOREACH(CNode* pnode, vNodes)
5763 alert.RelayTo(pnode);
5767 // Small DoS penalty so peers that send us lots of
5768 // duplicate/expired/invalid-signature/whatever alerts
5769 // eventually get banned.
5770 // This isn't a Misbehaving(100) (immediate ban) because the
5771 // peer might be an older or different implementation with
5772 // a different signature key, etc.
5773 Misbehaving(pfrom->GetId(), 10);
5779 else if (!(nLocalServices & NODE_BLOOM) &&
5780 (strCommand == "filterload" ||
5781 strCommand == "filteradd"))
5783 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
5784 Misbehaving(pfrom->GetId(), 100);
5786 } else if (GetBoolArg("-enforcenodebloom", false)) {
5787 pfrom->fDisconnect = true;
5793 else if (strCommand == "filterload")
5795 CBloomFilter filter;
5798 if (!filter.IsWithinSizeConstraints())
5799 // There is no excuse for sending a too-large filter
5800 Misbehaving(pfrom->GetId(), 100);
5803 LOCK(pfrom->cs_filter);
5804 delete pfrom->pfilter;
5805 pfrom->pfilter = new CBloomFilter(filter);
5806 pfrom->pfilter->UpdateEmptyFull();
5808 pfrom->fRelayTxes = true;
5812 else if (strCommand == "filteradd")
5814 vector<unsigned char> vData;
5817 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5818 // and thus, the maximum size any matched object can have) in a filteradd message
5819 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5821 Misbehaving(pfrom->GetId(), 100);
5823 LOCK(pfrom->cs_filter);
5825 pfrom->pfilter->insert(vData);
5827 Misbehaving(pfrom->GetId(), 100);
5832 else if (strCommand == "filterclear")
5834 LOCK(pfrom->cs_filter);
5835 if (nLocalServices & NODE_BLOOM) {
5836 delete pfrom->pfilter;
5837 pfrom->pfilter = new CBloomFilter();
5839 pfrom->fRelayTxes = true;
5843 else if (strCommand == "reject")
5847 string strMsg; unsigned char ccode; string strReason;
5848 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5851 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5853 if (strMsg == "block" || strMsg == "tx")
5857 ss << ": hash " << hash.ToString();
5859 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5860 } catch (const std::ios_base::failure&) {
5861 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5862 LogPrint("net", "Unparseable reject message received\n");
5867 else if (strCommand == "notfound") {
5868 // We do not care about the NOTFOUND message, but logging an Unknown Command
5869 // message would be undesirable as we transmit it ourselves.
5873 // Ignore unknown commands for extensibility
5874 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5882 // requires LOCK(cs_vRecvMsg)
5883 bool ProcessMessages(CNode* pfrom)
5886 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5890 // (4) message start
5898 if (!pfrom->vRecvGetData.empty())
5899 ProcessGetData(pfrom);
5901 // this maintains the order of responses
5902 if (!pfrom->vRecvGetData.empty()) return fOk;
5904 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5905 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5906 // Don't bother if send buffer is too full to respond anyway
5907 if (pfrom->nSendSize >= SendBufferSize())
5911 CNetMessage& msg = *it;
5914 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5915 // msg.hdr.nMessageSize, msg.vRecv.size(),
5916 // msg.complete() ? "Y" : "N");
5918 // end, if an incomplete message is found
5919 if (!msg.complete())
5922 // at this point, any failure means we can delete the current message
5925 // Scan for message start
5926 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5927 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5933 CMessageHeader& hdr = msg.hdr;
5934 if (!hdr.IsValid(Params().MessageStart()))
5936 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5939 string strCommand = hdr.GetCommand();
5942 unsigned int nMessageSize = hdr.nMessageSize;
5945 CDataStream& vRecv = msg.vRecv;
5946 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5947 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5948 if (nChecksum != hdr.nChecksum)
5950 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5951 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5959 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5960 boost::this_thread::interruption_point();
5962 catch (const std::ios_base::failure& e)
5964 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5965 if (strstr(e.what(), "end of data"))
5967 // Allow exceptions from under-length message on vRecv
5968 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());
5970 else if (strstr(e.what(), "size too large"))
5972 // Allow exceptions from over-long size
5973 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5977 PrintExceptionContinue(&e, "ProcessMessages()");
5980 catch (const boost::thread_interrupted&) {
5983 catch (const std::exception& e) {
5984 PrintExceptionContinue(&e, "ProcessMessages()");
5986 PrintExceptionContinue(NULL, "ProcessMessages()");
5990 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5995 // In case the connection got shut down, its receive buffer was wiped
5996 if (!pfrom->fDisconnect)
5997 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
6003 bool SendMessages(CNode* pto, bool fSendTrickle)
6005 const Consensus::Params& consensusParams = Params().GetConsensus();
6007 // Don't send anything until we get its version message
6008 if (pto->nVersion == 0)
6014 bool pingSend = false;
6015 if (pto->fPingQueued) {
6016 // RPC ping request by user
6019 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
6020 // Ping automatically sent as a latency probe & keepalive.
6025 while (nonce == 0) {
6026 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
6028 pto->fPingQueued = false;
6029 pto->nPingUsecStart = GetTimeMicros();
6030 if (pto->nVersion > BIP0031_VERSION) {
6031 pto->nPingNonceSent = nonce;
6032 pto->PushMessage("ping", nonce);
6034 // Peer is too old to support ping command with nonce, pong will never arrive.
6035 pto->nPingNonceSent = 0;
6036 pto->PushMessage("ping");
6040 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
6044 // Address refresh broadcast
6045 static int64_t nLastRebroadcast;
6046 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
6049 BOOST_FOREACH(CNode* pnode, vNodes)
6051 // Periodically clear addrKnown to allow refresh broadcasts
6052 if (nLastRebroadcast)
6053 pnode->addrKnown.reset();
6055 // Rebroadcast our address
6056 AdvertizeLocal(pnode);
6058 if (!vNodes.empty())
6059 nLastRebroadcast = GetTime();
6067 vector<CAddress> vAddr;
6068 vAddr.reserve(pto->vAddrToSend.size());
6069 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
6071 if (!pto->addrKnown.contains(addr.GetKey()))
6073 pto->addrKnown.insert(addr.GetKey());
6074 vAddr.push_back(addr);
6075 // receiver rejects addr messages larger than 1000
6076 if (vAddr.size() >= 1000)
6078 pto->PushMessage("addr", vAddr);
6083 pto->vAddrToSend.clear();
6085 pto->PushMessage("addr", vAddr);
6088 CNodeState &state = *State(pto->GetId());
6089 if (state.fShouldBan) {
6090 if (pto->fWhitelisted)
6091 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
6093 pto->fDisconnect = true;
6094 if (pto->addr.IsLocal())
6095 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
6098 CNode::Ban(pto->addr);
6101 state.fShouldBan = false;
6104 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
6105 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
6106 state.rejects.clear();
6109 if (pindexBestHeader == NULL)
6110 pindexBestHeader = chainActive.Tip();
6111 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.
6112 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
6113 // Only actively request headers from a single peer, unless we're close to today.
6114 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
6115 state.fSyncStarted = true;
6117 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
6118 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
6119 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
6123 // Resend wallet transactions that haven't gotten in a block yet
6124 // Except during reindex, importing and IBD, when old wallet
6125 // transactions become unconfirmed and spams other nodes.
6126 if (!fReindex && !fImporting && !IsInitialBlockDownload())
6128 GetMainSignals().Broadcast(nTimeBestReceived);
6132 // Message: inventory
6135 vector<CInv> vInvWait;
6137 LOCK(pto->cs_inventory);
6138 vInv.reserve(pto->vInventoryToSend.size());
6139 vInvWait.reserve(pto->vInventoryToSend.size());
6140 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
6142 if (pto->setInventoryKnown.count(inv))
6145 // trickle out tx inv to protect privacy
6146 if (inv.type == MSG_TX && !fSendTrickle)
6148 // 1/4 of tx invs blast to all immediately
6149 static uint256 hashSalt;
6150 if (hashSalt.IsNull())
6151 hashSalt = GetRandHash();
6152 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
6153 hashRand = Hash(BEGIN(hashRand), END(hashRand));
6154 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
6158 vInvWait.push_back(inv);
6163 // returns true if wasn't already contained in the set
6164 if (pto->setInventoryKnown.insert(inv).second)
6166 vInv.push_back(inv);
6167 if (vInv.size() >= 1000)
6169 pto->PushMessage("inv", vInv);
6174 pto->vInventoryToSend = vInvWait;
6177 pto->PushMessage("inv", vInv);
6179 // Detect whether we're stalling
6180 int64_t nNow = GetTimeMicros();
6181 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
6182 // Stalling only triggers when the block download window cannot move. During normal steady state,
6183 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6184 // should only happen during initial block download.
6185 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
6186 pto->fDisconnect = true;
6188 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
6189 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
6190 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
6191 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6192 // to unreasonably increase our timeout.
6193 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
6194 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
6195 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
6196 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
6197 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
6198 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
6199 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
6200 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
6201 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
6202 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
6203 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
6205 if (queuedBlock.nTimeDisconnect < nNow) {
6206 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
6207 pto->fDisconnect = true;
6212 // Message: getdata (blocks)
6214 vector<CInv> vGetData;
6215 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
6216 vector<CBlockIndex*> vToDownload;
6217 NodeId staller = -1;
6218 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
6219 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
6220 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
6221 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
6222 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6223 pindex->nHeight, pto->id);
6225 if (state.nBlocksInFlight == 0 && staller != -1) {
6226 if (State(staller)->nStallingSince == 0) {
6227 State(staller)->nStallingSince = nNow;
6228 LogPrint("net", "Stall started peer=%d\n", staller);
6234 // Message: getdata (non-blocks)
6236 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
6238 const CInv& inv = (*pto->mapAskFor.begin()).second;
6239 if (!AlreadyHave(inv))
6242 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
6243 vGetData.push_back(inv);
6244 if (vGetData.size() >= 1000)
6246 pto->PushMessage("getdata", vGetData);
6250 //If we're not going to ask, don't expect a response.
6251 pto->setAskFor.erase(inv.hash);
6253 pto->mapAskFor.erase(pto->mapAskFor.begin());
6255 if (!vGetData.empty())
6256 pto->PushMessage("getdata", vGetData);
6262 std::string CBlockFileInfo::ToString() const {
6263 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));
6268 static class CMainCleanup
6274 BlockMap::iterator it1 = mapBlockIndex.begin();
6275 for (; it1 != mapBlockIndex.end(); it1++)
6276 delete (*it1).second;
6277 mapBlockIndex.clear();
6279 // orphan transactions
6280 mapOrphanTransactions.clear();
6281 mapOrphanTransactionsByPrev.clear();
6283 } instance_of_cmaincleanup;
6286 // Set default values of new CMutableTransaction based on consensus rules at given height.
6287 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
6289 CMutableTransaction mtx;
6291 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
6292 if (isOverwintered) {
6293 mtx.fOverwintered = true;
6294 mtx.nExpiryHeight = nHeight + expiryDelta;
6296 if (NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING)) {
6297 mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
6298 mtx.nVersion = SAPLING_TX_VERSION;
6300 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
6301 mtx.nVersion = OVERWINTER_TX_VERSION;
6302 mtx.nExpiryHeight = std::min(
6304 static_cast<uint32_t>(consensusParams.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight - 1));