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).
881 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const int nHeight, const int dosLevel)
883 bool overwinterActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
884 bool saplingActive = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING);
885 bool isSprout = !overwinterActive;
887 // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond
888 if (isSprout && tx.fOverwintered) {
889 return state.DoS(IsInitialBlockDownload() ? 0 : dosLevel,
890 error("ContextualCheckTransaction(): overwinter is not active yet"),
891 REJECT_INVALID, "tx-overwinter-not-active");
895 // Reject transactions with valid version but missing overwintered flag
896 if (tx.nVersion >= SAPLING_MIN_TX_VERSION && !tx.fOverwintered) {
897 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwintered flag must be set"),
898 REJECT_INVALID, "tx-overwintered-flag-not-set");
901 // Reject transactions with non-Sapling version group ID
902 if (tx.fOverwintered && tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
903 return state.DoS(dosLevel, error("CheckTransaction(): invalid Sapling tx version"),
904 REJECT_INVALID, "bad-sapling-tx-version-group-id");
907 // Reject transactions with invalid version
908 if (tx.fOverwintered && tx.nVersion < SAPLING_MIN_TX_VERSION ) {
909 return state.DoS(100, error("CheckTransaction(): Sapling version too low"),
910 REJECT_INVALID, "bad-tx-sapling-version-too-low");
913 // Reject transactions with invalid version
914 if (tx.fOverwintered && tx.nVersion > SAPLING_MAX_TX_VERSION ) {
915 return state.DoS(100, error("CheckTransaction(): Sapling version too high"),
916 REJECT_INVALID, "bad-tx-sapling-version-too-high");
918 } else if (overwinterActive) {
919 // Reject transactions with valid version but missing overwinter flag
920 if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) {
921 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"),
922 REJECT_INVALID, "tx-overwinter-flag-not-set");
925 // Reject transactions with non-Overwinter version group ID
926 if (tx.fOverwintered && tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
927 return state.DoS(dosLevel, error("CheckTransaction(): invalid Overwinter tx version"),
928 REJECT_INVALID, "bad-overwinter-tx-version-group-id");
931 // Reject transactions with invalid version
932 if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) {
933 return state.DoS(100, error("CheckTransaction(): overwinter version too high"),
934 REJECT_INVALID, "bad-tx-overwinter-version-too-high");
938 // Rules that apply to Overwinter or later:
939 if (overwinterActive) {
940 // Reject transactions intended for Sprout
941 if (!tx.fOverwintered) {
942 return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"),
943 REJECT_INVALID, "tx-overwinter-active");
946 // Check that all transactions are unexpired
947 if (IsExpiredTx(tx, nHeight)) {
948 // Don't increase banscore if the transaction only just expired
949 int expiredDosLevel = IsExpiredTx(tx, nHeight - 1) ? dosLevel : 0;
950 return state.DoS(expiredDosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired");
954 // Rules that apply before Sapling:
955 if (!saplingActive) {
957 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
958 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_BEFORE_SAPLING)
959 return state.DoS(100, error("ContextualCheckTransaction(): size limits failed"),
960 REJECT_INVALID, "bad-txns-oversize");
963 uint256 dataToBeSigned;
965 if (!tx.vjoinsplit.empty() ||
966 !tx.vShieldedSpend.empty() ||
967 !tx.vShieldedOutput.empty())
969 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
970 // Empty output script.
973 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId);
974 } catch (std::logic_error ex) {
975 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
976 REJECT_INVALID, "error-computing-signature-hash");
980 if (!tx.vjoinsplit.empty())
982 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
984 // We rely on libsodium to check that the signature is canonical.
985 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
986 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
987 dataToBeSigned.begin(), 32,
988 tx.joinSplitPubKey.begin()
990 return state.DoS(IsInitialBlockDownload() ? 0 : 100,
991 error("CheckTransaction(): invalid joinsplit signature"),
992 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
996 if (!tx.vShieldedSpend.empty() ||
997 !tx.vShieldedOutput.empty())
999 auto ctx = librustzcash_sapling_verification_ctx_init();
1001 for (const SpendDescription &spend : tx.vShieldedSpend) {
1002 if (!librustzcash_sapling_check_spend(
1005 spend.anchor.begin(),
1006 spend.nullifier.begin(),
1008 spend.zkproof.begin(),
1009 spend.spendAuthSig.begin(),
1010 dataToBeSigned.begin()
1013 librustzcash_sapling_verification_ctx_free(ctx);
1014 return state.DoS(100, error("ContextualCheckTransaction(): Sapling spend description invalid"),
1015 REJECT_INVALID, "bad-txns-sapling-spend-description-invalid");
1019 for (const OutputDescription &output : tx.vShieldedOutput) {
1020 if (!librustzcash_sapling_check_output(
1024 output.ephemeralKey.begin(),
1025 output.zkproof.begin()
1028 librustzcash_sapling_verification_ctx_free(ctx);
1029 return state.DoS(100, error("ContextualCheckTransaction(): Sapling output description invalid"),
1030 REJECT_INVALID, "bad-txns-sapling-output-description-invalid");
1034 if (!librustzcash_sapling_final_check(
1037 tx.bindingSig.begin(),
1038 dataToBeSigned.begin()
1041 librustzcash_sapling_verification_ctx_free(ctx);
1042 return state.DoS(100, error("ContextualCheckTransaction(): Sapling binding signature invalid"),
1043 REJECT_INVALID, "bad-txns-sapling-binding-signature-invalid");
1046 librustzcash_sapling_verification_ctx_free(ctx);
1052 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
1053 libzcash::ProofVerifier& verifier)
1055 // Don't count coinbase transactions because mining skews the count
1056 if (!tx.IsCoinBase()) {
1057 transactionsValidated.increment();
1060 if (!CheckTransactionWithoutProofVerification(tx, state)) {
1063 // Ensure that zk-SNARKs verify
1064 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1065 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
1066 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
1067 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
1074 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
1076 // Basic checks that don't depend on any context
1080 * 1. The consensus rule below was:
1081 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
1082 * which checked if tx.nVersion fell within the range:
1083 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
1084 * 2. The parser allowed tx.nVersion to be negative
1087 * 1. The consensus rule checks to see if tx.Version falls within the range:
1088 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
1089 * 2. The previous consensus rule checked for negative values within the range:
1090 * INT32_MIN <= tx.nVersion < 0
1091 * This is unnecessary for Overwinter transactions since the parser now
1092 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
1093 * and when Overwinter is not active ContextualCheckTransaction rejects
1094 * transactions with fOverwintered set. When fOverwintered is set,
1095 * this function and ContextualCheckTransaction will together check to
1096 * ensure tx.nVersion avoids the following ranges:
1097 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
1098 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
1100 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
1101 return state.DoS(100, error("CheckTransaction(): version too low"),
1102 REJECT_INVALID, "bad-txns-version-too-low");
1104 else if (tx.fOverwintered) {
1105 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
1106 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
1107 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
1109 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID &&
1110 tx.nVersionGroupId != SAPLING_VERSION_GROUP_ID) {
1111 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
1112 REJECT_INVALID, "bad-tx-version-group-id");
1114 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
1115 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
1116 REJECT_INVALID, "bad-tx-expiry-height-too-high");
1120 // Transactions containing empty `vin` must have either non-empty
1121 // `vjoinsplit` or non-empty `vShieldedSpend`.
1122 if (tx.vin.empty() && tx.vjoinsplit.empty() && tx.vShieldedSpend.empty())
1123 return state.DoS(10, error("CheckTransaction(): vin empty"),
1124 REJECT_INVALID, "bad-txns-vin-empty");
1125 // Transactions containing empty `vout` must have either non-empty
1126 // `vjoinsplit` or non-empty `vShieldedOutput`.
1127 if (tx.vout.empty() && tx.vjoinsplit.empty() && tx.vShieldedOutput.empty())
1128 return state.DoS(10, error("CheckTransaction(): vout empty"),
1129 REJECT_INVALID, "bad-txns-vout-empty");
1132 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE >= MAX_TX_SIZE_AFTER_SAPLING); // sanity
1133 BOOST_STATIC_ASSERT(MAX_TX_SIZE_AFTER_SAPLING > MAX_TX_SIZE_BEFORE_SAPLING); // sanity
1134 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE_AFTER_SAPLING)
1135 return state.DoS(100, error("CheckTransaction(): size limits failed"),
1136 REJECT_INVALID, "bad-txns-oversize");
1138 // Check for negative or overflow output values
1139 CAmount nValueOut = 0;
1140 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1142 if (txout.nValue < 0)
1143 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
1144 REJECT_INVALID, "bad-txns-vout-negative");
1145 if (txout.nValue > MAX_MONEY)
1146 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
1147 REJECT_INVALID, "bad-txns-vout-toolarge");
1148 nValueOut += txout.nValue;
1149 if (!MoneyRange(nValueOut))
1150 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1151 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1154 // Check for non-zero valueBalance when there are no Sapling inputs or outputs
1155 if (tx.vShieldedSpend.empty() && tx.vShieldedOutput.empty() && tx.valueBalance != 0) {
1156 return state.DoS(100, error("CheckTransaction(): tx.valueBalance has no sources or sinks"),
1157 REJECT_INVALID, "bad-txns-valuebalance-nonzero");
1160 // Check for overflow valueBalance
1161 if (tx.valueBalance > MAX_MONEY || tx.valueBalance < -MAX_MONEY) {
1162 return state.DoS(100, error("CheckTransaction(): abs(tx.valueBalance) too large"),
1163 REJECT_INVALID, "bad-txns-valuebalance-toolarge");
1166 if (tx.valueBalance <= 0) {
1167 // NB: negative valueBalance "takes" money from the transparent value pool just as outputs do
1168 nValueOut += -tx.valueBalance;
1170 if (!MoneyRange(nValueOut)) {
1171 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1172 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1176 // Ensure that joinsplit values are well-formed
1177 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1179 if (joinsplit.vpub_old < 0) {
1180 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
1181 REJECT_INVALID, "bad-txns-vpub_old-negative");
1184 if (joinsplit.vpub_new < 0) {
1185 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
1186 REJECT_INVALID, "bad-txns-vpub_new-negative");
1189 if (joinsplit.vpub_old > MAX_MONEY) {
1190 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
1191 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
1194 if (joinsplit.vpub_new > MAX_MONEY) {
1195 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
1196 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
1199 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1200 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
1201 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1204 nValueOut += joinsplit.vpub_old;
1205 if (!MoneyRange(nValueOut)) {
1206 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1207 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1211 // Ensure input values do not exceed MAX_MONEY
1212 // We have not resolved the txin values at this stage,
1213 // but we do know what the joinsplits claim to add
1214 // to the value pool.
1216 CAmount nValueIn = 0;
1217 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1219 nValueIn += it->vpub_new;
1221 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1222 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1223 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1227 // Also check for Sapling
1228 if (tx.valueBalance >= 0) {
1229 // NB: positive valueBalance "adds" money to the transparent value pool, just as inputs do
1230 nValueIn += tx.valueBalance;
1232 if (!MoneyRange(nValueIn)) {
1233 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1234 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1239 // Check for duplicate inputs
1240 set<COutPoint> vInOutPoints;
1241 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1243 if (vInOutPoints.count(txin.prevout))
1244 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1245 REJECT_INVALID, "bad-txns-inputs-duplicate");
1246 vInOutPoints.insert(txin.prevout);
1249 // Check for duplicate joinsplit nullifiers in this transaction
1251 set<uint256> vJoinSplitNullifiers;
1252 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1254 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1256 if (vJoinSplitNullifiers.count(nf))
1257 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1258 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1260 vJoinSplitNullifiers.insert(nf);
1265 // Check for duplicate sapling nullifiers in this transaction
1267 set<uint256> vSaplingNullifiers;
1268 BOOST_FOREACH(const SpendDescription& spend_desc, tx.vShieldedSpend)
1270 if (vSaplingNullifiers.count(spend_desc.nullifier))
1271 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1272 REJECT_INVALID, "bad-spend-description-nullifiers-duplicate");
1274 vSaplingNullifiers.insert(spend_desc.nullifier);
1278 if (tx.IsCoinBase())
1280 // There should be no joinsplits in a coinbase transaction
1281 if (tx.vjoinsplit.size() > 0)
1282 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1283 REJECT_INVALID, "bad-cb-has-joinsplits");
1285 // A coinbase transaction cannot have spend descriptions or output descriptions
1286 if (tx.vShieldedSpend.size() > 0)
1287 return state.DoS(100, error("CheckTransaction(): coinbase has spend descriptions"),
1288 REJECT_INVALID, "bad-cb-has-spend-description");
1289 if (tx.vShieldedOutput.size() > 0)
1290 return state.DoS(100, error("CheckTransaction(): coinbase has output descriptions"),
1291 REJECT_INVALID, "bad-cb-has-output-description");
1293 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1294 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1295 REJECT_INVALID, "bad-cb-length");
1299 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1300 if (txin.prevout.IsNull())
1301 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1302 REJECT_INVALID, "bad-txns-prevout-null");
1308 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1312 uint256 hash = tx.GetHash();
1313 double dPriorityDelta = 0;
1314 CAmount nFeeDelta = 0;
1315 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1316 if (dPriorityDelta > 0 || nFeeDelta > 0)
1320 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1324 // There is a free transaction area in blocks created by most miners,
1325 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1326 // to be considered to fall into this category. We don't want to encourage sending
1327 // multiple transactions instead of one big transaction to avoid fees.
1328 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1332 if (!MoneyRange(nMinFee))
1333 nMinFee = MAX_MONEY;
1338 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1339 bool* pfMissingInputs, bool fRejectAbsurdFee)
1341 AssertLockHeld(cs_main);
1342 if (pfMissingInputs)
1343 *pfMissingInputs = false;
1345 int nextBlockHeight = chainActive.Height() + 1;
1346 auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus());
1348 // Node operator can choose to reject tx by number of transparent inputs
1349 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1350 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1351 if (NetworkUpgradeActive(nextBlockHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) {
1355 size_t n = tx.vin.size();
1357 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1362 auto verifier = libzcash::ProofVerifier::Strict();
1363 if (!CheckTransaction(tx, state, verifier))
1364 return error("AcceptToMemoryPool: CheckTransaction failed");
1366 // DoS level set to 10 to be more forgiving.
1367 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
1368 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1369 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1372 // Coinbase is only valid in a block, not as a loose transaction
1373 if (tx.IsCoinBase())
1374 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1375 REJECT_INVALID, "coinbase");
1377 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1379 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
1381 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1382 REJECT_NONSTANDARD, reason);
1384 // Only accept nLockTime-using transactions that can be mined in the next
1385 // block; we don't want our mempool filled up with transactions that can't
1387 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1388 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1390 // is it already in the memory pool?
1391 uint256 hash = tx.GetHash();
1392 if (pool.exists(hash))
1395 // Check for conflicts with in-memory transactions
1397 LOCK(pool.cs); // protect pool.mapNextTx
1398 for (unsigned int i = 0; i < tx.vin.size(); i++)
1400 COutPoint outpoint = tx.vin[i].prevout;
1401 if (pool.mapNextTx.count(outpoint))
1403 // Disable replacement feature for now
1407 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1408 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1409 if (pool.nullifierExists(nf, SPROUT)) {
1414 for (const SpendDescription &spendDescription : tx.vShieldedSpend) {
1415 if (pool.nullifierExists(spendDescription.nullifier, SAPLING)) {
1423 CCoinsViewCache view(&dummy);
1425 CAmount nValueIn = 0;
1428 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1429 view.SetBackend(viewMemPool);
1431 // do we already have it?
1432 if (view.HaveCoins(hash))
1435 // do all inputs exist?
1436 // Note that this does not check for the presence of actual outputs (see the next check for that),
1437 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1438 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1439 if (!view.HaveCoins(txin.prevout.hash)) {
1440 if (pfMissingInputs)
1441 *pfMissingInputs = true;
1446 // are the actual inputs available?
1447 if (!view.HaveInputs(tx))
1448 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1449 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1451 // are the joinsplit's requirements met?
1452 if (!view.HaveJoinSplitRequirements(tx))
1453 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1454 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1456 // Bring the best block into scope
1457 view.GetBestBlock();
1459 nValueIn = view.GetValueIn(tx);
1461 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1462 view.SetBackend(dummy);
1465 // Check for non-standard pay-to-script-hash in inputs
1466 if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId))
1467 return error("AcceptToMemoryPool: nonstandard transaction input");
1469 // Check that the transaction doesn't have an excessive number of
1470 // sigops, making it impossible to mine. Since the coinbase transaction
1471 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1472 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1473 // merely non-standard transaction.
1474 unsigned int nSigOps = GetLegacySigOpCount(tx);
1475 nSigOps += GetP2SHSigOpCount(tx, view);
1476 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1478 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1479 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1480 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1482 CAmount nValueOut = tx.GetValueOut();
1483 CAmount nFees = nValueIn-nValueOut;
1484 double dPriority = view.GetPriority(tx, chainActive.Height());
1486 // Keep track of transactions that spend a coinbase, which we re-scan
1487 // during reorgs to ensure COINBASE_MATURITY is still met.
1488 bool fSpendsCoinbase = false;
1489 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1490 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1491 if (coins->IsCoinBase()) {
1492 fSpendsCoinbase = true;
1497 // Grab the branch ID we expect this transaction to commit to. We don't
1498 // yet know if it does, but if the entry gets added to the mempool, then
1499 // it has passed ContextualCheckInputs and therefore this is correct.
1500 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1502 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
1503 unsigned int nSize = entry.GetTxSize();
1505 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1506 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1507 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1509 // Don't accept it if it can't get into a block
1510 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1511 if (fLimitFree && nFees < txMinFee)
1512 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1513 hash.ToString(), nFees, txMinFee),
1514 REJECT_INSUFFICIENTFEE, "insufficient fee");
1517 // Require that free transactions have sufficient priority to be mined in the next block.
1518 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1519 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1522 // Continuously rate-limit free (really, very-low-fee) transactions
1523 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1524 // be annoying or make others' transactions take longer to confirm.
1525 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1527 static CCriticalSection csFreeLimiter;
1528 static double dFreeCount;
1529 static int64_t nLastTime;
1530 int64_t nNow = GetTime();
1532 LOCK(csFreeLimiter);
1534 // Use an exponentially decaying ~10-minute window:
1535 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1537 // -limitfreerelay unit is thousand-bytes-per-minute
1538 // At default rate it would take over a month to fill 1GB
1539 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1540 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1541 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1542 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1543 dFreeCount += nSize;
1546 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) {
1547 string errmsg = strprintf("absurdly high fees %s, %d > %d",
1549 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1550 LogPrint("mempool", errmsg.c_str());
1551 return state.Error("AcceptToMemoryPool: " + errmsg);
1554 // Check against previous transactions
1555 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1556 PrecomputedTransactionData txdata(tx);
1557 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1559 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1562 // Check again against just the consensus-critical mandatory script
1563 // verification flags, in case of bugs in the standard flags that cause
1564 // transactions to pass as valid when they're actually invalid. For
1565 // instance the STRICTENC flag was incorrectly allowing certain
1566 // CHECKSIG NOT scripts to pass, even though they were invalid.
1568 // There is a similar check in CreateNewBlock() to prevent creating
1569 // invalid blocks, however allowing such transactions into the mempool
1570 // can be exploited as a DoS attack.
1571 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1573 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1576 // Store transaction in memory
1577 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1580 SyncWithWallets(tx, NULL);
1585 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1586 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1588 CBlockIndex *pindexSlow = NULL;
1592 if (mempool.lookup(hash, txOut))
1599 if (pblocktree->ReadTxIndex(hash, postx)) {
1600 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1602 return error("%s: OpenBlockFile failed", __func__);
1603 CBlockHeader header;
1606 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1608 } catch (const std::exception& e) {
1609 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1611 hashBlock = header.GetHash();
1612 if (txOut.GetHash() != hash)
1613 return error("%s: txid mismatch", __func__);
1618 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1621 CCoinsViewCache &view = *pcoinsTip;
1622 const CCoins* coins = view.AccessCoins(hash);
1624 nHeight = coins->nHeight;
1627 pindexSlow = chainActive[nHeight];
1632 if (ReadBlockFromDisk(block, pindexSlow)) {
1633 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1634 if (tx.GetHash() == hash) {
1636 hashBlock = pindexSlow->GetBlockHash();
1651 //////////////////////////////////////////////////////////////////////////////
1653 // CBlock and CBlockIndex
1656 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1658 // Open history file to append
1659 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1660 if (fileout.IsNull())
1661 return error("WriteBlockToDisk: OpenBlockFile failed");
1663 // Write index header
1664 unsigned int nSize = GetSerializeSize(fileout, block);
1665 fileout << FLATDATA(messageStart) << nSize;
1668 long fileOutPos = ftell(fileout.Get());
1670 return error("WriteBlockToDisk: ftell failed");
1671 pos.nPos = (unsigned int)fileOutPos;
1677 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1681 // Open history file to read
1682 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1683 if (filein.IsNull())
1684 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1690 catch (const std::exception& e) {
1691 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1695 if (!(CheckEquihashSolution(&block, Params()) &&
1696 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1697 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1702 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1704 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1706 if (block.GetHash() != pindex->GetBlockHash())
1707 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1708 pindex->ToString(), pindex->GetBlockPos().ToString());
1712 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1714 CAmount nSubsidy = 12.5 * COIN;
1716 // Mining slow start
1717 // The subsidy is ramped up linearly, skipping the middle payout of
1718 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1719 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1720 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1721 nSubsidy *= nHeight;
1723 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1724 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1725 nSubsidy *= (nHeight+1);
1729 assert(nHeight > consensusParams.SubsidySlowStartShift());
1730 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1731 // Force block reward to zero when right shift is undefined.
1735 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1736 nSubsidy >>= halvings;
1740 bool IsInitialBlockDownload()
1742 const CChainParams& chainParams = Params();
1744 // Once this function has returned false, it must remain false.
1745 static std::atomic<bool> latchToFalse{false};
1746 // Optimization: pre-test latch before taking the lock.
1747 if (latchToFalse.load(std::memory_order_relaxed))
1751 if (latchToFalse.load(std::memory_order_relaxed))
1753 if (fImporting || fReindex)
1755 if (chainActive.Tip() == NULL)
1757 if (chainActive.Tip()->nChainWork < UintToArith256(chainParams.GetConsensus().nMinimumChainWork))
1759 if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
1761 LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
1762 latchToFalse.store(true, std::memory_order_relaxed);
1766 static bool fLargeWorkForkFound = false;
1767 static bool fLargeWorkInvalidChainFound = false;
1768 static CBlockIndex *pindexBestForkTip = NULL;
1769 static CBlockIndex *pindexBestForkBase = NULL;
1771 void CheckForkWarningConditions()
1773 AssertLockHeld(cs_main);
1774 // Before we get past initial download, we cannot reliably alert about forks
1775 // (we assume we don't get stuck on a fork before finishing our initial sync)
1776 if (IsInitialBlockDownload())
1779 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1780 // of our head, drop it
1781 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1782 pindexBestForkTip = NULL;
1784 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1786 if (!fLargeWorkForkFound && pindexBestForkBase)
1788 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1789 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1790 CAlert::Notify(warning, true);
1792 if (pindexBestForkTip && pindexBestForkBase)
1794 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__,
1795 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1796 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1797 fLargeWorkForkFound = true;
1801 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1802 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1803 CAlert::Notify(warning, true);
1804 fLargeWorkInvalidChainFound = true;
1809 fLargeWorkForkFound = false;
1810 fLargeWorkInvalidChainFound = false;
1814 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1816 AssertLockHeld(cs_main);
1817 // If we are on a fork that is sufficiently large, set a warning flag
1818 CBlockIndex* pfork = pindexNewForkTip;
1819 CBlockIndex* plonger = chainActive.Tip();
1820 while (pfork && pfork != plonger)
1822 while (plonger && plonger->nHeight > pfork->nHeight)
1823 plonger = plonger->pprev;
1824 if (pfork == plonger)
1826 pfork = pfork->pprev;
1829 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1830 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1831 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1832 // hash rate operating on the fork.
1833 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1834 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1835 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1836 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1837 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1838 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1840 pindexBestForkTip = pindexNewForkTip;
1841 pindexBestForkBase = pfork;
1844 CheckForkWarningConditions();
1847 // Requires cs_main.
1848 void Misbehaving(NodeId pnode, int howmuch)
1853 CNodeState *state = State(pnode);
1857 state->nMisbehavior += howmuch;
1858 int banscore = GetArg("-banscore", 100);
1859 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1861 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1862 state->fShouldBan = true;
1864 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1867 void static InvalidChainFound(CBlockIndex* pindexNew)
1869 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1870 pindexBestInvalid = pindexNew;
1872 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1873 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1874 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1875 pindexNew->GetBlockTime()));
1876 CBlockIndex *tip = chainActive.Tip();
1878 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1879 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1880 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1881 CheckForkWarningConditions();
1884 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1886 if (state.IsInvalid(nDoS)) {
1887 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1888 if (it != mapBlockSource.end() && State(it->second)) {
1889 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1890 State(it->second)->rejects.push_back(reject);
1892 Misbehaving(it->second, nDoS);
1895 if (!state.CorruptionPossible()) {
1896 pindex->nStatus |= BLOCK_FAILED_VALID;
1897 setDirtyBlockIndex.insert(pindex);
1898 setBlockIndexCandidates.erase(pindex);
1899 InvalidChainFound(pindex);
1903 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1905 // mark inputs spent
1906 if (!tx.IsCoinBase()) {
1907 txundo.vprevout.reserve(tx.vin.size());
1908 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1909 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1910 unsigned nPos = txin.prevout.n;
1912 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1914 // mark an outpoint spent, and construct undo information
1915 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1917 if (coins->vout.size() == 0) {
1918 CTxInUndo& undo = txundo.vprevout.back();
1919 undo.nHeight = coins->nHeight;
1920 undo.fCoinBase = coins->fCoinBase;
1921 undo.nVersion = coins->nVersion;
1927 inputs.SetNullifiers(tx, true);
1930 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1933 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1936 UpdateCoins(tx, inputs, txundo, nHeight);
1939 bool CScriptCheck::operator()() {
1940 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1941 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) {
1942 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1947 int GetSpendHeight(const CCoinsViewCache& inputs)
1950 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1951 return pindexPrev->nHeight + 1;
1954 namespace Consensus {
1955 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1957 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1958 // for an attacker to attempt to split the network.
1959 if (!inputs.HaveInputs(tx))
1960 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1962 // are the JoinSplit's requirements met?
1963 if (!inputs.HaveJoinSplitRequirements(tx))
1964 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1966 CAmount nValueIn = 0;
1968 for (unsigned int i = 0; i < tx.vin.size(); i++)
1970 const COutPoint &prevout = tx.vin[i].prevout;
1971 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1974 if (coins->IsCoinBase()) {
1975 // Ensure that coinbases are matured
1976 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1977 return state.Invalid(
1978 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1979 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1982 // Ensure that coinbases cannot be spent to transparent outputs
1983 // Disabled on regtest
1984 if (fCoinbaseEnforcedProtectionEnabled &&
1985 consensusParams.fCoinbaseMustBeProtected &&
1987 return state.Invalid(
1988 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1989 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1993 // Check for negative or overflow input values
1994 nValueIn += coins->vout[prevout.n].nValue;
1995 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1996 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1997 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2001 nValueIn += tx.GetShieldedValueIn();
2002 if (!MoneyRange(nValueIn))
2003 return state.DoS(100, error("CheckInputs(): shielded input to transparent value pool out of range"),
2004 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
2006 if (nValueIn < tx.GetValueOut())
2007 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
2008 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
2009 REJECT_INVALID, "bad-txns-in-belowout");
2011 // Tally transaction fees
2012 CAmount nTxFee = nValueIn - tx.GetValueOut();
2014 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
2015 REJECT_INVALID, "bad-txns-fee-negative");
2017 if (!MoneyRange(nFees))
2018 return state.DoS(100, error("CheckInputs(): nFees out of range"),
2019 REJECT_INVALID, "bad-txns-fee-outofrange");
2022 }// namespace Consensus
2024 bool ContextualCheckInputs(
2025 const CTransaction& tx,
2026 CValidationState &state,
2027 const CCoinsViewCache &inputs,
2031 PrecomputedTransactionData& txdata,
2032 const Consensus::Params& consensusParams,
2033 uint32_t consensusBranchId,
2034 std::vector<CScriptCheck> *pvChecks)
2036 if (!tx.IsCoinBase())
2038 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
2043 pvChecks->reserve(tx.vin.size());
2045 // The first loop above does all the inexpensive checks.
2046 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
2047 // Helps prevent CPU exhaustion attacks.
2049 // Skip ECDSA signature verification when connecting blocks
2050 // before the last block chain checkpoint. This is safe because block merkle hashes are
2051 // still computed and checked, and any change will be caught at the next checkpoint.
2052 if (fScriptChecks) {
2053 for (unsigned int i = 0; i < tx.vin.size(); i++) {
2054 const COutPoint &prevout = tx.vin[i].prevout;
2055 const CCoins* coins = inputs.AccessCoins(prevout.hash);
2059 CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata);
2061 pvChecks->push_back(CScriptCheck());
2062 check.swap(pvChecks->back());
2063 } else if (!check()) {
2064 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
2065 // Check whether the failure was caused by a
2066 // non-mandatory script verification check, such as
2067 // non-standard DER encodings or non-null dummy
2068 // arguments; if so, don't trigger DoS protection to
2069 // avoid splitting the network between upgraded and
2070 // non-upgraded nodes.
2071 CScriptCheck check2(*coins, tx, i,
2072 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata);
2074 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
2076 // Failures of other flags indicate a transaction that is
2077 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
2078 // such nodes as they are not following the protocol. That
2079 // said during an upgrade careful thought should be taken
2080 // as to the correct behavior - we may want to continue
2081 // peering with non-upgraded nodes even after a soft-fork
2082 // super-majority vote has passed.
2083 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
2094 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
2096 // Open history file to append
2097 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
2098 if (fileout.IsNull())
2099 return error("%s: OpenUndoFile failed", __func__);
2101 // Write index header
2102 unsigned int nSize = GetSerializeSize(fileout, blockundo);
2103 fileout << FLATDATA(messageStart) << nSize;
2106 long fileOutPos = ftell(fileout.Get());
2108 return error("%s: ftell failed", __func__);
2109 pos.nPos = (unsigned int)fileOutPos;
2110 fileout << blockundo;
2112 // calculate & write checksum
2113 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2114 hasher << hashBlock;
2115 hasher << blockundo;
2116 fileout << hasher.GetHash();
2121 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
2123 // Open history file to read
2124 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
2125 if (filein.IsNull())
2126 return error("%s: OpenBlockFile failed", __func__);
2129 uint256 hashChecksum;
2131 filein >> blockundo;
2132 filein >> hashChecksum;
2134 catch (const std::exception& e) {
2135 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2139 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
2140 hasher << hashBlock;
2141 hasher << blockundo;
2142 if (hashChecksum != hasher.GetHash())
2143 return error("%s: Checksum mismatch", __func__);
2148 /** Abort with a message */
2149 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
2151 strMiscWarning = strMessage;
2152 LogPrintf("*** %s\n", strMessage);
2153 uiInterface.ThreadSafeMessageBox(
2154 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
2155 "", CClientUIInterface::MSG_ERROR);
2160 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
2162 AbortNode(strMessage, userMessage);
2163 return state.Error(strMessage);
2169 * Apply the undo operation of a CTxInUndo to the given chain state.
2170 * @param undo The undo object.
2171 * @param view The coins view to which to apply the changes.
2172 * @param out The out point that corresponds to the tx input.
2173 * @return True on success.
2175 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
2179 CCoinsModifier coins = view.ModifyCoins(out.hash);
2180 if (undo.nHeight != 0) {
2181 // undo data contains height: this is the last output of the prevout tx being spent
2182 if (!coins->IsPruned())
2183 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
2185 coins->fCoinBase = undo.fCoinBase;
2186 coins->nHeight = undo.nHeight;
2187 coins->nVersion = undo.nVersion;
2189 if (coins->IsPruned())
2190 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
2192 if (coins->IsAvailable(out.n))
2193 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
2194 if (coins->vout.size() < out.n+1)
2195 coins->vout.resize(out.n+1);
2196 coins->vout[out.n] = undo.txout;
2201 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
2203 assert(pindex->GetBlockHash() == view.GetBestBlock());
2210 CBlockUndo blockUndo;
2211 CDiskBlockPos pos = pindex->GetUndoPos();
2213 return error("DisconnectBlock(): no undo data available");
2214 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2215 return error("DisconnectBlock(): failure reading undo data");
2217 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2218 return error("DisconnectBlock(): block and undo data inconsistent");
2220 // undo transactions in reverse order
2221 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2222 const CTransaction &tx = block.vtx[i];
2223 uint256 hash = tx.GetHash();
2225 // Check that all outputs are available and match the outputs in the block itself
2228 CCoinsModifier outs = view.ModifyCoins(hash);
2229 outs->ClearUnspendable();
2231 CCoins outsBlock(tx, pindex->nHeight);
2232 // The CCoins serialization does not serialize negative numbers.
2233 // No network rules currently depend on the version here, so an inconsistency is harmless
2234 // but it must be corrected before txout nversion ever influences a network rule.
2235 if (outsBlock.nVersion < 0)
2236 outs->nVersion = outsBlock.nVersion;
2237 if (*outs != outsBlock)
2238 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2244 // unspend nullifiers
2245 view.SetNullifiers(tx, false);
2248 if (i > 0) { // not coinbases
2249 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2250 if (txundo.vprevout.size() != tx.vin.size())
2251 return error("DisconnectBlock(): transaction and undo data inconsistent");
2252 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2253 const COutPoint &out = tx.vin[j].prevout;
2254 const CTxInUndo &undo = txundo.vprevout[j];
2255 if (!ApplyTxInUndo(undo, view, out))
2261 // set the old best Sprout anchor back
2262 view.PopAnchor(blockUndo.old_sprout_tree_root, SPROUT);
2264 // set the old best Sapling anchor back
2265 // We can get this from the `hashFinalSaplingRoot` of the last block
2266 // However, this is only reliable if the last block was on or after
2267 // the Sapling activation height. Otherwise, the last anchor was the
2269 if (NetworkUpgradeActive(pindex->pprev->nHeight, Params().GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2270 view.PopAnchor(pindex->pprev->hashFinalSaplingRoot, SAPLING);
2272 view.PopAnchor(SaplingMerkleTree::empty_root(), SAPLING);
2275 // move best block pointer to prevout block
2276 view.SetBestBlock(pindex->pprev->GetBlockHash());
2286 void static FlushBlockFile(bool fFinalize = false)
2288 LOCK(cs_LastBlockFile);
2290 CDiskBlockPos posOld(nLastBlockFile, 0);
2292 FILE *fileOld = OpenBlockFile(posOld);
2295 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2296 FileCommit(fileOld);
2300 fileOld = OpenUndoFile(posOld);
2303 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2304 FileCommit(fileOld);
2309 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2311 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2313 void ThreadScriptCheck() {
2314 RenameThread("zcash-scriptch");
2315 scriptcheckqueue.Thread();
2319 // Called periodically asynchronously; alerts if it smells like
2320 // we're being fed a bad chain (blocks being generated much
2321 // too slowly or too quickly).
2323 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2324 int64_t nPowTargetSpacing)
2326 if (bestHeader == NULL || initialDownloadCheck()) return;
2328 static int64_t lastAlertTime = 0;
2329 int64_t now = GetAdjustedTime();
2330 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2332 const int SPAN_HOURS=4;
2333 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2334 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2336 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2338 std::string strWarning;
2339 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2342 const CBlockIndex* i = bestHeader;
2344 while (i->GetBlockTime() >= startTime) {
2347 if (i == NULL) return; // Ran out of chain, we must not be fully synced
2350 // How likely is it to find that many by chance?
2351 double p = boost::math::pdf(poisson, nBlocks);
2353 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2354 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2356 // Aim for one false-positive about every fifty years of normal running:
2357 const int FIFTY_YEARS = 50*365*24*60*60;
2358 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2360 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2362 // Many fewer blocks than expected: alert!
2363 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2364 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2366 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2368 // Many more blocks than expected: alert!
2369 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2370 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2372 if (!strWarning.empty())
2374 strMiscWarning = strWarning;
2375 CAlert::Notify(strWarning, true);
2376 lastAlertTime = now;
2380 static int64_t nTimeVerify = 0;
2381 static int64_t nTimeConnect = 0;
2382 static int64_t nTimeIndex = 0;
2383 static int64_t nTimeCallbacks = 0;
2384 static int64_t nTimeTotal = 0;
2386 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2388 const CChainParams& chainparams = Params();
2389 AssertLockHeld(cs_main);
2391 bool fExpensiveChecks = true;
2392 if (fCheckpointsEnabled) {
2393 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2394 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2395 // This block is an ancestor of a checkpoint: disable script checks
2396 fExpensiveChecks = false;
2400 auto verifier = libzcash::ProofVerifier::Strict();
2401 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2403 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2404 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2407 // verify that the view's current state corresponds to the previous block
2408 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2409 assert(hashPrevBlock == view.GetBestBlock());
2411 // Special case for the genesis block, skipping connection of its transactions
2412 // (its coinbase is unspendable)
2413 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2415 view.SetBestBlock(pindex->GetBlockHash());
2416 // Before the genesis block, there was an empty tree
2417 SproutMerkleTree tree;
2418 pindex->hashSproutAnchor = tree.root();
2419 // The genesis block contained no JoinSplits
2420 pindex->hashFinalSproutRoot = pindex->hashSproutAnchor;
2425 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2426 // unless those are already completely spent.
2427 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2428 const CCoins* coins = view.AccessCoins(tx.GetHash());
2429 if (coins && !coins->IsPruned())
2430 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2431 REJECT_INVALID, "bad-txns-BIP30");
2434 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2436 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2438 CBlockUndo blockundo;
2440 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2442 int64_t nTimeStart = GetTimeMicros();
2445 unsigned int nSigOps = 0;
2446 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2447 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2448 vPos.reserve(block.vtx.size());
2449 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2451 // Construct the incremental merkle tree at the current
2453 auto old_sprout_tree_root = view.GetBestAnchor(SPROUT);
2454 // saving the top anchor in the block index as we go.
2456 pindex->hashSproutAnchor = old_sprout_tree_root;
2458 SproutMerkleTree sprout_tree;
2459 // This should never fail: we should always be able to get the root
2460 // that is on the tip of our chain
2461 assert(view.GetSproutAnchorAt(old_sprout_tree_root, sprout_tree));
2464 // Consistency check: the root of the tree we're given should
2465 // match what we asked for.
2466 assert(sprout_tree.root() == old_sprout_tree_root);
2469 SaplingMerkleTree sapling_tree;
2470 assert(view.GetSaplingAnchorAt(view.GetBestAnchor(SAPLING), sapling_tree));
2472 // Grab the consensus branch ID for the block's height
2473 auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus());
2475 std::vector<PrecomputedTransactionData> txdata;
2476 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2477 for (unsigned int i = 0; i < block.vtx.size(); i++)
2479 const CTransaction &tx = block.vtx[i];
2481 nInputs += tx.vin.size();
2482 nSigOps += GetLegacySigOpCount(tx);
2483 if (nSigOps > MAX_BLOCK_SIGOPS)
2484 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2485 REJECT_INVALID, "bad-blk-sigops");
2487 if (!tx.IsCoinBase())
2489 if (!view.HaveInputs(tx))
2490 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2491 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2493 // are the JoinSplit's requirements met?
2494 if (!view.HaveJoinSplitRequirements(tx))
2495 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2496 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2498 // Add in sigops done by pay-to-script-hash inputs;
2499 // this is to prevent a "rogue miner" from creating
2500 // an incredibly-expensive-to-validate block.
2501 nSigOps += GetP2SHSigOpCount(tx, view);
2502 if (nSigOps > MAX_BLOCK_SIGOPS)
2503 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2504 REJECT_INVALID, "bad-blk-sigops");
2507 txdata.emplace_back(tx);
2509 if (!tx.IsCoinBase())
2511 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2513 std::vector<CScriptCheck> vChecks;
2514 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL))
2516 control.Add(vChecks);
2521 blockundo.vtxundo.push_back(CTxUndo());
2523 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2525 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2526 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2527 // Insert the note commitments into our temporary tree.
2529 sprout_tree.append(note_commitment);
2533 BOOST_FOREACH(const OutputDescription &outputDescription, tx.vShieldedOutput) {
2534 sapling_tree.append(outputDescription.cm);
2537 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2538 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2541 view.PushAnchor(sprout_tree);
2542 view.PushAnchor(sapling_tree);
2544 pindex->hashFinalSproutRoot = sprout_tree.root();
2546 blockundo.old_sprout_tree_root = old_sprout_tree_root;
2548 // If Sapling is active, block.hashFinalSaplingRoot must be the
2549 // same as the root of the Sapling tree
2550 if (NetworkUpgradeActive(pindex->nHeight, chainparams.GetConsensus(), Consensus::UPGRADE_SAPLING)) {
2551 if (block.hashFinalSaplingRoot != sapling_tree.root()) {
2552 return state.DoS(100,
2553 error("ConnectBlock(): block's hashFinalSaplingRoot is incorrect"),
2554 REJECT_INVALID, "bad-sapling-root-in-block");
2558 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2559 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);
2561 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2562 if (block.vtx[0].GetValueOut() > blockReward)
2563 return state.DoS(100,
2564 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2565 block.vtx[0].GetValueOut(), blockReward),
2566 REJECT_INVALID, "bad-cb-amount");
2568 if (!control.Wait())
2569 return state.DoS(100, false);
2570 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2571 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);
2576 // Write undo information to disk
2577 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2579 if (pindex->GetUndoPos().IsNull()) {
2581 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2582 return error("ConnectBlock(): FindUndoPos failed");
2583 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2584 return AbortNode(state, "Failed to write undo data");
2586 // update nUndoPos in block index
2587 pindex->nUndoPos = pos.nPos;
2588 pindex->nStatus |= BLOCK_HAVE_UNDO;
2591 // Now that all consensus rules have been validated, set nCachedBranchId.
2592 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2593 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
2594 "nCachedBranchId must be set after all consensus rules have been validated.");
2595 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2596 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
2597 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
2598 } else if (pindex->pprev) {
2599 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
2602 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2603 setDirtyBlockIndex.insert(pindex);
2607 if (!pblocktree->WriteTxIndex(vPos))
2608 return AbortNode(state, "Failed to write transaction index");
2610 // add this block to the view's block chain
2611 view.SetBestBlock(pindex->GetBlockHash());
2613 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2614 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2616 // Watch for changes to the previous coinbase transaction.
2617 static uint256 hashPrevBestCoinBase;
2618 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2619 hashPrevBestCoinBase = block.vtx[0].GetHash();
2621 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2622 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2627 enum FlushStateMode {
2629 FLUSH_STATE_IF_NEEDED,
2630 FLUSH_STATE_PERIODIC,
2635 * Update the on-disk chain state.
2636 * The caches and indexes are flushed depending on the mode we're called with
2637 * if they're too large, if it's been a while since the last write,
2638 * or always and in all cases if we're in prune mode and are deleting files.
2640 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2641 LOCK2(cs_main, cs_LastBlockFile);
2642 static int64_t nLastWrite = 0;
2643 static int64_t nLastFlush = 0;
2644 static int64_t nLastSetChain = 0;
2645 std::set<int> setFilesToPrune;
2646 bool fFlushForPrune = false;
2648 if (fPruneMode && fCheckForPruning && !fReindex) {
2649 FindFilesToPrune(setFilesToPrune);
2650 fCheckForPruning = false;
2651 if (!setFilesToPrune.empty()) {
2652 fFlushForPrune = true;
2654 pblocktree->WriteFlag("prunedblockfiles", true);
2659 int64_t nNow = GetTimeMicros();
2660 // Avoid writing/flushing immediately after startup.
2661 if (nLastWrite == 0) {
2664 if (nLastFlush == 0) {
2667 if (nLastSetChain == 0) {
2668 nLastSetChain = nNow;
2670 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2671 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2672 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2673 // The cache is over the limit, we have to write now.
2674 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2675 // 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.
2676 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2677 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2678 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2679 // Combine all conditions that result in a full cache flush.
2680 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2681 // Write blocks and block index to disk.
2682 if (fDoFullFlush || fPeriodicWrite) {
2683 // Depend on nMinDiskSpace to ensure we can write block index
2684 if (!CheckDiskSpace(0))
2685 return state.Error("out of disk space");
2686 // First make sure all block and undo data is flushed to disk.
2688 // Then update all block file information (which may refer to block and undo files).
2690 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2691 vFiles.reserve(setDirtyFileInfo.size());
2692 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2693 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2694 setDirtyFileInfo.erase(it++);
2696 std::vector<const CBlockIndex*> vBlocks;
2697 vBlocks.reserve(setDirtyBlockIndex.size());
2698 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2699 vBlocks.push_back(*it);
2700 setDirtyBlockIndex.erase(it++);
2702 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2703 return AbortNode(state, "Files to write to block index database");
2706 // Finally remove any pruned files
2708 UnlinkPrunedFiles(setFilesToPrune);
2711 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2713 // Typical CCoins structures on disk are around 128 bytes in size.
2714 // Pushing a new one to the database can cause it to be written
2715 // twice (once in the log, and once in the tables). This is already
2716 // an overestimation, as most will delete an existing entry or
2717 // overwrite one. Still, use a conservative safety factor of 2.
2718 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2719 return state.Error("out of disk space");
2720 // Flush the chainstate (which may refer to block index entries).
2721 if (!pcoinsTip->Flush())
2722 return AbortNode(state, "Failed to write to coin database");
2725 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2726 // Update best block in wallet (so we can detect restored wallets).
2727 GetMainSignals().SetBestChain(chainActive.GetLocator());
2728 nLastSetChain = nNow;
2730 } catch (const std::runtime_error& e) {
2731 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2736 void FlushStateToDisk() {
2737 CValidationState state;
2738 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2741 void PruneAndFlush() {
2742 CValidationState state;
2743 fCheckForPruning = true;
2744 FlushStateToDisk(state, FLUSH_STATE_NONE);
2747 /** Update chainActive and related internal data structures. */
2748 void static UpdateTip(CBlockIndex *pindexNew) {
2749 const CChainParams& chainParams = Params();
2750 chainActive.SetTip(pindexNew);
2753 nTimeBestReceived = GetTime();
2754 mempool.AddTransactionsUpdated(1);
2756 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2757 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2758 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2759 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2761 cvBlockChange.notify_all();
2763 // Check the version of the last 100 blocks to see if we need to upgrade:
2764 static bool fWarned = false;
2765 if (!IsInitialBlockDownload() && !fWarned)
2768 const CBlockIndex* pindex = chainActive.Tip();
2769 for (int i = 0; i < 100 && pindex != NULL; i++)
2771 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2773 pindex = pindex->pprev;
2776 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2777 if (nUpgraded > 100/2)
2779 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2780 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2781 CAlert::Notify(strMiscWarning, true);
2788 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2789 * mempool.removeWithoutBranchId after this, with cs_main held.
2791 bool static DisconnectTip(CValidationState &state, bool fBare = false) {
2792 CBlockIndex *pindexDelete = chainActive.Tip();
2793 assert(pindexDelete);
2794 // Read block from disk.
2796 if (!ReadBlockFromDisk(block, pindexDelete))
2797 return AbortNode(state, "Failed to read block");
2798 // Apply the block atomically to the chain state.
2799 uint256 sproutAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2800 uint256 saplingAnchorBeforeDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
2801 int64_t nStart = GetTimeMicros();
2803 CCoinsViewCache view(pcoinsTip);
2804 if (!DisconnectBlock(block, state, pindexDelete, view))
2805 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2806 assert(view.Flush());
2808 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2809 uint256 sproutAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SPROUT);
2810 uint256 saplingAnchorAfterDisconnect = pcoinsTip->GetBestAnchor(SAPLING);
2811 // Write the chain state to disk, if necessary.
2812 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2816 // Resurrect mempool transactions from the disconnected block.
2817 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2818 // ignore validation errors in resurrected transactions
2819 list<CTransaction> removed;
2820 CValidationState stateDummy;
2821 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2822 mempool.remove(tx, removed, true);
2824 if (sproutAnchorBeforeDisconnect != sproutAnchorAfterDisconnect) {
2825 // The anchor may not change between block disconnects,
2826 // in which case we don't want to evict from the mempool yet!
2827 mempool.removeWithAnchor(sproutAnchorBeforeDisconnect, SPROUT);
2829 if (saplingAnchorBeforeDisconnect != saplingAnchorAfterDisconnect) {
2830 // The anchor may not change between block disconnects,
2831 // in which case we don't want to evict from the mempool yet!
2832 mempool.removeWithAnchor(saplingAnchorBeforeDisconnect, SAPLING);
2836 // Update chainActive and related variables.
2837 UpdateTip(pindexDelete->pprev);
2838 // Get the current commitment tree
2839 SproutMerkleTree newSproutTree;
2840 SaplingMerkleTree newSaplingTree;
2841 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), newSproutTree));
2842 assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(SAPLING), newSaplingTree));
2843 // Let wallets know transactions went from 1-confirmed to
2844 // 0-confirmed or conflicted:
2845 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2846 SyncWithWallets(tx, NULL);
2848 // Update cached incremental witnesses
2849 GetMainSignals().ChainTip(pindexDelete, &block, newSproutTree, newSaplingTree, false);
2853 static int64_t nTimeReadFromDisk = 0;
2854 static int64_t nTimeConnectTotal = 0;
2855 static int64_t nTimeFlush = 0;
2856 static int64_t nTimeChainState = 0;
2857 static int64_t nTimePostConnect = 0;
2860 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2861 * corresponding to pindexNew, to bypass loading it again from disk.
2862 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
2864 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2865 assert(pindexNew->pprev == chainActive.Tip());
2866 // Read block from disk.
2867 int64_t nTime1 = GetTimeMicros();
2870 if (!ReadBlockFromDisk(block, pindexNew))
2871 return AbortNode(state, "Failed to read block");
2874 // Get the current commitment tree
2875 SproutMerkleTree oldSproutTree;
2876 SaplingMerkleTree oldSaplingTree;
2877 assert(pcoinsTip->GetSproutAnchorAt(pcoinsTip->GetBestAnchor(SPROUT), oldSproutTree));
2878 assert(pcoinsTip->GetSaplingAnchorAt(pcoinsTip->GetBestAnchor(SAPLING), oldSaplingTree));
2879 // Apply the block atomically to the chain state.
2880 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2882 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2884 CCoinsViewCache view(pcoinsTip);
2885 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2886 GetMainSignals().BlockChecked(*pblock, state);
2888 if (state.IsInvalid())
2889 InvalidBlockFound(pindexNew, state);
2890 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2892 mapBlockSource.erase(pindexNew->GetBlockHash());
2893 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2894 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2895 assert(view.Flush());
2897 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2898 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2899 // Write the chain state to disk, if necessary.
2900 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2902 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2903 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2904 // Remove conflicting transactions from the mempool.
2905 list<CTransaction> txConflicted;
2906 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2908 // Remove transactions that expire at new block height from mempool
2909 mempool.removeExpired(pindexNew->nHeight);
2911 // Update chainActive & related variables.
2912 UpdateTip(pindexNew);
2913 // Tell wallet about transactions that went from mempool
2915 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2916 SyncWithWallets(tx, NULL);
2918 // ... and about transactions that got confirmed:
2919 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2920 SyncWithWallets(tx, pblock);
2922 // Update cached incremental witnesses
2923 GetMainSignals().ChainTip(pindexNew, pblock, oldSproutTree, oldSaplingTree, true);
2925 EnforceNodeDeprecation(pindexNew->nHeight);
2927 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2928 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2929 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2934 * Return the tip of the chain with the most work in it, that isn't
2935 * known to be invalid (it's however far from certain to be valid).
2937 static CBlockIndex* FindMostWorkChain() {
2939 CBlockIndex *pindexNew = NULL;
2941 // Find the best candidate header.
2943 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2944 if (it == setBlockIndexCandidates.rend())
2949 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2950 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2951 CBlockIndex *pindexTest = pindexNew;
2952 bool fInvalidAncestor = false;
2953 while (pindexTest && !chainActive.Contains(pindexTest)) {
2954 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2956 // Pruned nodes may have entries in setBlockIndexCandidates for
2957 // which block files have been deleted. Remove those as candidates
2958 // for the most work chain if we come across them; we can't switch
2959 // to a chain unless we have all the non-active-chain parent blocks.
2960 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2961 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2962 if (fFailedChain || fMissingData) {
2963 // Candidate chain is not usable (either invalid or missing data)
2964 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2965 pindexBestInvalid = pindexNew;
2966 CBlockIndex *pindexFailed = pindexNew;
2967 // Remove the entire chain from the set.
2968 while (pindexTest != pindexFailed) {
2970 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2971 } else if (fMissingData) {
2972 // If we're missing data, then add back to mapBlocksUnlinked,
2973 // so that if the block arrives in the future we can try adding
2974 // to setBlockIndexCandidates again.
2975 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2977 setBlockIndexCandidates.erase(pindexFailed);
2978 pindexFailed = pindexFailed->pprev;
2980 setBlockIndexCandidates.erase(pindexTest);
2981 fInvalidAncestor = true;
2984 pindexTest = pindexTest->pprev;
2986 if (!fInvalidAncestor)
2991 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2992 static void PruneBlockIndexCandidates() {
2993 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2994 // reorganization to a better block fails.
2995 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2996 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2997 setBlockIndexCandidates.erase(it++);
2999 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
3000 assert(!setBlockIndexCandidates.empty());
3004 * Try to make some progress towards making pindexMostWork the active block.
3005 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
3007 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
3008 AssertLockHeld(cs_main);
3009 bool fInvalidFound = false;
3010 const CBlockIndex *pindexOldTip = chainActive.Tip();
3011 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
3013 // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks.
3014 // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain,
3015 // then pindexFork will be null, and we would need to remove the entire chain including
3016 // our genesis block. In practice this (probably) won't happen because of checks elsewhere.
3017 auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0;
3018 static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance");
3019 if (reorgLength > MAX_REORG_LENGTH) {
3020 auto msg = strprintf(_(
3021 "A block chain reorganization has been detected that would roll back %d blocks! "
3022 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
3023 ), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
3024 _("Reorganization details") + ":\n" +
3025 "- " + strprintf(_("Current tip: %s, height %d, work %s"),
3026 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" +
3027 "- " + strprintf(_("New tip: %s, height %d, work %s"),
3028 pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" +
3029 "- " + strprintf(_("Fork point: %s, height %d"),
3030 pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" +
3031 _("Please help, human!");
3032 LogPrintf("*** %s\n", msg);
3033 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
3038 // Disconnect active blocks which are no longer in the best chain.
3039 bool fBlocksDisconnected = false;
3040 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
3041 if (!DisconnectTip(state))
3043 fBlocksDisconnected = true;
3046 // Build list of new blocks to connect.
3047 std::vector<CBlockIndex*> vpindexToConnect;
3048 bool fContinue = true;
3049 int nHeight = pindexFork ? pindexFork->nHeight : -1;
3050 while (fContinue && nHeight != pindexMostWork->nHeight) {
3051 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
3052 // a few blocks along the way.
3053 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
3054 vpindexToConnect.clear();
3055 vpindexToConnect.reserve(nTargetHeight - nHeight);
3056 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
3057 while (pindexIter && pindexIter->nHeight != nHeight) {
3058 vpindexToConnect.push_back(pindexIter);
3059 pindexIter = pindexIter->pprev;
3061 nHeight = nTargetHeight;
3063 // Connect new blocks.
3064 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
3065 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
3066 if (state.IsInvalid()) {
3067 // The block violates a consensus rule.
3068 if (!state.CorruptionPossible())
3069 InvalidChainFound(vpindexToConnect.back());
3070 state = CValidationState();
3071 fInvalidFound = true;
3075 // A system error occurred (disk space, database error, ...).
3079 PruneBlockIndexCandidates();
3080 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
3081 // We're in a better position than we were. Return temporarily to release the lock.
3089 if (fBlocksDisconnected) {
3090 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3092 mempool.removeWithoutBranchId(
3093 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3094 mempool.check(pcoinsTip);
3096 // Callbacks/notifications for a new best chain.
3098 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
3100 CheckForkWarningConditions();
3106 * Make the best chain active, in multiple steps. The result is either failure
3107 * or an activated best chain. pblock is either NULL or a pointer to a block
3108 * that is already loaded (to avoid loading it again from disk).
3110 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
3111 CBlockIndex *pindexNewTip = NULL;
3112 CBlockIndex *pindexMostWork = NULL;
3113 const CChainParams& chainParams = Params();
3115 boost::this_thread::interruption_point();
3117 bool fInitialDownload;
3120 pindexMostWork = FindMostWorkChain();
3122 // Whether we have anything to do at all.
3123 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
3126 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
3129 pindexNewTip = chainActive.Tip();
3130 fInitialDownload = IsInitialBlockDownload();
3132 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
3134 // Notifications/callbacks that can run without cs_main
3135 if (!fInitialDownload) {
3136 uint256 hashNewTip = pindexNewTip->GetBlockHash();
3137 // Relay inventory, but don't relay old inventory during initial block download.
3138 int nBlockEstimate = 0;
3139 if (fCheckpointsEnabled)
3140 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
3141 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
3142 // in a stalled download if the block file is pruned before the request.
3143 if (nLocalServices & NODE_NETWORK) {
3145 BOOST_FOREACH(CNode* pnode, vNodes)
3146 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
3147 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
3149 // Notify external listeners about the new tip.
3150 GetMainSignals().UpdatedBlockTip(pindexNewTip);
3151 uiInterface.NotifyBlockTip(hashNewTip);
3153 } while(pindexMostWork != chainActive.Tip());
3156 // Write changes periodically to disk, after relay.
3157 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
3164 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
3165 AssertLockHeld(cs_main);
3167 // Mark the block itself as invalid.
3168 pindex->nStatus |= BLOCK_FAILED_VALID;
3169 setDirtyBlockIndex.insert(pindex);
3170 setBlockIndexCandidates.erase(pindex);
3172 while (chainActive.Contains(pindex)) {
3173 CBlockIndex *pindexWalk = chainActive.Tip();
3174 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
3175 setDirtyBlockIndex.insert(pindexWalk);
3176 setBlockIndexCandidates.erase(pindexWalk);
3177 // ActivateBestChain considers blocks already in chainActive
3178 // unconditionally valid already, so force disconnect away from it.
3179 if (!DisconnectTip(state)) {
3180 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3181 mempool.removeWithoutBranchId(
3182 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3187 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
3189 BlockMap::iterator it = mapBlockIndex.begin();
3190 while (it != mapBlockIndex.end()) {
3191 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
3192 setBlockIndexCandidates.insert(it->second);
3197 InvalidChainFound(pindex);
3198 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
3199 mempool.removeWithoutBranchId(
3200 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
3204 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
3205 AssertLockHeld(cs_main);
3207 int nHeight = pindex->nHeight;
3209 // Remove the invalidity flag from this block and all its descendants.
3210 BlockMap::iterator it = mapBlockIndex.begin();
3211 while (it != mapBlockIndex.end()) {
3212 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
3213 it->second->nStatus &= ~BLOCK_FAILED_MASK;
3214 setDirtyBlockIndex.insert(it->second);
3215 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
3216 setBlockIndexCandidates.insert(it->second);
3218 if (it->second == pindexBestInvalid) {
3219 // Reset invalid block marker if it was pointing to one of those.
3220 pindexBestInvalid = NULL;
3226 // Remove the invalidity flag from all ancestors too.
3227 while (pindex != NULL) {
3228 if (pindex->nStatus & BLOCK_FAILED_MASK) {
3229 pindex->nStatus &= ~BLOCK_FAILED_MASK;
3230 setDirtyBlockIndex.insert(pindex);
3232 pindex = pindex->pprev;
3237 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
3239 // Check for duplicate
3240 uint256 hash = block.GetHash();
3241 BlockMap::iterator it = mapBlockIndex.find(hash);
3242 if (it != mapBlockIndex.end())
3245 // Construct new block index object
3246 CBlockIndex* pindexNew = new CBlockIndex(block);
3248 // We assign the sequence id to blocks only when the full data is available,
3249 // to avoid miners withholding blocks but broadcasting headers, to get a
3250 // competitive advantage.
3251 pindexNew->nSequenceId = 0;
3252 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3253 pindexNew->phashBlock = &((*mi).first);
3254 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3255 if (miPrev != mapBlockIndex.end())
3257 pindexNew->pprev = (*miPrev).second;
3258 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3259 pindexNew->BuildSkip();
3261 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3262 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3263 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3264 pindexBestHeader = pindexNew;
3266 setDirtyBlockIndex.insert(pindexNew);
3271 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3272 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3274 pindexNew->nTx = block.vtx.size();
3275 pindexNew->nChainTx = 0;
3276 CAmount sproutValue = 0;
3277 CAmount saplingValue = 0;
3278 for (auto tx : block.vtx) {
3279 // Negative valueBalance "takes" money from the transparent value pool
3280 // and adds it to the Sapling value pool. Positive valueBalance "gives"
3281 // money to the transparent value pool, removing from the Sapling value
3282 // pool. So we invert the sign here.
3283 saplingValue += -tx.valueBalance;
3285 for (auto js : tx.vjoinsplit) {
3286 sproutValue += js.vpub_old;
3287 sproutValue -= js.vpub_new;
3290 pindexNew->nSproutValue = sproutValue;
3291 pindexNew->nChainSproutValue = boost::none;
3292 pindexNew->nSaplingValue = saplingValue;
3293 pindexNew->nChainSaplingValue = boost::none;
3294 pindexNew->nFile = pos.nFile;
3295 pindexNew->nDataPos = pos.nPos;
3296 pindexNew->nUndoPos = 0;
3297 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3298 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3299 setDirtyBlockIndex.insert(pindexNew);
3301 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3302 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3303 deque<CBlockIndex*> queue;
3304 queue.push_back(pindexNew);
3306 // Recursively process any descendant blocks that now may be eligible to be connected.
3307 while (!queue.empty()) {
3308 CBlockIndex *pindex = queue.front();
3310 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3311 if (pindex->pprev) {
3312 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3313 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3315 pindex->nChainSproutValue = boost::none;
3317 if (pindex->pprev->nChainSaplingValue) {
3318 pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue;
3320 pindex->nChainSaplingValue = boost::none;
3323 pindex->nChainSproutValue = pindex->nSproutValue;
3324 pindex->nChainSaplingValue = pindex->nSaplingValue;
3327 LOCK(cs_nBlockSequenceId);
3328 pindex->nSequenceId = nBlockSequenceId++;
3330 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3331 setBlockIndexCandidates.insert(pindex);
3333 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3334 while (range.first != range.second) {
3335 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3336 queue.push_back(it->second);
3338 mapBlocksUnlinked.erase(it);
3342 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3343 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3350 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3352 LOCK(cs_LastBlockFile);
3354 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3355 if (vinfoBlockFile.size() <= nFile) {
3356 vinfoBlockFile.resize(nFile + 1);
3360 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3362 if (vinfoBlockFile.size() <= nFile) {
3363 vinfoBlockFile.resize(nFile + 1);
3367 pos.nPos = vinfoBlockFile[nFile].nSize;
3370 if (nFile != nLastBlockFile) {
3372 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3374 FlushBlockFile(!fKnown);
3375 nLastBlockFile = nFile;
3378 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3380 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3382 vinfoBlockFile[nFile].nSize += nAddSize;
3385 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3386 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3387 if (nNewChunks > nOldChunks) {
3389 fCheckForPruning = true;
3390 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3391 FILE *file = OpenBlockFile(pos);
3393 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3394 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3399 return state.Error("out of disk space");
3403 setDirtyFileInfo.insert(nFile);
3407 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3411 LOCK(cs_LastBlockFile);
3413 unsigned int nNewSize;
3414 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3415 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3416 setDirtyFileInfo.insert(nFile);
3418 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3419 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3420 if (nNewChunks > nOldChunks) {
3422 fCheckForPruning = true;
3423 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3424 FILE *file = OpenUndoFile(pos);
3426 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3427 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3432 return state.Error("out of disk space");
3438 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
3440 // Check block version
3441 if (block.nVersion < MIN_BLOCK_VERSION)
3442 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
3443 REJECT_INVALID, "version-too-low");
3445 // Check Equihash solution is valid
3446 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
3447 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3448 REJECT_INVALID, "invalid-solution");
3450 // Check proof of work matches claimed amount
3451 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
3452 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
3453 REJECT_INVALID, "high-hash");
3456 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
3457 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
3458 REJECT_INVALID, "time-too-new");
3463 bool CheckBlock(const CBlock& block, CValidationState& state,
3464 libzcash::ProofVerifier& verifier,
3465 bool fCheckPOW, bool fCheckMerkleRoot)
3467 // These are checks that are independent of context.
3469 // Check that the header is valid (particularly PoW). This is mostly
3470 // redundant with the call in AcceptBlockHeader.
3471 if (!CheckBlockHeader(block, state, fCheckPOW))
3474 // Check the merkle root.
3475 if (fCheckMerkleRoot) {
3477 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3478 if (block.hashMerkleRoot != hashMerkleRoot2)
3479 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3480 REJECT_INVALID, "bad-txnmrklroot", true);
3482 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3483 // of transactions in a block without affecting the merkle root of a block,
3484 // while still invalidating it.
3486 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3487 REJECT_INVALID, "bad-txns-duplicate", true);
3490 // All potential-corruption validation must be done before we do any
3491 // transaction validation, as otherwise we may mark the header as invalid
3492 // because we receive the wrong transactions for it.
3495 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3496 return state.DoS(100, error("CheckBlock(): size limits failed"),
3497 REJECT_INVALID, "bad-blk-length");
3499 // First transaction must be coinbase, the rest must not be
3500 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3501 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3502 REJECT_INVALID, "bad-cb-missing");
3503 for (unsigned int i = 1; i < block.vtx.size(); i++)
3504 if (block.vtx[i].IsCoinBase())
3505 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3506 REJECT_INVALID, "bad-cb-multiple");
3508 // Check transactions
3509 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3510 if (!CheckTransaction(tx, state, verifier))
3511 return error("CheckBlock(): CheckTransaction failed");
3513 unsigned int nSigOps = 0;
3514 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3516 nSigOps += GetLegacySigOpCount(tx);
3518 if (nSigOps > MAX_BLOCK_SIGOPS)
3519 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3520 REJECT_INVALID, "bad-blk-sigops", true);
3525 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3527 const CChainParams& chainParams = Params();
3528 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3529 uint256 hash = block.GetHash();
3530 if (hash == consensusParams.hashGenesisBlock)
3535 int nHeight = pindexPrev->nHeight+1;
3537 // Check proof of work
3538 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3539 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3540 REJECT_INVALID, "bad-diffbits");
3542 // Check timestamp against prev
3543 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3544 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3545 REJECT_INVALID, "time-too-old");
3547 if (fCheckpointsEnabled)
3549 // Don't accept any forks from the main chain prior to last checkpoint
3550 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3551 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3552 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3555 // Reject block.nVersion < 4 blocks
3556 if (block.nVersion < 4)
3557 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3558 REJECT_OBSOLETE, "bad-version");
3563 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3565 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3566 const Consensus::Params& consensusParams = Params().GetConsensus();
3568 // Check that all transactions are finalized
3569 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3571 // Check transaction contextually against consensus rules at block height
3572 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3573 return false; // Failure reason has been set in validation state object
3576 int nLockTimeFlags = 0;
3577 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3578 ? pindexPrev->GetMedianTimePast()
3579 : block.GetBlockTime();
3580 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3581 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3585 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3586 // In Zcash this has been enforced since launch, except that the genesis
3587 // block didn't include the height in the coinbase (see Zcash protocol spec
3588 // section '6.8 Bitcoin Improvement Proposals').
3591 CScript expect = CScript() << nHeight;
3592 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3593 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3594 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3598 // Coinbase transaction must include an output sending 20% of
3599 // the block reward to a founders reward script, until the last founders
3600 // reward block is reached, with exception of the genesis block.
3601 // The last founders reward block is defined as the block just before the
3602 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3603 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3606 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3607 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3608 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3616 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3623 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3625 const CChainParams& chainparams = Params();
3626 AssertLockHeld(cs_main);
3627 // Check for duplicate
3628 uint256 hash = block.GetHash();
3629 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3630 CBlockIndex *pindex = NULL;
3631 if (miSelf != mapBlockIndex.end()) {
3632 // Block header is already known.
3633 pindex = miSelf->second;
3636 if (pindex->nStatus & BLOCK_FAILED_MASK)
3637 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3641 if (!CheckBlockHeader(block, state))
3644 // Get prev block index
3645 CBlockIndex* pindexPrev = NULL;
3646 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3647 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3648 if (mi == mapBlockIndex.end())
3649 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3650 pindexPrev = (*mi).second;
3651 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3652 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3655 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3659 pindex = AddToBlockIndex(block);
3667 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3669 const CChainParams& chainparams = Params();
3670 AssertLockHeld(cs_main);
3672 CBlockIndex *&pindex = *ppindex;
3674 if (!AcceptBlockHeader(block, state, &pindex))
3677 // Try to process all requested blocks that we don't have, but only
3678 // process an unrequested block if it's new and has enough work to
3679 // advance our tip, and isn't too many blocks ahead.
3680 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3681 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3682 // Blocks that are too out-of-order needlessly limit the effectiveness of
3683 // pruning, because pruning will not delete block files that contain any
3684 // blocks which are too close in height to the tip. Apply this test
3685 // regardless of whether pruning is enabled; it should generally be safe to
3686 // not process unrequested blocks.
3687 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3689 // TODO: deal better with return value and error conditions for duplicate
3690 // and unrequested blocks.
3691 if (fAlreadyHave) return true;
3692 if (!fRequested) { // If we didn't ask for it:
3693 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3694 if (!fHasMoreWork) return true; // Don't process less-work chains
3695 if (fTooFarAhead) return true; // Block height is too high
3698 // See method docstring for why this is always disabled
3699 auto verifier = libzcash::ProofVerifier::Disabled();
3700 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3701 if (state.IsInvalid() && !state.CorruptionPossible()) {
3702 pindex->nStatus |= BLOCK_FAILED_VALID;
3703 setDirtyBlockIndex.insert(pindex);
3708 int nHeight = pindex->nHeight;
3710 // Write block to history file
3712 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3713 CDiskBlockPos blockPos;
3716 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3717 return error("AcceptBlock(): FindBlockPos failed");
3719 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3720 AbortNode(state, "Failed to write block");
3721 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3722 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3723 } catch (const std::runtime_error& e) {
3724 return AbortNode(state, std::string("System error: ") + e.what());
3727 if (fCheckForPruning)
3728 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3733 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3735 unsigned int nFound = 0;
3736 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3738 if (pstart->nVersion >= minVersion)
3740 pstart = pstart->pprev;
3742 return (nFound >= nRequired);
3746 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3748 // Preliminary checks
3749 auto verifier = libzcash::ProofVerifier::Disabled();
3750 bool checked = CheckBlock(*pblock, state, verifier);
3754 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3755 fRequested |= fForceProcessing;
3757 return error("%s: CheckBlock FAILED", __func__);
3761 CBlockIndex *pindex = NULL;
3762 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3763 if (pindex && pfrom) {
3764 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3768 return error("%s: AcceptBlock FAILED", __func__);
3771 if (!ActivateBestChain(state, pblock))
3772 return error("%s: ActivateBestChain failed", __func__);
3777 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3779 AssertLockHeld(cs_main);
3780 assert(pindexPrev == chainActive.Tip());
3782 CCoinsViewCache viewNew(pcoinsTip);
3783 CBlockIndex indexDummy(block);
3784 indexDummy.pprev = pindexPrev;
3785 indexDummy.nHeight = pindexPrev->nHeight + 1;
3786 // JoinSplit proofs are verified in ConnectBlock
3787 auto verifier = libzcash::ProofVerifier::Disabled();
3789 // NOTE: CheckBlockHeader is called by CheckBlock
3790 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3792 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3794 if (!ContextualCheckBlock(block, state, pindexPrev))
3796 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3798 assert(state.IsValid());
3804 * BLOCK PRUNING CODE
3807 /* Calculate the amount of disk space the block & undo files currently use */
3808 uint64_t CalculateCurrentUsage()
3810 uint64_t retval = 0;
3811 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3812 retval += file.nSize + file.nUndoSize;
3817 /* Prune a block file (modify associated database entries)*/
3818 void PruneOneBlockFile(const int fileNumber)
3820 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3821 CBlockIndex* pindex = it->second;
3822 if (pindex->nFile == fileNumber) {
3823 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3824 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3826 pindex->nDataPos = 0;
3827 pindex->nUndoPos = 0;
3828 setDirtyBlockIndex.insert(pindex);
3830 // Prune from mapBlocksUnlinked -- any block we prune would have
3831 // to be downloaded again in order to consider its chain, at which
3832 // point it would be considered as a candidate for
3833 // mapBlocksUnlinked or setBlockIndexCandidates.
3834 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3835 while (range.first != range.second) {
3836 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3838 if (it->second == pindex) {
3839 mapBlocksUnlinked.erase(it);
3845 vinfoBlockFile[fileNumber].SetNull();
3846 setDirtyFileInfo.insert(fileNumber);
3850 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3852 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3853 CDiskBlockPos pos(*it, 0);
3854 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3855 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3856 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3860 /* Calculate the block/rev files that should be deleted to remain under target*/
3861 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3863 LOCK2(cs_main, cs_LastBlockFile);
3864 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3867 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3871 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3872 uint64_t nCurrentUsage = CalculateCurrentUsage();
3873 // We don't check to prune until after we've allocated new space for files
3874 // So we should leave a buffer under our target to account for another allocation
3875 // before the next pruning.
3876 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3877 uint64_t nBytesToPrune;
3880 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3881 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3882 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3884 if (vinfoBlockFile[fileNumber].nSize == 0)
3887 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3890 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3891 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3894 PruneOneBlockFile(fileNumber);
3895 // Queue up the files for removal
3896 setFilesToPrune.insert(fileNumber);
3897 nCurrentUsage -= nBytesToPrune;
3902 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3903 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3904 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3905 nLastBlockWeCanPrune, count);
3908 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3910 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3912 // Check for nMinDiskSpace bytes (currently 50MB)
3913 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3914 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3919 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3923 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3924 boost::filesystem::create_directories(path.parent_path());
3925 FILE* file = fopen(path.string().c_str(), "rb+");
3926 if (!file && !fReadOnly)
3927 file = fopen(path.string().c_str(), "wb+");
3929 LogPrintf("Unable to open file %s\n", path.string());
3933 if (fseek(file, pos.nPos, SEEK_SET)) {
3934 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3942 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3943 return OpenDiskFile(pos, "blk", fReadOnly);
3946 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3947 return OpenDiskFile(pos, "rev", fReadOnly);
3950 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3952 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3955 CBlockIndex * InsertBlockIndex(uint256 hash)
3961 BlockMap::iterator mi = mapBlockIndex.find(hash);
3962 if (mi != mapBlockIndex.end())
3963 return (*mi).second;
3966 CBlockIndex* pindexNew = new CBlockIndex();
3968 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3969 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3970 pindexNew->phashBlock = &((*mi).first);
3975 bool static LoadBlockIndexDB()
3977 const CChainParams& chainparams = Params();
3978 if (!pblocktree->LoadBlockIndexGuts())
3981 boost::this_thread::interruption_point();
3983 // Calculate nChainWork
3984 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3985 vSortedByHeight.reserve(mapBlockIndex.size());
3986 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3988 CBlockIndex* pindex = item.second;
3989 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3991 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3992 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3994 CBlockIndex* pindex = item.second;
3995 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3996 // We can link the chain of blocks for which we've received transactions at some point.
3997 // Pruned nodes may have deleted the block.
3998 if (pindex->nTx > 0) {
3999 if (pindex->pprev) {
4000 if (pindex->pprev->nChainTx) {
4001 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
4002 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
4003 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
4005 pindex->nChainSproutValue = boost::none;
4007 if (pindex->pprev->nChainSaplingValue) {
4008 pindex->nChainSaplingValue = *pindex->pprev->nChainSaplingValue + pindex->nSaplingValue;
4010 pindex->nChainSaplingValue = boost::none;
4013 pindex->nChainTx = 0;
4014 pindex->nChainSproutValue = boost::none;
4015 pindex->nChainSaplingValue = boost::none;
4016 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
4019 pindex->nChainTx = pindex->nTx;
4020 pindex->nChainSproutValue = pindex->nSproutValue;
4021 pindex->nChainSaplingValue = pindex->nSaplingValue;
4024 // Construct in-memory chain of branch IDs.
4025 // Relies on invariant: a block that does not activate a network upgrade
4026 // will always be valid under the same consensus rules as its parent.
4027 // Genesis block has a branch ID of zero by definition, but has no
4028 // validity status because it is side-loaded into a fresh chain.
4029 // Activation blocks will have branch IDs set (read from disk).
4030 if (pindex->pprev) {
4031 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
4032 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
4035 pindex->nCachedBranchId = SPROUT_BRANCH_ID;
4037 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
4038 setBlockIndexCandidates.insert(pindex);
4039 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
4040 pindexBestInvalid = pindex;
4042 pindex->BuildSkip();
4043 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
4044 pindexBestHeader = pindex;
4047 // Load block file info
4048 pblocktree->ReadLastBlockFile(nLastBlockFile);
4049 vinfoBlockFile.resize(nLastBlockFile + 1);
4050 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
4051 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
4052 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
4054 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
4055 for (int nFile = nLastBlockFile + 1; true; nFile++) {
4056 CBlockFileInfo info;
4057 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
4058 vinfoBlockFile.push_back(info);
4064 // Check presence of blk files
4065 LogPrintf("Checking all blk files are present...\n");
4066 set<int> setBlkDataFiles;
4067 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4069 CBlockIndex* pindex = item.second;
4070 if (pindex->nStatus & BLOCK_HAVE_DATA) {
4071 setBlkDataFiles.insert(pindex->nFile);
4074 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
4076 CDiskBlockPos pos(*it, 0);
4077 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
4082 // Check whether we have ever pruned block & undo files
4083 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
4085 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
4087 // Check whether we need to continue reindexing
4088 bool fReindexing = false;
4089 pblocktree->ReadReindexing(fReindexing);
4090 fReindex |= fReindexing;
4092 // Check whether we have a transaction index
4093 pblocktree->ReadFlag("txindex", fTxIndex);
4094 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
4096 // Fill in-memory data
4097 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
4099 CBlockIndex* pindex = item.second;
4100 // - This relationship will always be true even if pprev has multiple
4101 // children, because hashSproutAnchor is technically a property of pprev,
4102 // not its children.
4103 // - This will miss chain tips; we handle the best tip below, and other
4104 // tips will be handled by ConnectTip during a re-org.
4105 if (pindex->pprev) {
4106 pindex->pprev->hashFinalSproutRoot = pindex->hashSproutAnchor;
4110 // Load pointer to end of best chain
4111 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
4112 if (it == mapBlockIndex.end())
4114 chainActive.SetTip(it->second);
4115 // Set hashFinalSproutRoot for the end of best chain
4116 it->second->hashFinalSproutRoot = pcoinsTip->GetBestAnchor(SPROUT);
4118 PruneBlockIndexCandidates();
4120 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
4121 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
4122 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
4123 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
4125 EnforceNodeDeprecation(chainActive.Height(), true);
4130 CVerifyDB::CVerifyDB()
4132 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
4135 CVerifyDB::~CVerifyDB()
4137 uiInterface.ShowProgress("", 100);
4140 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
4143 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
4146 // Verify blocks in the best chain
4147 if (nCheckDepth <= 0)
4148 nCheckDepth = 1000000000; // suffices until the year 19000
4149 if (nCheckDepth > chainActive.Height())
4150 nCheckDepth = chainActive.Height();
4151 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
4152 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
4153 CCoinsViewCache coins(coinsview);
4154 CBlockIndex* pindexState = chainActive.Tip();
4155 CBlockIndex* pindexFailure = NULL;
4156 int nGoodTransactions = 0;
4157 CValidationState state;
4158 // No need to verify JoinSplits twice
4159 auto verifier = libzcash::ProofVerifier::Disabled();
4160 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
4162 boost::this_thread::interruption_point();
4163 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
4164 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
4167 // check level 0: read from disk
4168 if (!ReadBlockFromDisk(block, pindex))
4169 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4170 // check level 1: verify block validity
4171 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
4172 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4173 // check level 2: verify undo validity
4174 if (nCheckLevel >= 2 && pindex) {
4176 CDiskBlockPos pos = pindex->GetUndoPos();
4177 if (!pos.IsNull()) {
4178 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
4179 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4182 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
4183 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
4185 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
4186 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4187 pindexState = pindex->pprev;
4189 nGoodTransactions = 0;
4190 pindexFailure = pindex;
4192 nGoodTransactions += block.vtx.size();
4194 if (ShutdownRequested())
4198 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
4200 // check level 4: try reconnecting blocks
4201 if (nCheckLevel >= 4) {
4202 CBlockIndex *pindex = pindexState;
4203 while (pindex != chainActive.Tip()) {
4204 boost::this_thread::interruption_point();
4205 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
4206 pindex = chainActive.Next(pindex);
4208 if (!ReadBlockFromDisk(block, pindex))
4209 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4210 if (!ConnectBlock(block, state, pindex, coins))
4211 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
4215 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
4220 bool RewindBlockIndex(const CChainParams& params, bool& clearWitnessCaches)
4224 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
4225 // index will have nCachedBranchId set based on the values previously persisted
4226 // to disk. By definition, a set nCachedBranchId means that the block was
4227 // fully-validated under the corresponding consensus rules. Thus we can quickly
4228 // identify whether the current active chain matches our expected sequence of
4229 // consensus rule changes, with two checks:
4231 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
4232 // - nCachedBranchId for each block matches what we expect.
4233 auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) {
4234 auto consensus = params.GetConsensus();
4235 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
4236 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
4237 return fFlagSet == fFlagExpected &&
4238 pindex->nCachedBranchId &&
4239 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
4243 while (nHeight <= chainActive.Height()) {
4244 if (!sufficientlyValidated(chainActive[nHeight])) {
4250 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
4251 auto rewindLength = chainActive.Height() - nHeight;
4252 clearWitnessCaches = false;
4254 if (rewindLength > 0) {
4255 LogPrintf("*** First insufficiently validated block at height %d, rewind length %d\n", nHeight, rewindLength);
4256 const uint256 *phashFirstInsufValidated = chainActive[nHeight]->phashBlock;
4257 auto networkID = params.NetworkIDString();
4259 // This is true when we intend to do a long rewind.
4260 bool intendedRewind =
4261 (networkID == "test" && nHeight == 252500 && *phashFirstInsufValidated ==
4262 uint256S("0018bd16a9c6f15795a754c498d2b2083ab78f14dae44a66a8d0e90ba8464d9c"));
4264 clearWitnessCaches = (rewindLength > MAX_REORG_LENGTH && intendedRewind);
4266 if (clearWitnessCaches) {
4267 auto msg = strprintf(_(
4268 "An intended block chain rewind has been detected: network %s, hash %s, height %d"
4269 ), networkID, phashFirstInsufValidated->GetHex(), nHeight);
4270 LogPrintf("*** %s\n", msg);
4273 if (rewindLength > MAX_REORG_LENGTH && !intendedRewind) {
4274 auto pindexOldTip = chainActive.Tip();
4275 auto pindexRewind = chainActive[nHeight - 1];
4276 auto msg = strprintf(_(
4277 "A block chain rewind has been detected that would roll back %d blocks! "
4278 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
4279 ), rewindLength, MAX_REORG_LENGTH) + "\n\n" +
4280 _("Rewind details") + ":\n" +
4281 "- " + strprintf(_("Current tip: %s, height %d"),
4282 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" +
4283 "- " + strprintf(_("Rewinding to: %s, height %d"),
4284 pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" +
4285 _("Please help, human!");
4286 LogPrintf("*** %s\n", msg);
4287 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
4293 CValidationState state;
4294 CBlockIndex* pindex = chainActive.Tip();
4295 while (chainActive.Height() >= nHeight) {
4296 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4297 // If pruning, don't try rewinding past the HAVE_DATA point;
4298 // since older blocks can't be served anyway, there's
4299 // no need to walk further, and trying to DisconnectTip()
4300 // will fail (and require a needless reindex/redownload
4301 // of the blockchain).
4304 if (!DisconnectTip(state, true)) {
4305 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4307 // Occasionally flush state to disk.
4308 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
4312 // Collect blocks to be removed (blocks in mapBlockIndex must be at least BLOCK_VALID_TREE).
4313 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4314 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4315 std::vector<const CBlockIndex*> vBlocks;
4316 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4317 CBlockIndex* pindexIter = it->second;
4319 // Note: If we encounter an insufficiently validated block that
4320 // is on chainActive, it must be because we are a pruning node, and
4321 // this block or some successor doesn't HAVE_DATA, so we were unable to
4322 // rewind all the way. Blocks remaining on chainActive at this point
4323 // must not have their validity reduced.
4324 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
4325 // Add to the list of blocks to remove
4326 vBlocks.push_back(pindexIter);
4327 if (pindexIter == pindexBestInvalid) {
4328 // Reset invalid block marker if it was pointing to this block
4329 pindexBestInvalid = NULL;
4332 setBlockIndexCandidates.erase(pindexIter);
4333 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4334 while (ret.first != ret.second) {
4335 if (ret.first->second == pindexIter) {
4336 mapBlocksUnlinked.erase(ret.first++);
4341 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4342 setBlockIndexCandidates.insert(pindexIter);
4346 // Set pindexBestHeader to the current chain tip
4347 // (since we are about to delete the block it is pointing to)
4348 pindexBestHeader = chainActive.Tip();
4350 // Erase block indices on-disk
4351 if (!pblocktree->EraseBatchSync(vBlocks)) {
4352 return AbortNode(state, "Failed to erase from block index database");
4355 // Erase block indices in-memory
4356 for (auto pindex : vBlocks) {
4357 auto ret = mapBlockIndex.find(*pindex->phashBlock);
4358 if (ret != mapBlockIndex.end()) {
4359 mapBlockIndex.erase(ret);
4364 PruneBlockIndexCandidates();
4368 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4375 void UnloadBlockIndex()
4378 setBlockIndexCandidates.clear();
4379 chainActive.SetTip(NULL);
4380 pindexBestInvalid = NULL;
4381 pindexBestHeader = NULL;
4383 mapOrphanTransactions.clear();
4384 mapOrphanTransactionsByPrev.clear();
4386 mapBlocksUnlinked.clear();
4387 vinfoBlockFile.clear();
4389 nBlockSequenceId = 1;
4390 mapBlockSource.clear();
4391 mapBlocksInFlight.clear();
4392 nQueuedValidatedHeaders = 0;
4393 nPreferredDownload = 0;
4394 setDirtyBlockIndex.clear();
4395 setDirtyFileInfo.clear();
4396 mapNodeState.clear();
4397 recentRejects.reset(NULL);
4399 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4400 delete entry.second;
4402 mapBlockIndex.clear();
4403 fHavePruned = false;
4406 bool LoadBlockIndex()
4408 // Load block index from databases
4409 if (!fReindex && !LoadBlockIndexDB())
4415 bool InitBlockIndex() {
4416 const CChainParams& chainparams = Params();
4419 // Initialize global variables that cannot be constructed at startup.
4420 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4422 // Check whether we're already initialized
4423 if (chainActive.Genesis() != NULL)
4426 // Use the provided setting for -txindex in the new database
4427 fTxIndex = GetBoolArg("-txindex", false);
4428 pblocktree->WriteFlag("txindex", fTxIndex);
4429 LogPrintf("Initializing databases...\n");
4431 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4434 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4435 // Start new block file
4436 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4437 CDiskBlockPos blockPos;
4438 CValidationState state;
4439 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4440 return error("LoadBlockIndex(): FindBlockPos failed");
4441 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4442 return error("LoadBlockIndex(): writing genesis block to disk failed");
4443 CBlockIndex *pindex = AddToBlockIndex(block);
4444 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4445 return error("LoadBlockIndex(): genesis block not accepted");
4446 if (!ActivateBestChain(state, &block))
4447 return error("LoadBlockIndex(): genesis block cannot be activated");
4448 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4449 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4450 } catch (const std::runtime_error& e) {
4451 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4460 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4462 const CChainParams& chainparams = Params();
4463 // Map of disk positions for blocks with unknown parent (only used for reindex)
4464 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4465 int64_t nStart = GetTimeMillis();
4469 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4470 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4471 uint64_t nRewind = blkdat.GetPos();
4472 while (!blkdat.eof()) {
4473 boost::this_thread::interruption_point();
4475 blkdat.SetPos(nRewind);
4476 nRewind++; // start one byte further next time, in case of failure
4477 blkdat.SetLimit(); // remove former limit
4478 unsigned int nSize = 0;
4481 unsigned char buf[MESSAGE_START_SIZE];
4482 blkdat.FindByte(Params().MessageStart()[0]);
4483 nRewind = blkdat.GetPos()+1;
4484 blkdat >> FLATDATA(buf);
4485 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4489 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4491 } catch (const std::exception&) {
4492 // no valid block header found; don't complain
4497 uint64_t nBlockPos = blkdat.GetPos();
4499 dbp->nPos = nBlockPos;
4500 blkdat.SetLimit(nBlockPos + nSize);
4501 blkdat.SetPos(nBlockPos);
4504 nRewind = blkdat.GetPos();
4506 // detect out of order blocks, and store them for later
4507 uint256 hash = block.GetHash();
4508 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4509 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4510 block.hashPrevBlock.ToString());
4512 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4516 // process in case the block isn't known yet
4517 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4518 CValidationState state;
4519 if (ProcessNewBlock(state, NULL, &block, true, dbp))
4521 if (state.IsError())
4523 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4524 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4527 // Recursively process earlier encountered successors of this block
4528 deque<uint256> queue;
4529 queue.push_back(hash);
4530 while (!queue.empty()) {
4531 uint256 head = queue.front();
4533 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4534 while (range.first != range.second) {
4535 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4536 if (ReadBlockFromDisk(block, it->second))
4538 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4540 CValidationState dummy;
4541 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
4544 queue.push_back(block.GetHash());
4548 mapBlocksUnknownParent.erase(it);
4551 } catch (const std::exception& e) {
4552 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4555 } catch (const std::runtime_error& e) {
4556 AbortNode(std::string("System error: ") + e.what());
4559 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4563 void static CheckBlockIndex()
4565 const Consensus::Params& consensusParams = Params().GetConsensus();
4566 if (!fCheckBlockIndex) {
4572 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4573 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4574 // iterating the block tree require that chainActive has been initialized.)
4575 if (chainActive.Height() < 0) {
4576 assert(mapBlockIndex.size() <= 1);
4580 // Build forward-pointing map of the entire block tree.
4581 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4582 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4583 forward.insert(std::make_pair(it->second->pprev, it->second));
4586 assert(forward.size() == mapBlockIndex.size());
4588 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4589 CBlockIndex *pindex = rangeGenesis.first->second;
4590 rangeGenesis.first++;
4591 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4593 // Iterate over the entire block tree, using depth-first search.
4594 // Along the way, remember whether there are blocks on the path from genesis
4595 // block being explored which are the first to have certain properties.
4598 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4599 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4600 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4601 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4602 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4603 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4604 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4605 while (pindex != NULL) {
4607 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4608 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4609 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4610 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4611 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4612 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4613 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4615 // Begin: actual consistency checks.
4616 if (pindex->pprev == NULL) {
4617 // Genesis block checks.
4618 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4619 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4621 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4622 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4623 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4625 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4626 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4627 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4629 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4630 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4632 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4633 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4634 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4635 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4636 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4637 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4638 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.
4639 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4640 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4641 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4642 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4643 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4644 if (pindexFirstInvalid == NULL) {
4645 // Checks for not-invalid blocks.
4646 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4648 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4649 if (pindexFirstInvalid == NULL) {
4650 // If this block sorts at least as good as the current tip and
4651 // is valid and we have all data for its parents, it must be in
4652 // setBlockIndexCandidates. chainActive.Tip() must also be there
4653 // even if some data has been pruned.
4654 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4655 assert(setBlockIndexCandidates.count(pindex));
4657 // If some parent is missing, then it could be that this block was in
4658 // setBlockIndexCandidates but had to be removed because of the missing data.
4659 // In this case it must be in mapBlocksUnlinked -- see test below.
4661 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4662 assert(setBlockIndexCandidates.count(pindex) == 0);
4664 // Check whether this block is in mapBlocksUnlinked.
4665 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4666 bool foundInUnlinked = false;
4667 while (rangeUnlinked.first != rangeUnlinked.second) {
4668 assert(rangeUnlinked.first->first == pindex->pprev);
4669 if (rangeUnlinked.first->second == pindex) {
4670 foundInUnlinked = true;
4673 rangeUnlinked.first++;
4675 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4676 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4677 assert(foundInUnlinked);
4679 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4680 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4681 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4682 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4683 assert(fHavePruned); // We must have pruned.
4684 // This block may have entered mapBlocksUnlinked if:
4685 // - it has a descendant that at some point had more work than the
4687 // - we tried switching to that descendant but were missing
4688 // data for some intermediate block between chainActive and the
4690 // So if this block is itself better than chainActive.Tip() and it wasn't in
4691 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4692 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4693 if (pindexFirstInvalid == NULL) {
4694 assert(foundInUnlinked);
4698 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4699 // End: actual consistency checks.
4701 // Try descending into the first subnode.
4702 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4703 if (range.first != range.second) {
4704 // A subnode was found.
4705 pindex = range.first->second;
4709 // This is a leaf node.
4710 // Move upwards until we reach a node of which we have not yet visited the last child.
4712 // We are going to either move to a parent or a sibling of pindex.
4713 // If pindex was the first with a certain property, unset the corresponding variable.
4714 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4715 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4716 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4717 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4718 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4719 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4720 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4722 CBlockIndex* pindexPar = pindex->pprev;
4723 // Find which child we just visited.
4724 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4725 while (rangePar.first->second != pindex) {
4726 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4729 // Proceed to the next one.
4731 if (rangePar.first != rangePar.second) {
4732 // Move to the sibling.
4733 pindex = rangePar.first->second;
4744 // Check that we actually traversed the entire map.
4745 assert(nNodes == forward.size());
4748 //////////////////////////////////////////////////////////////////////////////
4753 std::string GetWarnings(const std::string& strFor)
4756 string strStatusBar;
4759 if (!CLIENT_VERSION_IS_RELEASE)
4760 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4762 if (GetBoolArg("-testsafemode", false))
4763 strStatusBar = strRPC = "testsafemode enabled";
4765 // Misc warnings like out of disk space and clock is wrong
4766 if (strMiscWarning != "")
4769 strStatusBar = strMiscWarning;
4772 if (fLargeWorkForkFound)
4775 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4777 else if (fLargeWorkInvalidChainFound)
4780 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.");
4786 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4788 const CAlert& alert = item.second;
4789 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4791 nPriority = alert.nPriority;
4792 strStatusBar = alert.strStatusBar;
4793 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4794 strRPC = alert.strRPCError;
4800 if (strFor == "statusbar")
4801 return strStatusBar;
4802 else if (strFor == "rpc")
4804 assert(!"GetWarnings(): invalid parameter");
4815 //////////////////////////////////////////////////////////////////////////////
4821 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4827 assert(recentRejects);
4828 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4830 // If the chain tip has changed previously rejected transactions
4831 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4832 // or a double-spend. Reset the rejects filter and give those
4833 // txs a second chance.
4834 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4835 recentRejects->reset();
4838 return recentRejects->contains(inv.hash) ||
4839 mempool.exists(inv.hash) ||
4840 mapOrphanTransactions.count(inv.hash) ||
4841 pcoinsTip->HaveCoins(inv.hash);
4844 return mapBlockIndex.count(inv.hash);
4846 // Don't know what it is, just say we already got one
4850 void static ProcessGetData(CNode* pfrom)
4852 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4854 vector<CInv> vNotFound;
4858 while (it != pfrom->vRecvGetData.end()) {
4859 // Don't bother if send buffer is too full to respond anyway
4860 if (pfrom->nSendSize >= SendBufferSize())
4863 const CInv &inv = *it;
4865 boost::this_thread::interruption_point();
4868 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4871 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4872 if (mi != mapBlockIndex.end())
4874 if (chainActive.Contains(mi->second)) {
4877 static const int nOneMonth = 30 * 24 * 60 * 60;
4878 // To prevent fingerprinting attacks, only send blocks outside of the active
4879 // chain if they are valid, and no more than a month older (both in time, and in
4880 // best equivalent proof of work) than the best header chain we know about.
4881 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4882 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4883 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4885 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4889 // Pruned nodes may have deleted the block, so check whether
4890 // it's available before trying to send.
4891 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4893 // Send block from disk
4895 if (!ReadBlockFromDisk(block, (*mi).second))
4896 assert(!"cannot load block from disk");
4897 if (inv.type == MSG_BLOCK)
4898 pfrom->PushMessage("block", block);
4899 else // MSG_FILTERED_BLOCK)
4901 LOCK(pfrom->cs_filter);
4904 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4905 pfrom->PushMessage("merkleblock", merkleBlock);
4906 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4907 // This avoids hurting performance by pointlessly requiring a round-trip
4908 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4909 // they must either disconnect and retry or request the full block.
4910 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4911 // however we MUST always provide at least what the remote peer needs
4912 typedef std::pair<unsigned int, uint256> PairType;
4913 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4914 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4915 pfrom->PushMessage("tx", block.vtx[pair.first]);
4921 // Trigger the peer node to send a getblocks request for the next batch of inventory
4922 if (inv.hash == pfrom->hashContinue)
4924 // Bypass PushInventory, this must send even if redundant,
4925 // and we want it right after the last block so they don't
4926 // wait for other stuff first.
4928 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4929 pfrom->PushMessage("inv", vInv);
4930 pfrom->hashContinue.SetNull();
4934 else if (inv.IsKnownType())
4936 // Send stream from relay memory
4937 bool pushed = false;
4940 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4941 if (mi != mapRelay.end()) {
4942 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4946 if (!pushed && inv.type == MSG_TX) {
4948 if (mempool.lookup(inv.hash, tx)) {
4949 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4952 pfrom->PushMessage("tx", ss);
4957 vNotFound.push_back(inv);
4961 // Track requests for our stuff.
4962 GetMainSignals().Inventory(inv.hash);
4964 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4969 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4971 if (!vNotFound.empty()) {
4972 // Let the peer know that we didn't find what it asked for, so it doesn't
4973 // have to wait around forever. Currently only SPV clients actually care
4974 // about this message: it's needed when they are recursively walking the
4975 // dependencies of relevant unconfirmed transactions. SPV clients want to
4976 // do that because they want to know about (and store and rebroadcast and
4977 // risk analyze) the dependencies of transactions relevant to them, without
4978 // having to download the entire memory pool.
4979 pfrom->PushMessage("notfound", vNotFound);
4983 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4985 const CChainParams& chainparams = Params();
4986 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4987 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4989 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4994 if (strCommand == "version")
4996 // Each connection can only send one version message
4997 if (pfrom->nVersion != 0)
4999 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
5000 Misbehaving(pfrom->GetId(), 1);
5007 uint64_t nNonce = 1;
5008 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
5009 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
5011 // disconnect from peers older than this proto version
5012 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5013 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5014 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
5015 pfrom->fDisconnect = true;
5019 // Reject incoming connections from nodes that don't know about the current epoch
5020 const Consensus::Params& params = Params().GetConsensus();
5021 auto currentEpoch = CurrentEpoch(GetHeight(), params);
5022 if (pfrom->nVersion < params.vUpgrades[currentEpoch].nProtocolVersion)
5024 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5025 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5026 strprintf("Version must be %d or greater",
5027 params.vUpgrades[currentEpoch].nProtocolVersion));
5028 pfrom->fDisconnect = true;
5032 if (pfrom->nVersion == 10300)
5033 pfrom->nVersion = 300;
5035 vRecv >> addrFrom >> nNonce;
5036 if (!vRecv.empty()) {
5037 vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH);
5038 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
5041 vRecv >> pfrom->nStartingHeight;
5043 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
5045 pfrom->fRelayTxes = true;
5047 // Disconnect if we connected to ourself
5048 if (nNonce == nLocalHostNonce && nNonce > 1)
5050 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
5051 pfrom->fDisconnect = true;
5055 pfrom->addrLocal = addrMe;
5056 if (pfrom->fInbound && addrMe.IsRoutable())
5061 // Be shy and don't send version until we hear
5062 if (pfrom->fInbound)
5063 pfrom->PushVersion();
5065 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
5067 // Potentially mark this peer as a preferred download peer.
5068 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
5071 pfrom->PushMessage("verack");
5072 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5074 if (!pfrom->fInbound)
5076 // Advertise our address
5077 if (fListen && !IsInitialBlockDownload())
5079 CAddress addr = GetLocalAddress(&pfrom->addr);
5080 if (addr.IsRoutable())
5082 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5083 pfrom->PushAddress(addr);
5084 } else if (IsPeerAddrLocalGood(pfrom)) {
5085 addr.SetIP(pfrom->addrLocal);
5086 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
5087 pfrom->PushAddress(addr);
5091 // Get recent addresses
5092 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
5094 pfrom->PushMessage("getaddr");
5095 pfrom->fGetAddr = true;
5097 addrman.Good(pfrom->addr);
5099 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
5101 addrman.Add(addrFrom, addrFrom);
5102 addrman.Good(addrFrom);
5109 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
5110 item.second.RelayTo(pfrom);
5113 pfrom->fSuccessfullyConnected = true;
5117 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
5119 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
5120 pfrom->cleanSubVer, pfrom->nVersion,
5121 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
5124 int64_t nTimeOffset = nTime - GetTime();
5125 pfrom->nTimeOffset = nTimeOffset;
5126 AddTimeData(pfrom->addr, nTimeOffset);
5130 else if (pfrom->nVersion == 0)
5132 // Must have a version message before anything else
5133 Misbehaving(pfrom->GetId(), 1);
5138 else if (strCommand == "verack")
5140 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
5142 // Mark this node as currently connected, so we update its timestamp later.
5143 if (pfrom->fNetworkNode) {
5145 State(pfrom->GetId())->fCurrentlyConnected = true;
5150 // Disconnect existing peer connection when:
5151 // 1. The version message has been received
5152 // 2. Peer version is below the minimum version for the current epoch
5153 else if (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[
5154 CurrentEpoch(GetHeight(), chainparams.GetConsensus())].nProtocolVersion)
5156 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
5157 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
5158 strprintf("Version must be %d or greater",
5159 chainparams.GetConsensus().vUpgrades[
5160 CurrentEpoch(GetHeight(), chainparams.GetConsensus())].nProtocolVersion));
5161 pfrom->fDisconnect = true;
5166 else if (strCommand == "addr")
5168 vector<CAddress> vAddr;
5171 // Don't want addr from older versions unless seeding
5172 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
5174 if (vAddr.size() > 1000)
5176 Misbehaving(pfrom->GetId(), 20);
5177 return error("message addr size() = %u", vAddr.size());
5180 // Store the new addresses
5181 vector<CAddress> vAddrOk;
5182 int64_t nNow = GetAdjustedTime();
5183 int64_t nSince = nNow - 10 * 60;
5184 BOOST_FOREACH(CAddress& addr, vAddr)
5186 boost::this_thread::interruption_point();
5188 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
5189 addr.nTime = nNow - 5 * 24 * 60 * 60;
5190 pfrom->AddAddressKnown(addr);
5191 bool fReachable = IsReachable(addr);
5192 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
5194 // Relay to a limited number of other nodes
5197 // Use deterministic randomness to send to the same nodes for 24 hours
5198 // at a time so the addrKnowns of the chosen nodes prevent repeats
5199 static uint256 hashSalt;
5200 if (hashSalt.IsNull())
5201 hashSalt = GetRandHash();
5202 uint64_t hashAddr = addr.GetHash();
5203 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
5204 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5205 multimap<uint256, CNode*> mapMix;
5206 BOOST_FOREACH(CNode* pnode, vNodes)
5208 if (pnode->nVersion < CADDR_TIME_VERSION)
5210 unsigned int nPointer;
5211 memcpy(&nPointer, &pnode, sizeof(nPointer));
5212 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
5213 hashKey = Hash(BEGIN(hashKey), END(hashKey));
5214 mapMix.insert(make_pair(hashKey, pnode));
5216 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
5217 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
5218 ((*mi).second)->PushAddress(addr);
5221 // Do not store addresses outside our network
5223 vAddrOk.push_back(addr);
5225 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
5226 if (vAddr.size() < 1000)
5227 pfrom->fGetAddr = false;
5228 if (pfrom->fOneShot)
5229 pfrom->fDisconnect = true;
5233 else if (strCommand == "inv")
5237 if (vInv.size() > MAX_INV_SZ)
5239 Misbehaving(pfrom->GetId(), 20);
5240 return error("message inv size() = %u", vInv.size());
5245 std::vector<CInv> vToFetch;
5247 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
5249 const CInv &inv = vInv[nInv];
5251 boost::this_thread::interruption_point();
5252 pfrom->AddInventoryKnown(inv);
5254 bool fAlreadyHave = AlreadyHave(inv);
5255 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
5257 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
5260 if (inv.type == MSG_BLOCK) {
5261 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
5262 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
5263 // First request the headers preceding the announced block. In the normal fully-synced
5264 // case where a new block is announced that succeeds the current tip (no reorganization),
5265 // there are no such headers.
5266 // Secondly, and only when we are close to being synced, we request the announced block directly,
5267 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
5268 // time the block arrives, the header chain leading up to it is already validated. Not
5269 // doing this will result in the received block being rejected as an orphan in case it is
5270 // not a direct successor.
5271 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
5272 CNodeState *nodestate = State(pfrom->GetId());
5273 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
5274 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5275 vToFetch.push_back(inv);
5276 // Mark block as in flight already, even though the actual "getdata" message only goes out
5277 // later (within the same cs_main lock, though).
5278 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
5280 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
5284 // Track requests for our stuff
5285 GetMainSignals().Inventory(inv.hash);
5287 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
5288 Misbehaving(pfrom->GetId(), 50);
5289 return error("send buffer size() = %u", pfrom->nSendSize);
5293 if (!vToFetch.empty())
5294 pfrom->PushMessage("getdata", vToFetch);
5298 else if (strCommand == "getdata")
5302 if (vInv.size() > MAX_INV_SZ)
5304 Misbehaving(pfrom->GetId(), 20);
5305 return error("message getdata size() = %u", vInv.size());
5308 if (fDebug || (vInv.size() != 1))
5309 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
5311 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
5312 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
5314 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
5315 ProcessGetData(pfrom);
5319 else if (strCommand == "getblocks")
5321 CBlockLocator locator;
5323 vRecv >> locator >> hashStop;
5327 // Find the last block the caller has in the main chain
5328 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
5330 // Send the rest of the chain
5332 pindex = chainActive.Next(pindex);
5334 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
5335 for (; pindex; pindex = chainActive.Next(pindex))
5337 if (pindex->GetBlockHash() == hashStop)
5339 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5342 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5345 // When this block is requested, we'll send an inv that'll
5346 // trigger the peer to getblocks the next batch of inventory.
5347 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5348 pfrom->hashContinue = pindex->GetBlockHash();
5355 else if (strCommand == "getheaders")
5357 CBlockLocator locator;
5359 vRecv >> locator >> hashStop;
5363 if (IsInitialBlockDownload())
5366 CBlockIndex* pindex = NULL;
5367 if (locator.IsNull())
5369 // If locator is null, return the hashStop block
5370 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
5371 if (mi == mapBlockIndex.end())
5373 pindex = (*mi).second;
5377 // Find the last block the caller has in the main chain
5378 pindex = FindForkInGlobalIndex(chainActive, locator);
5380 pindex = chainActive.Next(pindex);
5383 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5384 vector<CBlock> vHeaders;
5385 int nLimit = MAX_HEADERS_RESULTS;
5386 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5387 for (; pindex; pindex = chainActive.Next(pindex))
5389 vHeaders.push_back(pindex->GetBlockHeader());
5390 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5393 pfrom->PushMessage("headers", vHeaders);
5397 else if (strCommand == "tx")
5399 vector<uint256> vWorkQueue;
5400 vector<uint256> vEraseQueue;
5404 CInv inv(MSG_TX, tx.GetHash());
5405 pfrom->AddInventoryKnown(inv);
5409 bool fMissingInputs = false;
5410 CValidationState state;
5412 pfrom->setAskFor.erase(inv.hash);
5413 mapAlreadyAskedFor.erase(inv);
5415 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5417 mempool.check(pcoinsTip);
5418 RelayTransaction(tx);
5419 vWorkQueue.push_back(inv.hash);
5421 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5422 pfrom->id, pfrom->cleanSubVer,
5423 tx.GetHash().ToString(),
5424 mempool.mapTx.size());
5426 // Recursively process any orphan transactions that depended on this one
5427 set<NodeId> setMisbehaving;
5428 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5430 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5431 if (itByPrev == mapOrphanTransactionsByPrev.end())
5433 for (set<uint256>::iterator mi = itByPrev->second.begin();
5434 mi != itByPrev->second.end();
5437 const uint256& orphanHash = *mi;
5438 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5439 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5440 bool fMissingInputs2 = false;
5441 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5442 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5443 // anyone relaying LegitTxX banned)
5444 CValidationState stateDummy;
5447 if (setMisbehaving.count(fromPeer))
5449 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5451 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5452 RelayTransaction(orphanTx);
5453 vWorkQueue.push_back(orphanHash);
5454 vEraseQueue.push_back(orphanHash);
5456 else if (!fMissingInputs2)
5459 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5461 // Punish peer that gave us an invalid orphan tx
5462 Misbehaving(fromPeer, nDos);
5463 setMisbehaving.insert(fromPeer);
5464 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5466 // Has inputs but not accepted to mempool
5467 // Probably non-standard or insufficient fee/priority
5468 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5469 vEraseQueue.push_back(orphanHash);
5470 assert(recentRejects);
5471 recentRejects->insert(orphanHash);
5473 mempool.check(pcoinsTip);
5477 BOOST_FOREACH(uint256 hash, vEraseQueue)
5478 EraseOrphanTx(hash);
5480 // TODO: currently, prohibit joinsplits from entering mapOrphans
5481 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5483 AddOrphanTx(tx, pfrom->GetId());
5485 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5486 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5487 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5489 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5491 assert(recentRejects);
5492 recentRejects->insert(tx.GetHash());
5494 if (pfrom->fWhitelisted) {
5495 // Always relay transactions received from whitelisted peers, even
5496 // if they were already in the mempool or rejected from it due
5497 // to policy, allowing the node to function as a gateway for
5498 // nodes hidden behind it.
5500 // Never relay transactions that we would assign a non-zero DoS
5501 // score for, as we expect peers to do the same with us in that
5504 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5505 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5506 RelayTransaction(tx);
5508 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5509 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5514 if (state.IsInvalid(nDoS))
5516 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5517 pfrom->id, pfrom->cleanSubVer,
5518 state.GetRejectReason());
5519 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5520 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5522 Misbehaving(pfrom->GetId(), nDoS);
5527 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5529 std::vector<CBlockHeader> headers;
5531 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5532 unsigned int nCount = ReadCompactSize(vRecv);
5533 if (nCount > MAX_HEADERS_RESULTS) {
5534 Misbehaving(pfrom->GetId(), 20);
5535 return error("headers message size = %u", nCount);
5537 headers.resize(nCount);
5538 for (unsigned int n = 0; n < nCount; n++) {
5539 vRecv >> headers[n];
5540 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5546 // Nothing interesting. Stop asking this peers for more headers.
5550 CBlockIndex *pindexLast = NULL;
5551 BOOST_FOREACH(const CBlockHeader& header, headers) {
5552 CValidationState state;
5553 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5554 Misbehaving(pfrom->GetId(), 20);
5555 return error("non-continuous headers sequence");
5557 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5559 if (state.IsInvalid(nDoS)) {
5561 Misbehaving(pfrom->GetId(), nDoS);
5562 return error("invalid header received");
5568 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5570 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5571 // Headers message had its maximum size; the peer may have more headers.
5572 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5573 // from there instead.
5574 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5575 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5581 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5586 CInv inv(MSG_BLOCK, block.GetHash());
5587 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5589 pfrom->AddInventoryKnown(inv);
5591 CValidationState state;
5592 // Process all blocks from whitelisted peers, even if not requested,
5593 // unless we're still syncing with the network.
5594 // Such an unrequested block may still be processed, subject to the
5595 // conditions in AcceptBlock().
5596 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5597 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
5599 if (state.IsInvalid(nDoS)) {
5600 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5601 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5604 Misbehaving(pfrom->GetId(), nDoS);
5611 // This asymmetric behavior for inbound and outbound connections was introduced
5612 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5613 // to users' AddrMan and later request them by sending getaddr messages.
5614 // Making nodes which are behind NAT and can only make outgoing connections ignore
5615 // the getaddr message mitigates the attack.
5616 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5618 // Only send one GetAddr response per connection to reduce resource waste
5619 // and discourage addr stamping of INV announcements.
5620 if (pfrom->fSentAddr) {
5621 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5624 pfrom->fSentAddr = true;
5626 pfrom->vAddrToSend.clear();
5627 vector<CAddress> vAddr = addrman.GetAddr();
5628 BOOST_FOREACH(const CAddress &addr, vAddr)
5629 pfrom->PushAddress(addr);
5633 else if (strCommand == "mempool")
5635 LOCK2(cs_main, pfrom->cs_filter);
5637 std::vector<uint256> vtxid;
5638 mempool.queryHashes(vtxid);
5640 BOOST_FOREACH(uint256& hash, vtxid) {
5641 CInv inv(MSG_TX, hash);
5642 if (pfrom->pfilter) {
5644 bool fInMemPool = mempool.lookup(hash, tx);
5645 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5646 if (!pfrom->pfilter->IsRelevantAndUpdate(tx)) continue;
5648 vInv.push_back(inv);
5649 if (vInv.size() == MAX_INV_SZ) {
5650 pfrom->PushMessage("inv", vInv);
5654 if (vInv.size() > 0)
5655 pfrom->PushMessage("inv", vInv);
5659 else if (strCommand == "ping")
5661 if (pfrom->nVersion > BIP0031_VERSION)
5665 // Echo the message back with the nonce. This allows for two useful features:
5667 // 1) A remote node can quickly check if the connection is operational
5668 // 2) Remote nodes can measure the latency of the network thread. If this node
5669 // is overloaded it won't respond to pings quickly and the remote node can
5670 // avoid sending us more work, like chain download requests.
5672 // The nonce stops the remote getting confused between different pings: without
5673 // it, if the remote node sends a ping once per second and this node takes 5
5674 // seconds to respond to each, the 5th ping the remote sends would appear to
5675 // return very quickly.
5676 pfrom->PushMessage("pong", nonce);
5681 else if (strCommand == "pong")
5683 int64_t pingUsecEnd = nTimeReceived;
5685 size_t nAvail = vRecv.in_avail();
5686 bool bPingFinished = false;
5687 std::string sProblem;
5689 if (nAvail >= sizeof(nonce)) {
5692 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5693 if (pfrom->nPingNonceSent != 0) {
5694 if (nonce == pfrom->nPingNonceSent) {
5695 // Matching pong received, this ping is no longer outstanding
5696 bPingFinished = true;
5697 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5698 if (pingUsecTime > 0) {
5699 // Successful ping time measurement, replace previous
5700 pfrom->nPingUsecTime = pingUsecTime;
5701 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5703 // This should never happen
5704 sProblem = "Timing mishap";
5707 // Nonce mismatches are normal when pings are overlapping
5708 sProblem = "Nonce mismatch";
5710 // This is most likely a bug in another implementation somewhere; cancel this ping
5711 bPingFinished = true;
5712 sProblem = "Nonce zero";
5716 sProblem = "Unsolicited pong without ping";
5719 // This is most likely a bug in another implementation somewhere; cancel this ping
5720 bPingFinished = true;
5721 sProblem = "Short payload";
5724 if (!(sProblem.empty())) {
5725 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5729 pfrom->nPingNonceSent,
5733 if (bPingFinished) {
5734 pfrom->nPingNonceSent = 0;
5739 else if (fAlerts && strCommand == "alert")
5744 uint256 alertHash = alert.GetHash();
5745 if (pfrom->setKnown.count(alertHash) == 0)
5747 if (alert.ProcessAlert(Params().AlertKey()))
5750 pfrom->setKnown.insert(alertHash);
5753 BOOST_FOREACH(CNode* pnode, vNodes)
5754 alert.RelayTo(pnode);
5758 // Small DoS penalty so peers that send us lots of
5759 // duplicate/expired/invalid-signature/whatever alerts
5760 // eventually get banned.
5761 // This isn't a Misbehaving(100) (immediate ban) because the
5762 // peer might be an older or different implementation with
5763 // a different signature key, etc.
5764 Misbehaving(pfrom->GetId(), 10);
5770 else if (!(nLocalServices & NODE_BLOOM) &&
5771 (strCommand == "filterload" ||
5772 strCommand == "filteradd"))
5774 if (pfrom->nVersion >= NO_BLOOM_VERSION) {
5775 Misbehaving(pfrom->GetId(), 100);
5777 } else if (GetBoolArg("-enforcenodebloom", false)) {
5778 pfrom->fDisconnect = true;
5784 else if (strCommand == "filterload")
5786 CBloomFilter filter;
5789 if (!filter.IsWithinSizeConstraints())
5790 // There is no excuse for sending a too-large filter
5791 Misbehaving(pfrom->GetId(), 100);
5794 LOCK(pfrom->cs_filter);
5795 delete pfrom->pfilter;
5796 pfrom->pfilter = new CBloomFilter(filter);
5797 pfrom->pfilter->UpdateEmptyFull();
5799 pfrom->fRelayTxes = true;
5803 else if (strCommand == "filteradd")
5805 vector<unsigned char> vData;
5808 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5809 // and thus, the maximum size any matched object can have) in a filteradd message
5810 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5812 Misbehaving(pfrom->GetId(), 100);
5814 LOCK(pfrom->cs_filter);
5816 pfrom->pfilter->insert(vData);
5818 Misbehaving(pfrom->GetId(), 100);
5823 else if (strCommand == "filterclear")
5825 LOCK(pfrom->cs_filter);
5826 if (nLocalServices & NODE_BLOOM) {
5827 delete pfrom->pfilter;
5828 pfrom->pfilter = new CBloomFilter();
5830 pfrom->fRelayTxes = true;
5834 else if (strCommand == "reject")
5838 string strMsg; unsigned char ccode; string strReason;
5839 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5842 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5844 if (strMsg == "block" || strMsg == "tx")
5848 ss << ": hash " << hash.ToString();
5850 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5851 } catch (const std::ios_base::failure&) {
5852 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5853 LogPrint("net", "Unparseable reject message received\n");
5858 else if (strCommand == "notfound") {
5859 // We do not care about the NOTFOUND message, but logging an Unknown Command
5860 // message would be undesirable as we transmit it ourselves.
5864 // Ignore unknown commands for extensibility
5865 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5873 // requires LOCK(cs_vRecvMsg)
5874 bool ProcessMessages(CNode* pfrom)
5877 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5881 // (4) message start
5889 if (!pfrom->vRecvGetData.empty())
5890 ProcessGetData(pfrom);
5892 // this maintains the order of responses
5893 if (!pfrom->vRecvGetData.empty()) return fOk;
5895 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5896 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5897 // Don't bother if send buffer is too full to respond anyway
5898 if (pfrom->nSendSize >= SendBufferSize())
5902 CNetMessage& msg = *it;
5905 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5906 // msg.hdr.nMessageSize, msg.vRecv.size(),
5907 // msg.complete() ? "Y" : "N");
5909 // end, if an incomplete message is found
5910 if (!msg.complete())
5913 // at this point, any failure means we can delete the current message
5916 // Scan for message start
5917 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5918 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5924 CMessageHeader& hdr = msg.hdr;
5925 if (!hdr.IsValid(Params().MessageStart()))
5927 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5930 string strCommand = hdr.GetCommand();
5933 unsigned int nMessageSize = hdr.nMessageSize;
5936 CDataStream& vRecv = msg.vRecv;
5937 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5938 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5939 if (nChecksum != hdr.nChecksum)
5941 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5942 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5950 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5951 boost::this_thread::interruption_point();
5953 catch (const std::ios_base::failure& e)
5955 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5956 if (strstr(e.what(), "end of data"))
5958 // Allow exceptions from under-length message on vRecv
5959 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());
5961 else if (strstr(e.what(), "size too large"))
5963 // Allow exceptions from over-long size
5964 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5968 PrintExceptionContinue(&e, "ProcessMessages()");
5971 catch (const boost::thread_interrupted&) {
5974 catch (const std::exception& e) {
5975 PrintExceptionContinue(&e, "ProcessMessages()");
5977 PrintExceptionContinue(NULL, "ProcessMessages()");
5981 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5986 // In case the connection got shut down, its receive buffer was wiped
5987 if (!pfrom->fDisconnect)
5988 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5994 bool SendMessages(CNode* pto, bool fSendTrickle)
5996 const Consensus::Params& consensusParams = Params().GetConsensus();
5998 // Don't send anything until we get its version message
5999 if (pto->nVersion == 0)
6005 bool pingSend = false;
6006 if (pto->fPingQueued) {
6007 // RPC ping request by user
6010 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
6011 // Ping automatically sent as a latency probe & keepalive.
6016 while (nonce == 0) {
6017 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
6019 pto->fPingQueued = false;
6020 pto->nPingUsecStart = GetTimeMicros();
6021 if (pto->nVersion > BIP0031_VERSION) {
6022 pto->nPingNonceSent = nonce;
6023 pto->PushMessage("ping", nonce);
6025 // Peer is too old to support ping command with nonce, pong will never arrive.
6026 pto->nPingNonceSent = 0;
6027 pto->PushMessage("ping");
6031 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
6035 // Address refresh broadcast
6036 static int64_t nLastRebroadcast;
6037 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
6040 BOOST_FOREACH(CNode* pnode, vNodes)
6042 // Periodically clear addrKnown to allow refresh broadcasts
6043 if (nLastRebroadcast)
6044 pnode->addrKnown.reset();
6046 // Rebroadcast our address
6047 AdvertizeLocal(pnode);
6049 if (!vNodes.empty())
6050 nLastRebroadcast = GetTime();
6058 vector<CAddress> vAddr;
6059 vAddr.reserve(pto->vAddrToSend.size());
6060 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
6062 if (!pto->addrKnown.contains(addr.GetKey()))
6064 pto->addrKnown.insert(addr.GetKey());
6065 vAddr.push_back(addr);
6066 // receiver rejects addr messages larger than 1000
6067 if (vAddr.size() >= 1000)
6069 pto->PushMessage("addr", vAddr);
6074 pto->vAddrToSend.clear();
6076 pto->PushMessage("addr", vAddr);
6079 CNodeState &state = *State(pto->GetId());
6080 if (state.fShouldBan) {
6081 if (pto->fWhitelisted)
6082 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
6084 pto->fDisconnect = true;
6085 if (pto->addr.IsLocal())
6086 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
6089 CNode::Ban(pto->addr);
6092 state.fShouldBan = false;
6095 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
6096 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
6097 state.rejects.clear();
6100 if (pindexBestHeader == NULL)
6101 pindexBestHeader = chainActive.Tip();
6102 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.
6103 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
6104 // Only actively request headers from a single peer, unless we're close to today.
6105 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
6106 state.fSyncStarted = true;
6108 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
6109 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
6110 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
6114 // Resend wallet transactions that haven't gotten in a block yet
6115 // Except during reindex, importing and IBD, when old wallet
6116 // transactions become unconfirmed and spams other nodes.
6117 if (!fReindex && !fImporting && !IsInitialBlockDownload())
6119 GetMainSignals().Broadcast(nTimeBestReceived);
6123 // Message: inventory
6126 vector<CInv> vInvWait;
6128 LOCK(pto->cs_inventory);
6129 vInv.reserve(pto->vInventoryToSend.size());
6130 vInvWait.reserve(pto->vInventoryToSend.size());
6131 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
6133 if (pto->setInventoryKnown.count(inv))
6136 // trickle out tx inv to protect privacy
6137 if (inv.type == MSG_TX && !fSendTrickle)
6139 // 1/4 of tx invs blast to all immediately
6140 static uint256 hashSalt;
6141 if (hashSalt.IsNull())
6142 hashSalt = GetRandHash();
6143 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
6144 hashRand = Hash(BEGIN(hashRand), END(hashRand));
6145 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
6149 vInvWait.push_back(inv);
6154 // returns true if wasn't already contained in the set
6155 if (pto->setInventoryKnown.insert(inv).second)
6157 vInv.push_back(inv);
6158 if (vInv.size() >= 1000)
6160 pto->PushMessage("inv", vInv);
6165 pto->vInventoryToSend = vInvWait;
6168 pto->PushMessage("inv", vInv);
6170 // Detect whether we're stalling
6171 int64_t nNow = GetTimeMicros();
6172 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
6173 // Stalling only triggers when the block download window cannot move. During normal steady state,
6174 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
6175 // should only happen during initial block download.
6176 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
6177 pto->fDisconnect = true;
6179 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
6180 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
6181 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
6182 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
6183 // to unreasonably increase our timeout.
6184 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
6185 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
6186 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
6187 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
6188 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
6189 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
6190 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
6191 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
6192 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
6193 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
6194 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
6196 if (queuedBlock.nTimeDisconnect < nNow) {
6197 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
6198 pto->fDisconnect = true;
6203 // Message: getdata (blocks)
6205 vector<CInv> vGetData;
6206 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
6207 vector<CBlockIndex*> vToDownload;
6208 NodeId staller = -1;
6209 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
6210 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
6211 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
6212 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
6213 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
6214 pindex->nHeight, pto->id);
6216 if (state.nBlocksInFlight == 0 && staller != -1) {
6217 if (State(staller)->nStallingSince == 0) {
6218 State(staller)->nStallingSince = nNow;
6219 LogPrint("net", "Stall started peer=%d\n", staller);
6225 // Message: getdata (non-blocks)
6227 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
6229 const CInv& inv = (*pto->mapAskFor.begin()).second;
6230 if (!AlreadyHave(inv))
6233 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
6234 vGetData.push_back(inv);
6235 if (vGetData.size() >= 1000)
6237 pto->PushMessage("getdata", vGetData);
6241 //If we're not going to ask, don't expect a response.
6242 pto->setAskFor.erase(inv.hash);
6244 pto->mapAskFor.erase(pto->mapAskFor.begin());
6246 if (!vGetData.empty())
6247 pto->PushMessage("getdata", vGetData);
6253 std::string CBlockFileInfo::ToString() const {
6254 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));
6259 static class CMainCleanup
6265 BlockMap::iterator it1 = mapBlockIndex.begin();
6266 for (; it1 != mapBlockIndex.end(); it1++)
6267 delete (*it1).second;
6268 mapBlockIndex.clear();
6270 // orphan transactions
6271 mapOrphanTransactions.clear();
6272 mapOrphanTransactionsByPrev.clear();
6274 } instance_of_cmaincleanup;
6277 // Set default values of new CMutableTransaction based on consensus rules at given height.
6278 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
6280 CMutableTransaction mtx;
6282 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
6283 if (isOverwintered) {
6284 mtx.fOverwintered = true;
6285 mtx.nExpiryHeight = nHeight + expiryDelta;
6287 if (NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_SAPLING)) {
6288 mtx.nVersionGroupId = SAPLING_VERSION_GROUP_ID;
6289 mtx.nVersion = SAPLING_TX_VERSION;
6291 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
6292 mtx.nVersion = OVERWINTER_TX_VERSION;
6293 mtx.nExpiryHeight = std::min(
6295 static_cast<uint32_t>(consensusParams.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight - 1));