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"
36 #include <boost/algorithm/string/replace.hpp>
37 #include <boost/filesystem.hpp>
38 #include <boost/filesystem/fstream.hpp>
39 #include <boost/math/distributions/poisson.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/static_assert.hpp>
46 # error "Zcash cannot be compiled without assertions."
53 CCriticalSection cs_main;
55 BlockMap mapBlockIndex;
57 CBlockIndex *pindexBestHeader = NULL;
58 int64_t nTimeBestReceived = 0;
59 CWaitableCriticalSection csBestBlock;
60 CConditionVariable cvBlockChange;
61 int nScriptCheckThreads = 0;
62 bool fExperimentalMode = false;
63 bool fImporting = false;
64 bool fReindex = false;
65 bool fTxIndex = false;
66 bool fHavePruned = false;
67 bool fPruneMode = false;
68 bool fIsBareMultisigStd = true;
69 bool fCheckBlockIndex = false;
70 bool fCheckpointsEnabled = true;
71 bool fCoinbaseEnforcedProtectionEnabled = true;
72 size_t nCoinCacheUsage = 5000 * 300;
73 uint64_t nPruneTarget = 0;
74 bool fAlerts = DEFAULT_ALERTS;
76 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
77 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
79 CTxMemPool mempool(::minRelayTxFee);
85 map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);;
86 map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_main);;
87 void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
90 * Returns true if there are nRequired or more blocks of minVersion or above
91 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
93 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
94 static void CheckBlockIndex();
96 /** Constant stuff for coinbase transactions we create: */
97 CScript COINBASE_FLAGS;
99 const string strMessageMagic = "Zcash Signed Message:\n";
104 struct CBlockIndexWorkComparator
106 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
107 // First sort by most total work, ...
108 if (pa->nChainWork > pb->nChainWork) return false;
109 if (pa->nChainWork < pb->nChainWork) return true;
111 // ... then by earliest time received, ...
112 if (pa->nSequenceId < pb->nSequenceId) return false;
113 if (pa->nSequenceId > pb->nSequenceId) return true;
115 // Use pointer address as tie breaker (should only happen with blocks
116 // loaded from disk, as those all have id 0).
117 if (pa < pb) return false;
118 if (pa > pb) return true;
125 CBlockIndex *pindexBestInvalid;
128 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
129 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
130 * missing the data for the block.
132 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
133 /** Number of nodes with fSyncStarted. */
134 int nSyncStarted = 0;
135 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
136 * Pruned nodes may have entries where B is missing data.
138 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
140 CCriticalSection cs_LastBlockFile;
141 std::vector<CBlockFileInfo> vinfoBlockFile;
142 int nLastBlockFile = 0;
143 /** Global flag to indicate we should check to see if there are
144 * block/undo files that should be deleted. Set on startup
145 * or if we allocate more file space when we're in prune mode
147 bool fCheckForPruning = false;
150 * Every received block is assigned a unique and increasing identifier, so we
151 * know which one to give priority in case of a fork.
153 CCriticalSection cs_nBlockSequenceId;
154 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
155 uint32_t nBlockSequenceId = 1;
158 * Sources of received blocks, saved to be able to send them reject
159 * messages or ban them when processing happens afterwards. Protected by
162 map<uint256, NodeId> mapBlockSource;
165 * Filter for transactions that were recently rejected by
166 * AcceptToMemoryPool. These are not rerequested until the chain tip
167 * changes, at which point the entire filter is reset. Protected by
170 * Without this filter we'd be re-requesting txs from each of our peers,
171 * increasing bandwidth consumption considerably. For instance, with 100
172 * peers, half of which relay a tx we don't accept, that might be a 50x
173 * bandwidth increase. A flooding attacker attempting to roll-over the
174 * filter using minimum-sized, 60byte, transactions might manage to send
175 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
176 * two minute window to send invs to us.
178 * Decreasing the false positive rate is fairly cheap, so we pick one in a
179 * million to make it highly unlikely for users to have issues with this
184 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
185 uint256 hashRecentRejectsChainTip;
187 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
190 CBlockIndex *pindex; //! Optional.
191 int64_t nTime; //! Time of "getdata" request in microseconds.
192 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
193 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
195 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
197 /** Number of blocks in flight with validated headers. */
198 int nQueuedValidatedHeaders = 0;
200 /** Number of preferable block download peers. */
201 int nPreferredDownload = 0;
203 /** Dirty block index entries. */
204 set<CBlockIndex*> setDirtyBlockIndex;
206 /** Dirty block file entries. */
207 set<int> setDirtyFileInfo;
210 //////////////////////////////////////////////////////////////////////////////
212 // Registration of network node signals.
217 struct CBlockReject {
218 unsigned char chRejectCode;
219 string strRejectReason;
224 * Maintain validation-specific state about nodes, protected by cs_main, instead
225 * by CNode's own locks. This simplifies asynchronous operation, where
226 * processing of incoming data is done after the ProcessMessage call returns,
227 * and we're no longer holding the node's locks.
230 //! The peer's address
232 //! Whether we have a fully established connection.
233 bool fCurrentlyConnected;
234 //! Accumulated misbehaviour score for this peer.
236 //! Whether this peer should be disconnected and banned (unless whitelisted).
238 //! String name of this peer (debugging/logging purposes).
240 //! List of asynchronously-determined block rejections to notify this peer about.
241 std::vector<CBlockReject> rejects;
242 //! The best known block we know this peer has announced.
243 CBlockIndex *pindexBestKnownBlock;
244 //! The hash of the last unknown block this peer has announced.
245 uint256 hashLastUnknownBlock;
246 //! The last full block we both have.
247 CBlockIndex *pindexLastCommonBlock;
248 //! Whether we've started headers synchronization with this peer.
250 //! Since when we're stalling block download progress (in microseconds), or 0.
251 int64_t nStallingSince;
252 list<QueuedBlock> vBlocksInFlight;
254 int nBlocksInFlightValidHeaders;
255 //! Whether we consider this a preferred download peer.
256 bool fPreferredDownload;
259 fCurrentlyConnected = false;
262 pindexBestKnownBlock = NULL;
263 hashLastUnknownBlock.SetNull();
264 pindexLastCommonBlock = NULL;
265 fSyncStarted = false;
268 nBlocksInFlightValidHeaders = 0;
269 fPreferredDownload = false;
273 /** Map maintaining per-node state. Requires cs_main. */
274 map<NodeId, CNodeState> mapNodeState;
277 CNodeState *State(NodeId pnode) {
278 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
279 if (it == mapNodeState.end())
287 return chainActive.Height();
290 void UpdatePreferredDownload(CNode* node, CNodeState* state)
292 nPreferredDownload -= state->fPreferredDownload;
294 // Whether this node should be marked as a preferred download node.
295 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
297 nPreferredDownload += state->fPreferredDownload;
300 // Returns time at which to timeout block request (nTime in microseconds)
301 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
303 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
306 void InitializeNode(NodeId nodeid, const CNode *pnode) {
308 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
309 state.name = pnode->addrName;
310 state.address = pnode->addr;
313 void FinalizeNode(NodeId nodeid) {
315 CNodeState *state = State(nodeid);
317 if (state->fSyncStarted)
320 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
321 AddressCurrentlyConnected(state->address);
324 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
325 mapBlocksInFlight.erase(entry.hash);
326 EraseOrphansFor(nodeid);
327 nPreferredDownload -= state->fPreferredDownload;
329 mapNodeState.erase(nodeid);
333 // Returns a bool indicating whether we requested this block.
334 bool MarkBlockAsReceived(const uint256& hash) {
335 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
336 if (itInFlight != mapBlocksInFlight.end()) {
337 CNodeState *state = State(itInFlight->second.first);
338 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
339 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
340 state->vBlocksInFlight.erase(itInFlight->second.second);
341 state->nBlocksInFlight--;
342 state->nStallingSince = 0;
343 mapBlocksInFlight.erase(itInFlight);
350 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
351 CNodeState *state = State(nodeid);
352 assert(state != NULL);
354 // Make sure it's not listed somewhere already.
355 MarkBlockAsReceived(hash);
357 int64_t nNow = GetTimeMicros();
358 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
359 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
360 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
361 state->nBlocksInFlight++;
362 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
363 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
366 /** Check whether the last unknown block a peer advertized is not yet known. */
367 void ProcessBlockAvailability(NodeId nodeid) {
368 CNodeState *state = State(nodeid);
369 assert(state != NULL);
371 if (!state->hashLastUnknownBlock.IsNull()) {
372 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
373 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
374 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
375 state->pindexBestKnownBlock = itOld->second;
376 state->hashLastUnknownBlock.SetNull();
381 /** Update tracking information about which blocks a peer is assumed to have. */
382 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
383 CNodeState *state = State(nodeid);
384 assert(state != NULL);
386 ProcessBlockAvailability(nodeid);
388 BlockMap::iterator it = mapBlockIndex.find(hash);
389 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
390 // An actually better block was announced.
391 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
392 state->pindexBestKnownBlock = it->second;
394 // An unknown block was announced; just assume that the latest one is the best one.
395 state->hashLastUnknownBlock = hash;
399 /** Find the last common ancestor two blocks have.
400 * Both pa and pb must be non-NULL. */
401 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
402 if (pa->nHeight > pb->nHeight) {
403 pa = pa->GetAncestor(pb->nHeight);
404 } else if (pb->nHeight > pa->nHeight) {
405 pb = pb->GetAncestor(pa->nHeight);
408 while (pa != pb && pa && pb) {
413 // Eventually all chain branches meet at the genesis block.
418 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
419 * at most count entries. */
420 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
424 vBlocks.reserve(vBlocks.size() + count);
425 CNodeState *state = State(nodeid);
426 assert(state != NULL);
428 // Make sure pindexBestKnownBlock is up to date, we'll need it.
429 ProcessBlockAvailability(nodeid);
431 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
432 // This peer has nothing interesting.
436 if (state->pindexLastCommonBlock == NULL) {
437 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
438 // Guessing wrong in either direction is not a problem.
439 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
442 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
443 // of its current tip anymore. Go back enough to fix that.
444 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
445 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
448 std::vector<CBlockIndex*> vToFetch;
449 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
450 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
451 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
452 // download that next block if the window were 1 larger.
453 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
454 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
455 NodeId waitingfor = -1;
456 while (pindexWalk->nHeight < nMaxHeight) {
457 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
458 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
459 // as iterating over ~100 CBlockIndex* entries anyway.
460 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
461 vToFetch.resize(nToFetch);
462 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
463 vToFetch[nToFetch - 1] = pindexWalk;
464 for (unsigned int i = nToFetch - 1; i > 0; i--) {
465 vToFetch[i - 1] = vToFetch[i]->pprev;
468 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
469 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
470 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
471 // already part of our chain (and therefore don't need it even if pruned).
472 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
473 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
474 // We consider the chain that this peer is on invalid.
477 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
478 if (pindex->nChainTx)
479 state->pindexLastCommonBlock = pindex;
480 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
481 // The block is not already downloaded, and not yet in flight.
482 if (pindex->nHeight > nWindowEnd) {
483 // We reached the end of the window.
484 if (vBlocks.size() == 0 && waitingfor != nodeid) {
485 // We aren't able to fetch anything, but we would be if the download window was one larger.
486 nodeStaller = waitingfor;
490 vBlocks.push_back(pindex);
491 if (vBlocks.size() == count) {
494 } else if (waitingfor == -1) {
495 // This is the first already-in-flight block.
496 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
504 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
506 CNodeState *state = State(nodeid);
509 stats.nMisbehavior = state->nMisbehavior;
510 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
511 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
512 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
514 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
519 void RegisterNodeSignals(CNodeSignals& nodeSignals)
521 nodeSignals.GetHeight.connect(&GetHeight);
522 nodeSignals.ProcessMessages.connect(&ProcessMessages);
523 nodeSignals.SendMessages.connect(&SendMessages);
524 nodeSignals.InitializeNode.connect(&InitializeNode);
525 nodeSignals.FinalizeNode.connect(&FinalizeNode);
528 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
530 nodeSignals.GetHeight.disconnect(&GetHeight);
531 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
532 nodeSignals.SendMessages.disconnect(&SendMessages);
533 nodeSignals.InitializeNode.disconnect(&InitializeNode);
534 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
537 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
539 // Find the first block the caller has in the main chain
540 BOOST_FOREACH(const uint256& hash, locator.vHave) {
541 BlockMap::iterator mi = mapBlockIndex.find(hash);
542 if (mi != mapBlockIndex.end())
544 CBlockIndex* pindex = (*mi).second;
545 if (chain.Contains(pindex))
547 if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
552 return chain.Genesis();
555 CCoinsViewCache *pcoinsTip = NULL;
556 CBlockTreeDB *pblocktree = NULL;
558 //////////////////////////////////////////////////////////////////////////////
560 // mapOrphanTransactions
563 bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
565 uint256 hash = tx.GetHash();
566 if (mapOrphanTransactions.count(hash))
569 // Ignore big transactions, to avoid a
570 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
571 // large transaction with a missing parent then we assume
572 // it will rebroadcast it later, after the parent transaction(s)
573 // have been mined or received.
574 // 10,000 orphans, each of which is at most 5,000 bytes big is
575 // at most 500 megabytes of orphans:
576 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
579 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
583 mapOrphanTransactions[hash].tx = tx;
584 mapOrphanTransactions[hash].fromPeer = peer;
585 BOOST_FOREACH(const CTxIn& txin, tx.vin)
586 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
588 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
589 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
593 void static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
595 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
596 if (it == mapOrphanTransactions.end())
598 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
600 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
601 if (itPrev == mapOrphanTransactionsByPrev.end())
603 itPrev->second.erase(hash);
604 if (itPrev->second.empty())
605 mapOrphanTransactionsByPrev.erase(itPrev);
607 mapOrphanTransactions.erase(it);
610 void EraseOrphansFor(NodeId peer)
613 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
614 while (iter != mapOrphanTransactions.end())
616 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
617 if (maybeErase->second.fromPeer == peer)
619 EraseOrphanTx(maybeErase->second.tx.GetHash());
623 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
627 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
629 unsigned int nEvicted = 0;
630 while (mapOrphanTransactions.size() > nMaxOrphans)
632 // Evict a random orphan:
633 uint256 randomhash = GetRandHash();
634 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
635 if (it == mapOrphanTransactions.end())
636 it = mapOrphanTransactions.begin();
637 EraseOrphanTx(it->first);
644 bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight)
646 bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
649 // Overwinter standard rules apply
650 if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) {
651 reason = "overwinter-version";
655 // Sprout standard rules apply
656 if (tx.nVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION) {
662 BOOST_FOREACH(const CTxIn& txin, tx.vin)
664 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
665 // keys. (remember the 520 byte limit on redeemScript size) That works
666 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
667 // bytes of scriptSig, which we round off to 1650 bytes for some minor
668 // future-proofing. That's also enough to spend a 20-of-20
669 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
670 // considered standard)
671 if (txin.scriptSig.size() > 1650) {
672 reason = "scriptsig-size";
675 if (!txin.scriptSig.IsPushOnly()) {
676 reason = "scriptsig-not-pushonly";
681 unsigned int nDataOut = 0;
682 txnouttype whichType;
683 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
684 if (!::IsStandard(txout.scriptPubKey, whichType)) {
685 reason = "scriptpubkey";
689 if (whichType == TX_NULL_DATA)
691 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
692 reason = "bare-multisig";
694 } else if (txout.IsDust(::minRelayTxFee)) {
700 // only one OP_RETURN txout is permitted
702 reason = "multi-op-return";
709 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
711 if (tx.nLockTime == 0)
713 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
715 BOOST_FOREACH(const CTxIn& txin, tx.vin)
721 bool CheckFinalTx(const CTransaction &tx, int flags)
723 AssertLockHeld(cs_main);
725 // By convention a negative value for flags indicates that the
726 // current network-enforced consensus rules should be used. In
727 // a future soft-fork scenario that would mean checking which
728 // rules would be enforced for the next block and setting the
729 // appropriate flags. At the present time no soft-forks are
730 // scheduled, so no flags are set.
731 flags = std::max(flags, 0);
733 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
734 // nLockTime because when IsFinalTx() is called within
735 // CBlock::AcceptBlock(), the height of the block *being*
736 // evaluated is what is used. Thus if we want to know if a
737 // transaction can be part of the *next* block, we need to call
738 // IsFinalTx() with one more than chainActive.Height().
739 const int nBlockHeight = chainActive.Height() + 1;
741 // Timestamps on the other hand don't get any special treatment,
742 // because we can't know what timestamp the next block will have,
743 // and there aren't timestamp applications where it matters.
744 // However this changes once median past time-locks are enforced:
745 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
746 ? chainActive.Tip()->GetMedianTimePast()
749 return IsFinalTx(tx, nBlockHeight, nBlockTime);
753 * Check transaction inputs to mitigate two
754 * potential denial-of-service attacks:
756 * 1. scriptSigs with extra data stuffed into them,
757 * not consumed by scriptPubKey (or P2SH script)
758 * 2. P2SH scripts with a crazy number of expensive
759 * CHECKSIG/CHECKMULTISIG operations
761 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
764 return true; // Coinbases don't use vin normally
766 for (unsigned int i = 0; i < tx.vin.size(); i++)
768 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
770 vector<vector<unsigned char> > vSolutions;
771 txnouttype whichType;
772 // get the scriptPubKey corresponding to this input:
773 const CScript& prevScript = prev.scriptPubKey;
774 if (!Solver(prevScript, whichType, vSolutions))
776 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
777 if (nArgsExpected < 0)
780 // Transactions with extra stuff in their scriptSigs are
781 // non-standard. Note that this EvalScript() call will
782 // be quick, because if there are any operations
783 // beside "push data" in the scriptSig
784 // IsStandardTx() will have already returned false
785 // and this method isn't called.
786 vector<vector<unsigned char> > stack;
787 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), SIGVERSION_BASE))
790 if (whichType == TX_SCRIPTHASH)
794 CScript subscript(stack.back().begin(), stack.back().end());
795 vector<vector<unsigned char> > vSolutions2;
796 txnouttype whichType2;
797 if (Solver(subscript, whichType2, vSolutions2))
799 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
802 nArgsExpected += tmpExpected;
806 // Any other Script with less than 15 sigops OK:
807 unsigned int sigops = subscript.GetSigOpCount(true);
808 // ... extra data left on the stack after execution is OK, too:
809 return (sigops <= MAX_P2SH_SIGOPS);
813 if (stack.size() != (unsigned int)nArgsExpected)
820 unsigned int GetLegacySigOpCount(const CTransaction& tx)
822 unsigned int nSigOps = 0;
823 BOOST_FOREACH(const CTxIn& txin, tx.vin)
825 nSigOps += txin.scriptSig.GetSigOpCount(false);
827 BOOST_FOREACH(const CTxOut& txout, tx.vout)
829 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
834 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
839 unsigned int nSigOps = 0;
840 for (unsigned int i = 0; i < tx.vin.size(); i++)
842 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
843 if (prevout.scriptPubKey.IsPayToScriptHash())
844 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
850 * Check a transaction contextually against a set of consensus rules valid at a given block height.
853 * 1. AcceptToMemoryPool calls CheckTransaction and this function.
854 * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction)
855 * and ContextualCheckBlock (which calls this function).
857 bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const int nHeight, const int dosLevel)
859 bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER);
860 bool isSprout = !isOverwinter;
862 // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond
863 if (isSprout && tx.fOverwintered) {
864 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter is not active yet"),
865 REJECT_INVALID, "tx-overwinter-not-active");
868 // If Overwinter rules apply:
870 // Reject transactions with valid version but missing overwinter flag
871 if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) {
872 return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"),
873 REJECT_INVALID, "tx-overwinter-flag-not-set");
876 // Reject transactions with invalid version
877 if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) {
878 return state.DoS(100, error("CheckTransaction(): overwinter version too high"),
879 REJECT_INVALID, "bad-tx-overwinter-version-too-high");
882 // Reject transactions intended for Sprout
883 if (!tx.fOverwintered) {
884 return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"),
885 REJECT_INVALID, "tx-overwinter-active");
893 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
894 libzcash::ProofVerifier& verifier)
896 // Don't count coinbase transactions because mining skews the count
897 if (!tx.IsCoinBase()) {
898 transactionsValidated.increment();
901 if (!CheckTransactionWithoutProofVerification(tx, state)) {
904 // Ensure that zk-SNARKs verify
905 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
906 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
907 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
908 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
915 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
917 // Basic checks that don't depend on any context
921 * 1. The consensus rule below was:
922 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
923 * which checked if tx.nVersion fell within the range:
924 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
925 * 2. The parser allowed tx.nVersion to be negative
928 * 1. The consensus rule checks to see if tx.Version falls within the range:
929 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
930 * 2. The previous consensus rule checked for negative values within the range:
931 * INT32_MIN <= tx.nVersion < 0
932 * This is unnecessary for Overwinter transactions since the parser now
933 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
934 * and when Overwinter is not active ContextualCheckTransaction rejects
935 * transactions with fOverwintered set. When fOverwintered is set,
936 * this function and ContextualCheckTransaction will together check to
937 * ensure tx.nVersion avoids the following ranges:
938 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
939 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
941 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
942 return state.DoS(100, error("CheckTransaction(): version too low"),
943 REJECT_INVALID, "bad-txns-version-too-low");
945 else if (tx.fOverwintered) {
946 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
947 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
948 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
950 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
951 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
952 REJECT_INVALID, "bad-tx-version-group-id");
954 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
955 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
956 REJECT_INVALID, "bad-tx-expiry-height-too-high");
960 // Transactions can contain empty `vin` and `vout` so long as
961 // `vjoinsplit` is non-empty.
962 if (tx.vin.empty() && tx.vjoinsplit.empty())
963 return state.DoS(10, error("CheckTransaction(): vin empty"),
964 REJECT_INVALID, "bad-txns-vin-empty");
965 if (tx.vout.empty() && tx.vjoinsplit.empty())
966 return state.DoS(10, error("CheckTransaction(): vout empty"),
967 REJECT_INVALID, "bad-txns-vout-empty");
970 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
971 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
972 return state.DoS(100, error("CheckTransaction(): size limits failed"),
973 REJECT_INVALID, "bad-txns-oversize");
975 // Check for negative or overflow output values
976 CAmount nValueOut = 0;
977 BOOST_FOREACH(const CTxOut& txout, tx.vout)
979 if (txout.nValue < 0)
980 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
981 REJECT_INVALID, "bad-txns-vout-negative");
982 if (txout.nValue > MAX_MONEY)
983 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
984 REJECT_INVALID, "bad-txns-vout-toolarge");
985 nValueOut += txout.nValue;
986 if (!MoneyRange(nValueOut))
987 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
988 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
991 // Ensure that joinsplit values are well-formed
992 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
994 if (joinsplit.vpub_old < 0) {
995 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
996 REJECT_INVALID, "bad-txns-vpub_old-negative");
999 if (joinsplit.vpub_new < 0) {
1000 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
1001 REJECT_INVALID, "bad-txns-vpub_new-negative");
1004 if (joinsplit.vpub_old > MAX_MONEY) {
1005 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
1006 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
1009 if (joinsplit.vpub_new > MAX_MONEY) {
1010 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
1011 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
1014 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1015 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
1016 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1019 nValueOut += joinsplit.vpub_old;
1020 if (!MoneyRange(nValueOut)) {
1021 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1022 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1026 // Ensure input values do not exceed MAX_MONEY
1027 // We have not resolved the txin values at this stage,
1028 // but we do know what the joinsplits claim to add
1029 // to the value pool.
1031 CAmount nValueIn = 0;
1032 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1034 nValueIn += it->vpub_new;
1036 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1037 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1038 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1044 // Check for duplicate inputs
1045 set<COutPoint> vInOutPoints;
1046 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1048 if (vInOutPoints.count(txin.prevout))
1049 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1050 REJECT_INVALID, "bad-txns-inputs-duplicate");
1051 vInOutPoints.insert(txin.prevout);
1054 // Check for duplicate joinsplit nullifiers in this transaction
1055 set<uint256> vJoinSplitNullifiers;
1056 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1058 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1060 if (vJoinSplitNullifiers.count(nf))
1061 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1062 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1064 vJoinSplitNullifiers.insert(nf);
1068 if (tx.IsCoinBase())
1070 // There should be no joinsplits in a coinbase transaction
1071 if (tx.vjoinsplit.size() > 0)
1072 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1073 REJECT_INVALID, "bad-cb-has-joinsplits");
1075 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1076 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1077 REJECT_INVALID, "bad-cb-length");
1081 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1082 if (txin.prevout.IsNull())
1083 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1084 REJECT_INVALID, "bad-txns-prevout-null");
1086 if (tx.vjoinsplit.size() > 0) {
1087 // Empty output script.
1089 uint256 dataToBeSigned;
1091 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, SIGVERSION_BASE);
1092 } catch (std::logic_error ex) {
1093 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1094 REJECT_INVALID, "error-computing-signature-hash");
1097 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1099 // We rely on libsodium to check that the signature is canonical.
1100 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1101 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1102 dataToBeSigned.begin(), 32,
1103 tx.joinSplitPubKey.begin()
1105 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1106 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1114 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1118 uint256 hash = tx.GetHash();
1119 double dPriorityDelta = 0;
1120 CAmount nFeeDelta = 0;
1121 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1122 if (dPriorityDelta > 0 || nFeeDelta > 0)
1126 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1130 // There is a free transaction area in blocks created by most miners,
1131 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1132 // to be considered to fall into this category. We don't want to encourage sending
1133 // multiple transactions instead of one big transaction to avoid fees.
1134 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1138 if (!MoneyRange(nMinFee))
1139 nMinFee = MAX_MONEY;
1144 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1145 bool* pfMissingInputs, bool fRejectAbsurdFee)
1147 AssertLockHeld(cs_main);
1148 if (pfMissingInputs)
1149 *pfMissingInputs = false;
1151 // Node operator can choose to reject tx by number of transparent inputs
1152 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1153 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1155 size_t n = tx.vin.size();
1157 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1162 auto verifier = libzcash::ProofVerifier::Strict();
1163 if (!CheckTransaction(tx, state, verifier))
1164 return error("AcceptToMemoryPool: CheckTransaction failed");
1166 // DoS level set to 10 to be more forgiving.
1167 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
1168 int nextBlockHeight = chainActive.Height() + 1;
1169 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1170 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1173 // Coinbase is only valid in a block, not as a loose transaction
1174 if (tx.IsCoinBase())
1175 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1176 REJECT_INVALID, "coinbase");
1178 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1180 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
1182 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1183 REJECT_NONSTANDARD, reason);
1185 // Only accept nLockTime-using transactions that can be mined in the next
1186 // block; we don't want our mempool filled up with transactions that can't
1188 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1189 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1191 // is it already in the memory pool?
1192 uint256 hash = tx.GetHash();
1193 if (pool.exists(hash))
1196 // Check for conflicts with in-memory transactions
1198 LOCK(pool.cs); // protect pool.mapNextTx
1199 for (unsigned int i = 0; i < tx.vin.size(); i++)
1201 COutPoint outpoint = tx.vin[i].prevout;
1202 if (pool.mapNextTx.count(outpoint))
1204 // Disable replacement feature for now
1208 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1209 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1210 if (pool.mapNullifiers.count(nf))
1220 CCoinsViewCache view(&dummy);
1222 CAmount nValueIn = 0;
1225 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1226 view.SetBackend(viewMemPool);
1228 // do we already have it?
1229 if (view.HaveCoins(hash))
1232 // do all inputs exist?
1233 // Note that this does not check for the presence of actual outputs (see the next check for that),
1234 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1235 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1236 if (!view.HaveCoins(txin.prevout.hash)) {
1237 if (pfMissingInputs)
1238 *pfMissingInputs = true;
1243 // are the actual inputs available?
1244 if (!view.HaveInputs(tx))
1245 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1246 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1248 // are the joinsplit's requirements met?
1249 if (!view.HaveJoinSplitRequirements(tx))
1250 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1251 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1253 // Bring the best block into scope
1254 view.GetBestBlock();
1256 nValueIn = view.GetValueIn(tx);
1258 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1259 view.SetBackend(dummy);
1262 // Check for non-standard pay-to-script-hash in inputs
1263 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1264 return error("AcceptToMemoryPool: nonstandard transaction input");
1266 // Check that the transaction doesn't have an excessive number of
1267 // sigops, making it impossible to mine. Since the coinbase transaction
1268 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1269 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1270 // merely non-standard transaction.
1271 unsigned int nSigOps = GetLegacySigOpCount(tx);
1272 nSigOps += GetP2SHSigOpCount(tx, view);
1273 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1275 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1276 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1277 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1279 CAmount nValueOut = tx.GetValueOut();
1280 CAmount nFees = nValueIn-nValueOut;
1281 double dPriority = view.GetPriority(tx, chainActive.Height());
1283 // Keep track of transactions that spend a coinbase, which we re-scan
1284 // during reorgs to ensure COINBASE_MATURITY is still met.
1285 bool fSpendsCoinbase = false;
1286 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1287 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1288 if (coins->IsCoinBase()) {
1289 fSpendsCoinbase = true;
1294 // Grab the branch ID we expect this transaction to commit to. We don't
1295 // yet know if it does, but if the entry gets added to the mempool, then
1296 // it has passed ContextualCheckInputs and therefore this is correct.
1297 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1299 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
1300 unsigned int nSize = entry.GetTxSize();
1302 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1303 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1304 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1306 // Don't accept it if it can't get into a block
1307 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1308 if (fLimitFree && nFees < txMinFee)
1309 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1310 hash.ToString(), nFees, txMinFee),
1311 REJECT_INSUFFICIENTFEE, "insufficient fee");
1314 // Require that free transactions have sufficient priority to be mined in the next block.
1315 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1316 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1319 // Continuously rate-limit free (really, very-low-fee) transactions
1320 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1321 // be annoying or make others' transactions take longer to confirm.
1322 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1324 static CCriticalSection csFreeLimiter;
1325 static double dFreeCount;
1326 static int64_t nLastTime;
1327 int64_t nNow = GetTime();
1329 LOCK(csFreeLimiter);
1331 // Use an exponentially decaying ~10-minute window:
1332 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1334 // -limitfreerelay unit is thousand-bytes-per-minute
1335 // At default rate it would take over a month to fill 1GB
1336 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1337 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1338 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1339 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1340 dFreeCount += nSize;
1343 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1344 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1346 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1348 // Check against previous transactions
1349 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1350 PrecomputedTransactionData txdata(tx);
1351 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus()))
1353 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1356 // Check again against just the consensus-critical mandatory script
1357 // verification flags, in case of bugs in the standard flags that cause
1358 // transactions to pass as valid when they're actually invalid. For
1359 // instance the STRICTENC flag was incorrectly allowing certain
1360 // CHECKSIG NOT scripts to pass, even though they were invalid.
1362 // There is a similar check in CreateNewBlock() to prevent creating
1363 // invalid blocks, however allowing such transactions into the mempool
1364 // can be exploited as a DoS attack.
1365 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus()))
1367 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1370 // Store transaction in memory
1371 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1374 SyncWithWallets(tx, NULL);
1379 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1380 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1382 CBlockIndex *pindexSlow = NULL;
1386 if (mempool.lookup(hash, txOut))
1393 if (pblocktree->ReadTxIndex(hash, postx)) {
1394 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1396 return error("%s: OpenBlockFile failed", __func__);
1397 CBlockHeader header;
1400 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1402 } catch (const std::exception& e) {
1403 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1405 hashBlock = header.GetHash();
1406 if (txOut.GetHash() != hash)
1407 return error("%s: txid mismatch", __func__);
1412 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1415 CCoinsViewCache &view = *pcoinsTip;
1416 const CCoins* coins = view.AccessCoins(hash);
1418 nHeight = coins->nHeight;
1421 pindexSlow = chainActive[nHeight];
1426 if (ReadBlockFromDisk(block, pindexSlow)) {
1427 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1428 if (tx.GetHash() == hash) {
1430 hashBlock = pindexSlow->GetBlockHash();
1445 //////////////////////////////////////////////////////////////////////////////
1447 // CBlock and CBlockIndex
1450 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1452 // Open history file to append
1453 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1454 if (fileout.IsNull())
1455 return error("WriteBlockToDisk: OpenBlockFile failed");
1457 // Write index header
1458 unsigned int nSize = fileout.GetSerializeSize(block);
1459 fileout << FLATDATA(messageStart) << nSize;
1462 long fileOutPos = ftell(fileout.Get());
1464 return error("WriteBlockToDisk: ftell failed");
1465 pos.nPos = (unsigned int)fileOutPos;
1471 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1475 // Open history file to read
1476 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1477 if (filein.IsNull())
1478 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1484 catch (const std::exception& e) {
1485 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1489 if (!(CheckEquihashSolution(&block, Params()) &&
1490 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1491 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1496 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1498 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1500 if (block.GetHash() != pindex->GetBlockHash())
1501 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1502 pindex->ToString(), pindex->GetBlockPos().ToString());
1506 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1508 CAmount nSubsidy = 12.5 * COIN;
1510 // Mining slow start
1511 // The subsidy is ramped up linearly, skipping the middle payout of
1512 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1513 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1514 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1515 nSubsidy *= nHeight;
1517 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1518 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1519 nSubsidy *= (nHeight+1);
1523 assert(nHeight > consensusParams.SubsidySlowStartShift());
1524 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1525 // Force block reward to zero when right shift is undefined.
1529 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1530 nSubsidy >>= halvings;
1534 bool IsInitialBlockDownload()
1536 const CChainParams& chainParams = Params();
1538 if (fImporting || fReindex)
1540 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1542 static bool lockIBDState = false;
1545 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1546 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1548 lockIBDState = true;
1552 bool fLargeWorkForkFound = false;
1553 bool fLargeWorkInvalidChainFound = false;
1554 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1556 void CheckForkWarningConditions()
1558 AssertLockHeld(cs_main);
1559 // Before we get past initial download, we cannot reliably alert about forks
1560 // (we assume we don't get stuck on a fork before the last checkpoint)
1561 if (IsInitialBlockDownload())
1564 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1565 // of our head, drop it
1566 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1567 pindexBestForkTip = NULL;
1569 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1571 if (!fLargeWorkForkFound && pindexBestForkBase)
1573 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1574 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1575 CAlert::Notify(warning, true);
1577 if (pindexBestForkTip && pindexBestForkBase)
1579 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__,
1580 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1581 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1582 fLargeWorkForkFound = true;
1586 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1587 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1588 CAlert::Notify(warning, true);
1589 fLargeWorkInvalidChainFound = true;
1594 fLargeWorkForkFound = false;
1595 fLargeWorkInvalidChainFound = false;
1599 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1601 AssertLockHeld(cs_main);
1602 // If we are on a fork that is sufficiently large, set a warning flag
1603 CBlockIndex* pfork = pindexNewForkTip;
1604 CBlockIndex* plonger = chainActive.Tip();
1605 while (pfork && pfork != plonger)
1607 while (plonger && plonger->nHeight > pfork->nHeight)
1608 plonger = plonger->pprev;
1609 if (pfork == plonger)
1611 pfork = pfork->pprev;
1614 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1615 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1616 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1617 // hash rate operating on the fork.
1618 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1619 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1620 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1621 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1622 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1623 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1625 pindexBestForkTip = pindexNewForkTip;
1626 pindexBestForkBase = pfork;
1629 CheckForkWarningConditions();
1632 // Requires cs_main.
1633 void Misbehaving(NodeId pnode, int howmuch)
1638 CNodeState *state = State(pnode);
1642 state->nMisbehavior += howmuch;
1643 int banscore = GetArg("-banscore", 100);
1644 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1646 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1647 state->fShouldBan = true;
1649 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1652 void static InvalidChainFound(CBlockIndex* pindexNew)
1654 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1655 pindexBestInvalid = pindexNew;
1657 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1658 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1659 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1660 pindexNew->GetBlockTime()));
1661 CBlockIndex *tip = chainActive.Tip();
1663 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1664 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1665 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1666 CheckForkWarningConditions();
1669 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1671 if (state.IsInvalid(nDoS)) {
1672 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1673 if (it != mapBlockSource.end() && State(it->second)) {
1674 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1675 State(it->second)->rejects.push_back(reject);
1677 Misbehaving(it->second, nDoS);
1680 if (!state.CorruptionPossible()) {
1681 pindex->nStatus |= BLOCK_FAILED_VALID;
1682 setDirtyBlockIndex.insert(pindex);
1683 setBlockIndexCandidates.erase(pindex);
1684 InvalidChainFound(pindex);
1688 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1690 // mark inputs spent
1691 if (!tx.IsCoinBase()) {
1692 txundo.vprevout.reserve(tx.vin.size());
1693 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1694 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1695 unsigned nPos = txin.prevout.n;
1697 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1699 // mark an outpoint spent, and construct undo information
1700 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1702 if (coins->vout.size() == 0) {
1703 CTxInUndo& undo = txundo.vprevout.back();
1704 undo.nHeight = coins->nHeight;
1705 undo.fCoinBase = coins->fCoinBase;
1706 undo.nVersion = coins->nVersion;
1712 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1713 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1714 inputs.SetNullifier(nf, true);
1719 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1722 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1725 UpdateCoins(tx, inputs, txundo, nHeight);
1728 bool CScriptCheck::operator()() {
1729 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1730 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), &error)) {
1731 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1736 int GetSpendHeight(const CCoinsViewCache& inputs)
1739 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1740 return pindexPrev->nHeight + 1;
1743 namespace Consensus {
1744 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1746 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1747 // for an attacker to attempt to split the network.
1748 if (!inputs.HaveInputs(tx))
1749 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1751 // are the JoinSplit's requirements met?
1752 if (!inputs.HaveJoinSplitRequirements(tx))
1753 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1755 CAmount nValueIn = 0;
1757 for (unsigned int i = 0; i < tx.vin.size(); i++)
1759 const COutPoint &prevout = tx.vin[i].prevout;
1760 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1763 if (coins->IsCoinBase()) {
1764 // Ensure that coinbases are matured
1765 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1766 return state.Invalid(
1767 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1768 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1771 // Ensure that coinbases cannot be spent to transparent outputs
1772 // Disabled on regtest
1773 if (fCoinbaseEnforcedProtectionEnabled &&
1774 consensusParams.fCoinbaseMustBeProtected &&
1776 return state.Invalid(
1777 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1778 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1782 // Check for negative or overflow input values
1783 nValueIn += coins->vout[prevout.n].nValue;
1784 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1785 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1786 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1790 nValueIn += tx.GetJoinSplitValueIn();
1791 if (!MoneyRange(nValueIn))
1792 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1793 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1795 if (nValueIn < tx.GetValueOut())
1796 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1797 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1798 REJECT_INVALID, "bad-txns-in-belowout");
1800 // Tally transaction fees
1801 CAmount nTxFee = nValueIn - tx.GetValueOut();
1803 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1804 REJECT_INVALID, "bad-txns-fee-negative");
1806 if (!MoneyRange(nFees))
1807 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1808 REJECT_INVALID, "bad-txns-fee-outofrange");
1811 }// namespace Consensus
1813 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, PrecomputedTransactionData& txdata, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1815 if (!tx.IsCoinBase())
1817 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
1822 pvChecks->reserve(tx.vin.size());
1824 // The first loop above does all the inexpensive checks.
1825 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1826 // Helps prevent CPU exhaustion attacks.
1828 // Skip ECDSA signature verification when connecting blocks
1829 // before the last block chain checkpoint. This is safe because block merkle hashes are
1830 // still computed and checked, and any change will be caught at the next checkpoint.
1831 if (fScriptChecks) {
1832 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1833 const COutPoint &prevout = tx.vin[i].prevout;
1834 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1838 CScriptCheck check(*coins, tx, i, flags, cacheStore, &txdata);
1840 pvChecks->push_back(CScriptCheck());
1841 check.swap(pvChecks->back());
1842 } else if (!check()) {
1843 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1844 // Check whether the failure was caused by a
1845 // non-mandatory script verification check, such as
1846 // non-standard DER encodings or non-null dummy
1847 // arguments; if so, don't trigger DoS protection to
1848 // avoid splitting the network between upgraded and
1849 // non-upgraded nodes.
1850 CScriptCheck check2(*coins, tx, i,
1851 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, &txdata);
1853 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1855 // Failures of other flags indicate a transaction that is
1856 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1857 // such nodes as they are not following the protocol. That
1858 // said during an upgrade careful thought should be taken
1859 // as to the correct behavior - we may want to continue
1860 // peering with non-upgraded nodes even after a soft-fork
1861 // super-majority vote has passed.
1862 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1873 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1875 // Open history file to append
1876 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1877 if (fileout.IsNull())
1878 return error("%s: OpenUndoFile failed", __func__);
1880 // Write index header
1881 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1882 fileout << FLATDATA(messageStart) << nSize;
1885 long fileOutPos = ftell(fileout.Get());
1887 return error("%s: ftell failed", __func__);
1888 pos.nPos = (unsigned int)fileOutPos;
1889 fileout << blockundo;
1891 // calculate & write checksum
1892 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1893 hasher << hashBlock;
1894 hasher << blockundo;
1895 fileout << hasher.GetHash();
1900 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1902 // Open history file to read
1903 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1904 if (filein.IsNull())
1905 return error("%s: OpenBlockFile failed", __func__);
1908 uint256 hashChecksum;
1910 filein >> blockundo;
1911 filein >> hashChecksum;
1913 catch (const std::exception& e) {
1914 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1918 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1919 hasher << hashBlock;
1920 hasher << blockundo;
1921 if (hashChecksum != hasher.GetHash())
1922 return error("%s: Checksum mismatch", __func__);
1927 /** Abort with a message */
1928 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1930 strMiscWarning = strMessage;
1931 LogPrintf("*** %s\n", strMessage);
1932 uiInterface.ThreadSafeMessageBox(
1933 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1934 "", CClientUIInterface::MSG_ERROR);
1939 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1941 AbortNode(strMessage, userMessage);
1942 return state.Error(strMessage);
1948 * Apply the undo operation of a CTxInUndo to the given chain state.
1949 * @param undo The undo object.
1950 * @param view The coins view to which to apply the changes.
1951 * @param out The out point that corresponds to the tx input.
1952 * @return True on success.
1954 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1958 CCoinsModifier coins = view.ModifyCoins(out.hash);
1959 if (undo.nHeight != 0) {
1960 // undo data contains height: this is the last output of the prevout tx being spent
1961 if (!coins->IsPruned())
1962 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1964 coins->fCoinBase = undo.fCoinBase;
1965 coins->nHeight = undo.nHeight;
1966 coins->nVersion = undo.nVersion;
1968 if (coins->IsPruned())
1969 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1971 if (coins->IsAvailable(out.n))
1972 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1973 if (coins->vout.size() < out.n+1)
1974 coins->vout.resize(out.n+1);
1975 coins->vout[out.n] = undo.txout;
1980 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1982 assert(pindex->GetBlockHash() == view.GetBestBlock());
1989 CBlockUndo blockUndo;
1990 CDiskBlockPos pos = pindex->GetUndoPos();
1992 return error("DisconnectBlock(): no undo data available");
1993 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1994 return error("DisconnectBlock(): failure reading undo data");
1996 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1997 return error("DisconnectBlock(): block and undo data inconsistent");
1999 // undo transactions in reverse order
2000 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2001 const CTransaction &tx = block.vtx[i];
2002 uint256 hash = tx.GetHash();
2004 // Check that all outputs are available and match the outputs in the block itself
2007 CCoinsModifier outs = view.ModifyCoins(hash);
2008 outs->ClearUnspendable();
2010 CCoins outsBlock(tx, pindex->nHeight);
2011 // The CCoins serialization does not serialize negative numbers.
2012 // No network rules currently depend on the version here, so an inconsistency is harmless
2013 // but it must be corrected before txout nversion ever influences a network rule.
2014 if (outsBlock.nVersion < 0)
2015 outs->nVersion = outsBlock.nVersion;
2016 if (*outs != outsBlock)
2017 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2023 // unspend nullifiers
2024 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2025 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2026 view.SetNullifier(nf, false);
2031 if (i > 0) { // not coinbases
2032 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2033 if (txundo.vprevout.size() != tx.vin.size())
2034 return error("DisconnectBlock(): transaction and undo data inconsistent");
2035 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2036 const COutPoint &out = tx.vin[j].prevout;
2037 const CTxInUndo &undo = txundo.vprevout[j];
2038 if (!ApplyTxInUndo(undo, view, out))
2044 // set the old best anchor back
2045 view.PopAnchor(blockUndo.old_tree_root);
2047 // move best block pointer to prevout block
2048 view.SetBestBlock(pindex->pprev->GetBlockHash());
2058 void static FlushBlockFile(bool fFinalize = false)
2060 LOCK(cs_LastBlockFile);
2062 CDiskBlockPos posOld(nLastBlockFile, 0);
2064 FILE *fileOld = OpenBlockFile(posOld);
2067 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2068 FileCommit(fileOld);
2072 fileOld = OpenUndoFile(posOld);
2075 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2076 FileCommit(fileOld);
2081 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2083 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2085 void ThreadScriptCheck() {
2086 RenameThread("zcash-scriptch");
2087 scriptcheckqueue.Thread();
2091 // Called periodically asynchronously; alerts if it smells like
2092 // we're being fed a bad chain (blocks being generated much
2093 // too slowly or too quickly).
2095 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2096 int64_t nPowTargetSpacing)
2098 if (bestHeader == NULL || initialDownloadCheck()) return;
2100 static int64_t lastAlertTime = 0;
2101 int64_t now = GetAdjustedTime();
2102 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2104 const int SPAN_HOURS=4;
2105 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2106 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2108 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2110 std::string strWarning;
2111 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2114 const CBlockIndex* i = bestHeader;
2116 while (i->GetBlockTime() >= startTime) {
2119 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2122 // How likely is it to find that many by chance?
2123 double p = boost::math::pdf(poisson, nBlocks);
2125 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2126 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2128 // Aim for one false-positive about every fifty years of normal running:
2129 const int FIFTY_YEARS = 50*365*24*60*60;
2130 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2132 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2134 // Many fewer blocks than expected: alert!
2135 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2136 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2138 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2140 // Many more blocks than expected: alert!
2141 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2142 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2144 if (!strWarning.empty())
2146 strMiscWarning = strWarning;
2147 CAlert::Notify(strWarning, true);
2148 lastAlertTime = now;
2152 static int64_t nTimeVerify = 0;
2153 static int64_t nTimeConnect = 0;
2154 static int64_t nTimeIndex = 0;
2155 static int64_t nTimeCallbacks = 0;
2156 static int64_t nTimeTotal = 0;
2158 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2160 const CChainParams& chainparams = Params();
2161 AssertLockHeld(cs_main);
2163 bool fExpensiveChecks = true;
2164 if (fCheckpointsEnabled) {
2165 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2166 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2167 // This block is an ancestor of a checkpoint: disable script checks
2168 fExpensiveChecks = false;
2172 auto verifier = libzcash::ProofVerifier::Strict();
2173 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2175 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2176 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2179 // verify that the view's current state corresponds to the previous block
2180 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2181 assert(hashPrevBlock == view.GetBestBlock());
2183 // Special case for the genesis block, skipping connection of its transactions
2184 // (its coinbase is unspendable)
2185 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2187 view.SetBestBlock(pindex->GetBlockHash());
2188 // Before the genesis block, there was an empty tree
2189 ZCIncrementalMerkleTree tree;
2190 pindex->hashAnchor = tree.root();
2191 // The genesis block contained no JoinSplits
2192 pindex->hashAnchorEnd = pindex->hashAnchor;
2197 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2198 // unless those are already completely spent.
2199 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2200 const CCoins* coins = view.AccessCoins(tx.GetHash());
2201 if (coins && !coins->IsPruned())
2202 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2203 REJECT_INVALID, "bad-txns-BIP30");
2206 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2208 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2210 CBlockUndo blockundo;
2212 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2214 int64_t nTimeStart = GetTimeMicros();
2217 unsigned int nSigOps = 0;
2218 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2219 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2220 vPos.reserve(block.vtx.size());
2221 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2223 // Construct the incremental merkle tree at the current
2225 auto old_tree_root = view.GetBestAnchor();
2226 // saving the top anchor in the block index as we go.
2228 pindex->hashAnchor = old_tree_root;
2230 ZCIncrementalMerkleTree tree;
2231 // This should never fail: we should always be able to get the root
2232 // that is on the tip of our chain
2233 assert(view.GetAnchorAt(old_tree_root, tree));
2236 // Consistency check: the root of the tree we're given should
2237 // match what we asked for.
2238 assert(tree.root() == old_tree_root);
2241 std::vector<PrecomputedTransactionData> txdata;
2242 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2243 for (unsigned int i = 0; i < block.vtx.size(); i++)
2245 const CTransaction &tx = block.vtx[i];
2247 nInputs += tx.vin.size();
2248 nSigOps += GetLegacySigOpCount(tx);
2249 if (nSigOps > MAX_BLOCK_SIGOPS)
2250 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2251 REJECT_INVALID, "bad-blk-sigops");
2253 if (!tx.IsCoinBase())
2255 if (!view.HaveInputs(tx))
2256 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2257 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2259 // are the JoinSplit's requirements met?
2260 if (!view.HaveJoinSplitRequirements(tx))
2261 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2262 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2264 // Add in sigops done by pay-to-script-hash inputs;
2265 // this is to prevent a "rogue miner" from creating
2266 // an incredibly-expensive-to-validate block.
2267 nSigOps += GetP2SHSigOpCount(tx, view);
2268 if (nSigOps > MAX_BLOCK_SIGOPS)
2269 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2270 REJECT_INVALID, "bad-blk-sigops");
2273 txdata.emplace_back(tx);
2275 if (!tx.IsCoinBase())
2277 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2279 std::vector<CScriptCheck> vChecks;
2280 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2282 control.Add(vChecks);
2287 blockundo.vtxundo.push_back(CTxUndo());
2289 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2291 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2292 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2293 // Insert the note commitments into our temporary tree.
2295 tree.append(note_commitment);
2299 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2300 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2303 view.PushAnchor(tree);
2305 pindex->hashAnchorEnd = tree.root();
2307 blockundo.old_tree_root = old_tree_root;
2309 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2310 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);
2312 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2313 if (block.vtx[0].GetValueOut() > blockReward)
2314 return state.DoS(100,
2315 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2316 block.vtx[0].GetValueOut(), blockReward),
2317 REJECT_INVALID, "bad-cb-amount");
2319 if (!control.Wait())
2320 return state.DoS(100, false);
2321 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2322 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);
2327 // Write undo information to disk
2328 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2330 if (pindex->GetUndoPos().IsNull()) {
2332 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2333 return error("ConnectBlock(): FindUndoPos failed");
2334 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2335 return AbortNode(state, "Failed to write undo data");
2337 // update nUndoPos in block index
2338 pindex->nUndoPos = pos.nPos;
2339 pindex->nStatus |= BLOCK_HAVE_UNDO;
2342 // Now that all consensus rules have been validated, set nCachedBranchId.
2343 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2344 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
2345 "nCachedBranchId must be set after all consensus rules have been validated.");
2346 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2347 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
2348 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
2349 } else if (pindex->pprev) {
2350 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
2353 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2354 setDirtyBlockIndex.insert(pindex);
2358 if (!pblocktree->WriteTxIndex(vPos))
2359 return AbortNode(state, "Failed to write transaction index");
2361 // add this block to the view's block chain
2362 view.SetBestBlock(pindex->GetBlockHash());
2364 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2365 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2367 // Watch for changes to the previous coinbase transaction.
2368 static uint256 hashPrevBestCoinBase;
2369 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2370 hashPrevBestCoinBase = block.vtx[0].GetHash();
2372 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2373 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2378 enum FlushStateMode {
2380 FLUSH_STATE_IF_NEEDED,
2381 FLUSH_STATE_PERIODIC,
2386 * Update the on-disk chain state.
2387 * The caches and indexes are flushed depending on the mode we're called with
2388 * if they're too large, if it's been a while since the last write,
2389 * or always and in all cases if we're in prune mode and are deleting files.
2391 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2392 LOCK2(cs_main, cs_LastBlockFile);
2393 static int64_t nLastWrite = 0;
2394 static int64_t nLastFlush = 0;
2395 static int64_t nLastSetChain = 0;
2396 std::set<int> setFilesToPrune;
2397 bool fFlushForPrune = false;
2399 if (fPruneMode && fCheckForPruning && !fReindex) {
2400 FindFilesToPrune(setFilesToPrune);
2401 fCheckForPruning = false;
2402 if (!setFilesToPrune.empty()) {
2403 fFlushForPrune = true;
2405 pblocktree->WriteFlag("prunedblockfiles", true);
2410 int64_t nNow = GetTimeMicros();
2411 // Avoid writing/flushing immediately after startup.
2412 if (nLastWrite == 0) {
2415 if (nLastFlush == 0) {
2418 if (nLastSetChain == 0) {
2419 nLastSetChain = nNow;
2421 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2422 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2423 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2424 // The cache is over the limit, we have to write now.
2425 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2426 // 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.
2427 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2428 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2429 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2430 // Combine all conditions that result in a full cache flush.
2431 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2432 // Write blocks and block index to disk.
2433 if (fDoFullFlush || fPeriodicWrite) {
2434 // Depend on nMinDiskSpace to ensure we can write block index
2435 if (!CheckDiskSpace(0))
2436 return state.Error("out of disk space");
2437 // First make sure all block and undo data is flushed to disk.
2439 // Then update all block file information (which may refer to block and undo files).
2441 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2442 vFiles.reserve(setDirtyFileInfo.size());
2443 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2444 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2445 setDirtyFileInfo.erase(it++);
2447 std::vector<const CBlockIndex*> vBlocks;
2448 vBlocks.reserve(setDirtyBlockIndex.size());
2449 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2450 vBlocks.push_back(*it);
2451 setDirtyBlockIndex.erase(it++);
2453 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2454 return AbortNode(state, "Files to write to block index database");
2457 // Finally remove any pruned files
2459 UnlinkPrunedFiles(setFilesToPrune);
2462 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2464 // Typical CCoins structures on disk are around 128 bytes in size.
2465 // Pushing a new one to the database can cause it to be written
2466 // twice (once in the log, and once in the tables). This is already
2467 // an overestimation, as most will delete an existing entry or
2468 // overwrite one. Still, use a conservative safety factor of 2.
2469 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2470 return state.Error("out of disk space");
2471 // Flush the chainstate (which may refer to block index entries).
2472 if (!pcoinsTip->Flush())
2473 return AbortNode(state, "Failed to write to coin database");
2476 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2477 // Update best block in wallet (so we can detect restored wallets).
2478 GetMainSignals().SetBestChain(chainActive.GetLocator());
2479 nLastSetChain = nNow;
2481 } catch (const std::runtime_error& e) {
2482 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2487 void FlushStateToDisk() {
2488 CValidationState state;
2489 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2492 void PruneAndFlush() {
2493 CValidationState state;
2494 fCheckForPruning = true;
2495 FlushStateToDisk(state, FLUSH_STATE_NONE);
2498 /** Update chainActive and related internal data structures. */
2499 void static UpdateTip(CBlockIndex *pindexNew) {
2500 const CChainParams& chainParams = Params();
2501 chainActive.SetTip(pindexNew);
2504 nTimeBestReceived = GetTime();
2505 mempool.AddTransactionsUpdated(1);
2507 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2508 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2509 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2510 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2512 cvBlockChange.notify_all();
2514 // Check the version of the last 100 blocks to see if we need to upgrade:
2515 static bool fWarned = false;
2516 if (!IsInitialBlockDownload() && !fWarned)
2519 const CBlockIndex* pindex = chainActive.Tip();
2520 for (int i = 0; i < 100 && pindex != NULL; i++)
2522 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2524 pindex = pindex->pprev;
2527 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2528 if (nUpgraded > 100/2)
2530 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2531 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2532 CAlert::Notify(strMiscWarning, true);
2539 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2540 * mempool.removeWithoutBranchId after this, with cs_main held.
2542 bool static DisconnectTip(CValidationState &state, bool fBare = false) {
2543 CBlockIndex *pindexDelete = chainActive.Tip();
2544 assert(pindexDelete);
2545 // Read block from disk.
2547 if (!ReadBlockFromDisk(block, pindexDelete))
2548 return AbortNode(state, "Failed to read block");
2549 // Apply the block atomically to the chain state.
2550 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2551 int64_t nStart = GetTimeMicros();
2553 CCoinsViewCache view(pcoinsTip);
2554 if (!DisconnectBlock(block, state, pindexDelete, view))
2555 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2556 assert(view.Flush());
2558 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2559 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2560 // Write the chain state to disk, if necessary.
2561 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2565 // Resurrect mempool transactions from the disconnected block.
2566 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2567 // ignore validation errors in resurrected transactions
2568 list<CTransaction> removed;
2569 CValidationState stateDummy;
2570 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2571 mempool.remove(tx, removed, true);
2573 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2574 // The anchor may not change between block disconnects,
2575 // in which case we don't want to evict from the mempool yet!
2576 mempool.removeWithAnchor(anchorBeforeDisconnect);
2580 // Update chainActive and related variables.
2581 UpdateTip(pindexDelete->pprev);
2582 // Get the current commitment tree
2583 ZCIncrementalMerkleTree newTree;
2584 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2585 // Let wallets know transactions went from 1-confirmed to
2586 // 0-confirmed or conflicted:
2587 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2588 SyncWithWallets(tx, NULL);
2590 // Update cached incremental witnesses
2591 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2595 static int64_t nTimeReadFromDisk = 0;
2596 static int64_t nTimeConnectTotal = 0;
2597 static int64_t nTimeFlush = 0;
2598 static int64_t nTimeChainState = 0;
2599 static int64_t nTimePostConnect = 0;
2602 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2603 * corresponding to pindexNew, to bypass loading it again from disk.
2604 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
2606 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2607 assert(pindexNew->pprev == chainActive.Tip());
2608 // Read block from disk.
2609 int64_t nTime1 = GetTimeMicros();
2612 if (!ReadBlockFromDisk(block, pindexNew))
2613 return AbortNode(state, "Failed to read block");
2616 // Get the current commitment tree
2617 ZCIncrementalMerkleTree oldTree;
2618 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2619 // Apply the block atomically to the chain state.
2620 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2622 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2624 CCoinsViewCache view(pcoinsTip);
2625 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2626 GetMainSignals().BlockChecked(*pblock, state);
2628 if (state.IsInvalid())
2629 InvalidBlockFound(pindexNew, state);
2630 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2632 mapBlockSource.erase(pindexNew->GetBlockHash());
2633 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2634 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2635 assert(view.Flush());
2637 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2638 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2639 // Write the chain state to disk, if necessary.
2640 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2642 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2643 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2644 // Remove conflicting transactions from the mempool.
2645 list<CTransaction> txConflicted;
2646 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2647 // Update chainActive & related variables.
2648 UpdateTip(pindexNew);
2649 // Tell wallet about transactions that went from mempool
2651 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2652 SyncWithWallets(tx, NULL);
2654 // ... and about transactions that got confirmed:
2655 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2656 SyncWithWallets(tx, pblock);
2658 // Update cached incremental witnesses
2659 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2661 EnforceNodeDeprecation(pindexNew->nHeight);
2663 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2664 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2665 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2670 * Return the tip of the chain with the most work in it, that isn't
2671 * known to be invalid (it's however far from certain to be valid).
2673 static CBlockIndex* FindMostWorkChain() {
2675 CBlockIndex *pindexNew = NULL;
2677 // Find the best candidate header.
2679 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2680 if (it == setBlockIndexCandidates.rend())
2685 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2686 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2687 CBlockIndex *pindexTest = pindexNew;
2688 bool fInvalidAncestor = false;
2689 while (pindexTest && !chainActive.Contains(pindexTest)) {
2690 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2692 // Pruned nodes may have entries in setBlockIndexCandidates for
2693 // which block files have been deleted. Remove those as candidates
2694 // for the most work chain if we come across them; we can't switch
2695 // to a chain unless we have all the non-active-chain parent blocks.
2696 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2697 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2698 if (fFailedChain || fMissingData) {
2699 // Candidate chain is not usable (either invalid or missing data)
2700 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2701 pindexBestInvalid = pindexNew;
2702 CBlockIndex *pindexFailed = pindexNew;
2703 // Remove the entire chain from the set.
2704 while (pindexTest != pindexFailed) {
2706 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2707 } else if (fMissingData) {
2708 // If we're missing data, then add back to mapBlocksUnlinked,
2709 // so that if the block arrives in the future we can try adding
2710 // to setBlockIndexCandidates again.
2711 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2713 setBlockIndexCandidates.erase(pindexFailed);
2714 pindexFailed = pindexFailed->pprev;
2716 setBlockIndexCandidates.erase(pindexTest);
2717 fInvalidAncestor = true;
2720 pindexTest = pindexTest->pprev;
2722 if (!fInvalidAncestor)
2727 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2728 static void PruneBlockIndexCandidates() {
2729 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2730 // reorganization to a better block fails.
2731 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2732 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2733 setBlockIndexCandidates.erase(it++);
2735 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2736 assert(!setBlockIndexCandidates.empty());
2740 * Try to make some progress towards making pindexMostWork the active block.
2741 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2743 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2744 AssertLockHeld(cs_main);
2745 bool fInvalidFound = false;
2746 const CBlockIndex *pindexOldTip = chainActive.Tip();
2747 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2749 // Disconnect active blocks which are no longer in the best chain.
2750 bool fBlocksDisconnected = false;
2751 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2752 if (!DisconnectTip(state))
2754 fBlocksDisconnected = true;
2757 // Build list of new blocks to connect.
2758 std::vector<CBlockIndex*> vpindexToConnect;
2759 bool fContinue = true;
2760 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2761 while (fContinue && nHeight != pindexMostWork->nHeight) {
2762 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2763 // a few blocks along the way.
2764 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2765 vpindexToConnect.clear();
2766 vpindexToConnect.reserve(nTargetHeight - nHeight);
2767 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2768 while (pindexIter && pindexIter->nHeight != nHeight) {
2769 vpindexToConnect.push_back(pindexIter);
2770 pindexIter = pindexIter->pprev;
2772 nHeight = nTargetHeight;
2774 // Connect new blocks.
2775 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2776 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2777 if (state.IsInvalid()) {
2778 // The block violates a consensus rule.
2779 if (!state.CorruptionPossible())
2780 InvalidChainFound(vpindexToConnect.back());
2781 state = CValidationState();
2782 fInvalidFound = true;
2786 // A system error occurred (disk space, database error, ...).
2790 PruneBlockIndexCandidates();
2791 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2792 // We're in a better position than we were. Return temporarily to release the lock.
2800 if (fBlocksDisconnected) {
2801 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2803 mempool.removeWithoutBranchId(
2804 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2805 mempool.check(pcoinsTip);
2807 // Callbacks/notifications for a new best chain.
2809 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2811 CheckForkWarningConditions();
2817 * Make the best chain active, in multiple steps. The result is either failure
2818 * or an activated best chain. pblock is either NULL or a pointer to a block
2819 * that is already loaded (to avoid loading it again from disk).
2821 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2822 CBlockIndex *pindexNewTip = NULL;
2823 CBlockIndex *pindexMostWork = NULL;
2824 const CChainParams& chainParams = Params();
2826 boost::this_thread::interruption_point();
2828 bool fInitialDownload;
2831 pindexMostWork = FindMostWorkChain();
2833 // Whether we have anything to do at all.
2834 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2837 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2840 pindexNewTip = chainActive.Tip();
2841 fInitialDownload = IsInitialBlockDownload();
2843 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2845 // Notifications/callbacks that can run without cs_main
2846 if (!fInitialDownload) {
2847 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2848 // Relay inventory, but don't relay old inventory during initial block download.
2849 int nBlockEstimate = 0;
2850 if (fCheckpointsEnabled)
2851 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2852 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2853 // in a stalled download if the block file is pruned before the request.
2854 if (nLocalServices & NODE_NETWORK) {
2856 BOOST_FOREACH(CNode* pnode, vNodes)
2857 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2858 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2860 // Notify external listeners about the new tip.
2861 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2862 uiInterface.NotifyBlockTip(hashNewTip);
2864 } while(pindexMostWork != chainActive.Tip());
2867 // Write changes periodically to disk, after relay.
2868 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2875 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2876 AssertLockHeld(cs_main);
2878 // Mark the block itself as invalid.
2879 pindex->nStatus |= BLOCK_FAILED_VALID;
2880 setDirtyBlockIndex.insert(pindex);
2881 setBlockIndexCandidates.erase(pindex);
2883 while (chainActive.Contains(pindex)) {
2884 CBlockIndex *pindexWalk = chainActive.Tip();
2885 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2886 setDirtyBlockIndex.insert(pindexWalk);
2887 setBlockIndexCandidates.erase(pindexWalk);
2888 // ActivateBestChain considers blocks already in chainActive
2889 // unconditionally valid already, so force disconnect away from it.
2890 if (!DisconnectTip(state)) {
2891 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2892 mempool.removeWithoutBranchId(
2893 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2898 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2900 BlockMap::iterator it = mapBlockIndex.begin();
2901 while (it != mapBlockIndex.end()) {
2902 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2903 setBlockIndexCandidates.insert(it->second);
2908 InvalidChainFound(pindex);
2909 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2910 mempool.removeWithoutBranchId(
2911 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2915 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2916 AssertLockHeld(cs_main);
2918 int nHeight = pindex->nHeight;
2920 // Remove the invalidity flag from this block and all its descendants.
2921 BlockMap::iterator it = mapBlockIndex.begin();
2922 while (it != mapBlockIndex.end()) {
2923 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2924 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2925 setDirtyBlockIndex.insert(it->second);
2926 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2927 setBlockIndexCandidates.insert(it->second);
2929 if (it->second == pindexBestInvalid) {
2930 // Reset invalid block marker if it was pointing to one of those.
2931 pindexBestInvalid = NULL;
2937 // Remove the invalidity flag from all ancestors too.
2938 while (pindex != NULL) {
2939 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2940 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2941 setDirtyBlockIndex.insert(pindex);
2943 pindex = pindex->pprev;
2948 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2950 // Check for duplicate
2951 uint256 hash = block.GetHash();
2952 BlockMap::iterator it = mapBlockIndex.find(hash);
2953 if (it != mapBlockIndex.end())
2956 // Construct new block index object
2957 CBlockIndex* pindexNew = new CBlockIndex(block);
2959 // We assign the sequence id to blocks only when the full data is available,
2960 // to avoid miners withholding blocks but broadcasting headers, to get a
2961 // competitive advantage.
2962 pindexNew->nSequenceId = 0;
2963 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2964 pindexNew->phashBlock = &((*mi).first);
2965 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2966 if (miPrev != mapBlockIndex.end())
2968 pindexNew->pprev = (*miPrev).second;
2969 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2970 pindexNew->BuildSkip();
2972 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2973 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2974 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2975 pindexBestHeader = pindexNew;
2977 setDirtyBlockIndex.insert(pindexNew);
2982 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2983 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2985 pindexNew->nTx = block.vtx.size();
2986 pindexNew->nChainTx = 0;
2987 CAmount sproutValue = 0;
2988 for (auto tx : block.vtx) {
2989 for (auto js : tx.vjoinsplit) {
2990 sproutValue += js.vpub_old;
2991 sproutValue -= js.vpub_new;
2994 pindexNew->nSproutValue = sproutValue;
2995 pindexNew->nChainSproutValue = boost::none;
2996 pindexNew->nFile = pos.nFile;
2997 pindexNew->nDataPos = pos.nPos;
2998 pindexNew->nUndoPos = 0;
2999 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3000 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3001 setDirtyBlockIndex.insert(pindexNew);
3003 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3004 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3005 deque<CBlockIndex*> queue;
3006 queue.push_back(pindexNew);
3008 // Recursively process any descendant blocks that now may be eligible to be connected.
3009 while (!queue.empty()) {
3010 CBlockIndex *pindex = queue.front();
3012 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3013 if (pindex->pprev) {
3014 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3015 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3017 pindex->nChainSproutValue = boost::none;
3020 pindex->nChainSproutValue = pindex->nSproutValue;
3023 LOCK(cs_nBlockSequenceId);
3024 pindex->nSequenceId = nBlockSequenceId++;
3026 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3027 setBlockIndexCandidates.insert(pindex);
3029 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3030 while (range.first != range.second) {
3031 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3032 queue.push_back(it->second);
3034 mapBlocksUnlinked.erase(it);
3038 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3039 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3046 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3048 LOCK(cs_LastBlockFile);
3050 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3051 if (vinfoBlockFile.size() <= nFile) {
3052 vinfoBlockFile.resize(nFile + 1);
3056 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3058 if (vinfoBlockFile.size() <= nFile) {
3059 vinfoBlockFile.resize(nFile + 1);
3063 pos.nPos = vinfoBlockFile[nFile].nSize;
3066 if (nFile != nLastBlockFile) {
3068 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3070 FlushBlockFile(!fKnown);
3071 nLastBlockFile = nFile;
3074 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3076 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3078 vinfoBlockFile[nFile].nSize += nAddSize;
3081 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3082 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3083 if (nNewChunks > nOldChunks) {
3085 fCheckForPruning = true;
3086 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3087 FILE *file = OpenBlockFile(pos);
3089 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3090 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3095 return state.Error("out of disk space");
3099 setDirtyFileInfo.insert(nFile);
3103 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3107 LOCK(cs_LastBlockFile);
3109 unsigned int nNewSize;
3110 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3111 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3112 setDirtyFileInfo.insert(nFile);
3114 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3115 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3116 if (nNewChunks > nOldChunks) {
3118 fCheckForPruning = true;
3119 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3120 FILE *file = OpenUndoFile(pos);
3122 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3123 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3128 return state.Error("out of disk space");
3134 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
3136 // Check block version
3137 if (block.nVersion < MIN_BLOCK_VERSION)
3138 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
3139 REJECT_INVALID, "version-too-low");
3141 // Check Equihash solution is valid
3142 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
3143 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3144 REJECT_INVALID, "invalid-solution");
3146 // Check proof of work matches claimed amount
3147 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
3148 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
3149 REJECT_INVALID, "high-hash");
3152 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
3153 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
3154 REJECT_INVALID, "time-too-new");
3159 bool CheckBlock(const CBlock& block, CValidationState& state,
3160 libzcash::ProofVerifier& verifier,
3161 bool fCheckPOW, bool fCheckMerkleRoot)
3163 // These are checks that are independent of context.
3165 // Check that the header is valid (particularly PoW). This is mostly
3166 // redundant with the call in AcceptBlockHeader.
3167 if (!CheckBlockHeader(block, state, fCheckPOW))
3170 // Check the merkle root.
3171 if (fCheckMerkleRoot) {
3173 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3174 if (block.hashMerkleRoot != hashMerkleRoot2)
3175 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3176 REJECT_INVALID, "bad-txnmrklroot", true);
3178 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3179 // of transactions in a block without affecting the merkle root of a block,
3180 // while still invalidating it.
3182 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3183 REJECT_INVALID, "bad-txns-duplicate", true);
3186 // All potential-corruption validation must be done before we do any
3187 // transaction validation, as otherwise we may mark the header as invalid
3188 // because we receive the wrong transactions for it.
3191 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3192 return state.DoS(100, error("CheckBlock(): size limits failed"),
3193 REJECT_INVALID, "bad-blk-length");
3195 // First transaction must be coinbase, the rest must not be
3196 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3197 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3198 REJECT_INVALID, "bad-cb-missing");
3199 for (unsigned int i = 1; i < block.vtx.size(); i++)
3200 if (block.vtx[i].IsCoinBase())
3201 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3202 REJECT_INVALID, "bad-cb-multiple");
3204 // Check transactions
3205 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3206 if (!CheckTransaction(tx, state, verifier))
3207 return error("CheckBlock(): CheckTransaction failed");
3209 unsigned int nSigOps = 0;
3210 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3212 nSigOps += GetLegacySigOpCount(tx);
3214 if (nSigOps > MAX_BLOCK_SIGOPS)
3215 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3216 REJECT_INVALID, "bad-blk-sigops", true);
3221 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3223 const CChainParams& chainParams = Params();
3224 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3225 uint256 hash = block.GetHash();
3226 if (hash == consensusParams.hashGenesisBlock)
3231 int nHeight = pindexPrev->nHeight+1;
3233 // Check proof of work
3234 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3235 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3236 REJECT_INVALID, "bad-diffbits");
3238 // Check timestamp against prev
3239 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3240 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3241 REJECT_INVALID, "time-too-old");
3243 if (fCheckpointsEnabled)
3245 // Don't accept any forks from the main chain prior to last checkpoint
3246 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3247 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3248 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3251 // Reject block.nVersion < 4 blocks
3252 if (block.nVersion < 4)
3253 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3254 REJECT_OBSOLETE, "bad-version");
3259 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3261 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3262 const Consensus::Params& consensusParams = Params().GetConsensus();
3264 // Check that all transactions are finalized
3265 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3267 // Check transaction contextually against consensus rules at block height
3268 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3269 return false; // Failure reason has been set in validation state object
3272 int nLockTimeFlags = 0;
3273 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3274 ? pindexPrev->GetMedianTimePast()
3275 : block.GetBlockTime();
3276 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3277 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3281 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3282 // In Zcash this has been enforced since launch, except that the genesis
3283 // block didn't include the height in the coinbase (see Zcash protocol spec
3284 // section '6.8 Bitcoin Improvement Proposals').
3287 CScript expect = CScript() << nHeight;
3288 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3289 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3290 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3294 // Coinbase transaction must include an output sending 20% of
3295 // the block reward to a founders reward script, until the last founders
3296 // reward block is reached, with exception of the genesis block.
3297 // The last founders reward block is defined as the block just before the
3298 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3299 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3302 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3303 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3304 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3312 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3319 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3321 const CChainParams& chainparams = Params();
3322 AssertLockHeld(cs_main);
3323 // Check for duplicate
3324 uint256 hash = block.GetHash();
3325 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3326 CBlockIndex *pindex = NULL;
3327 if (miSelf != mapBlockIndex.end()) {
3328 // Block header is already known.
3329 pindex = miSelf->second;
3332 if (pindex->nStatus & BLOCK_FAILED_MASK)
3333 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3337 if (!CheckBlockHeader(block, state))
3340 // Get prev block index
3341 CBlockIndex* pindexPrev = NULL;
3342 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3343 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3344 if (mi == mapBlockIndex.end())
3345 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3346 pindexPrev = (*mi).second;
3347 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3348 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3351 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3355 pindex = AddToBlockIndex(block);
3363 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3365 const CChainParams& chainparams = Params();
3366 AssertLockHeld(cs_main);
3368 CBlockIndex *&pindex = *ppindex;
3370 if (!AcceptBlockHeader(block, state, &pindex))
3373 // Try to process all requested blocks that we don't have, but only
3374 // process an unrequested block if it's new and has enough work to
3375 // advance our tip, and isn't too many blocks ahead.
3376 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3377 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3378 // Blocks that are too out-of-order needlessly limit the effectiveness of
3379 // pruning, because pruning will not delete block files that contain any
3380 // blocks which are too close in height to the tip. Apply this test
3381 // regardless of whether pruning is enabled; it should generally be safe to
3382 // not process unrequested blocks.
3383 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3385 // TODO: deal better with return value and error conditions for duplicate
3386 // and unrequested blocks.
3387 if (fAlreadyHave) return true;
3388 if (!fRequested) { // If we didn't ask for it:
3389 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3390 if (!fHasMoreWork) return true; // Don't process less-work chains
3391 if (fTooFarAhead) return true; // Block height is too high
3394 // See method docstring for why this is always disabled
3395 auto verifier = libzcash::ProofVerifier::Disabled();
3396 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3397 if (state.IsInvalid() && !state.CorruptionPossible()) {
3398 pindex->nStatus |= BLOCK_FAILED_VALID;
3399 setDirtyBlockIndex.insert(pindex);
3404 int nHeight = pindex->nHeight;
3406 // Write block to history file
3408 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3409 CDiskBlockPos blockPos;
3412 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3413 return error("AcceptBlock(): FindBlockPos failed");
3415 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3416 AbortNode(state, "Failed to write block");
3417 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3418 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3419 } catch (const std::runtime_error& e) {
3420 return AbortNode(state, std::string("System error: ") + e.what());
3423 if (fCheckForPruning)
3424 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3429 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3431 unsigned int nFound = 0;
3432 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3434 if (pstart->nVersion >= minVersion)
3436 pstart = pstart->pprev;
3438 return (nFound >= nRequired);
3442 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3444 // Preliminary checks
3445 auto verifier = libzcash::ProofVerifier::Disabled();
3446 bool checked = CheckBlock(*pblock, state, verifier);
3450 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3451 fRequested |= fForceProcessing;
3453 return error("%s: CheckBlock FAILED", __func__);
3457 CBlockIndex *pindex = NULL;
3458 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3459 if (pindex && pfrom) {
3460 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3464 return error("%s: AcceptBlock FAILED", __func__);
3467 if (!ActivateBestChain(state, pblock))
3468 return error("%s: ActivateBestChain failed", __func__);
3473 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3475 AssertLockHeld(cs_main);
3476 assert(pindexPrev == chainActive.Tip());
3478 CCoinsViewCache viewNew(pcoinsTip);
3479 CBlockIndex indexDummy(block);
3480 indexDummy.pprev = pindexPrev;
3481 indexDummy.nHeight = pindexPrev->nHeight + 1;
3482 // JoinSplit proofs are verified in ConnectBlock
3483 auto verifier = libzcash::ProofVerifier::Disabled();
3485 // NOTE: CheckBlockHeader is called by CheckBlock
3486 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3488 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3490 if (!ContextualCheckBlock(block, state, pindexPrev))
3492 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3494 assert(state.IsValid());
3500 * BLOCK PRUNING CODE
3503 /* Calculate the amount of disk space the block & undo files currently use */
3504 uint64_t CalculateCurrentUsage()
3506 uint64_t retval = 0;
3507 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3508 retval += file.nSize + file.nUndoSize;
3513 /* Prune a block file (modify associated database entries)*/
3514 void PruneOneBlockFile(const int fileNumber)
3516 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3517 CBlockIndex* pindex = it->second;
3518 if (pindex->nFile == fileNumber) {
3519 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3520 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3522 pindex->nDataPos = 0;
3523 pindex->nUndoPos = 0;
3524 setDirtyBlockIndex.insert(pindex);
3526 // Prune from mapBlocksUnlinked -- any block we prune would have
3527 // to be downloaded again in order to consider its chain, at which
3528 // point it would be considered as a candidate for
3529 // mapBlocksUnlinked or setBlockIndexCandidates.
3530 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3531 while (range.first != range.second) {
3532 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3534 if (it->second == pindex) {
3535 mapBlocksUnlinked.erase(it);
3541 vinfoBlockFile[fileNumber].SetNull();
3542 setDirtyFileInfo.insert(fileNumber);
3546 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3548 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3549 CDiskBlockPos pos(*it, 0);
3550 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3551 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3552 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3556 /* Calculate the block/rev files that should be deleted to remain under target*/
3557 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3559 LOCK2(cs_main, cs_LastBlockFile);
3560 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3563 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3567 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3568 uint64_t nCurrentUsage = CalculateCurrentUsage();
3569 // We don't check to prune until after we've allocated new space for files
3570 // So we should leave a buffer under our target to account for another allocation
3571 // before the next pruning.
3572 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3573 uint64_t nBytesToPrune;
3576 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3577 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3578 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3580 if (vinfoBlockFile[fileNumber].nSize == 0)
3583 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3586 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3587 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3590 PruneOneBlockFile(fileNumber);
3591 // Queue up the files for removal
3592 setFilesToPrune.insert(fileNumber);
3593 nCurrentUsage -= nBytesToPrune;
3598 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3599 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3600 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3601 nLastBlockWeCanPrune, count);
3604 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3606 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3608 // Check for nMinDiskSpace bytes (currently 50MB)
3609 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3610 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3615 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3619 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3620 boost::filesystem::create_directories(path.parent_path());
3621 FILE* file = fopen(path.string().c_str(), "rb+");
3622 if (!file && !fReadOnly)
3623 file = fopen(path.string().c_str(), "wb+");
3625 LogPrintf("Unable to open file %s\n", path.string());
3629 if (fseek(file, pos.nPos, SEEK_SET)) {
3630 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3638 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3639 return OpenDiskFile(pos, "blk", fReadOnly);
3642 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3643 return OpenDiskFile(pos, "rev", fReadOnly);
3646 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3648 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3651 CBlockIndex * InsertBlockIndex(uint256 hash)
3657 BlockMap::iterator mi = mapBlockIndex.find(hash);
3658 if (mi != mapBlockIndex.end())
3659 return (*mi).second;
3662 CBlockIndex* pindexNew = new CBlockIndex();
3664 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3665 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3666 pindexNew->phashBlock = &((*mi).first);
3671 bool static LoadBlockIndexDB()
3673 const CChainParams& chainparams = Params();
3674 if (!pblocktree->LoadBlockIndexGuts())
3677 boost::this_thread::interruption_point();
3679 // Calculate nChainWork
3680 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3681 vSortedByHeight.reserve(mapBlockIndex.size());
3682 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3684 CBlockIndex* pindex = item.second;
3685 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3687 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3688 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3690 CBlockIndex* pindex = item.second;
3691 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3692 // We can link the chain of blocks for which we've received transactions at some point.
3693 // Pruned nodes may have deleted the block.
3694 if (pindex->nTx > 0) {
3695 if (pindex->pprev) {
3696 if (pindex->pprev->nChainTx) {
3697 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3698 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3699 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3701 pindex->nChainSproutValue = boost::none;
3704 pindex->nChainTx = 0;
3705 pindex->nChainSproutValue = boost::none;
3706 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3709 pindex->nChainTx = pindex->nTx;
3710 pindex->nChainSproutValue = pindex->nSproutValue;
3713 // Construct in-memory chain of branch IDs.
3714 // Relies on invariant: a block that does not activate a network upgrade
3715 // will always be valid under the same consensus rules as its parent.
3716 // Genesis block has a branch ID of zero by definition, but has no
3717 // validity status because it is side-loaded into a fresh chain.
3718 // Activation blocks will have branch IDs set (read from disk).
3719 if (pindex->pprev) {
3720 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
3721 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
3724 pindex->nCachedBranchId = NetworkUpgradeInfo[Consensus::BASE_SPROUT].nBranchId;
3726 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3727 setBlockIndexCandidates.insert(pindex);
3728 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3729 pindexBestInvalid = pindex;
3731 pindex->BuildSkip();
3732 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3733 pindexBestHeader = pindex;
3736 // Load block file info
3737 pblocktree->ReadLastBlockFile(nLastBlockFile);
3738 vinfoBlockFile.resize(nLastBlockFile + 1);
3739 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3740 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3741 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3743 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3744 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3745 CBlockFileInfo info;
3746 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3747 vinfoBlockFile.push_back(info);
3753 // Check presence of blk files
3754 LogPrintf("Checking all blk files are present...\n");
3755 set<int> setBlkDataFiles;
3756 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3758 CBlockIndex* pindex = item.second;
3759 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3760 setBlkDataFiles.insert(pindex->nFile);
3763 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3765 CDiskBlockPos pos(*it, 0);
3766 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3771 // Check whether we have ever pruned block & undo files
3772 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3774 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3776 // Check whether we need to continue reindexing
3777 bool fReindexing = false;
3778 pblocktree->ReadReindexing(fReindexing);
3779 fReindex |= fReindexing;
3781 // Check whether we have a transaction index
3782 pblocktree->ReadFlag("txindex", fTxIndex);
3783 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3785 // Fill in-memory data
3786 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3788 CBlockIndex* pindex = item.second;
3789 // - This relationship will always be true even if pprev has multiple
3790 // children, because hashAnchor is technically a property of pprev,
3791 // not its children.
3792 // - This will miss chain tips; we handle the best tip below, and other
3793 // tips will be handled by ConnectTip during a re-org.
3794 if (pindex->pprev) {
3795 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3799 // Load pointer to end of best chain
3800 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3801 if (it == mapBlockIndex.end())
3803 chainActive.SetTip(it->second);
3804 // Set hashAnchorEnd for the end of best chain
3805 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3807 PruneBlockIndexCandidates();
3809 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3810 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3811 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3812 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3814 EnforceNodeDeprecation(chainActive.Height(), true);
3819 CVerifyDB::CVerifyDB()
3821 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3824 CVerifyDB::~CVerifyDB()
3826 uiInterface.ShowProgress("", 100);
3829 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3832 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3835 // Verify blocks in the best chain
3836 if (nCheckDepth <= 0)
3837 nCheckDepth = 1000000000; // suffices until the year 19000
3838 if (nCheckDepth > chainActive.Height())
3839 nCheckDepth = chainActive.Height();
3840 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3841 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3842 CCoinsViewCache coins(coinsview);
3843 CBlockIndex* pindexState = chainActive.Tip();
3844 CBlockIndex* pindexFailure = NULL;
3845 int nGoodTransactions = 0;
3846 CValidationState state;
3847 // No need to verify JoinSplits twice
3848 auto verifier = libzcash::ProofVerifier::Disabled();
3849 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3851 boost::this_thread::interruption_point();
3852 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3853 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3856 // check level 0: read from disk
3857 if (!ReadBlockFromDisk(block, pindex))
3858 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3859 // check level 1: verify block validity
3860 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
3861 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3862 // check level 2: verify undo validity
3863 if (nCheckLevel >= 2 && pindex) {
3865 CDiskBlockPos pos = pindex->GetUndoPos();
3866 if (!pos.IsNull()) {
3867 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3868 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3871 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3872 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3874 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3875 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3876 pindexState = pindex->pprev;
3878 nGoodTransactions = 0;
3879 pindexFailure = pindex;
3881 nGoodTransactions += block.vtx.size();
3883 if (ShutdownRequested())
3887 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3889 // check level 4: try reconnecting blocks
3890 if (nCheckLevel >= 4) {
3891 CBlockIndex *pindex = pindexState;
3892 while (pindex != chainActive.Tip()) {
3893 boost::this_thread::interruption_point();
3894 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3895 pindex = chainActive.Next(pindex);
3897 if (!ReadBlockFromDisk(block, pindex))
3898 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3899 if (!ConnectBlock(block, state, pindex, coins))
3900 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3904 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3909 bool RewindBlockIndex(const CChainParams& params)
3913 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
3914 // index will have nCachedBranchId set based on the values previously persisted
3915 // to disk. By definition, a set nCachedBranchId means that the block was
3916 // fully-validated under the corresponding consensus rules. Thus we can quickly
3917 // identify whether the current active chain matches our expected sequence of
3918 // consensus rule changes, with two checks:
3920 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
3921 // - nCachedBranchId for each block matches what we expect.
3922 auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) {
3923 auto consensus = params.GetConsensus();
3924 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
3925 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
3926 return fFlagSet == fFlagExpected &&
3927 pindex->nCachedBranchId &&
3928 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
3932 while (nHeight <= chainActive.Height()) {
3933 if (!sufficientlyValidated(chainActive[nHeight])) {
3939 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3940 CValidationState state;
3941 CBlockIndex* pindex = chainActive.Tip();
3942 while (chainActive.Height() >= nHeight) {
3943 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
3944 // If pruning, don't try rewinding past the HAVE_DATA point;
3945 // since older blocks can't be served anyway, there's
3946 // no need to walk further, and trying to DisconnectTip()
3947 // will fail (and require a needless reindex/redownload
3948 // of the blockchain).
3951 if (!DisconnectTip(state, true)) {
3952 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
3954 // Occasionally flush state to disk.
3955 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
3959 // Reduce validity flag and have-data flags.
3960 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
3961 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
3962 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3963 CBlockIndex* pindexIter = it->second;
3965 // Note: If we encounter an insufficiently validated block that
3966 // is on chainActive, it must be because we are a pruning node, and
3967 // this block or some successor doesn't HAVE_DATA, so we were unable to
3968 // rewind all the way. Blocks remaining on chainActive at this point
3969 // must not have their validity reduced.
3970 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
3972 pindexIter->nStatus =
3973 std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) |
3974 (pindexIter->nStatus & ~BLOCK_VALID_MASK);
3975 // Remove have-data flags
3976 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
3978 pindexIter->nStatus &= ~BLOCK_ACTIVATES_UPGRADE;
3979 pindexIter->nCachedBranchId = boost::none;
3980 // Remove storage location
3981 pindexIter->nFile = 0;
3982 pindexIter->nDataPos = 0;
3983 pindexIter->nUndoPos = 0;
3984 // Remove various other things
3985 pindexIter->nTx = 0;
3986 pindexIter->nChainTx = 0;
3987 pindexIter->nSproutValue = boost::none;
3988 pindexIter->nChainSproutValue = boost::none;
3989 pindexIter->nSequenceId = 0;
3990 // Make sure it gets written
3991 setDirtyBlockIndex.insert(pindexIter);
3993 setBlockIndexCandidates.erase(pindexIter);
3994 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
3995 while (ret.first != ret.second) {
3996 if (ret.first->second == pindexIter) {
3997 mapBlocksUnlinked.erase(ret.first++);
4002 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4003 setBlockIndexCandidates.insert(pindexIter);
4007 PruneBlockIndexCandidates();
4011 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4018 void UnloadBlockIndex()
4021 setBlockIndexCandidates.clear();
4022 chainActive.SetTip(NULL);
4023 pindexBestInvalid = NULL;
4024 pindexBestHeader = NULL;
4026 mapOrphanTransactions.clear();
4027 mapOrphanTransactionsByPrev.clear();
4029 mapBlocksUnlinked.clear();
4030 vinfoBlockFile.clear();
4032 nBlockSequenceId = 1;
4033 mapBlockSource.clear();
4034 mapBlocksInFlight.clear();
4035 nQueuedValidatedHeaders = 0;
4036 nPreferredDownload = 0;
4037 setDirtyBlockIndex.clear();
4038 setDirtyFileInfo.clear();
4039 mapNodeState.clear();
4040 recentRejects.reset(NULL);
4042 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4043 delete entry.second;
4045 mapBlockIndex.clear();
4046 fHavePruned = false;
4049 bool LoadBlockIndex()
4051 // Load block index from databases
4052 if (!fReindex && !LoadBlockIndexDB())
4058 bool InitBlockIndex() {
4059 const CChainParams& chainparams = Params();
4062 // Initialize global variables that cannot be constructed at startup.
4063 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4065 // Check whether we're already initialized
4066 if (chainActive.Genesis() != NULL)
4069 // Use the provided setting for -txindex in the new database
4070 fTxIndex = GetBoolArg("-txindex", false);
4071 pblocktree->WriteFlag("txindex", fTxIndex);
4072 LogPrintf("Initializing databases...\n");
4074 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4077 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4078 // Start new block file
4079 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4080 CDiskBlockPos blockPos;
4081 CValidationState state;
4082 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4083 return error("LoadBlockIndex(): FindBlockPos failed");
4084 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4085 return error("LoadBlockIndex(): writing genesis block to disk failed");
4086 CBlockIndex *pindex = AddToBlockIndex(block);
4087 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4088 return error("LoadBlockIndex(): genesis block not accepted");
4089 if (!ActivateBestChain(state, &block))
4090 return error("LoadBlockIndex(): genesis block cannot be activated");
4091 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4092 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4093 } catch (const std::runtime_error& e) {
4094 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4103 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4105 const CChainParams& chainparams = Params();
4106 // Map of disk positions for blocks with unknown parent (only used for reindex)
4107 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4108 int64_t nStart = GetTimeMillis();
4112 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4113 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4114 uint64_t nRewind = blkdat.GetPos();
4115 while (!blkdat.eof()) {
4116 boost::this_thread::interruption_point();
4118 blkdat.SetPos(nRewind);
4119 nRewind++; // start one byte further next time, in case of failure
4120 blkdat.SetLimit(); // remove former limit
4121 unsigned int nSize = 0;
4124 unsigned char buf[MESSAGE_START_SIZE];
4125 blkdat.FindByte(Params().MessageStart()[0]);
4126 nRewind = blkdat.GetPos()+1;
4127 blkdat >> FLATDATA(buf);
4128 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4132 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4134 } catch (const std::exception&) {
4135 // no valid block header found; don't complain
4140 uint64_t nBlockPos = blkdat.GetPos();
4142 dbp->nPos = nBlockPos;
4143 blkdat.SetLimit(nBlockPos + nSize);
4144 blkdat.SetPos(nBlockPos);
4147 nRewind = blkdat.GetPos();
4149 // detect out of order blocks, and store them for later
4150 uint256 hash = block.GetHash();
4151 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4152 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4153 block.hashPrevBlock.ToString());
4155 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4159 // process in case the block isn't known yet
4160 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4161 CValidationState state;
4162 if (ProcessNewBlock(state, NULL, &block, true, dbp))
4164 if (state.IsError())
4166 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4167 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4170 // Recursively process earlier encountered successors of this block
4171 deque<uint256> queue;
4172 queue.push_back(hash);
4173 while (!queue.empty()) {
4174 uint256 head = queue.front();
4176 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4177 while (range.first != range.second) {
4178 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4179 if (ReadBlockFromDisk(block, it->second))
4181 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4183 CValidationState dummy;
4184 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
4187 queue.push_back(block.GetHash());
4191 mapBlocksUnknownParent.erase(it);
4194 } catch (const std::exception& e) {
4195 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4198 } catch (const std::runtime_error& e) {
4199 AbortNode(std::string("System error: ") + e.what());
4202 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4206 void static CheckBlockIndex()
4208 const Consensus::Params& consensusParams = Params().GetConsensus();
4209 if (!fCheckBlockIndex) {
4215 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4216 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4217 // iterating the block tree require that chainActive has been initialized.)
4218 if (chainActive.Height() < 0) {
4219 assert(mapBlockIndex.size() <= 1);
4223 // Build forward-pointing map of the entire block tree.
4224 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4225 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4226 forward.insert(std::make_pair(it->second->pprev, it->second));
4229 assert(forward.size() == mapBlockIndex.size());
4231 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4232 CBlockIndex *pindex = rangeGenesis.first->second;
4233 rangeGenesis.first++;
4234 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4236 // Iterate over the entire block tree, using depth-first search.
4237 // Along the way, remember whether there are blocks on the path from genesis
4238 // block being explored which are the first to have certain properties.
4241 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4242 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4243 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4244 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4245 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4246 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4247 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4248 while (pindex != NULL) {
4250 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4251 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4252 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4253 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4254 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4255 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4256 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4258 // Begin: actual consistency checks.
4259 if (pindex->pprev == NULL) {
4260 // Genesis block checks.
4261 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4262 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4264 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4265 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4266 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4268 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4269 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4270 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4272 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4273 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4275 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4276 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4277 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4278 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4279 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4280 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4281 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.
4282 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4283 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4284 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4285 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4286 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4287 if (pindexFirstInvalid == NULL) {
4288 // Checks for not-invalid blocks.
4289 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4291 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4292 if (pindexFirstInvalid == NULL) {
4293 // If this block sorts at least as good as the current tip and
4294 // is valid and we have all data for its parents, it must be in
4295 // setBlockIndexCandidates. chainActive.Tip() must also be there
4296 // even if some data has been pruned.
4297 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4298 assert(setBlockIndexCandidates.count(pindex));
4300 // If some parent is missing, then it could be that this block was in
4301 // setBlockIndexCandidates but had to be removed because of the missing data.
4302 // In this case it must be in mapBlocksUnlinked -- see test below.
4304 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4305 assert(setBlockIndexCandidates.count(pindex) == 0);
4307 // Check whether this block is in mapBlocksUnlinked.
4308 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4309 bool foundInUnlinked = false;
4310 while (rangeUnlinked.first != rangeUnlinked.second) {
4311 assert(rangeUnlinked.first->first == pindex->pprev);
4312 if (rangeUnlinked.first->second == pindex) {
4313 foundInUnlinked = true;
4316 rangeUnlinked.first++;
4318 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4319 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4320 assert(foundInUnlinked);
4322 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4323 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4324 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4325 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4326 assert(fHavePruned); // We must have pruned.
4327 // This block may have entered mapBlocksUnlinked if:
4328 // - it has a descendant that at some point had more work than the
4330 // - we tried switching to that descendant but were missing
4331 // data for some intermediate block between chainActive and the
4333 // So if this block is itself better than chainActive.Tip() and it wasn't in
4334 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4335 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4336 if (pindexFirstInvalid == NULL) {
4337 assert(foundInUnlinked);
4341 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4342 // End: actual consistency checks.
4344 // Try descending into the first subnode.
4345 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4346 if (range.first != range.second) {
4347 // A subnode was found.
4348 pindex = range.first->second;
4352 // This is a leaf node.
4353 // Move upwards until we reach a node of which we have not yet visited the last child.
4355 // We are going to either move to a parent or a sibling of pindex.
4356 // If pindex was the first with a certain property, unset the corresponding variable.
4357 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4358 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4359 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4360 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4361 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4362 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4363 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4365 CBlockIndex* pindexPar = pindex->pprev;
4366 // Find which child we just visited.
4367 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4368 while (rangePar.first->second != pindex) {
4369 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4372 // Proceed to the next one.
4374 if (rangePar.first != rangePar.second) {
4375 // Move to the sibling.
4376 pindex = rangePar.first->second;
4387 // Check that we actually traversed the entire map.
4388 assert(nNodes == forward.size());
4391 //////////////////////////////////////////////////////////////////////////////
4396 std::string GetWarnings(const std::string& strFor)
4399 string strStatusBar;
4402 if (!CLIENT_VERSION_IS_RELEASE)
4403 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4405 if (GetBoolArg("-testsafemode", false))
4406 strStatusBar = strRPC = "testsafemode enabled";
4408 // Misc warnings like out of disk space and clock is wrong
4409 if (strMiscWarning != "")
4412 strStatusBar = strMiscWarning;
4415 if (fLargeWorkForkFound)
4418 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4420 else if (fLargeWorkInvalidChainFound)
4423 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.");
4429 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4431 const CAlert& alert = item.second;
4432 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4434 nPriority = alert.nPriority;
4435 strStatusBar = alert.strStatusBar;
4436 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4437 strRPC = alert.strRPCError;
4443 if (strFor == "statusbar")
4444 return strStatusBar;
4445 else if (strFor == "rpc")
4447 assert(!"GetWarnings(): invalid parameter");
4458 //////////////////////////////////////////////////////////////////////////////
4464 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4470 assert(recentRejects);
4471 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4473 // If the chain tip has changed previously rejected transactions
4474 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4475 // or a double-spend. Reset the rejects filter and give those
4476 // txs a second chance.
4477 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4478 recentRejects->reset();
4481 return recentRejects->contains(inv.hash) ||
4482 mempool.exists(inv.hash) ||
4483 mapOrphanTransactions.count(inv.hash) ||
4484 pcoinsTip->HaveCoins(inv.hash);
4487 return mapBlockIndex.count(inv.hash);
4489 // Don't know what it is, just say we already got one
4493 void static ProcessGetData(CNode* pfrom)
4495 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4497 vector<CInv> vNotFound;
4501 while (it != pfrom->vRecvGetData.end()) {
4502 // Don't bother if send buffer is too full to respond anyway
4503 if (pfrom->nSendSize >= SendBufferSize())
4506 const CInv &inv = *it;
4508 boost::this_thread::interruption_point();
4511 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4514 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4515 if (mi != mapBlockIndex.end())
4517 if (chainActive.Contains(mi->second)) {
4520 static const int nOneMonth = 30 * 24 * 60 * 60;
4521 // To prevent fingerprinting attacks, only send blocks outside of the active
4522 // chain if they are valid, and no more than a month older (both in time, and in
4523 // best equivalent proof of work) than the best header chain we know about.
4524 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4525 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4526 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4528 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4532 // Pruned nodes may have deleted the block, so check whether
4533 // it's available before trying to send.
4534 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4536 // Send block from disk
4538 if (!ReadBlockFromDisk(block, (*mi).second))
4539 assert(!"cannot load block from disk");
4540 if (inv.type == MSG_BLOCK)
4541 pfrom->PushMessage("block", block);
4542 else // MSG_FILTERED_BLOCK)
4544 LOCK(pfrom->cs_filter);
4547 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4548 pfrom->PushMessage("merkleblock", merkleBlock);
4549 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4550 // This avoids hurting performance by pointlessly requiring a round-trip
4551 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4552 // they must either disconnect and retry or request the full block.
4553 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4554 // however we MUST always provide at least what the remote peer needs
4555 typedef std::pair<unsigned int, uint256> PairType;
4556 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4557 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4558 pfrom->PushMessage("tx", block.vtx[pair.first]);
4564 // Trigger the peer node to send a getblocks request for the next batch of inventory
4565 if (inv.hash == pfrom->hashContinue)
4567 // Bypass PushInventory, this must send even if redundant,
4568 // and we want it right after the last block so they don't
4569 // wait for other stuff first.
4571 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4572 pfrom->PushMessage("inv", vInv);
4573 pfrom->hashContinue.SetNull();
4577 else if (inv.IsKnownType())
4579 // Send stream from relay memory
4580 bool pushed = false;
4583 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4584 if (mi != mapRelay.end()) {
4585 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4589 if (!pushed && inv.type == MSG_TX) {
4591 if (mempool.lookup(inv.hash, tx)) {
4592 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4595 pfrom->PushMessage("tx", ss);
4600 vNotFound.push_back(inv);
4604 // Track requests for our stuff.
4605 GetMainSignals().Inventory(inv.hash);
4607 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4612 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4614 if (!vNotFound.empty()) {
4615 // Let the peer know that we didn't find what it asked for, so it doesn't
4616 // have to wait around forever. Currently only SPV clients actually care
4617 // about this message: it's needed when they are recursively walking the
4618 // dependencies of relevant unconfirmed transactions. SPV clients want to
4619 // do that because they want to know about (and store and rebroadcast and
4620 // risk analyze) the dependencies of transactions relevant to them, without
4621 // having to download the entire memory pool.
4622 pfrom->PushMessage("notfound", vNotFound);
4626 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4628 const CChainParams& chainparams = Params();
4629 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4630 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4632 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4639 if (strCommand == "version")
4641 // Each connection can only send one version message
4642 if (pfrom->nVersion != 0)
4644 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4645 Misbehaving(pfrom->GetId(), 1);
4652 uint64_t nNonce = 1;
4653 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4654 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4656 // disconnect from peers older than this proto version
4657 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4658 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4659 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4660 pfrom->fDisconnect = true;
4664 if (pfrom->nVersion == 10300)
4665 pfrom->nVersion = 300;
4667 vRecv >> addrFrom >> nNonce;
4668 if (!vRecv.empty()) {
4669 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4670 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4673 vRecv >> pfrom->nStartingHeight;
4675 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4677 pfrom->fRelayTxes = true;
4679 // Disconnect if we connected to ourself
4680 if (nNonce == nLocalHostNonce && nNonce > 1)
4682 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4683 pfrom->fDisconnect = true;
4687 pfrom->addrLocal = addrMe;
4688 if (pfrom->fInbound && addrMe.IsRoutable())
4693 // Be shy and don't send version until we hear
4694 if (pfrom->fInbound)
4695 pfrom->PushVersion();
4697 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4699 // Potentially mark this peer as a preferred download peer.
4700 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4703 pfrom->PushMessage("verack");
4704 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4706 if (!pfrom->fInbound)
4708 // Advertise our address
4709 if (fListen && !IsInitialBlockDownload())
4711 CAddress addr = GetLocalAddress(&pfrom->addr);
4712 if (addr.IsRoutable())
4714 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4715 pfrom->PushAddress(addr);
4716 } else if (IsPeerAddrLocalGood(pfrom)) {
4717 addr.SetIP(pfrom->addrLocal);
4718 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4719 pfrom->PushAddress(addr);
4723 // Get recent addresses
4724 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4726 pfrom->PushMessage("getaddr");
4727 pfrom->fGetAddr = true;
4729 addrman.Good(pfrom->addr);
4731 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4733 addrman.Add(addrFrom, addrFrom);
4734 addrman.Good(addrFrom);
4741 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4742 item.second.RelayTo(pfrom);
4745 pfrom->fSuccessfullyConnected = true;
4749 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4751 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4752 pfrom->cleanSubVer, pfrom->nVersion,
4753 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4756 int64_t nTimeOffset = nTime - GetTime();
4757 pfrom->nTimeOffset = nTimeOffset;
4758 AddTimeData(pfrom->addr, nTimeOffset);
4762 else if (pfrom->nVersion == 0)
4764 // Must have a version message before anything else
4765 Misbehaving(pfrom->GetId(), 1);
4770 else if (strCommand == "verack")
4772 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4774 // Mark this node as currently connected, so we update its timestamp later.
4775 if (pfrom->fNetworkNode) {
4777 State(pfrom->GetId())->fCurrentlyConnected = true;
4782 else if (strCommand == "addr")
4784 vector<CAddress> vAddr;
4787 // Don't want addr from older versions unless seeding
4788 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4790 if (vAddr.size() > 1000)
4792 Misbehaving(pfrom->GetId(), 20);
4793 return error("message addr size() = %u", vAddr.size());
4796 // Store the new addresses
4797 vector<CAddress> vAddrOk;
4798 int64_t nNow = GetAdjustedTime();
4799 int64_t nSince = nNow - 10 * 60;
4800 BOOST_FOREACH(CAddress& addr, vAddr)
4802 boost::this_thread::interruption_point();
4804 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4805 addr.nTime = nNow - 5 * 24 * 60 * 60;
4806 pfrom->AddAddressKnown(addr);
4807 bool fReachable = IsReachable(addr);
4808 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4810 // Relay to a limited number of other nodes
4813 // Use deterministic randomness to send to the same nodes for 24 hours
4814 // at a time so the addrKnowns of the chosen nodes prevent repeats
4815 static uint256 hashSalt;
4816 if (hashSalt.IsNull())
4817 hashSalt = GetRandHash();
4818 uint64_t hashAddr = addr.GetHash();
4819 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4820 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4821 multimap<uint256, CNode*> mapMix;
4822 BOOST_FOREACH(CNode* pnode, vNodes)
4824 if (pnode->nVersion < CADDR_TIME_VERSION)
4826 unsigned int nPointer;
4827 memcpy(&nPointer, &pnode, sizeof(nPointer));
4828 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4829 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4830 mapMix.insert(make_pair(hashKey, pnode));
4832 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4833 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4834 ((*mi).second)->PushAddress(addr);
4837 // Do not store addresses outside our network
4839 vAddrOk.push_back(addr);
4841 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4842 if (vAddr.size() < 1000)
4843 pfrom->fGetAddr = false;
4844 if (pfrom->fOneShot)
4845 pfrom->fDisconnect = true;
4849 else if (strCommand == "inv")
4853 if (vInv.size() > MAX_INV_SZ)
4855 Misbehaving(pfrom->GetId(), 20);
4856 return error("message inv size() = %u", vInv.size());
4861 std::vector<CInv> vToFetch;
4863 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4865 const CInv &inv = vInv[nInv];
4867 boost::this_thread::interruption_point();
4868 pfrom->AddInventoryKnown(inv);
4870 bool fAlreadyHave = AlreadyHave(inv);
4871 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4873 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4876 if (inv.type == MSG_BLOCK) {
4877 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4878 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4879 // First request the headers preceding the announced block. In the normal fully-synced
4880 // case where a new block is announced that succeeds the current tip (no reorganization),
4881 // there are no such headers.
4882 // Secondly, and only when we are close to being synced, we request the announced block directly,
4883 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4884 // time the block arrives, the header chain leading up to it is already validated. Not
4885 // doing this will result in the received block being rejected as an orphan in case it is
4886 // not a direct successor.
4887 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4888 CNodeState *nodestate = State(pfrom->GetId());
4889 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4890 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4891 vToFetch.push_back(inv);
4892 // Mark block as in flight already, even though the actual "getdata" message only goes out
4893 // later (within the same cs_main lock, though).
4894 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4896 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4900 // Track requests for our stuff
4901 GetMainSignals().Inventory(inv.hash);
4903 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4904 Misbehaving(pfrom->GetId(), 50);
4905 return error("send buffer size() = %u", pfrom->nSendSize);
4909 if (!vToFetch.empty())
4910 pfrom->PushMessage("getdata", vToFetch);
4914 else if (strCommand == "getdata")
4918 if (vInv.size() > MAX_INV_SZ)
4920 Misbehaving(pfrom->GetId(), 20);
4921 return error("message getdata size() = %u", vInv.size());
4924 if (fDebug || (vInv.size() != 1))
4925 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4927 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4928 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4930 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4931 ProcessGetData(pfrom);
4935 else if (strCommand == "getblocks")
4937 CBlockLocator locator;
4939 vRecv >> locator >> hashStop;
4943 // Find the last block the caller has in the main chain
4944 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4946 // Send the rest of the chain
4948 pindex = chainActive.Next(pindex);
4950 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4951 for (; pindex; pindex = chainActive.Next(pindex))
4953 if (pindex->GetBlockHash() == hashStop)
4955 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4958 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4961 // When this block is requested, we'll send an inv that'll
4962 // trigger the peer to getblocks the next batch of inventory.
4963 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4964 pfrom->hashContinue = pindex->GetBlockHash();
4971 else if (strCommand == "getheaders")
4973 CBlockLocator locator;
4975 vRecv >> locator >> hashStop;
4979 if (IsInitialBlockDownload())
4982 CBlockIndex* pindex = NULL;
4983 if (locator.IsNull())
4985 // If locator is null, return the hashStop block
4986 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4987 if (mi == mapBlockIndex.end())
4989 pindex = (*mi).second;
4993 // Find the last block the caller has in the main chain
4994 pindex = FindForkInGlobalIndex(chainActive, locator);
4996 pindex = chainActive.Next(pindex);
4999 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5000 vector<CBlock> vHeaders;
5001 int nLimit = MAX_HEADERS_RESULTS;
5002 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5003 for (; pindex; pindex = chainActive.Next(pindex))
5005 vHeaders.push_back(pindex->GetBlockHeader());
5006 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5009 pfrom->PushMessage("headers", vHeaders);
5013 else if (strCommand == "tx")
5015 vector<uint256> vWorkQueue;
5016 vector<uint256> vEraseQueue;
5020 CInv inv(MSG_TX, tx.GetHash());
5021 pfrom->AddInventoryKnown(inv);
5025 bool fMissingInputs = false;
5026 CValidationState state;
5028 pfrom->setAskFor.erase(inv.hash);
5029 mapAlreadyAskedFor.erase(inv);
5031 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5033 mempool.check(pcoinsTip);
5034 RelayTransaction(tx);
5035 vWorkQueue.push_back(inv.hash);
5037 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5038 pfrom->id, pfrom->cleanSubVer,
5039 tx.GetHash().ToString(),
5040 mempool.mapTx.size());
5042 // Recursively process any orphan transactions that depended on this one
5043 set<NodeId> setMisbehaving;
5044 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5046 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5047 if (itByPrev == mapOrphanTransactionsByPrev.end())
5049 for (set<uint256>::iterator mi = itByPrev->second.begin();
5050 mi != itByPrev->second.end();
5053 const uint256& orphanHash = *mi;
5054 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5055 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5056 bool fMissingInputs2 = false;
5057 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5058 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5059 // anyone relaying LegitTxX banned)
5060 CValidationState stateDummy;
5063 if (setMisbehaving.count(fromPeer))
5065 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5067 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5068 RelayTransaction(orphanTx);
5069 vWorkQueue.push_back(orphanHash);
5070 vEraseQueue.push_back(orphanHash);
5072 else if (!fMissingInputs2)
5075 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5077 // Punish peer that gave us an invalid orphan tx
5078 Misbehaving(fromPeer, nDos);
5079 setMisbehaving.insert(fromPeer);
5080 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5082 // Has inputs but not accepted to mempool
5083 // Probably non-standard or insufficient fee/priority
5084 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5085 vEraseQueue.push_back(orphanHash);
5086 assert(recentRejects);
5087 recentRejects->insert(orphanHash);
5089 mempool.check(pcoinsTip);
5093 BOOST_FOREACH(uint256 hash, vEraseQueue)
5094 EraseOrphanTx(hash);
5096 // TODO: currently, prohibit joinsplits from entering mapOrphans
5097 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5099 AddOrphanTx(tx, pfrom->GetId());
5101 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5102 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5103 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5105 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5107 assert(recentRejects);
5108 recentRejects->insert(tx.GetHash());
5110 if (pfrom->fWhitelisted) {
5111 // Always relay transactions received from whitelisted peers, even
5112 // if they were already in the mempool or rejected from it due
5113 // to policy, allowing the node to function as a gateway for
5114 // nodes hidden behind it.
5116 // Never relay transactions that we would assign a non-zero DoS
5117 // score for, as we expect peers to do the same with us in that
5120 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5121 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5122 RelayTransaction(tx);
5124 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5125 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5130 if (state.IsInvalid(nDoS))
5132 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5133 pfrom->id, pfrom->cleanSubVer,
5134 state.GetRejectReason());
5135 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5136 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5138 Misbehaving(pfrom->GetId(), nDoS);
5143 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5145 std::vector<CBlockHeader> headers;
5147 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5148 unsigned int nCount = ReadCompactSize(vRecv);
5149 if (nCount > MAX_HEADERS_RESULTS) {
5150 Misbehaving(pfrom->GetId(), 20);
5151 return error("headers message size = %u", nCount);
5153 headers.resize(nCount);
5154 for (unsigned int n = 0; n < nCount; n++) {
5155 vRecv >> headers[n];
5156 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5162 // Nothing interesting. Stop asking this peers for more headers.
5166 CBlockIndex *pindexLast = NULL;
5167 BOOST_FOREACH(const CBlockHeader& header, headers) {
5168 CValidationState state;
5169 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5170 Misbehaving(pfrom->GetId(), 20);
5171 return error("non-continuous headers sequence");
5173 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5175 if (state.IsInvalid(nDoS)) {
5177 Misbehaving(pfrom->GetId(), nDoS);
5178 return error("invalid header received");
5184 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5186 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5187 // Headers message had its maximum size; the peer may have more headers.
5188 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5189 // from there instead.
5190 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5191 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5197 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5202 CInv inv(MSG_BLOCK, block.GetHash());
5203 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5205 pfrom->AddInventoryKnown(inv);
5207 CValidationState state;
5208 // Process all blocks from whitelisted peers, even if not requested,
5209 // unless we're still syncing with the network.
5210 // Such an unrequested block may still be processed, subject to the
5211 // conditions in AcceptBlock().
5212 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5213 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
5215 if (state.IsInvalid(nDoS)) {
5216 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5217 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5220 Misbehaving(pfrom->GetId(), nDoS);
5227 // This asymmetric behavior for inbound and outbound connections was introduced
5228 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5229 // to users' AddrMan and later request them by sending getaddr messages.
5230 // Making nodes which are behind NAT and can only make outgoing connections ignore
5231 // the getaddr message mitigates the attack.
5232 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5234 // Only send one GetAddr response per connection to reduce resource waste
5235 // and discourage addr stamping of INV announcements.
5236 if (pfrom->fSentAddr) {
5237 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5240 pfrom->fSentAddr = true;
5242 pfrom->vAddrToSend.clear();
5243 vector<CAddress> vAddr = addrman.GetAddr();
5244 BOOST_FOREACH(const CAddress &addr, vAddr)
5245 pfrom->PushAddress(addr);
5249 else if (strCommand == "mempool")
5251 LOCK2(cs_main, pfrom->cs_filter);
5253 std::vector<uint256> vtxid;
5254 mempool.queryHashes(vtxid);
5256 BOOST_FOREACH(uint256& hash, vtxid) {
5257 CInv inv(MSG_TX, hash);
5259 bool fInMemPool = mempool.lookup(hash, tx);
5260 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5261 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5263 vInv.push_back(inv);
5264 if (vInv.size() == MAX_INV_SZ) {
5265 pfrom->PushMessage("inv", vInv);
5269 if (vInv.size() > 0)
5270 pfrom->PushMessage("inv", vInv);
5274 else if (strCommand == "ping")
5276 if (pfrom->nVersion > BIP0031_VERSION)
5280 // Echo the message back with the nonce. This allows for two useful features:
5282 // 1) A remote node can quickly check if the connection is operational
5283 // 2) Remote nodes can measure the latency of the network thread. If this node
5284 // is overloaded it won't respond to pings quickly and the remote node can
5285 // avoid sending us more work, like chain download requests.
5287 // The nonce stops the remote getting confused between different pings: without
5288 // it, if the remote node sends a ping once per second and this node takes 5
5289 // seconds to respond to each, the 5th ping the remote sends would appear to
5290 // return very quickly.
5291 pfrom->PushMessage("pong", nonce);
5296 else if (strCommand == "pong")
5298 int64_t pingUsecEnd = nTimeReceived;
5300 size_t nAvail = vRecv.in_avail();
5301 bool bPingFinished = false;
5302 std::string sProblem;
5304 if (nAvail >= sizeof(nonce)) {
5307 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5308 if (pfrom->nPingNonceSent != 0) {
5309 if (nonce == pfrom->nPingNonceSent) {
5310 // Matching pong received, this ping is no longer outstanding
5311 bPingFinished = true;
5312 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5313 if (pingUsecTime > 0) {
5314 // Successful ping time measurement, replace previous
5315 pfrom->nPingUsecTime = pingUsecTime;
5316 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5318 // This should never happen
5319 sProblem = "Timing mishap";
5322 // Nonce mismatches are normal when pings are overlapping
5323 sProblem = "Nonce mismatch";
5325 // This is most likely a bug in another implementation somewhere; cancel this ping
5326 bPingFinished = true;
5327 sProblem = "Nonce zero";
5331 sProblem = "Unsolicited pong without ping";
5334 // This is most likely a bug in another implementation somewhere; cancel this ping
5335 bPingFinished = true;
5336 sProblem = "Short payload";
5339 if (!(sProblem.empty())) {
5340 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5344 pfrom->nPingNonceSent,
5348 if (bPingFinished) {
5349 pfrom->nPingNonceSent = 0;
5354 else if (fAlerts && strCommand == "alert")
5359 uint256 alertHash = alert.GetHash();
5360 if (pfrom->setKnown.count(alertHash) == 0)
5362 if (alert.ProcessAlert(Params().AlertKey()))
5365 pfrom->setKnown.insert(alertHash);
5368 BOOST_FOREACH(CNode* pnode, vNodes)
5369 alert.RelayTo(pnode);
5373 // Small DoS penalty so peers that send us lots of
5374 // duplicate/expired/invalid-signature/whatever alerts
5375 // eventually get banned.
5376 // This isn't a Misbehaving(100) (immediate ban) because the
5377 // peer might be an older or different implementation with
5378 // a different signature key, etc.
5379 Misbehaving(pfrom->GetId(), 10);
5385 else if (strCommand == "filterload")
5387 CBloomFilter filter;
5390 if (!filter.IsWithinSizeConstraints())
5391 // There is no excuse for sending a too-large filter
5392 Misbehaving(pfrom->GetId(), 100);
5395 LOCK(pfrom->cs_filter);
5396 delete pfrom->pfilter;
5397 pfrom->pfilter = new CBloomFilter(filter);
5398 pfrom->pfilter->UpdateEmptyFull();
5400 pfrom->fRelayTxes = true;
5404 else if (strCommand == "filteradd")
5406 vector<unsigned char> vData;
5409 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5410 // and thus, the maximum size any matched object can have) in a filteradd message
5411 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5413 Misbehaving(pfrom->GetId(), 100);
5415 LOCK(pfrom->cs_filter);
5417 pfrom->pfilter->insert(vData);
5419 Misbehaving(pfrom->GetId(), 100);
5424 else if (strCommand == "filterclear")
5426 LOCK(pfrom->cs_filter);
5427 delete pfrom->pfilter;
5428 pfrom->pfilter = new CBloomFilter();
5429 pfrom->fRelayTxes = true;
5433 else if (strCommand == "reject")
5437 string strMsg; unsigned char ccode; string strReason;
5438 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5441 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5443 if (strMsg == "block" || strMsg == "tx")
5447 ss << ": hash " << hash.ToString();
5449 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5450 } catch (const std::ios_base::failure&) {
5451 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5452 LogPrint("net", "Unparseable reject message received\n");
5457 else if (strCommand == "notfound") {
5458 // We do not care about the NOTFOUND message, but logging an Unknown Command
5459 // message would be undesirable as we transmit it ourselves.
5463 // Ignore unknown commands for extensibility
5464 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5472 // requires LOCK(cs_vRecvMsg)
5473 bool ProcessMessages(CNode* pfrom)
5476 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5480 // (4) message start
5488 if (!pfrom->vRecvGetData.empty())
5489 ProcessGetData(pfrom);
5491 // this maintains the order of responses
5492 if (!pfrom->vRecvGetData.empty()) return fOk;
5494 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5495 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5496 // Don't bother if send buffer is too full to respond anyway
5497 if (pfrom->nSendSize >= SendBufferSize())
5501 CNetMessage& msg = *it;
5504 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5505 // msg.hdr.nMessageSize, msg.vRecv.size(),
5506 // msg.complete() ? "Y" : "N");
5508 // end, if an incomplete message is found
5509 if (!msg.complete())
5512 // at this point, any failure means we can delete the current message
5515 // Scan for message start
5516 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5517 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5523 CMessageHeader& hdr = msg.hdr;
5524 if (!hdr.IsValid(Params().MessageStart()))
5526 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5529 string strCommand = hdr.GetCommand();
5532 unsigned int nMessageSize = hdr.nMessageSize;
5535 CDataStream& vRecv = msg.vRecv;
5536 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5537 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5538 if (nChecksum != hdr.nChecksum)
5540 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5541 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5549 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5550 boost::this_thread::interruption_point();
5552 catch (const std::ios_base::failure& e)
5554 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5555 if (strstr(e.what(), "end of data"))
5557 // Allow exceptions from under-length message on vRecv
5558 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());
5560 else if (strstr(e.what(), "size too large"))
5562 // Allow exceptions from over-long size
5563 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5567 PrintExceptionContinue(&e, "ProcessMessages()");
5570 catch (const boost::thread_interrupted&) {
5573 catch (const std::exception& e) {
5574 PrintExceptionContinue(&e, "ProcessMessages()");
5576 PrintExceptionContinue(NULL, "ProcessMessages()");
5580 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5585 // In case the connection got shut down, its receive buffer was wiped
5586 if (!pfrom->fDisconnect)
5587 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5593 bool SendMessages(CNode* pto, bool fSendTrickle)
5595 const Consensus::Params& consensusParams = Params().GetConsensus();
5597 // Don't send anything until we get its version message
5598 if (pto->nVersion == 0)
5604 bool pingSend = false;
5605 if (pto->fPingQueued) {
5606 // RPC ping request by user
5609 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5610 // Ping automatically sent as a latency probe & keepalive.
5615 while (nonce == 0) {
5616 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5618 pto->fPingQueued = false;
5619 pto->nPingUsecStart = GetTimeMicros();
5620 if (pto->nVersion > BIP0031_VERSION) {
5621 pto->nPingNonceSent = nonce;
5622 pto->PushMessage("ping", nonce);
5624 // Peer is too old to support ping command with nonce, pong will never arrive.
5625 pto->nPingNonceSent = 0;
5626 pto->PushMessage("ping");
5630 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5634 // Address refresh broadcast
5635 static int64_t nLastRebroadcast;
5636 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5639 BOOST_FOREACH(CNode* pnode, vNodes)
5641 // Periodically clear addrKnown to allow refresh broadcasts
5642 if (nLastRebroadcast)
5643 pnode->addrKnown.reset();
5645 // Rebroadcast our address
5646 AdvertizeLocal(pnode);
5648 if (!vNodes.empty())
5649 nLastRebroadcast = GetTime();
5657 vector<CAddress> vAddr;
5658 vAddr.reserve(pto->vAddrToSend.size());
5659 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5661 if (!pto->addrKnown.contains(addr.GetKey()))
5663 pto->addrKnown.insert(addr.GetKey());
5664 vAddr.push_back(addr);
5665 // receiver rejects addr messages larger than 1000
5666 if (vAddr.size() >= 1000)
5668 pto->PushMessage("addr", vAddr);
5673 pto->vAddrToSend.clear();
5675 pto->PushMessage("addr", vAddr);
5678 CNodeState &state = *State(pto->GetId());
5679 if (state.fShouldBan) {
5680 if (pto->fWhitelisted)
5681 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5683 pto->fDisconnect = true;
5684 if (pto->addr.IsLocal())
5685 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5688 CNode::Ban(pto->addr);
5691 state.fShouldBan = false;
5694 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5695 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5696 state.rejects.clear();
5699 if (pindexBestHeader == NULL)
5700 pindexBestHeader = chainActive.Tip();
5701 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.
5702 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5703 // Only actively request headers from a single peer, unless we're close to today.
5704 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5705 state.fSyncStarted = true;
5707 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5708 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5709 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5713 // Resend wallet transactions that haven't gotten in a block yet
5714 // Except during reindex, importing and IBD, when old wallet
5715 // transactions become unconfirmed and spams other nodes.
5716 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5718 GetMainSignals().Broadcast(nTimeBestReceived);
5722 // Message: inventory
5725 vector<CInv> vInvWait;
5727 LOCK(pto->cs_inventory);
5728 vInv.reserve(pto->vInventoryToSend.size());
5729 vInvWait.reserve(pto->vInventoryToSend.size());
5730 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5732 if (pto->setInventoryKnown.count(inv))
5735 // trickle out tx inv to protect privacy
5736 if (inv.type == MSG_TX && !fSendTrickle)
5738 // 1/4 of tx invs blast to all immediately
5739 static uint256 hashSalt;
5740 if (hashSalt.IsNull())
5741 hashSalt = GetRandHash();
5742 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5743 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5744 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5748 vInvWait.push_back(inv);
5753 // returns true if wasn't already contained in the set
5754 if (pto->setInventoryKnown.insert(inv).second)
5756 vInv.push_back(inv);
5757 if (vInv.size() >= 1000)
5759 pto->PushMessage("inv", vInv);
5764 pto->vInventoryToSend = vInvWait;
5767 pto->PushMessage("inv", vInv);
5769 // Detect whether we're stalling
5770 int64_t nNow = GetTimeMicros();
5771 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5772 // Stalling only triggers when the block download window cannot move. During normal steady state,
5773 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5774 // should only happen during initial block download.
5775 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5776 pto->fDisconnect = true;
5778 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5779 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5780 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5781 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5782 // to unreasonably increase our timeout.
5783 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5784 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5785 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5786 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5787 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5788 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5789 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5790 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5791 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5792 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5793 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5795 if (queuedBlock.nTimeDisconnect < nNow) {
5796 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5797 pto->fDisconnect = true;
5802 // Message: getdata (blocks)
5804 vector<CInv> vGetData;
5805 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5806 vector<CBlockIndex*> vToDownload;
5807 NodeId staller = -1;
5808 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5809 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5810 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5811 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5812 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5813 pindex->nHeight, pto->id);
5815 if (state.nBlocksInFlight == 0 && staller != -1) {
5816 if (State(staller)->nStallingSince == 0) {
5817 State(staller)->nStallingSince = nNow;
5818 LogPrint("net", "Stall started peer=%d\n", staller);
5824 // Message: getdata (non-blocks)
5826 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5828 const CInv& inv = (*pto->mapAskFor.begin()).second;
5829 if (!AlreadyHave(inv))
5832 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5833 vGetData.push_back(inv);
5834 if (vGetData.size() >= 1000)
5836 pto->PushMessage("getdata", vGetData);
5840 //If we're not going to ask, don't expect a response.
5841 pto->setAskFor.erase(inv.hash);
5843 pto->mapAskFor.erase(pto->mapAskFor.begin());
5845 if (!vGetData.empty())
5846 pto->PushMessage("getdata", vGetData);
5852 std::string CBlockFileInfo::ToString() const {
5853 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));
5864 BlockMap::iterator it1 = mapBlockIndex.begin();
5865 for (; it1 != mapBlockIndex.end(); it1++)
5866 delete (*it1).second;
5867 mapBlockIndex.clear();
5869 // orphan transactions
5870 mapOrphanTransactions.clear();
5871 mapOrphanTransactionsByPrev.clear();
5873 } instance_of_cmaincleanup;
5876 // Set default values of new CMutableTransaction based on consensus rules at given height.
5877 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
5879 CMutableTransaction mtx;
5881 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
5882 if (isOverwintered) {
5883 mtx.fOverwintered = true;
5884 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
5886 // Expiry height is not set. Only fields required for a parser to treat as a valid Overwinter V3 tx.
5888 // TODO: In future, when moving from Overwinter to Sapling, it will be useful
5889 // to set the expiry height to: min(activation_height - 1, default_expiry_height)