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, uint32_t consensusBranchId)
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(), consensusBranchId))
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");
889 if (!(tx.IsCoinBase() || tx.vjoinsplit.empty())) {
890 auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
891 // Empty output script.
893 uint256 dataToBeSigned;
895 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId);
896 } catch (std::logic_error ex) {
897 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
898 REJECT_INVALID, "error-computing-signature-hash");
901 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
903 // We rely on libsodium to check that the signature is canonical.
904 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
905 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
906 dataToBeSigned.begin(), 32,
907 tx.joinSplitPubKey.begin()
909 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
910 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
917 bool CheckTransaction(const CTransaction& tx, CValidationState &state,
918 libzcash::ProofVerifier& verifier)
920 // Don't count coinbase transactions because mining skews the count
921 if (!tx.IsCoinBase()) {
922 transactionsValidated.increment();
925 if (!CheckTransactionWithoutProofVerification(tx, state)) {
928 // Ensure that zk-SNARKs verify
929 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
930 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
931 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
932 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
939 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
941 // Basic checks that don't depend on any context
945 * 1. The consensus rule below was:
946 * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... }
947 * which checked if tx.nVersion fell within the range:
948 * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION
949 * 2. The parser allowed tx.nVersion to be negative
952 * 1. The consensus rule checks to see if tx.Version falls within the range:
953 * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION
954 * 2. The previous consensus rule checked for negative values within the range:
955 * INT32_MIN <= tx.nVersion < 0
956 * This is unnecessary for Overwinter transactions since the parser now
957 * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0,
958 * and when Overwinter is not active ContextualCheckTransaction rejects
959 * transactions with fOverwintered set. When fOverwintered is set,
960 * this function and ContextualCheckTransaction will together check to
961 * ensure tx.nVersion avoids the following ranges:
962 * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION
963 * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX
965 if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) {
966 return state.DoS(100, error("CheckTransaction(): version too low"),
967 REJECT_INVALID, "bad-txns-version-too-low");
969 else if (tx.fOverwintered) {
970 if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) {
971 return state.DoS(100, error("CheckTransaction(): overwinter version too low"),
972 REJECT_INVALID, "bad-tx-overwinter-version-too-low");
974 if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) {
975 return state.DoS(100, error("CheckTransaction(): unknown tx version group id"),
976 REJECT_INVALID, "bad-tx-version-group-id");
978 if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) {
979 return state.DoS(100, error("CheckTransaction(): expiry height is too high"),
980 REJECT_INVALID, "bad-tx-expiry-height-too-high");
984 // Transactions can contain empty `vin` and `vout` so long as
985 // `vjoinsplit` is non-empty.
986 if (tx.vin.empty() && tx.vjoinsplit.empty())
987 return state.DoS(10, error("CheckTransaction(): vin empty"),
988 REJECT_INVALID, "bad-txns-vin-empty");
989 if (tx.vout.empty() && tx.vjoinsplit.empty())
990 return state.DoS(10, error("CheckTransaction(): vout empty"),
991 REJECT_INVALID, "bad-txns-vout-empty");
994 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
995 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
996 return state.DoS(100, error("CheckTransaction(): size limits failed"),
997 REJECT_INVALID, "bad-txns-oversize");
999 // Check for negative or overflow output values
1000 CAmount nValueOut = 0;
1001 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1003 if (txout.nValue < 0)
1004 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
1005 REJECT_INVALID, "bad-txns-vout-negative");
1006 if (txout.nValue > MAX_MONEY)
1007 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
1008 REJECT_INVALID, "bad-txns-vout-toolarge");
1009 nValueOut += txout.nValue;
1010 if (!MoneyRange(nValueOut))
1011 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1012 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1015 // Ensure that joinsplit values are well-formed
1016 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1018 if (joinsplit.vpub_old < 0) {
1019 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
1020 REJECT_INVALID, "bad-txns-vpub_old-negative");
1023 if (joinsplit.vpub_new < 0) {
1024 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
1025 REJECT_INVALID, "bad-txns-vpub_new-negative");
1028 if (joinsplit.vpub_old > MAX_MONEY) {
1029 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
1030 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
1033 if (joinsplit.vpub_new > MAX_MONEY) {
1034 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
1035 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
1038 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
1039 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
1040 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
1043 nValueOut += joinsplit.vpub_old;
1044 if (!MoneyRange(nValueOut)) {
1045 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
1046 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
1050 // Ensure input values do not exceed MAX_MONEY
1051 // We have not resolved the txin values at this stage,
1052 // but we do know what the joinsplits claim to add
1053 // to the value pool.
1055 CAmount nValueIn = 0;
1056 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
1058 nValueIn += it->vpub_new;
1060 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
1061 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
1062 REJECT_INVALID, "bad-txns-txintotal-toolarge");
1068 // Check for duplicate inputs
1069 set<COutPoint> vInOutPoints;
1070 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1072 if (vInOutPoints.count(txin.prevout))
1073 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
1074 REJECT_INVALID, "bad-txns-inputs-duplicate");
1075 vInOutPoints.insert(txin.prevout);
1078 // Check for duplicate joinsplit nullifiers in this transaction
1079 set<uint256> vJoinSplitNullifiers;
1080 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
1082 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
1084 if (vJoinSplitNullifiers.count(nf))
1085 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
1086 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
1088 vJoinSplitNullifiers.insert(nf);
1092 if (tx.IsCoinBase())
1094 // There should be no joinsplits in a coinbase transaction
1095 if (tx.vjoinsplit.size() > 0)
1096 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
1097 REJECT_INVALID, "bad-cb-has-joinsplits");
1099 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
1100 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
1101 REJECT_INVALID, "bad-cb-length");
1105 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1106 if (txin.prevout.IsNull())
1107 return state.DoS(10, error("CheckTransaction(): prevout is null"),
1108 REJECT_INVALID, "bad-txns-prevout-null");
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 int nextBlockHeight = chainActive.Height() + 1;
1152 auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus());
1154 // Node operator can choose to reject tx by number of transparent inputs
1155 static_assert(std::numeric_limits<size_t>::max() >= std::numeric_limits<int64_t>::max(), "size_t too small");
1156 size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0);
1158 size_t n = tx.vin.size();
1160 LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit );
1165 auto verifier = libzcash::ProofVerifier::Strict();
1166 if (!CheckTransaction(tx, state, verifier))
1167 return error("AcceptToMemoryPool: CheckTransaction failed");
1169 // DoS level set to 10 to be more forgiving.
1170 // Check transaction contextually against the set of consensus rules which apply in the next block to be mined.
1171 if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) {
1172 return error("AcceptToMemoryPool: ContextualCheckTransaction failed");
1175 // Coinbase is only valid in a block, not as a loose transaction
1176 if (tx.IsCoinBase())
1177 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1178 REJECT_INVALID, "coinbase");
1180 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1182 if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight))
1184 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1185 REJECT_NONSTANDARD, reason);
1187 // Only accept nLockTime-using transactions that can be mined in the next
1188 // block; we don't want our mempool filled up with transactions that can't
1190 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1191 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1193 // is it already in the memory pool?
1194 uint256 hash = tx.GetHash();
1195 if (pool.exists(hash))
1198 // Check for conflicts with in-memory transactions
1200 LOCK(pool.cs); // protect pool.mapNextTx
1201 for (unsigned int i = 0; i < tx.vin.size(); i++)
1203 COutPoint outpoint = tx.vin[i].prevout;
1204 if (pool.mapNextTx.count(outpoint))
1206 // Disable replacement feature for now
1210 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1211 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1212 if (pool.mapNullifiers.count(nf))
1222 CCoinsViewCache view(&dummy);
1224 CAmount nValueIn = 0;
1227 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1228 view.SetBackend(viewMemPool);
1230 // do we already have it?
1231 if (view.HaveCoins(hash))
1234 // do all inputs exist?
1235 // Note that this does not check for the presence of actual outputs (see the next check for that),
1236 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1237 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1238 if (!view.HaveCoins(txin.prevout.hash)) {
1239 if (pfMissingInputs)
1240 *pfMissingInputs = true;
1245 // are the actual inputs available?
1246 if (!view.HaveInputs(tx))
1247 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1248 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1250 // are the joinsplit's requirements met?
1251 if (!view.HaveJoinSplitRequirements(tx))
1252 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1253 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1255 // Bring the best block into scope
1256 view.GetBestBlock();
1258 nValueIn = view.GetValueIn(tx);
1260 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1261 view.SetBackend(dummy);
1264 // Check for non-standard pay-to-script-hash in inputs
1265 if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId))
1266 return error("AcceptToMemoryPool: nonstandard transaction input");
1268 // Check that the transaction doesn't have an excessive number of
1269 // sigops, making it impossible to mine. Since the coinbase transaction
1270 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1271 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1272 // merely non-standard transaction.
1273 unsigned int nSigOps = GetLegacySigOpCount(tx);
1274 nSigOps += GetP2SHSigOpCount(tx, view);
1275 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1277 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1278 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1279 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1281 CAmount nValueOut = tx.GetValueOut();
1282 CAmount nFees = nValueIn-nValueOut;
1283 double dPriority = view.GetPriority(tx, chainActive.Height());
1285 // Keep track of transactions that spend a coinbase, which we re-scan
1286 // during reorgs to ensure COINBASE_MATURITY is still met.
1287 bool fSpendsCoinbase = false;
1288 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1289 const CCoins *coins = view.AccessCoins(txin.prevout.hash);
1290 if (coins->IsCoinBase()) {
1291 fSpendsCoinbase = true;
1296 // Grab the branch ID we expect this transaction to commit to. We don't
1297 // yet know if it does, but if the entry gets added to the mempool, then
1298 // it has passed ContextualCheckInputs and therefore this is correct.
1299 auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus());
1301 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId);
1302 unsigned int nSize = entry.GetTxSize();
1304 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1305 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1306 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1308 // Don't accept it if it can't get into a block
1309 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1310 if (fLimitFree && nFees < txMinFee)
1311 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1312 hash.ToString(), nFees, txMinFee),
1313 REJECT_INSUFFICIENTFEE, "insufficient fee");
1316 // Require that free transactions have sufficient priority to be mined in the next block.
1317 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1318 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1321 // Continuously rate-limit free (really, very-low-fee) transactions
1322 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1323 // be annoying or make others' transactions take longer to confirm.
1324 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1326 static CCriticalSection csFreeLimiter;
1327 static double dFreeCount;
1328 static int64_t nLastTime;
1329 int64_t nNow = GetTime();
1331 LOCK(csFreeLimiter);
1333 // Use an exponentially decaying ~10-minute window:
1334 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1336 // -limitfreerelay unit is thousand-bytes-per-minute
1337 // At default rate it would take over a month to fill 1GB
1338 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1339 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1340 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1341 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1342 dFreeCount += nSize;
1345 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1346 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1348 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1350 // Check against previous transactions
1351 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1352 PrecomputedTransactionData txdata(tx);
1353 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1355 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1358 // Check again against just the consensus-critical mandatory script
1359 // verification flags, in case of bugs in the standard flags that cause
1360 // transactions to pass as valid when they're actually invalid. For
1361 // instance the STRICTENC flag was incorrectly allowing certain
1362 // CHECKSIG NOT scripts to pass, even though they were invalid.
1364 // There is a similar check in CreateNewBlock() to prevent creating
1365 // invalid blocks, however allowing such transactions into the mempool
1366 // can be exploited as a DoS attack.
1367 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId))
1369 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1372 // Store transaction in memory
1373 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1376 SyncWithWallets(tx, NULL);
1381 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1382 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1384 CBlockIndex *pindexSlow = NULL;
1388 if (mempool.lookup(hash, txOut))
1395 if (pblocktree->ReadTxIndex(hash, postx)) {
1396 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1398 return error("%s: OpenBlockFile failed", __func__);
1399 CBlockHeader header;
1402 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1404 } catch (const std::exception& e) {
1405 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1407 hashBlock = header.GetHash();
1408 if (txOut.GetHash() != hash)
1409 return error("%s: txid mismatch", __func__);
1414 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1417 CCoinsViewCache &view = *pcoinsTip;
1418 const CCoins* coins = view.AccessCoins(hash);
1420 nHeight = coins->nHeight;
1423 pindexSlow = chainActive[nHeight];
1428 if (ReadBlockFromDisk(block, pindexSlow)) {
1429 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1430 if (tx.GetHash() == hash) {
1432 hashBlock = pindexSlow->GetBlockHash();
1447 //////////////////////////////////////////////////////////////////////////////
1449 // CBlock and CBlockIndex
1452 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1454 // Open history file to append
1455 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1456 if (fileout.IsNull())
1457 return error("WriteBlockToDisk: OpenBlockFile failed");
1459 // Write index header
1460 unsigned int nSize = fileout.GetSerializeSize(block);
1461 fileout << FLATDATA(messageStart) << nSize;
1464 long fileOutPos = ftell(fileout.Get());
1466 return error("WriteBlockToDisk: ftell failed");
1467 pos.nPos = (unsigned int)fileOutPos;
1473 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1477 // Open history file to read
1478 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1479 if (filein.IsNull())
1480 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1486 catch (const std::exception& e) {
1487 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1491 if (!(CheckEquihashSolution(&block, Params()) &&
1492 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1493 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1498 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1500 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1502 if (block.GetHash() != pindex->GetBlockHash())
1503 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1504 pindex->ToString(), pindex->GetBlockPos().ToString());
1508 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1510 CAmount nSubsidy = 12.5 * COIN;
1512 // Mining slow start
1513 // The subsidy is ramped up linearly, skipping the middle payout of
1514 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1515 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1516 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1517 nSubsidy *= nHeight;
1519 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1520 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1521 nSubsidy *= (nHeight+1);
1525 assert(nHeight > consensusParams.SubsidySlowStartShift());
1526 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1527 // Force block reward to zero when right shift is undefined.
1531 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1532 nSubsidy >>= halvings;
1536 bool IsInitialBlockDownload()
1538 const CChainParams& chainParams = Params();
1540 if (fImporting || fReindex)
1542 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1544 static bool lockIBDState = false;
1547 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1548 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1550 lockIBDState = true;
1554 bool fLargeWorkForkFound = false;
1555 bool fLargeWorkInvalidChainFound = false;
1556 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1558 void CheckForkWarningConditions()
1560 AssertLockHeld(cs_main);
1561 // Before we get past initial download, we cannot reliably alert about forks
1562 // (we assume we don't get stuck on a fork before the last checkpoint)
1563 if (IsInitialBlockDownload())
1566 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1567 // of our head, drop it
1568 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1569 pindexBestForkTip = NULL;
1571 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1573 if (!fLargeWorkForkFound && pindexBestForkBase)
1575 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1576 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1577 CAlert::Notify(warning, true);
1579 if (pindexBestForkTip && pindexBestForkBase)
1581 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__,
1582 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1583 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1584 fLargeWorkForkFound = true;
1588 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1589 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1590 CAlert::Notify(warning, true);
1591 fLargeWorkInvalidChainFound = true;
1596 fLargeWorkForkFound = false;
1597 fLargeWorkInvalidChainFound = false;
1601 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1603 AssertLockHeld(cs_main);
1604 // If we are on a fork that is sufficiently large, set a warning flag
1605 CBlockIndex* pfork = pindexNewForkTip;
1606 CBlockIndex* plonger = chainActive.Tip();
1607 while (pfork && pfork != plonger)
1609 while (plonger && plonger->nHeight > pfork->nHeight)
1610 plonger = plonger->pprev;
1611 if (pfork == plonger)
1613 pfork = pfork->pprev;
1616 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1617 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1618 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1619 // hash rate operating on the fork.
1620 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1621 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1622 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1623 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1624 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1625 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1627 pindexBestForkTip = pindexNewForkTip;
1628 pindexBestForkBase = pfork;
1631 CheckForkWarningConditions();
1634 // Requires cs_main.
1635 void Misbehaving(NodeId pnode, int howmuch)
1640 CNodeState *state = State(pnode);
1644 state->nMisbehavior += howmuch;
1645 int banscore = GetArg("-banscore", 100);
1646 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1648 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1649 state->fShouldBan = true;
1651 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1654 void static InvalidChainFound(CBlockIndex* pindexNew)
1656 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1657 pindexBestInvalid = pindexNew;
1659 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1660 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1661 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1662 pindexNew->GetBlockTime()));
1663 CBlockIndex *tip = chainActive.Tip();
1665 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1666 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1667 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1668 CheckForkWarningConditions();
1671 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1673 if (state.IsInvalid(nDoS)) {
1674 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1675 if (it != mapBlockSource.end() && State(it->second)) {
1676 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1677 State(it->second)->rejects.push_back(reject);
1679 Misbehaving(it->second, nDoS);
1682 if (!state.CorruptionPossible()) {
1683 pindex->nStatus |= BLOCK_FAILED_VALID;
1684 setDirtyBlockIndex.insert(pindex);
1685 setBlockIndexCandidates.erase(pindex);
1686 InvalidChainFound(pindex);
1690 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
1692 // mark inputs spent
1693 if (!tx.IsCoinBase()) {
1694 txundo.vprevout.reserve(tx.vin.size());
1695 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1696 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1697 unsigned nPos = txin.prevout.n;
1699 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1701 // mark an outpoint spent, and construct undo information
1702 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1704 if (coins->vout.size() == 0) {
1705 CTxInUndo& undo = txundo.vprevout.back();
1706 undo.nHeight = coins->nHeight;
1707 undo.fCoinBase = coins->fCoinBase;
1708 undo.nVersion = coins->nVersion;
1714 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1715 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1716 inputs.SetNullifier(nf, true);
1721 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1724 void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
1727 UpdateCoins(tx, inputs, txundo, nHeight);
1730 bool CScriptCheck::operator()() {
1731 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1732 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) {
1733 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1738 int GetSpendHeight(const CCoinsViewCache& inputs)
1741 CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1742 return pindexPrev->nHeight + 1;
1745 namespace Consensus {
1746 bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams)
1748 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1749 // for an attacker to attempt to split the network.
1750 if (!inputs.HaveInputs(tx))
1751 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1753 // are the JoinSplit's requirements met?
1754 if (!inputs.HaveJoinSplitRequirements(tx))
1755 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1757 CAmount nValueIn = 0;
1759 for (unsigned int i = 0; i < tx.vin.size(); i++)
1761 const COutPoint &prevout = tx.vin[i].prevout;
1762 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1765 if (coins->IsCoinBase()) {
1766 // Ensure that coinbases are matured
1767 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1768 return state.Invalid(
1769 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1770 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1773 // Ensure that coinbases cannot be spent to transparent outputs
1774 // Disabled on regtest
1775 if (fCoinbaseEnforcedProtectionEnabled &&
1776 consensusParams.fCoinbaseMustBeProtected &&
1778 return state.Invalid(
1779 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1780 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1784 // Check for negative or overflow input values
1785 nValueIn += coins->vout[prevout.n].nValue;
1786 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1787 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1788 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1792 nValueIn += tx.GetJoinSplitValueIn();
1793 if (!MoneyRange(nValueIn))
1794 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1795 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1797 if (nValueIn < tx.GetValueOut())
1798 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1799 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1800 REJECT_INVALID, "bad-txns-in-belowout");
1802 // Tally transaction fees
1803 CAmount nTxFee = nValueIn - tx.GetValueOut();
1805 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1806 REJECT_INVALID, "bad-txns-fee-negative");
1808 if (!MoneyRange(nFees))
1809 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1810 REJECT_INVALID, "bad-txns-fee-outofrange");
1813 }// namespace Consensus
1815 bool ContextualCheckInputs(
1816 const CTransaction& tx,
1817 CValidationState &state,
1818 const CCoinsViewCache &inputs,
1822 PrecomputedTransactionData& txdata,
1823 const Consensus::Params& consensusParams,
1824 uint32_t consensusBranchId,
1825 std::vector<CScriptCheck> *pvChecks)
1827 if (!tx.IsCoinBase())
1829 if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) {
1834 pvChecks->reserve(tx.vin.size());
1836 // The first loop above does all the inexpensive checks.
1837 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1838 // Helps prevent CPU exhaustion attacks.
1840 // Skip ECDSA signature verification when connecting blocks
1841 // before the last block chain checkpoint. This is safe because block merkle hashes are
1842 // still computed and checked, and any change will be caught at the next checkpoint.
1843 if (fScriptChecks) {
1844 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1845 const COutPoint &prevout = tx.vin[i].prevout;
1846 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1850 CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata);
1852 pvChecks->push_back(CScriptCheck());
1853 check.swap(pvChecks->back());
1854 } else if (!check()) {
1855 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1856 // Check whether the failure was caused by a
1857 // non-mandatory script verification check, such as
1858 // non-standard DER encodings or non-null dummy
1859 // arguments; if so, don't trigger DoS protection to
1860 // avoid splitting the network between upgraded and
1861 // non-upgraded nodes.
1862 CScriptCheck check2(*coins, tx, i,
1863 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata);
1865 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1867 // Failures of other flags indicate a transaction that is
1868 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1869 // such nodes as they are not following the protocol. That
1870 // said during an upgrade careful thought should be taken
1871 // as to the correct behavior - we may want to continue
1872 // peering with non-upgraded nodes even after a soft-fork
1873 // super-majority vote has passed.
1874 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1885 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1887 // Open history file to append
1888 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1889 if (fileout.IsNull())
1890 return error("%s: OpenUndoFile failed", __func__);
1892 // Write index header
1893 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1894 fileout << FLATDATA(messageStart) << nSize;
1897 long fileOutPos = ftell(fileout.Get());
1899 return error("%s: ftell failed", __func__);
1900 pos.nPos = (unsigned int)fileOutPos;
1901 fileout << blockundo;
1903 // calculate & write checksum
1904 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1905 hasher << hashBlock;
1906 hasher << blockundo;
1907 fileout << hasher.GetHash();
1912 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1914 // Open history file to read
1915 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1916 if (filein.IsNull())
1917 return error("%s: OpenBlockFile failed", __func__);
1920 uint256 hashChecksum;
1922 filein >> blockundo;
1923 filein >> hashChecksum;
1925 catch (const std::exception& e) {
1926 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1930 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1931 hasher << hashBlock;
1932 hasher << blockundo;
1933 if (hashChecksum != hasher.GetHash())
1934 return error("%s: Checksum mismatch", __func__);
1939 /** Abort with a message */
1940 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1942 strMiscWarning = strMessage;
1943 LogPrintf("*** %s\n", strMessage);
1944 uiInterface.ThreadSafeMessageBox(
1945 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1946 "", CClientUIInterface::MSG_ERROR);
1951 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1953 AbortNode(strMessage, userMessage);
1954 return state.Error(strMessage);
1960 * Apply the undo operation of a CTxInUndo to the given chain state.
1961 * @param undo The undo object.
1962 * @param view The coins view to which to apply the changes.
1963 * @param out The out point that corresponds to the tx input.
1964 * @return True on success.
1966 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1970 CCoinsModifier coins = view.ModifyCoins(out.hash);
1971 if (undo.nHeight != 0) {
1972 // undo data contains height: this is the last output of the prevout tx being spent
1973 if (!coins->IsPruned())
1974 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1976 coins->fCoinBase = undo.fCoinBase;
1977 coins->nHeight = undo.nHeight;
1978 coins->nVersion = undo.nVersion;
1980 if (coins->IsPruned())
1981 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1983 if (coins->IsAvailable(out.n))
1984 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1985 if (coins->vout.size() < out.n+1)
1986 coins->vout.resize(out.n+1);
1987 coins->vout[out.n] = undo.txout;
1992 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1994 assert(pindex->GetBlockHash() == view.GetBestBlock());
2001 CBlockUndo blockUndo;
2002 CDiskBlockPos pos = pindex->GetUndoPos();
2004 return error("DisconnectBlock(): no undo data available");
2005 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
2006 return error("DisconnectBlock(): failure reading undo data");
2008 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
2009 return error("DisconnectBlock(): block and undo data inconsistent");
2011 // undo transactions in reverse order
2012 for (int i = block.vtx.size() - 1; i >= 0; i--) {
2013 const CTransaction &tx = block.vtx[i];
2014 uint256 hash = tx.GetHash();
2016 // Check that all outputs are available and match the outputs in the block itself
2019 CCoinsModifier outs = view.ModifyCoins(hash);
2020 outs->ClearUnspendable();
2022 CCoins outsBlock(tx, pindex->nHeight);
2023 // The CCoins serialization does not serialize negative numbers.
2024 // No network rules currently depend on the version here, so an inconsistency is harmless
2025 // but it must be corrected before txout nversion ever influences a network rule.
2026 if (outsBlock.nVersion < 0)
2027 outs->nVersion = outsBlock.nVersion;
2028 if (*outs != outsBlock)
2029 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
2035 // unspend nullifiers
2036 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2037 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
2038 view.SetNullifier(nf, false);
2043 if (i > 0) { // not coinbases
2044 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
2045 if (txundo.vprevout.size() != tx.vin.size())
2046 return error("DisconnectBlock(): transaction and undo data inconsistent");
2047 for (unsigned int j = tx.vin.size(); j-- > 0;) {
2048 const COutPoint &out = tx.vin[j].prevout;
2049 const CTxInUndo &undo = txundo.vprevout[j];
2050 if (!ApplyTxInUndo(undo, view, out))
2056 // set the old best anchor back
2057 view.PopAnchor(blockUndo.old_tree_root);
2059 // move best block pointer to prevout block
2060 view.SetBestBlock(pindex->pprev->GetBlockHash());
2070 void static FlushBlockFile(bool fFinalize = false)
2072 LOCK(cs_LastBlockFile);
2074 CDiskBlockPos posOld(nLastBlockFile, 0);
2076 FILE *fileOld = OpenBlockFile(posOld);
2079 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
2080 FileCommit(fileOld);
2084 fileOld = OpenUndoFile(posOld);
2087 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
2088 FileCommit(fileOld);
2093 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
2095 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
2097 void ThreadScriptCheck() {
2098 RenameThread("zcash-scriptch");
2099 scriptcheckqueue.Thread();
2103 // Called periodically asynchronously; alerts if it smells like
2104 // we're being fed a bad chain (blocks being generated much
2105 // too slowly or too quickly).
2107 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
2108 int64_t nPowTargetSpacing)
2110 if (bestHeader == NULL || initialDownloadCheck()) return;
2112 static int64_t lastAlertTime = 0;
2113 int64_t now = GetAdjustedTime();
2114 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
2116 const int SPAN_HOURS=4;
2117 const int SPAN_SECONDS=SPAN_HOURS*60*60;
2118 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
2120 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
2122 std::string strWarning;
2123 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
2126 const CBlockIndex* i = bestHeader;
2128 while (i->GetBlockTime() >= startTime) {
2131 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2134 // How likely is it to find that many by chance?
2135 double p = boost::math::pdf(poisson, nBlocks);
2137 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2138 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2140 // Aim for one false-positive about every fifty years of normal running:
2141 const int FIFTY_YEARS = 50*365*24*60*60;
2142 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2144 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2146 // Many fewer blocks than expected: alert!
2147 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2148 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2150 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2152 // Many more blocks than expected: alert!
2153 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2154 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2156 if (!strWarning.empty())
2158 strMiscWarning = strWarning;
2159 CAlert::Notify(strWarning, true);
2160 lastAlertTime = now;
2164 static int64_t nTimeVerify = 0;
2165 static int64_t nTimeConnect = 0;
2166 static int64_t nTimeIndex = 0;
2167 static int64_t nTimeCallbacks = 0;
2168 static int64_t nTimeTotal = 0;
2170 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2172 const CChainParams& chainparams = Params();
2173 AssertLockHeld(cs_main);
2175 bool fExpensiveChecks = true;
2176 if (fCheckpointsEnabled) {
2177 CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints());
2178 if (pindexLastCheckpoint && pindexLastCheckpoint->GetAncestor(pindex->nHeight) == pindex) {
2179 // This block is an ancestor of a checkpoint: disable script checks
2180 fExpensiveChecks = false;
2184 auto verifier = libzcash::ProofVerifier::Strict();
2185 auto disabledVerifier = libzcash::ProofVerifier::Disabled();
2187 // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in
2188 if (!CheckBlock(block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck))
2191 // verify that the view's current state corresponds to the previous block
2192 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2193 assert(hashPrevBlock == view.GetBestBlock());
2195 // Special case for the genesis block, skipping connection of its transactions
2196 // (its coinbase is unspendable)
2197 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2199 view.SetBestBlock(pindex->GetBlockHash());
2200 // Before the genesis block, there was an empty tree
2201 ZCIncrementalMerkleTree tree;
2202 pindex->hashAnchor = tree.root();
2203 // The genesis block contained no JoinSplits
2204 pindex->hashAnchorEnd = pindex->hashAnchor;
2209 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2210 // unless those are already completely spent.
2211 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2212 const CCoins* coins = view.AccessCoins(tx.GetHash());
2213 if (coins && !coins->IsPruned())
2214 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2215 REJECT_INVALID, "bad-txns-BIP30");
2218 unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2220 // DERSIG (BIP66) is also always enforced, but does not have a flag.
2222 CBlockUndo blockundo;
2224 CCheckQueueControl<CScriptCheck> control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2226 int64_t nTimeStart = GetTimeMicros();
2229 unsigned int nSigOps = 0;
2230 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2231 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2232 vPos.reserve(block.vtx.size());
2233 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2235 // Construct the incremental merkle tree at the current
2237 auto old_tree_root = view.GetBestAnchor();
2238 // saving the top anchor in the block index as we go.
2240 pindex->hashAnchor = old_tree_root;
2242 ZCIncrementalMerkleTree tree;
2243 // This should never fail: we should always be able to get the root
2244 // that is on the tip of our chain
2245 assert(view.GetAnchorAt(old_tree_root, tree));
2248 // Consistency check: the root of the tree we're given should
2249 // match what we asked for.
2250 assert(tree.root() == old_tree_root);
2253 // Grab the consensus branch ID for the block's height
2254 auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus());
2256 std::vector<PrecomputedTransactionData> txdata;
2257 txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
2258 for (unsigned int i = 0; i < block.vtx.size(); i++)
2260 const CTransaction &tx = block.vtx[i];
2262 nInputs += tx.vin.size();
2263 nSigOps += GetLegacySigOpCount(tx);
2264 if (nSigOps > MAX_BLOCK_SIGOPS)
2265 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2266 REJECT_INVALID, "bad-blk-sigops");
2268 if (!tx.IsCoinBase())
2270 if (!view.HaveInputs(tx))
2271 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2272 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2274 // are the JoinSplit's requirements met?
2275 if (!view.HaveJoinSplitRequirements(tx))
2276 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2277 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2279 // Add in sigops done by pay-to-script-hash inputs;
2280 // this is to prevent a "rogue miner" from creating
2281 // an incredibly-expensive-to-validate block.
2282 nSigOps += GetP2SHSigOpCount(tx, view);
2283 if (nSigOps > MAX_BLOCK_SIGOPS)
2284 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2285 REJECT_INVALID, "bad-blk-sigops");
2288 txdata.emplace_back(tx);
2290 if (!tx.IsCoinBase())
2292 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2294 std::vector<CScriptCheck> vChecks;
2295 if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL))
2297 control.Add(vChecks);
2302 blockundo.vtxundo.push_back(CTxUndo());
2304 UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2306 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2307 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2308 // Insert the note commitments into our temporary tree.
2310 tree.append(note_commitment);
2314 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2315 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2318 view.PushAnchor(tree);
2320 pindex->hashAnchorEnd = tree.root();
2322 blockundo.old_tree_root = old_tree_root;
2324 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2325 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);
2327 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2328 if (block.vtx[0].GetValueOut() > blockReward)
2329 return state.DoS(100,
2330 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2331 block.vtx[0].GetValueOut(), blockReward),
2332 REJECT_INVALID, "bad-cb-amount");
2334 if (!control.Wait())
2335 return state.DoS(100, false);
2336 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2337 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);
2342 // Write undo information to disk
2343 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2345 if (pindex->GetUndoPos().IsNull()) {
2347 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2348 return error("ConnectBlock(): FindUndoPos failed");
2349 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2350 return AbortNode(state, "Failed to write undo data");
2352 // update nUndoPos in block index
2353 pindex->nUndoPos = pos.nPos;
2354 pindex->nStatus |= BLOCK_HAVE_UNDO;
2357 // Now that all consensus rules have been validated, set nCachedBranchId.
2358 // Move this if BLOCK_VALID_CONSENSUS is ever altered.
2359 static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS,
2360 "nCachedBranchId must be set after all consensus rules have been validated.");
2361 if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) {
2362 pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE;
2363 pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus());
2364 } else if (pindex->pprev) {
2365 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
2368 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2369 setDirtyBlockIndex.insert(pindex);
2373 if (!pblocktree->WriteTxIndex(vPos))
2374 return AbortNode(state, "Failed to write transaction index");
2376 // add this block to the view's block chain
2377 view.SetBestBlock(pindex->GetBlockHash());
2379 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2380 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2382 // Watch for changes to the previous coinbase transaction.
2383 static uint256 hashPrevBestCoinBase;
2384 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2385 hashPrevBestCoinBase = block.vtx[0].GetHash();
2387 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2388 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2393 enum FlushStateMode {
2395 FLUSH_STATE_IF_NEEDED,
2396 FLUSH_STATE_PERIODIC,
2401 * Update the on-disk chain state.
2402 * The caches and indexes are flushed depending on the mode we're called with
2403 * if they're too large, if it's been a while since the last write,
2404 * or always and in all cases if we're in prune mode and are deleting files.
2406 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2407 LOCK2(cs_main, cs_LastBlockFile);
2408 static int64_t nLastWrite = 0;
2409 static int64_t nLastFlush = 0;
2410 static int64_t nLastSetChain = 0;
2411 std::set<int> setFilesToPrune;
2412 bool fFlushForPrune = false;
2414 if (fPruneMode && fCheckForPruning && !fReindex) {
2415 FindFilesToPrune(setFilesToPrune);
2416 fCheckForPruning = false;
2417 if (!setFilesToPrune.empty()) {
2418 fFlushForPrune = true;
2420 pblocktree->WriteFlag("prunedblockfiles", true);
2425 int64_t nNow = GetTimeMicros();
2426 // Avoid writing/flushing immediately after startup.
2427 if (nLastWrite == 0) {
2430 if (nLastFlush == 0) {
2433 if (nLastSetChain == 0) {
2434 nLastSetChain = nNow;
2436 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2437 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2438 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2439 // The cache is over the limit, we have to write now.
2440 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2441 // 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.
2442 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2443 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2444 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2445 // Combine all conditions that result in a full cache flush.
2446 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2447 // Write blocks and block index to disk.
2448 if (fDoFullFlush || fPeriodicWrite) {
2449 // Depend on nMinDiskSpace to ensure we can write block index
2450 if (!CheckDiskSpace(0))
2451 return state.Error("out of disk space");
2452 // First make sure all block and undo data is flushed to disk.
2454 // Then update all block file information (which may refer to block and undo files).
2456 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2457 vFiles.reserve(setDirtyFileInfo.size());
2458 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2459 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2460 setDirtyFileInfo.erase(it++);
2462 std::vector<const CBlockIndex*> vBlocks;
2463 vBlocks.reserve(setDirtyBlockIndex.size());
2464 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2465 vBlocks.push_back(*it);
2466 setDirtyBlockIndex.erase(it++);
2468 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2469 return AbortNode(state, "Files to write to block index database");
2472 // Finally remove any pruned files
2474 UnlinkPrunedFiles(setFilesToPrune);
2477 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2479 // Typical CCoins structures on disk are around 128 bytes in size.
2480 // Pushing a new one to the database can cause it to be written
2481 // twice (once in the log, and once in the tables). This is already
2482 // an overestimation, as most will delete an existing entry or
2483 // overwrite one. Still, use a conservative safety factor of 2.
2484 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2485 return state.Error("out of disk space");
2486 // Flush the chainstate (which may refer to block index entries).
2487 if (!pcoinsTip->Flush())
2488 return AbortNode(state, "Failed to write to coin database");
2491 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2492 // Update best block in wallet (so we can detect restored wallets).
2493 GetMainSignals().SetBestChain(chainActive.GetLocator());
2494 nLastSetChain = nNow;
2496 } catch (const std::runtime_error& e) {
2497 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2502 void FlushStateToDisk() {
2503 CValidationState state;
2504 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2507 void PruneAndFlush() {
2508 CValidationState state;
2509 fCheckForPruning = true;
2510 FlushStateToDisk(state, FLUSH_STATE_NONE);
2513 /** Update chainActive and related internal data structures. */
2514 void static UpdateTip(CBlockIndex *pindexNew) {
2515 const CChainParams& chainParams = Params();
2516 chainActive.SetTip(pindexNew);
2519 nTimeBestReceived = GetTime();
2520 mempool.AddTransactionsUpdated(1);
2522 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2523 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2524 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2525 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2527 cvBlockChange.notify_all();
2529 // Check the version of the last 100 blocks to see if we need to upgrade:
2530 static bool fWarned = false;
2531 if (!IsInitialBlockDownload() && !fWarned)
2534 const CBlockIndex* pindex = chainActive.Tip();
2535 for (int i = 0; i < 100 && pindex != NULL; i++)
2537 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2539 pindex = pindex->pprev;
2542 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2543 if (nUpgraded > 100/2)
2545 // strMiscWarning is read by GetWarnings(), called by the JSON-RPC code to warn the user:
2546 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2547 CAlert::Notify(strMiscWarning, true);
2554 * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and
2555 * mempool.removeWithoutBranchId after this, with cs_main held.
2557 bool static DisconnectTip(CValidationState &state, bool fBare = false) {
2558 CBlockIndex *pindexDelete = chainActive.Tip();
2559 assert(pindexDelete);
2560 // Read block from disk.
2562 if (!ReadBlockFromDisk(block, pindexDelete))
2563 return AbortNode(state, "Failed to read block");
2564 // Apply the block atomically to the chain state.
2565 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2566 int64_t nStart = GetTimeMicros();
2568 CCoinsViewCache view(pcoinsTip);
2569 if (!DisconnectBlock(block, state, pindexDelete, view))
2570 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2571 assert(view.Flush());
2573 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2574 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2575 // Write the chain state to disk, if necessary.
2576 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2580 // Resurrect mempool transactions from the disconnected block.
2581 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2582 // ignore validation errors in resurrected transactions
2583 list<CTransaction> removed;
2584 CValidationState stateDummy;
2585 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2586 mempool.remove(tx, removed, true);
2588 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2589 // The anchor may not change between block disconnects,
2590 // in which case we don't want to evict from the mempool yet!
2591 mempool.removeWithAnchor(anchorBeforeDisconnect);
2595 // Update chainActive and related variables.
2596 UpdateTip(pindexDelete->pprev);
2597 // Get the current commitment tree
2598 ZCIncrementalMerkleTree newTree;
2599 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2600 // Let wallets know transactions went from 1-confirmed to
2601 // 0-confirmed or conflicted:
2602 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2603 SyncWithWallets(tx, NULL);
2605 // Update cached incremental witnesses
2606 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2610 static int64_t nTimeReadFromDisk = 0;
2611 static int64_t nTimeConnectTotal = 0;
2612 static int64_t nTimeFlush = 0;
2613 static int64_t nTimeChainState = 0;
2614 static int64_t nTimePostConnect = 0;
2617 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2618 * corresponding to pindexNew, to bypass loading it again from disk.
2619 * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held.
2621 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2622 assert(pindexNew->pprev == chainActive.Tip());
2623 // Read block from disk.
2624 int64_t nTime1 = GetTimeMicros();
2627 if (!ReadBlockFromDisk(block, pindexNew))
2628 return AbortNode(state, "Failed to read block");
2631 // Get the current commitment tree
2632 ZCIncrementalMerkleTree oldTree;
2633 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2634 // Apply the block atomically to the chain state.
2635 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2637 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2639 CCoinsViewCache view(pcoinsTip);
2640 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2641 GetMainSignals().BlockChecked(*pblock, state);
2643 if (state.IsInvalid())
2644 InvalidBlockFound(pindexNew, state);
2645 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2647 mapBlockSource.erase(pindexNew->GetBlockHash());
2648 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2649 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2650 assert(view.Flush());
2652 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2653 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2654 // Write the chain state to disk, if necessary.
2655 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2657 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2658 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2659 // Remove conflicting transactions from the mempool.
2660 list<CTransaction> txConflicted;
2661 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2662 // Update chainActive & related variables.
2663 UpdateTip(pindexNew);
2664 // Tell wallet about transactions that went from mempool
2666 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2667 SyncWithWallets(tx, NULL);
2669 // ... and about transactions that got confirmed:
2670 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2671 SyncWithWallets(tx, pblock);
2673 // Update cached incremental witnesses
2674 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2676 EnforceNodeDeprecation(pindexNew->nHeight);
2678 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2679 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2680 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2685 * Return the tip of the chain with the most work in it, that isn't
2686 * known to be invalid (it's however far from certain to be valid).
2688 static CBlockIndex* FindMostWorkChain() {
2690 CBlockIndex *pindexNew = NULL;
2692 // Find the best candidate header.
2694 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2695 if (it == setBlockIndexCandidates.rend())
2700 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2701 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2702 CBlockIndex *pindexTest = pindexNew;
2703 bool fInvalidAncestor = false;
2704 while (pindexTest && !chainActive.Contains(pindexTest)) {
2705 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2707 // Pruned nodes may have entries in setBlockIndexCandidates for
2708 // which block files have been deleted. Remove those as candidates
2709 // for the most work chain if we come across them; we can't switch
2710 // to a chain unless we have all the non-active-chain parent blocks.
2711 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2712 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2713 if (fFailedChain || fMissingData) {
2714 // Candidate chain is not usable (either invalid or missing data)
2715 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2716 pindexBestInvalid = pindexNew;
2717 CBlockIndex *pindexFailed = pindexNew;
2718 // Remove the entire chain from the set.
2719 while (pindexTest != pindexFailed) {
2721 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2722 } else if (fMissingData) {
2723 // If we're missing data, then add back to mapBlocksUnlinked,
2724 // so that if the block arrives in the future we can try adding
2725 // to setBlockIndexCandidates again.
2726 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2728 setBlockIndexCandidates.erase(pindexFailed);
2729 pindexFailed = pindexFailed->pprev;
2731 setBlockIndexCandidates.erase(pindexTest);
2732 fInvalidAncestor = true;
2735 pindexTest = pindexTest->pprev;
2737 if (!fInvalidAncestor)
2742 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2743 static void PruneBlockIndexCandidates() {
2744 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2745 // reorganization to a better block fails.
2746 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2747 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2748 setBlockIndexCandidates.erase(it++);
2750 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2751 assert(!setBlockIndexCandidates.empty());
2755 * Try to make some progress towards making pindexMostWork the active block.
2756 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2758 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2759 AssertLockHeld(cs_main);
2760 bool fInvalidFound = false;
2761 const CBlockIndex *pindexOldTip = chainActive.Tip();
2762 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2764 // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks.
2765 // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain,
2766 // then pindexFork will be null, and we would need to remove the entire chain including
2767 // our genesis block. In practice this (probably) won't happen because of checks elsewhere.
2768 auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0;
2769 static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance");
2770 if (reorgLength > MAX_REORG_LENGTH) {
2771 auto msg = strprintf(_(
2772 "A block chain reorganization has been detected that would roll back %d blocks! "
2773 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
2774 ), reorgLength, MAX_REORG_LENGTH) + "\n\n" +
2775 _("Reorganization details") + ":\n" +
2776 "- " + strprintf(_("Current tip: %s, height %d, work %s"),
2777 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" +
2778 "- " + strprintf(_("New tip: %s, height %d, work %s"),
2779 pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" +
2780 "- " + strprintf(_("Fork point: %s, height %d"),
2781 pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" +
2782 _("Please help, human!");
2783 LogPrintf("*** %s\n", msg);
2784 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
2789 // Disconnect active blocks which are no longer in the best chain.
2790 bool fBlocksDisconnected = false;
2791 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2792 if (!DisconnectTip(state))
2794 fBlocksDisconnected = true;
2797 // Build list of new blocks to connect.
2798 std::vector<CBlockIndex*> vpindexToConnect;
2799 bool fContinue = true;
2800 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2801 while (fContinue && nHeight != pindexMostWork->nHeight) {
2802 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2803 // a few blocks along the way.
2804 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2805 vpindexToConnect.clear();
2806 vpindexToConnect.reserve(nTargetHeight - nHeight);
2807 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2808 while (pindexIter && pindexIter->nHeight != nHeight) {
2809 vpindexToConnect.push_back(pindexIter);
2810 pindexIter = pindexIter->pprev;
2812 nHeight = nTargetHeight;
2814 // Connect new blocks.
2815 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2816 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2817 if (state.IsInvalid()) {
2818 // The block violates a consensus rule.
2819 if (!state.CorruptionPossible())
2820 InvalidChainFound(vpindexToConnect.back());
2821 state = CValidationState();
2822 fInvalidFound = true;
2826 // A system error occurred (disk space, database error, ...).
2830 PruneBlockIndexCandidates();
2831 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2832 // We're in a better position than we were. Return temporarily to release the lock.
2840 if (fBlocksDisconnected) {
2841 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2843 mempool.removeWithoutBranchId(
2844 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2845 mempool.check(pcoinsTip);
2847 // Callbacks/notifications for a new best chain.
2849 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2851 CheckForkWarningConditions();
2857 * Make the best chain active, in multiple steps. The result is either failure
2858 * or an activated best chain. pblock is either NULL or a pointer to a block
2859 * that is already loaded (to avoid loading it again from disk).
2861 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2862 CBlockIndex *pindexNewTip = NULL;
2863 CBlockIndex *pindexMostWork = NULL;
2864 const CChainParams& chainParams = Params();
2866 boost::this_thread::interruption_point();
2868 bool fInitialDownload;
2871 pindexMostWork = FindMostWorkChain();
2873 // Whether we have anything to do at all.
2874 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2877 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2880 pindexNewTip = chainActive.Tip();
2881 fInitialDownload = IsInitialBlockDownload();
2883 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2885 // Notifications/callbacks that can run without cs_main
2886 if (!fInitialDownload) {
2887 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2888 // Relay inventory, but don't relay old inventory during initial block download.
2889 int nBlockEstimate = 0;
2890 if (fCheckpointsEnabled)
2891 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2892 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2893 // in a stalled download if the block file is pruned before the request.
2894 if (nLocalServices & NODE_NETWORK) {
2896 BOOST_FOREACH(CNode* pnode, vNodes)
2897 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2898 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2900 // Notify external listeners about the new tip.
2901 GetMainSignals().UpdatedBlockTip(pindexNewTip);
2902 uiInterface.NotifyBlockTip(hashNewTip);
2904 } while(pindexMostWork != chainActive.Tip());
2907 // Write changes periodically to disk, after relay.
2908 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2915 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2916 AssertLockHeld(cs_main);
2918 // Mark the block itself as invalid.
2919 pindex->nStatus |= BLOCK_FAILED_VALID;
2920 setDirtyBlockIndex.insert(pindex);
2921 setBlockIndexCandidates.erase(pindex);
2923 while (chainActive.Contains(pindex)) {
2924 CBlockIndex *pindexWalk = chainActive.Tip();
2925 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2926 setDirtyBlockIndex.insert(pindexWalk);
2927 setBlockIndexCandidates.erase(pindexWalk);
2928 // ActivateBestChain considers blocks already in chainActive
2929 // unconditionally valid already, so force disconnect away from it.
2930 if (!DisconnectTip(state)) {
2931 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2932 mempool.removeWithoutBranchId(
2933 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2938 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2940 BlockMap::iterator it = mapBlockIndex.begin();
2941 while (it != mapBlockIndex.end()) {
2942 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2943 setBlockIndexCandidates.insert(it->second);
2948 InvalidChainFound(pindex);
2949 mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
2950 mempool.removeWithoutBranchId(
2951 CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus()));
2955 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2956 AssertLockHeld(cs_main);
2958 int nHeight = pindex->nHeight;
2960 // Remove the invalidity flag from this block and all its descendants.
2961 BlockMap::iterator it = mapBlockIndex.begin();
2962 while (it != mapBlockIndex.end()) {
2963 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2964 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2965 setDirtyBlockIndex.insert(it->second);
2966 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2967 setBlockIndexCandidates.insert(it->second);
2969 if (it->second == pindexBestInvalid) {
2970 // Reset invalid block marker if it was pointing to one of those.
2971 pindexBestInvalid = NULL;
2977 // Remove the invalidity flag from all ancestors too.
2978 while (pindex != NULL) {
2979 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2980 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2981 setDirtyBlockIndex.insert(pindex);
2983 pindex = pindex->pprev;
2988 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2990 // Check for duplicate
2991 uint256 hash = block.GetHash();
2992 BlockMap::iterator it = mapBlockIndex.find(hash);
2993 if (it != mapBlockIndex.end())
2996 // Construct new block index object
2997 CBlockIndex* pindexNew = new CBlockIndex(block);
2999 // We assign the sequence id to blocks only when the full data is available,
3000 // to avoid miners withholding blocks but broadcasting headers, to get a
3001 // competitive advantage.
3002 pindexNew->nSequenceId = 0;
3003 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3004 pindexNew->phashBlock = &((*mi).first);
3005 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
3006 if (miPrev != mapBlockIndex.end())
3008 pindexNew->pprev = (*miPrev).second;
3009 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
3010 pindexNew->BuildSkip();
3012 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
3013 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
3014 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
3015 pindexBestHeader = pindexNew;
3017 setDirtyBlockIndex.insert(pindexNew);
3022 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
3023 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
3025 pindexNew->nTx = block.vtx.size();
3026 pindexNew->nChainTx = 0;
3027 CAmount sproutValue = 0;
3028 for (auto tx : block.vtx) {
3029 for (auto js : tx.vjoinsplit) {
3030 sproutValue += js.vpub_old;
3031 sproutValue -= js.vpub_new;
3034 pindexNew->nSproutValue = sproutValue;
3035 pindexNew->nChainSproutValue = boost::none;
3036 pindexNew->nFile = pos.nFile;
3037 pindexNew->nDataPos = pos.nPos;
3038 pindexNew->nUndoPos = 0;
3039 pindexNew->nStatus |= BLOCK_HAVE_DATA;
3040 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
3041 setDirtyBlockIndex.insert(pindexNew);
3043 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
3044 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
3045 deque<CBlockIndex*> queue;
3046 queue.push_back(pindexNew);
3048 // Recursively process any descendant blocks that now may be eligible to be connected.
3049 while (!queue.empty()) {
3050 CBlockIndex *pindex = queue.front();
3052 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
3053 if (pindex->pprev) {
3054 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3055 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3057 pindex->nChainSproutValue = boost::none;
3060 pindex->nChainSproutValue = pindex->nSproutValue;
3063 LOCK(cs_nBlockSequenceId);
3064 pindex->nSequenceId = nBlockSequenceId++;
3066 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
3067 setBlockIndexCandidates.insert(pindex);
3069 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
3070 while (range.first != range.second) {
3071 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
3072 queue.push_back(it->second);
3074 mapBlocksUnlinked.erase(it);
3078 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
3079 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
3086 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
3088 LOCK(cs_LastBlockFile);
3090 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
3091 if (vinfoBlockFile.size() <= nFile) {
3092 vinfoBlockFile.resize(nFile + 1);
3096 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
3098 if (vinfoBlockFile.size() <= nFile) {
3099 vinfoBlockFile.resize(nFile + 1);
3103 pos.nPos = vinfoBlockFile[nFile].nSize;
3106 if (nFile != nLastBlockFile) {
3108 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
3110 FlushBlockFile(!fKnown);
3111 nLastBlockFile = nFile;
3114 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
3116 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
3118 vinfoBlockFile[nFile].nSize += nAddSize;
3121 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3122 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
3123 if (nNewChunks > nOldChunks) {
3125 fCheckForPruning = true;
3126 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
3127 FILE *file = OpenBlockFile(pos);
3129 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
3130 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
3135 return state.Error("out of disk space");
3139 setDirtyFileInfo.insert(nFile);
3143 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
3147 LOCK(cs_LastBlockFile);
3149 unsigned int nNewSize;
3150 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
3151 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
3152 setDirtyFileInfo.insert(nFile);
3154 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3155 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
3156 if (nNewChunks > nOldChunks) {
3158 fCheckForPruning = true;
3159 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
3160 FILE *file = OpenUndoFile(pos);
3162 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
3163 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
3168 return state.Error("out of disk space");
3174 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
3176 // Check block version
3177 if (block.nVersion < MIN_BLOCK_VERSION)
3178 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
3179 REJECT_INVALID, "version-too-low");
3181 // Check Equihash solution is valid
3182 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
3183 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
3184 REJECT_INVALID, "invalid-solution");
3186 // Check proof of work matches claimed amount
3187 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
3188 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
3189 REJECT_INVALID, "high-hash");
3192 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
3193 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
3194 REJECT_INVALID, "time-too-new");
3199 bool CheckBlock(const CBlock& block, CValidationState& state,
3200 libzcash::ProofVerifier& verifier,
3201 bool fCheckPOW, bool fCheckMerkleRoot)
3203 // These are checks that are independent of context.
3205 // Check that the header is valid (particularly PoW). This is mostly
3206 // redundant with the call in AcceptBlockHeader.
3207 if (!CheckBlockHeader(block, state, fCheckPOW))
3210 // Check the merkle root.
3211 if (fCheckMerkleRoot) {
3213 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
3214 if (block.hashMerkleRoot != hashMerkleRoot2)
3215 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
3216 REJECT_INVALID, "bad-txnmrklroot", true);
3218 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
3219 // of transactions in a block without affecting the merkle root of a block,
3220 // while still invalidating it.
3222 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3223 REJECT_INVALID, "bad-txns-duplicate", true);
3226 // All potential-corruption validation must be done before we do any
3227 // transaction validation, as otherwise we may mark the header as invalid
3228 // because we receive the wrong transactions for it.
3231 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3232 return state.DoS(100, error("CheckBlock(): size limits failed"),
3233 REJECT_INVALID, "bad-blk-length");
3235 // First transaction must be coinbase, the rest must not be
3236 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3237 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3238 REJECT_INVALID, "bad-cb-missing");
3239 for (unsigned int i = 1; i < block.vtx.size(); i++)
3240 if (block.vtx[i].IsCoinBase())
3241 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3242 REJECT_INVALID, "bad-cb-multiple");
3244 // Check transactions
3245 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3246 if (!CheckTransaction(tx, state, verifier))
3247 return error("CheckBlock(): CheckTransaction failed");
3249 unsigned int nSigOps = 0;
3250 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3252 nSigOps += GetLegacySigOpCount(tx);
3254 if (nSigOps > MAX_BLOCK_SIGOPS)
3255 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3256 REJECT_INVALID, "bad-blk-sigops", true);
3261 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3263 const CChainParams& chainParams = Params();
3264 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3265 uint256 hash = block.GetHash();
3266 if (hash == consensusParams.hashGenesisBlock)
3271 int nHeight = pindexPrev->nHeight+1;
3273 // Check proof of work
3274 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3275 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3276 REJECT_INVALID, "bad-diffbits");
3278 // Check timestamp against prev
3279 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3280 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3281 REJECT_INVALID, "time-too-old");
3283 if (fCheckpointsEnabled)
3285 // Don't accept any forks from the main chain prior to last checkpoint
3286 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3287 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3288 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3291 // Reject block.nVersion < 4 blocks
3292 if (block.nVersion < 4)
3293 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3294 REJECT_OBSOLETE, "bad-version");
3299 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3301 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3302 const Consensus::Params& consensusParams = Params().GetConsensus();
3304 // Check that all transactions are finalized
3305 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3307 // Check transaction contextually against consensus rules at block height
3308 if (!ContextualCheckTransaction(tx, state, nHeight, 100)) {
3309 return false; // Failure reason has been set in validation state object
3312 int nLockTimeFlags = 0;
3313 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3314 ? pindexPrev->GetMedianTimePast()
3315 : block.GetBlockTime();
3316 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3317 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3321 // Enforce BIP 34 rule that the coinbase starts with serialized block height.
3322 // In Zcash this has been enforced since launch, except that the genesis
3323 // block didn't include the height in the coinbase (see Zcash protocol spec
3324 // section '6.8 Bitcoin Improvement Proposals').
3327 CScript expect = CScript() << nHeight;
3328 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3329 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3330 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3334 // Coinbase transaction must include an output sending 20% of
3335 // the block reward to a founders reward script, until the last founders
3336 // reward block is reached, with exception of the genesis block.
3337 // The last founders reward block is defined as the block just before the
3338 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3339 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3342 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3343 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3344 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3352 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3359 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3361 const CChainParams& chainparams = Params();
3362 AssertLockHeld(cs_main);
3363 // Check for duplicate
3364 uint256 hash = block.GetHash();
3365 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3366 CBlockIndex *pindex = NULL;
3367 if (miSelf != mapBlockIndex.end()) {
3368 // Block header is already known.
3369 pindex = miSelf->second;
3372 if (pindex->nStatus & BLOCK_FAILED_MASK)
3373 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3377 if (!CheckBlockHeader(block, state))
3380 // Get prev block index
3381 CBlockIndex* pindexPrev = NULL;
3382 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3383 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3384 if (mi == mapBlockIndex.end())
3385 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3386 pindexPrev = (*mi).second;
3387 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3388 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3391 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3395 pindex = AddToBlockIndex(block);
3403 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3405 const CChainParams& chainparams = Params();
3406 AssertLockHeld(cs_main);
3408 CBlockIndex *&pindex = *ppindex;
3410 if (!AcceptBlockHeader(block, state, &pindex))
3413 // Try to process all requested blocks that we don't have, but only
3414 // process an unrequested block if it's new and has enough work to
3415 // advance our tip, and isn't too many blocks ahead.
3416 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3417 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3418 // Blocks that are too out-of-order needlessly limit the effectiveness of
3419 // pruning, because pruning will not delete block files that contain any
3420 // blocks which are too close in height to the tip. Apply this test
3421 // regardless of whether pruning is enabled; it should generally be safe to
3422 // not process unrequested blocks.
3423 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3425 // TODO: deal better with return value and error conditions for duplicate
3426 // and unrequested blocks.
3427 if (fAlreadyHave) return true;
3428 if (!fRequested) { // If we didn't ask for it:
3429 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3430 if (!fHasMoreWork) return true; // Don't process less-work chains
3431 if (fTooFarAhead) return true; // Block height is too high
3434 // See method docstring for why this is always disabled
3435 auto verifier = libzcash::ProofVerifier::Disabled();
3436 if ((!CheckBlock(block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3437 if (state.IsInvalid() && !state.CorruptionPossible()) {
3438 pindex->nStatus |= BLOCK_FAILED_VALID;
3439 setDirtyBlockIndex.insert(pindex);
3444 int nHeight = pindex->nHeight;
3446 // Write block to history file
3448 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3449 CDiskBlockPos blockPos;
3452 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3453 return error("AcceptBlock(): FindBlockPos failed");
3455 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3456 AbortNode(state, "Failed to write block");
3457 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3458 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3459 } catch (const std::runtime_error& e) {
3460 return AbortNode(state, std::string("System error: ") + e.what());
3463 if (fCheckForPruning)
3464 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3469 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3471 unsigned int nFound = 0;
3472 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3474 if (pstart->nVersion >= minVersion)
3476 pstart = pstart->pprev;
3478 return (nFound >= nRequired);
3482 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3484 // Preliminary checks
3485 auto verifier = libzcash::ProofVerifier::Disabled();
3486 bool checked = CheckBlock(*pblock, state, verifier);
3490 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3491 fRequested |= fForceProcessing;
3493 return error("%s: CheckBlock FAILED", __func__);
3497 CBlockIndex *pindex = NULL;
3498 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3499 if (pindex && pfrom) {
3500 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3504 return error("%s: AcceptBlock FAILED", __func__);
3507 if (!ActivateBestChain(state, pblock))
3508 return error("%s: ActivateBestChain failed", __func__);
3513 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3515 AssertLockHeld(cs_main);
3516 assert(pindexPrev == chainActive.Tip());
3518 CCoinsViewCache viewNew(pcoinsTip);
3519 CBlockIndex indexDummy(block);
3520 indexDummy.pprev = pindexPrev;
3521 indexDummy.nHeight = pindexPrev->nHeight + 1;
3522 // JoinSplit proofs are verified in ConnectBlock
3523 auto verifier = libzcash::ProofVerifier::Disabled();
3525 // NOTE: CheckBlockHeader is called by CheckBlock
3526 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3528 if (!CheckBlock(block, state, verifier, fCheckPOW, fCheckMerkleRoot))
3530 if (!ContextualCheckBlock(block, state, pindexPrev))
3532 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3534 assert(state.IsValid());
3540 * BLOCK PRUNING CODE
3543 /* Calculate the amount of disk space the block & undo files currently use */
3544 uint64_t CalculateCurrentUsage()
3546 uint64_t retval = 0;
3547 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3548 retval += file.nSize + file.nUndoSize;
3553 /* Prune a block file (modify associated database entries)*/
3554 void PruneOneBlockFile(const int fileNumber)
3556 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3557 CBlockIndex* pindex = it->second;
3558 if (pindex->nFile == fileNumber) {
3559 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3560 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3562 pindex->nDataPos = 0;
3563 pindex->nUndoPos = 0;
3564 setDirtyBlockIndex.insert(pindex);
3566 // Prune from mapBlocksUnlinked -- any block we prune would have
3567 // to be downloaded again in order to consider its chain, at which
3568 // point it would be considered as a candidate for
3569 // mapBlocksUnlinked or setBlockIndexCandidates.
3570 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3571 while (range.first != range.second) {
3572 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3574 if (it->second == pindex) {
3575 mapBlocksUnlinked.erase(it);
3581 vinfoBlockFile[fileNumber].SetNull();
3582 setDirtyFileInfo.insert(fileNumber);
3586 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3588 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3589 CDiskBlockPos pos(*it, 0);
3590 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3591 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3592 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3596 /* Calculate the block/rev files that should be deleted to remain under target*/
3597 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3599 LOCK2(cs_main, cs_LastBlockFile);
3600 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3603 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3607 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3608 uint64_t nCurrentUsage = CalculateCurrentUsage();
3609 // We don't check to prune until after we've allocated new space for files
3610 // So we should leave a buffer under our target to account for another allocation
3611 // before the next pruning.
3612 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3613 uint64_t nBytesToPrune;
3616 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3617 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3618 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3620 if (vinfoBlockFile[fileNumber].nSize == 0)
3623 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3626 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3627 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3630 PruneOneBlockFile(fileNumber);
3631 // Queue up the files for removal
3632 setFilesToPrune.insert(fileNumber);
3633 nCurrentUsage -= nBytesToPrune;
3638 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3639 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3640 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3641 nLastBlockWeCanPrune, count);
3644 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3646 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3648 // Check for nMinDiskSpace bytes (currently 50MB)
3649 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3650 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3655 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3659 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3660 boost::filesystem::create_directories(path.parent_path());
3661 FILE* file = fopen(path.string().c_str(), "rb+");
3662 if (!file && !fReadOnly)
3663 file = fopen(path.string().c_str(), "wb+");
3665 LogPrintf("Unable to open file %s\n", path.string());
3669 if (fseek(file, pos.nPos, SEEK_SET)) {
3670 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3678 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3679 return OpenDiskFile(pos, "blk", fReadOnly);
3682 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3683 return OpenDiskFile(pos, "rev", fReadOnly);
3686 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3688 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3691 CBlockIndex * InsertBlockIndex(uint256 hash)
3697 BlockMap::iterator mi = mapBlockIndex.find(hash);
3698 if (mi != mapBlockIndex.end())
3699 return (*mi).second;
3702 CBlockIndex* pindexNew = new CBlockIndex();
3704 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3705 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3706 pindexNew->phashBlock = &((*mi).first);
3711 bool static LoadBlockIndexDB()
3713 const CChainParams& chainparams = Params();
3714 if (!pblocktree->LoadBlockIndexGuts())
3717 boost::this_thread::interruption_point();
3719 // Calculate nChainWork
3720 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3721 vSortedByHeight.reserve(mapBlockIndex.size());
3722 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3724 CBlockIndex* pindex = item.second;
3725 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3727 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3728 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3730 CBlockIndex* pindex = item.second;
3731 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3732 // We can link the chain of blocks for which we've received transactions at some point.
3733 // Pruned nodes may have deleted the block.
3734 if (pindex->nTx > 0) {
3735 if (pindex->pprev) {
3736 if (pindex->pprev->nChainTx) {
3737 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3738 if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) {
3739 pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue;
3741 pindex->nChainSproutValue = boost::none;
3744 pindex->nChainTx = 0;
3745 pindex->nChainSproutValue = boost::none;
3746 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3749 pindex->nChainTx = pindex->nTx;
3750 pindex->nChainSproutValue = pindex->nSproutValue;
3753 // Construct in-memory chain of branch IDs.
3754 // Relies on invariant: a block that does not activate a network upgrade
3755 // will always be valid under the same consensus rules as its parent.
3756 // Genesis block has a branch ID of zero by definition, but has no
3757 // validity status because it is side-loaded into a fresh chain.
3758 // Activation blocks will have branch IDs set (read from disk).
3759 if (pindex->pprev) {
3760 if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) {
3761 pindex->nCachedBranchId = pindex->pprev->nCachedBranchId;
3764 pindex->nCachedBranchId = SPROUT_BRANCH_ID;
3766 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3767 setBlockIndexCandidates.insert(pindex);
3768 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3769 pindexBestInvalid = pindex;
3771 pindex->BuildSkip();
3772 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3773 pindexBestHeader = pindex;
3776 // Load block file info
3777 pblocktree->ReadLastBlockFile(nLastBlockFile);
3778 vinfoBlockFile.resize(nLastBlockFile + 1);
3779 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3780 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3781 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3783 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3784 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3785 CBlockFileInfo info;
3786 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3787 vinfoBlockFile.push_back(info);
3793 // Check presence of blk files
3794 LogPrintf("Checking all blk files are present...\n");
3795 set<int> setBlkDataFiles;
3796 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3798 CBlockIndex* pindex = item.second;
3799 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3800 setBlkDataFiles.insert(pindex->nFile);
3803 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3805 CDiskBlockPos pos(*it, 0);
3806 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3811 // Check whether we have ever pruned block & undo files
3812 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3814 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3816 // Check whether we need to continue reindexing
3817 bool fReindexing = false;
3818 pblocktree->ReadReindexing(fReindexing);
3819 fReindex |= fReindexing;
3821 // Check whether we have a transaction index
3822 pblocktree->ReadFlag("txindex", fTxIndex);
3823 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3825 // Fill in-memory data
3826 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3828 CBlockIndex* pindex = item.second;
3829 // - This relationship will always be true even if pprev has multiple
3830 // children, because hashAnchor is technically a property of pprev,
3831 // not its children.
3832 // - This will miss chain tips; we handle the best tip below, and other
3833 // tips will be handled by ConnectTip during a re-org.
3834 if (pindex->pprev) {
3835 pindex->pprev->hashAnchorEnd = pindex->hashAnchor;
3839 // Load pointer to end of best chain
3840 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3841 if (it == mapBlockIndex.end())
3843 chainActive.SetTip(it->second);
3844 // Set hashAnchorEnd for the end of best chain
3845 it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor();
3847 PruneBlockIndexCandidates();
3849 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3850 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3851 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3852 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3854 EnforceNodeDeprecation(chainActive.Height(), true);
3859 CVerifyDB::CVerifyDB()
3861 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3864 CVerifyDB::~CVerifyDB()
3866 uiInterface.ShowProgress("", 100);
3869 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3872 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3875 // Verify blocks in the best chain
3876 if (nCheckDepth <= 0)
3877 nCheckDepth = 1000000000; // suffices until the year 19000
3878 if (nCheckDepth > chainActive.Height())
3879 nCheckDepth = chainActive.Height();
3880 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3881 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3882 CCoinsViewCache coins(coinsview);
3883 CBlockIndex* pindexState = chainActive.Tip();
3884 CBlockIndex* pindexFailure = NULL;
3885 int nGoodTransactions = 0;
3886 CValidationState state;
3887 // No need to verify JoinSplits twice
3888 auto verifier = libzcash::ProofVerifier::Disabled();
3889 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3891 boost::this_thread::interruption_point();
3892 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3893 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3896 // check level 0: read from disk
3897 if (!ReadBlockFromDisk(block, pindex))
3898 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3899 // check level 1: verify block validity
3900 if (nCheckLevel >= 1 && !CheckBlock(block, state, verifier))
3901 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3902 // check level 2: verify undo validity
3903 if (nCheckLevel >= 2 && pindex) {
3905 CDiskBlockPos pos = pindex->GetUndoPos();
3906 if (!pos.IsNull()) {
3907 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3908 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3911 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3912 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3914 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3915 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3916 pindexState = pindex->pprev;
3918 nGoodTransactions = 0;
3919 pindexFailure = pindex;
3921 nGoodTransactions += block.vtx.size();
3923 if (ShutdownRequested())
3927 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3929 // check level 4: try reconnecting blocks
3930 if (nCheckLevel >= 4) {
3931 CBlockIndex *pindex = pindexState;
3932 while (pindex != chainActive.Tip()) {
3933 boost::this_thread::interruption_point();
3934 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3935 pindex = chainActive.Next(pindex);
3937 if (!ReadBlockFromDisk(block, pindex))
3938 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3939 if (!ConnectBlock(block, state, pindex, coins))
3940 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3944 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3949 bool RewindBlockIndex(const CChainParams& params)
3953 // RewindBlockIndex is called after LoadBlockIndex, so at this point every block
3954 // index will have nCachedBranchId set based on the values previously persisted
3955 // to disk. By definition, a set nCachedBranchId means that the block was
3956 // fully-validated under the corresponding consensus rules. Thus we can quickly
3957 // identify whether the current active chain matches our expected sequence of
3958 // consensus rule changes, with two checks:
3960 // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades.
3961 // - nCachedBranchId for each block matches what we expect.
3962 auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) {
3963 auto consensus = params.GetConsensus();
3964 bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE;
3965 bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus);
3966 return fFlagSet == fFlagExpected &&
3967 pindex->nCachedBranchId &&
3968 *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus);
3972 while (nHeight <= chainActive.Height()) {
3973 if (!sufficientlyValidated(chainActive[nHeight])) {
3979 // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
3980 auto rewindLength = chainActive.Height() - nHeight;
3981 if (rewindLength > 0 && rewindLength > MAX_REORG_LENGTH) {
3982 auto pindexOldTip = chainActive.Tip();
3983 auto pindexRewind = chainActive[nHeight - 1];
3984 auto msg = strprintf(_(
3985 "A block chain rewind has been detected that would roll back %d blocks! "
3986 "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety."
3987 ), rewindLength, MAX_REORG_LENGTH) + "\n\n" +
3988 _("Rewind details") + ":\n" +
3989 "- " + strprintf(_("Current tip: %s, height %d"),
3990 pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" +
3991 "- " + strprintf(_("Rewinding to: %s, height %d"),
3992 pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" +
3993 _("Please help, human!");
3994 LogPrintf("*** %s\n", msg);
3995 uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR);
4000 CValidationState state;
4001 CBlockIndex* pindex = chainActive.Tip();
4002 while (chainActive.Height() >= nHeight) {
4003 if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
4004 // If pruning, don't try rewinding past the HAVE_DATA point;
4005 // since older blocks can't be served anyway, there's
4006 // no need to walk further, and trying to DisconnectTip()
4007 // will fail (and require a needless reindex/redownload
4008 // of the blockchain).
4011 if (!DisconnectTip(state, true)) {
4012 return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
4014 // Occasionally flush state to disk.
4015 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC))
4019 // Reduce validity flag and have-data flags.
4020 // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
4021 // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
4022 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4023 CBlockIndex* pindexIter = it->second;
4025 // Note: If we encounter an insufficiently validated block that
4026 // is on chainActive, it must be because we are a pruning node, and
4027 // this block or some successor doesn't HAVE_DATA, so we were unable to
4028 // rewind all the way. Blocks remaining on chainActive at this point
4029 // must not have their validity reduced.
4030 if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) {
4032 pindexIter->nStatus =
4033 std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) |
4034 (pindexIter->nStatus & ~BLOCK_VALID_MASK);
4035 // Remove have-data flags
4036 pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
4038 pindexIter->nStatus &= ~BLOCK_ACTIVATES_UPGRADE;
4039 pindexIter->nCachedBranchId = boost::none;
4040 // Remove storage location
4041 pindexIter->nFile = 0;
4042 pindexIter->nDataPos = 0;
4043 pindexIter->nUndoPos = 0;
4044 // Remove various other things
4045 pindexIter->nTx = 0;
4046 pindexIter->nChainTx = 0;
4047 pindexIter->nSproutValue = boost::none;
4048 pindexIter->nChainSproutValue = boost::none;
4049 pindexIter->nSequenceId = 0;
4050 // Make sure it gets written
4051 setDirtyBlockIndex.insert(pindexIter);
4053 setBlockIndexCandidates.erase(pindexIter);
4054 auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
4055 while (ret.first != ret.second) {
4056 if (ret.first->second == pindexIter) {
4057 mapBlocksUnlinked.erase(ret.first++);
4062 } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
4063 setBlockIndexCandidates.insert(pindexIter);
4067 PruneBlockIndexCandidates();
4071 if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) {
4078 void UnloadBlockIndex()
4081 setBlockIndexCandidates.clear();
4082 chainActive.SetTip(NULL);
4083 pindexBestInvalid = NULL;
4084 pindexBestHeader = NULL;
4086 mapOrphanTransactions.clear();
4087 mapOrphanTransactionsByPrev.clear();
4089 mapBlocksUnlinked.clear();
4090 vinfoBlockFile.clear();
4092 nBlockSequenceId = 1;
4093 mapBlockSource.clear();
4094 mapBlocksInFlight.clear();
4095 nQueuedValidatedHeaders = 0;
4096 nPreferredDownload = 0;
4097 setDirtyBlockIndex.clear();
4098 setDirtyFileInfo.clear();
4099 mapNodeState.clear();
4100 recentRejects.reset(NULL);
4102 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
4103 delete entry.second;
4105 mapBlockIndex.clear();
4106 fHavePruned = false;
4109 bool LoadBlockIndex()
4111 // Load block index from databases
4112 if (!fReindex && !LoadBlockIndexDB())
4118 bool InitBlockIndex() {
4119 const CChainParams& chainparams = Params();
4122 // Initialize global variables that cannot be constructed at startup.
4123 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
4125 // Check whether we're already initialized
4126 if (chainActive.Genesis() != NULL)
4129 // Use the provided setting for -txindex in the new database
4130 fTxIndex = GetBoolArg("-txindex", false);
4131 pblocktree->WriteFlag("txindex", fTxIndex);
4132 LogPrintf("Initializing databases...\n");
4134 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
4137 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
4138 // Start new block file
4139 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
4140 CDiskBlockPos blockPos;
4141 CValidationState state;
4142 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
4143 return error("LoadBlockIndex(): FindBlockPos failed");
4144 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
4145 return error("LoadBlockIndex(): writing genesis block to disk failed");
4146 CBlockIndex *pindex = AddToBlockIndex(block);
4147 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
4148 return error("LoadBlockIndex(): genesis block not accepted");
4149 if (!ActivateBestChain(state, &block))
4150 return error("LoadBlockIndex(): genesis block cannot be activated");
4151 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
4152 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
4153 } catch (const std::runtime_error& e) {
4154 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
4163 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
4165 const CChainParams& chainparams = Params();
4166 // Map of disk positions for blocks with unknown parent (only used for reindex)
4167 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
4168 int64_t nStart = GetTimeMillis();
4172 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
4173 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
4174 uint64_t nRewind = blkdat.GetPos();
4175 while (!blkdat.eof()) {
4176 boost::this_thread::interruption_point();
4178 blkdat.SetPos(nRewind);
4179 nRewind++; // start one byte further next time, in case of failure
4180 blkdat.SetLimit(); // remove former limit
4181 unsigned int nSize = 0;
4184 unsigned char buf[MESSAGE_START_SIZE];
4185 blkdat.FindByte(Params().MessageStart()[0]);
4186 nRewind = blkdat.GetPos()+1;
4187 blkdat >> FLATDATA(buf);
4188 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
4192 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
4194 } catch (const std::exception&) {
4195 // no valid block header found; don't complain
4200 uint64_t nBlockPos = blkdat.GetPos();
4202 dbp->nPos = nBlockPos;
4203 blkdat.SetLimit(nBlockPos + nSize);
4204 blkdat.SetPos(nBlockPos);
4207 nRewind = blkdat.GetPos();
4209 // detect out of order blocks, and store them for later
4210 uint256 hash = block.GetHash();
4211 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
4212 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
4213 block.hashPrevBlock.ToString());
4215 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
4219 // process in case the block isn't known yet
4220 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
4221 CValidationState state;
4222 if (ProcessNewBlock(state, NULL, &block, true, dbp))
4224 if (state.IsError())
4226 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
4227 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
4230 // Recursively process earlier encountered successors of this block
4231 deque<uint256> queue;
4232 queue.push_back(hash);
4233 while (!queue.empty()) {
4234 uint256 head = queue.front();
4236 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
4237 while (range.first != range.second) {
4238 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
4239 if (ReadBlockFromDisk(block, it->second))
4241 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
4243 CValidationState dummy;
4244 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
4247 queue.push_back(block.GetHash());
4251 mapBlocksUnknownParent.erase(it);
4254 } catch (const std::exception& e) {
4255 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
4258 } catch (const std::runtime_error& e) {
4259 AbortNode(std::string("System error: ") + e.what());
4262 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
4266 void static CheckBlockIndex()
4268 const Consensus::Params& consensusParams = Params().GetConsensus();
4269 if (!fCheckBlockIndex) {
4275 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
4276 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
4277 // iterating the block tree require that chainActive has been initialized.)
4278 if (chainActive.Height() < 0) {
4279 assert(mapBlockIndex.size() <= 1);
4283 // Build forward-pointing map of the entire block tree.
4284 std::multimap<CBlockIndex*,CBlockIndex*> forward;
4285 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
4286 forward.insert(std::make_pair(it->second->pprev, it->second));
4289 assert(forward.size() == mapBlockIndex.size());
4291 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
4292 CBlockIndex *pindex = rangeGenesis.first->second;
4293 rangeGenesis.first++;
4294 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
4296 // Iterate over the entire block tree, using depth-first search.
4297 // Along the way, remember whether there are blocks on the path from genesis
4298 // block being explored which are the first to have certain properties.
4301 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
4302 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
4303 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
4304 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
4305 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
4306 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
4307 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
4308 while (pindex != NULL) {
4310 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
4311 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
4312 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
4313 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
4314 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
4315 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
4316 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
4318 // Begin: actual consistency checks.
4319 if (pindex->pprev == NULL) {
4320 // Genesis block checks.
4321 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
4322 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
4324 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
4325 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
4326 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
4328 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
4329 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
4330 assert(pindexFirstMissing == pindexFirstNeverProcessed);
4332 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
4333 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
4335 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
4336 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
4337 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
4338 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
4339 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
4340 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
4341 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.
4342 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
4343 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
4344 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
4345 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
4346 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
4347 if (pindexFirstInvalid == NULL) {
4348 // Checks for not-invalid blocks.
4349 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
4351 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
4352 if (pindexFirstInvalid == NULL) {
4353 // If this block sorts at least as good as the current tip and
4354 // is valid and we have all data for its parents, it must be in
4355 // setBlockIndexCandidates. chainActive.Tip() must also be there
4356 // even if some data has been pruned.
4357 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
4358 assert(setBlockIndexCandidates.count(pindex));
4360 // If some parent is missing, then it could be that this block was in
4361 // setBlockIndexCandidates but had to be removed because of the missing data.
4362 // In this case it must be in mapBlocksUnlinked -- see test below.
4364 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
4365 assert(setBlockIndexCandidates.count(pindex) == 0);
4367 // Check whether this block is in mapBlocksUnlinked.
4368 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
4369 bool foundInUnlinked = false;
4370 while (rangeUnlinked.first != rangeUnlinked.second) {
4371 assert(rangeUnlinked.first->first == pindex->pprev);
4372 if (rangeUnlinked.first->second == pindex) {
4373 foundInUnlinked = true;
4376 rangeUnlinked.first++;
4378 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
4379 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
4380 assert(foundInUnlinked);
4382 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
4383 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
4384 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
4385 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
4386 assert(fHavePruned); // We must have pruned.
4387 // This block may have entered mapBlocksUnlinked if:
4388 // - it has a descendant that at some point had more work than the
4390 // - we tried switching to that descendant but were missing
4391 // data for some intermediate block between chainActive and the
4393 // So if this block is itself better than chainActive.Tip() and it wasn't in
4394 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
4395 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4396 if (pindexFirstInvalid == NULL) {
4397 assert(foundInUnlinked);
4401 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4402 // End: actual consistency checks.
4404 // Try descending into the first subnode.
4405 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4406 if (range.first != range.second) {
4407 // A subnode was found.
4408 pindex = range.first->second;
4412 // This is a leaf node.
4413 // Move upwards until we reach a node of which we have not yet visited the last child.
4415 // We are going to either move to a parent or a sibling of pindex.
4416 // If pindex was the first with a certain property, unset the corresponding variable.
4417 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4418 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4419 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4420 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4421 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4422 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4423 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4425 CBlockIndex* pindexPar = pindex->pprev;
4426 // Find which child we just visited.
4427 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4428 while (rangePar.first->second != pindex) {
4429 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4432 // Proceed to the next one.
4434 if (rangePar.first != rangePar.second) {
4435 // Move to the sibling.
4436 pindex = rangePar.first->second;
4447 // Check that we actually traversed the entire map.
4448 assert(nNodes == forward.size());
4451 //////////////////////////////////////////////////////////////////////////////
4456 std::string GetWarnings(const std::string& strFor)
4459 string strStatusBar;
4462 if (!CLIENT_VERSION_IS_RELEASE)
4463 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4465 if (GetBoolArg("-testsafemode", false))
4466 strStatusBar = strRPC = "testsafemode enabled";
4468 // Misc warnings like out of disk space and clock is wrong
4469 if (strMiscWarning != "")
4472 strStatusBar = strMiscWarning;
4475 if (fLargeWorkForkFound)
4478 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4480 else if (fLargeWorkInvalidChainFound)
4483 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.");
4489 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4491 const CAlert& alert = item.second;
4492 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4494 nPriority = alert.nPriority;
4495 strStatusBar = alert.strStatusBar;
4496 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4497 strRPC = alert.strRPCError;
4503 if (strFor == "statusbar")
4504 return strStatusBar;
4505 else if (strFor == "rpc")
4507 assert(!"GetWarnings(): invalid parameter");
4518 //////////////////////////////////////////////////////////////////////////////
4524 bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
4530 assert(recentRejects);
4531 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4533 // If the chain tip has changed previously rejected transactions
4534 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4535 // or a double-spend. Reset the rejects filter and give those
4536 // txs a second chance.
4537 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4538 recentRejects->reset();
4541 return recentRejects->contains(inv.hash) ||
4542 mempool.exists(inv.hash) ||
4543 mapOrphanTransactions.count(inv.hash) ||
4544 pcoinsTip->HaveCoins(inv.hash);
4547 return mapBlockIndex.count(inv.hash);
4549 // Don't know what it is, just say we already got one
4553 void static ProcessGetData(CNode* pfrom)
4555 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4557 vector<CInv> vNotFound;
4561 while (it != pfrom->vRecvGetData.end()) {
4562 // Don't bother if send buffer is too full to respond anyway
4563 if (pfrom->nSendSize >= SendBufferSize())
4566 const CInv &inv = *it;
4568 boost::this_thread::interruption_point();
4571 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4574 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4575 if (mi != mapBlockIndex.end())
4577 if (chainActive.Contains(mi->second)) {
4580 static const int nOneMonth = 30 * 24 * 60 * 60;
4581 // To prevent fingerprinting attacks, only send blocks outside of the active
4582 // chain if they are valid, and no more than a month older (both in time, and in
4583 // best equivalent proof of work) than the best header chain we know about.
4584 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4585 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4586 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4588 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4592 // Pruned nodes may have deleted the block, so check whether
4593 // it's available before trying to send.
4594 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4596 // Send block from disk
4598 if (!ReadBlockFromDisk(block, (*mi).second))
4599 assert(!"cannot load block from disk");
4600 if (inv.type == MSG_BLOCK)
4601 pfrom->PushMessage("block", block);
4602 else // MSG_FILTERED_BLOCK)
4604 LOCK(pfrom->cs_filter);
4607 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4608 pfrom->PushMessage("merkleblock", merkleBlock);
4609 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4610 // This avoids hurting performance by pointlessly requiring a round-trip
4611 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4612 // they must either disconnect and retry or request the full block.
4613 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4614 // however we MUST always provide at least what the remote peer needs
4615 typedef std::pair<unsigned int, uint256> PairType;
4616 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4617 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4618 pfrom->PushMessage("tx", block.vtx[pair.first]);
4624 // Trigger the peer node to send a getblocks request for the next batch of inventory
4625 if (inv.hash == pfrom->hashContinue)
4627 // Bypass PushInventory, this must send even if redundant,
4628 // and we want it right after the last block so they don't
4629 // wait for other stuff first.
4631 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4632 pfrom->PushMessage("inv", vInv);
4633 pfrom->hashContinue.SetNull();
4637 else if (inv.IsKnownType())
4639 // Send stream from relay memory
4640 bool pushed = false;
4643 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4644 if (mi != mapRelay.end()) {
4645 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4649 if (!pushed && inv.type == MSG_TX) {
4651 if (mempool.lookup(inv.hash, tx)) {
4652 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4655 pfrom->PushMessage("tx", ss);
4660 vNotFound.push_back(inv);
4664 // Track requests for our stuff.
4665 GetMainSignals().Inventory(inv.hash);
4667 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4672 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4674 if (!vNotFound.empty()) {
4675 // Let the peer know that we didn't find what it asked for, so it doesn't
4676 // have to wait around forever. Currently only SPV clients actually care
4677 // about this message: it's needed when they are recursively walking the
4678 // dependencies of relevant unconfirmed transactions. SPV clients want to
4679 // do that because they want to know about (and store and rebroadcast and
4680 // risk analyze) the dependencies of transactions relevant to them, without
4681 // having to download the entire memory pool.
4682 pfrom->PushMessage("notfound", vNotFound);
4686 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4688 const CChainParams& chainparams = Params();
4689 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4690 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4692 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4699 if (strCommand == "version")
4701 // Each connection can only send one version message
4702 if (pfrom->nVersion != 0)
4704 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4705 Misbehaving(pfrom->GetId(), 1);
4712 uint64_t nNonce = 1;
4713 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4714 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4716 // disconnect from peers older than this proto version
4717 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4718 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4719 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4720 pfrom->fDisconnect = true;
4724 if (pfrom->nVersion == 10300)
4725 pfrom->nVersion = 300;
4727 vRecv >> addrFrom >> nNonce;
4728 if (!vRecv.empty()) {
4729 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4730 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4733 vRecv >> pfrom->nStartingHeight;
4735 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4737 pfrom->fRelayTxes = true;
4739 // Disconnect if we connected to ourself
4740 if (nNonce == nLocalHostNonce && nNonce > 1)
4742 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4743 pfrom->fDisconnect = true;
4747 pfrom->addrLocal = addrMe;
4748 if (pfrom->fInbound && addrMe.IsRoutable())
4753 // Be shy and don't send version until we hear
4754 if (pfrom->fInbound)
4755 pfrom->PushVersion();
4757 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4759 // Potentially mark this peer as a preferred download peer.
4760 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4763 pfrom->PushMessage("verack");
4764 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4766 if (!pfrom->fInbound)
4768 // Advertise our address
4769 if (fListen && !IsInitialBlockDownload())
4771 CAddress addr = GetLocalAddress(&pfrom->addr);
4772 if (addr.IsRoutable())
4774 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4775 pfrom->PushAddress(addr);
4776 } else if (IsPeerAddrLocalGood(pfrom)) {
4777 addr.SetIP(pfrom->addrLocal);
4778 LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
4779 pfrom->PushAddress(addr);
4783 // Get recent addresses
4784 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4786 pfrom->PushMessage("getaddr");
4787 pfrom->fGetAddr = true;
4789 addrman.Good(pfrom->addr);
4791 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4793 addrman.Add(addrFrom, addrFrom);
4794 addrman.Good(addrFrom);
4801 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4802 item.second.RelayTo(pfrom);
4805 pfrom->fSuccessfullyConnected = true;
4809 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4811 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4812 pfrom->cleanSubVer, pfrom->nVersion,
4813 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4816 int64_t nTimeOffset = nTime - GetTime();
4817 pfrom->nTimeOffset = nTimeOffset;
4818 AddTimeData(pfrom->addr, nTimeOffset);
4822 else if (pfrom->nVersion == 0)
4824 // Must have a version message before anything else
4825 Misbehaving(pfrom->GetId(), 1);
4830 else if (strCommand == "verack")
4832 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4834 // Mark this node as currently connected, so we update its timestamp later.
4835 if (pfrom->fNetworkNode) {
4837 State(pfrom->GetId())->fCurrentlyConnected = true;
4842 else if (strCommand == "addr")
4844 vector<CAddress> vAddr;
4847 // Don't want addr from older versions unless seeding
4848 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4850 if (vAddr.size() > 1000)
4852 Misbehaving(pfrom->GetId(), 20);
4853 return error("message addr size() = %u", vAddr.size());
4856 // Store the new addresses
4857 vector<CAddress> vAddrOk;
4858 int64_t nNow = GetAdjustedTime();
4859 int64_t nSince = nNow - 10 * 60;
4860 BOOST_FOREACH(CAddress& addr, vAddr)
4862 boost::this_thread::interruption_point();
4864 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4865 addr.nTime = nNow - 5 * 24 * 60 * 60;
4866 pfrom->AddAddressKnown(addr);
4867 bool fReachable = IsReachable(addr);
4868 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4870 // Relay to a limited number of other nodes
4873 // Use deterministic randomness to send to the same nodes for 24 hours
4874 // at a time so the addrKnowns of the chosen nodes prevent repeats
4875 static uint256 hashSalt;
4876 if (hashSalt.IsNull())
4877 hashSalt = GetRandHash();
4878 uint64_t hashAddr = addr.GetHash();
4879 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4880 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4881 multimap<uint256, CNode*> mapMix;
4882 BOOST_FOREACH(CNode* pnode, vNodes)
4884 if (pnode->nVersion < CADDR_TIME_VERSION)
4886 unsigned int nPointer;
4887 memcpy(&nPointer, &pnode, sizeof(nPointer));
4888 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4889 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4890 mapMix.insert(make_pair(hashKey, pnode));
4892 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4893 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4894 ((*mi).second)->PushAddress(addr);
4897 // Do not store addresses outside our network
4899 vAddrOk.push_back(addr);
4901 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4902 if (vAddr.size() < 1000)
4903 pfrom->fGetAddr = false;
4904 if (pfrom->fOneShot)
4905 pfrom->fDisconnect = true;
4909 else if (strCommand == "inv")
4913 if (vInv.size() > MAX_INV_SZ)
4915 Misbehaving(pfrom->GetId(), 20);
4916 return error("message inv size() = %u", vInv.size());
4921 std::vector<CInv> vToFetch;
4923 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4925 const CInv &inv = vInv[nInv];
4927 boost::this_thread::interruption_point();
4928 pfrom->AddInventoryKnown(inv);
4930 bool fAlreadyHave = AlreadyHave(inv);
4931 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4933 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4936 if (inv.type == MSG_BLOCK) {
4937 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4938 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4939 // First request the headers preceding the announced block. In the normal fully-synced
4940 // case where a new block is announced that succeeds the current tip (no reorganization),
4941 // there are no such headers.
4942 // Secondly, and only when we are close to being synced, we request the announced block directly,
4943 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4944 // time the block arrives, the header chain leading up to it is already validated. Not
4945 // doing this will result in the received block being rejected as an orphan in case it is
4946 // not a direct successor.
4947 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4948 CNodeState *nodestate = State(pfrom->GetId());
4949 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4950 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4951 vToFetch.push_back(inv);
4952 // Mark block as in flight already, even though the actual "getdata" message only goes out
4953 // later (within the same cs_main lock, though).
4954 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4956 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4960 // Track requests for our stuff
4961 GetMainSignals().Inventory(inv.hash);
4963 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4964 Misbehaving(pfrom->GetId(), 50);
4965 return error("send buffer size() = %u", pfrom->nSendSize);
4969 if (!vToFetch.empty())
4970 pfrom->PushMessage("getdata", vToFetch);
4974 else if (strCommand == "getdata")
4978 if (vInv.size() > MAX_INV_SZ)
4980 Misbehaving(pfrom->GetId(), 20);
4981 return error("message getdata size() = %u", vInv.size());
4984 if (fDebug || (vInv.size() != 1))
4985 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4987 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4988 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4990 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4991 ProcessGetData(pfrom);
4995 else if (strCommand == "getblocks")
4997 CBlockLocator locator;
4999 vRecv >> locator >> hashStop;
5003 // Find the last block the caller has in the main chain
5004 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
5006 // Send the rest of the chain
5008 pindex = chainActive.Next(pindex);
5010 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
5011 for (; pindex; pindex = chainActive.Next(pindex))
5013 if (pindex->GetBlockHash() == hashStop)
5015 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5018 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5021 // When this block is requested, we'll send an inv that'll
5022 // trigger the peer to getblocks the next batch of inventory.
5023 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
5024 pfrom->hashContinue = pindex->GetBlockHash();
5031 else if (strCommand == "getheaders")
5033 CBlockLocator locator;
5035 vRecv >> locator >> hashStop;
5039 if (IsInitialBlockDownload())
5042 CBlockIndex* pindex = NULL;
5043 if (locator.IsNull())
5045 // If locator is null, return the hashStop block
5046 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
5047 if (mi == mapBlockIndex.end())
5049 pindex = (*mi).second;
5053 // Find the last block the caller has in the main chain
5054 pindex = FindForkInGlobalIndex(chainActive, locator);
5056 pindex = chainActive.Next(pindex);
5059 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
5060 vector<CBlock> vHeaders;
5061 int nLimit = MAX_HEADERS_RESULTS;
5062 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
5063 for (; pindex; pindex = chainActive.Next(pindex))
5065 vHeaders.push_back(pindex->GetBlockHeader());
5066 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
5069 pfrom->PushMessage("headers", vHeaders);
5073 else if (strCommand == "tx")
5075 vector<uint256> vWorkQueue;
5076 vector<uint256> vEraseQueue;
5080 CInv inv(MSG_TX, tx.GetHash());
5081 pfrom->AddInventoryKnown(inv);
5085 bool fMissingInputs = false;
5086 CValidationState state;
5088 pfrom->setAskFor.erase(inv.hash);
5089 mapAlreadyAskedFor.erase(inv);
5091 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
5093 mempool.check(pcoinsTip);
5094 RelayTransaction(tx);
5095 vWorkQueue.push_back(inv.hash);
5097 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
5098 pfrom->id, pfrom->cleanSubVer,
5099 tx.GetHash().ToString(),
5100 mempool.mapTx.size());
5102 // Recursively process any orphan transactions that depended on this one
5103 set<NodeId> setMisbehaving;
5104 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
5106 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
5107 if (itByPrev == mapOrphanTransactionsByPrev.end())
5109 for (set<uint256>::iterator mi = itByPrev->second.begin();
5110 mi != itByPrev->second.end();
5113 const uint256& orphanHash = *mi;
5114 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
5115 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
5116 bool fMissingInputs2 = false;
5117 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
5118 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
5119 // anyone relaying LegitTxX banned)
5120 CValidationState stateDummy;
5123 if (setMisbehaving.count(fromPeer))
5125 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
5127 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
5128 RelayTransaction(orphanTx);
5129 vWorkQueue.push_back(orphanHash);
5130 vEraseQueue.push_back(orphanHash);
5132 else if (!fMissingInputs2)
5135 if (stateDummy.IsInvalid(nDos) && nDos > 0)
5137 // Punish peer that gave us an invalid orphan tx
5138 Misbehaving(fromPeer, nDos);
5139 setMisbehaving.insert(fromPeer);
5140 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
5142 // Has inputs but not accepted to mempool
5143 // Probably non-standard or insufficient fee/priority
5144 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
5145 vEraseQueue.push_back(orphanHash);
5146 assert(recentRejects);
5147 recentRejects->insert(orphanHash);
5149 mempool.check(pcoinsTip);
5153 BOOST_FOREACH(uint256 hash, vEraseQueue)
5154 EraseOrphanTx(hash);
5156 // TODO: currently, prohibit joinsplits from entering mapOrphans
5157 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
5159 AddOrphanTx(tx, pfrom->GetId());
5161 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
5162 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
5163 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
5165 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
5167 assert(recentRejects);
5168 recentRejects->insert(tx.GetHash());
5170 if (pfrom->fWhitelisted) {
5171 // Always relay transactions received from whitelisted peers, even
5172 // if they were already in the mempool or rejected from it due
5173 // to policy, allowing the node to function as a gateway for
5174 // nodes hidden behind it.
5176 // Never relay transactions that we would assign a non-zero DoS
5177 // score for, as we expect peers to do the same with us in that
5180 if (!state.IsInvalid(nDoS) || nDoS == 0) {
5181 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
5182 RelayTransaction(tx);
5184 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
5185 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
5190 if (state.IsInvalid(nDoS))
5192 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
5193 pfrom->id, pfrom->cleanSubVer,
5194 state.GetRejectReason());
5195 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5196 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5198 Misbehaving(pfrom->GetId(), nDoS);
5203 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
5205 std::vector<CBlockHeader> headers;
5207 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
5208 unsigned int nCount = ReadCompactSize(vRecv);
5209 if (nCount > MAX_HEADERS_RESULTS) {
5210 Misbehaving(pfrom->GetId(), 20);
5211 return error("headers message size = %u", nCount);
5213 headers.resize(nCount);
5214 for (unsigned int n = 0; n < nCount; n++) {
5215 vRecv >> headers[n];
5216 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
5222 // Nothing interesting. Stop asking this peers for more headers.
5226 CBlockIndex *pindexLast = NULL;
5227 BOOST_FOREACH(const CBlockHeader& header, headers) {
5228 CValidationState state;
5229 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
5230 Misbehaving(pfrom->GetId(), 20);
5231 return error("non-continuous headers sequence");
5233 if (!AcceptBlockHeader(header, state, &pindexLast)) {
5235 if (state.IsInvalid(nDoS)) {
5237 Misbehaving(pfrom->GetId(), nDoS);
5238 return error("invalid header received");
5244 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
5246 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
5247 // Headers message had its maximum size; the peer may have more headers.
5248 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
5249 // from there instead.
5250 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
5251 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
5257 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
5262 CInv inv(MSG_BLOCK, block.GetHash());
5263 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
5265 pfrom->AddInventoryKnown(inv);
5267 CValidationState state;
5268 // Process all blocks from whitelisted peers, even if not requested,
5269 // unless we're still syncing with the network.
5270 // Such an unrequested block may still be processed, subject to the
5271 // conditions in AcceptBlock().
5272 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
5273 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
5275 if (state.IsInvalid(nDoS)) {
5276 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
5277 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
5280 Misbehaving(pfrom->GetId(), nDoS);
5287 // This asymmetric behavior for inbound and outbound connections was introduced
5288 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
5289 // to users' AddrMan and later request them by sending getaddr messages.
5290 // Making nodes which are behind NAT and can only make outgoing connections ignore
5291 // the getaddr message mitigates the attack.
5292 else if ((strCommand == "getaddr") && (pfrom->fInbound))
5294 // Only send one GetAddr response per connection to reduce resource waste
5295 // and discourage addr stamping of INV announcements.
5296 if (pfrom->fSentAddr) {
5297 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
5300 pfrom->fSentAddr = true;
5302 pfrom->vAddrToSend.clear();
5303 vector<CAddress> vAddr = addrman.GetAddr();
5304 BOOST_FOREACH(const CAddress &addr, vAddr)
5305 pfrom->PushAddress(addr);
5309 else if (strCommand == "mempool")
5311 LOCK2(cs_main, pfrom->cs_filter);
5313 std::vector<uint256> vtxid;
5314 mempool.queryHashes(vtxid);
5316 BOOST_FOREACH(uint256& hash, vtxid) {
5317 CInv inv(MSG_TX, hash);
5319 bool fInMemPool = mempool.lookup(hash, tx);
5320 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
5321 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
5323 vInv.push_back(inv);
5324 if (vInv.size() == MAX_INV_SZ) {
5325 pfrom->PushMessage("inv", vInv);
5329 if (vInv.size() > 0)
5330 pfrom->PushMessage("inv", vInv);
5334 else if (strCommand == "ping")
5336 if (pfrom->nVersion > BIP0031_VERSION)
5340 // Echo the message back with the nonce. This allows for two useful features:
5342 // 1) A remote node can quickly check if the connection is operational
5343 // 2) Remote nodes can measure the latency of the network thread. If this node
5344 // is overloaded it won't respond to pings quickly and the remote node can
5345 // avoid sending us more work, like chain download requests.
5347 // The nonce stops the remote getting confused between different pings: without
5348 // it, if the remote node sends a ping once per second and this node takes 5
5349 // seconds to respond to each, the 5th ping the remote sends would appear to
5350 // return very quickly.
5351 pfrom->PushMessage("pong", nonce);
5356 else if (strCommand == "pong")
5358 int64_t pingUsecEnd = nTimeReceived;
5360 size_t nAvail = vRecv.in_avail();
5361 bool bPingFinished = false;
5362 std::string sProblem;
5364 if (nAvail >= sizeof(nonce)) {
5367 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
5368 if (pfrom->nPingNonceSent != 0) {
5369 if (nonce == pfrom->nPingNonceSent) {
5370 // Matching pong received, this ping is no longer outstanding
5371 bPingFinished = true;
5372 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
5373 if (pingUsecTime > 0) {
5374 // Successful ping time measurement, replace previous
5375 pfrom->nPingUsecTime = pingUsecTime;
5376 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
5378 // This should never happen
5379 sProblem = "Timing mishap";
5382 // Nonce mismatches are normal when pings are overlapping
5383 sProblem = "Nonce mismatch";
5385 // This is most likely a bug in another implementation somewhere; cancel this ping
5386 bPingFinished = true;
5387 sProblem = "Nonce zero";
5391 sProblem = "Unsolicited pong without ping";
5394 // This is most likely a bug in another implementation somewhere; cancel this ping
5395 bPingFinished = true;
5396 sProblem = "Short payload";
5399 if (!(sProblem.empty())) {
5400 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5404 pfrom->nPingNonceSent,
5408 if (bPingFinished) {
5409 pfrom->nPingNonceSent = 0;
5414 else if (fAlerts && strCommand == "alert")
5419 uint256 alertHash = alert.GetHash();
5420 if (pfrom->setKnown.count(alertHash) == 0)
5422 if (alert.ProcessAlert(Params().AlertKey()))
5425 pfrom->setKnown.insert(alertHash);
5428 BOOST_FOREACH(CNode* pnode, vNodes)
5429 alert.RelayTo(pnode);
5433 // Small DoS penalty so peers that send us lots of
5434 // duplicate/expired/invalid-signature/whatever alerts
5435 // eventually get banned.
5436 // This isn't a Misbehaving(100) (immediate ban) because the
5437 // peer might be an older or different implementation with
5438 // a different signature key, etc.
5439 Misbehaving(pfrom->GetId(), 10);
5445 else if (strCommand == "filterload")
5447 CBloomFilter filter;
5450 if (!filter.IsWithinSizeConstraints())
5451 // There is no excuse for sending a too-large filter
5452 Misbehaving(pfrom->GetId(), 100);
5455 LOCK(pfrom->cs_filter);
5456 delete pfrom->pfilter;
5457 pfrom->pfilter = new CBloomFilter(filter);
5458 pfrom->pfilter->UpdateEmptyFull();
5460 pfrom->fRelayTxes = true;
5464 else if (strCommand == "filteradd")
5466 vector<unsigned char> vData;
5469 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5470 // and thus, the maximum size any matched object can have) in a filteradd message
5471 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5473 Misbehaving(pfrom->GetId(), 100);
5475 LOCK(pfrom->cs_filter);
5477 pfrom->pfilter->insert(vData);
5479 Misbehaving(pfrom->GetId(), 100);
5484 else if (strCommand == "filterclear")
5486 LOCK(pfrom->cs_filter);
5487 delete pfrom->pfilter;
5488 pfrom->pfilter = new CBloomFilter();
5489 pfrom->fRelayTxes = true;
5493 else if (strCommand == "reject")
5497 string strMsg; unsigned char ccode; string strReason;
5498 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5501 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5503 if (strMsg == "block" || strMsg == "tx")
5507 ss << ": hash " << hash.ToString();
5509 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5510 } catch (const std::ios_base::failure&) {
5511 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5512 LogPrint("net", "Unparseable reject message received\n");
5517 else if (strCommand == "notfound") {
5518 // We do not care about the NOTFOUND message, but logging an Unknown Command
5519 // message would be undesirable as we transmit it ourselves.
5523 // Ignore unknown commands for extensibility
5524 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5532 // requires LOCK(cs_vRecvMsg)
5533 bool ProcessMessages(CNode* pfrom)
5536 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5540 // (4) message start
5548 if (!pfrom->vRecvGetData.empty())
5549 ProcessGetData(pfrom);
5551 // this maintains the order of responses
5552 if (!pfrom->vRecvGetData.empty()) return fOk;
5554 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5555 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5556 // Don't bother if send buffer is too full to respond anyway
5557 if (pfrom->nSendSize >= SendBufferSize())
5561 CNetMessage& msg = *it;
5564 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5565 // msg.hdr.nMessageSize, msg.vRecv.size(),
5566 // msg.complete() ? "Y" : "N");
5568 // end, if an incomplete message is found
5569 if (!msg.complete())
5572 // at this point, any failure means we can delete the current message
5575 // Scan for message start
5576 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5577 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5583 CMessageHeader& hdr = msg.hdr;
5584 if (!hdr.IsValid(Params().MessageStart()))
5586 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5589 string strCommand = hdr.GetCommand();
5592 unsigned int nMessageSize = hdr.nMessageSize;
5595 CDataStream& vRecv = msg.vRecv;
5596 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5597 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5598 if (nChecksum != hdr.nChecksum)
5600 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5601 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5609 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5610 boost::this_thread::interruption_point();
5612 catch (const std::ios_base::failure& e)
5614 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5615 if (strstr(e.what(), "end of data"))
5617 // Allow exceptions from under-length message on vRecv
5618 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());
5620 else if (strstr(e.what(), "size too large"))
5622 // Allow exceptions from over-long size
5623 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5627 PrintExceptionContinue(&e, "ProcessMessages()");
5630 catch (const boost::thread_interrupted&) {
5633 catch (const std::exception& e) {
5634 PrintExceptionContinue(&e, "ProcessMessages()");
5636 PrintExceptionContinue(NULL, "ProcessMessages()");
5640 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5645 // In case the connection got shut down, its receive buffer was wiped
5646 if (!pfrom->fDisconnect)
5647 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5653 bool SendMessages(CNode* pto, bool fSendTrickle)
5655 const Consensus::Params& consensusParams = Params().GetConsensus();
5657 // Don't send anything until we get its version message
5658 if (pto->nVersion == 0)
5664 bool pingSend = false;
5665 if (pto->fPingQueued) {
5666 // RPC ping request by user
5669 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5670 // Ping automatically sent as a latency probe & keepalive.
5675 while (nonce == 0) {
5676 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5678 pto->fPingQueued = false;
5679 pto->nPingUsecStart = GetTimeMicros();
5680 if (pto->nVersion > BIP0031_VERSION) {
5681 pto->nPingNonceSent = nonce;
5682 pto->PushMessage("ping", nonce);
5684 // Peer is too old to support ping command with nonce, pong will never arrive.
5685 pto->nPingNonceSent = 0;
5686 pto->PushMessage("ping");
5690 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5694 // Address refresh broadcast
5695 static int64_t nLastRebroadcast;
5696 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5699 BOOST_FOREACH(CNode* pnode, vNodes)
5701 // Periodically clear addrKnown to allow refresh broadcasts
5702 if (nLastRebroadcast)
5703 pnode->addrKnown.reset();
5705 // Rebroadcast our address
5706 AdvertizeLocal(pnode);
5708 if (!vNodes.empty())
5709 nLastRebroadcast = GetTime();
5717 vector<CAddress> vAddr;
5718 vAddr.reserve(pto->vAddrToSend.size());
5719 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5721 if (!pto->addrKnown.contains(addr.GetKey()))
5723 pto->addrKnown.insert(addr.GetKey());
5724 vAddr.push_back(addr);
5725 // receiver rejects addr messages larger than 1000
5726 if (vAddr.size() >= 1000)
5728 pto->PushMessage("addr", vAddr);
5733 pto->vAddrToSend.clear();
5735 pto->PushMessage("addr", vAddr);
5738 CNodeState &state = *State(pto->GetId());
5739 if (state.fShouldBan) {
5740 if (pto->fWhitelisted)
5741 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5743 pto->fDisconnect = true;
5744 if (pto->addr.IsLocal())
5745 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5748 CNode::Ban(pto->addr);
5751 state.fShouldBan = false;
5754 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5755 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5756 state.rejects.clear();
5759 if (pindexBestHeader == NULL)
5760 pindexBestHeader = chainActive.Tip();
5761 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.
5762 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5763 // Only actively request headers from a single peer, unless we're close to today.
5764 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5765 state.fSyncStarted = true;
5767 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5768 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5769 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5773 // Resend wallet transactions that haven't gotten in a block yet
5774 // Except during reindex, importing and IBD, when old wallet
5775 // transactions become unconfirmed and spams other nodes.
5776 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5778 GetMainSignals().Broadcast(nTimeBestReceived);
5782 // Message: inventory
5785 vector<CInv> vInvWait;
5787 LOCK(pto->cs_inventory);
5788 vInv.reserve(pto->vInventoryToSend.size());
5789 vInvWait.reserve(pto->vInventoryToSend.size());
5790 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5792 if (pto->setInventoryKnown.count(inv))
5795 // trickle out tx inv to protect privacy
5796 if (inv.type == MSG_TX && !fSendTrickle)
5798 // 1/4 of tx invs blast to all immediately
5799 static uint256 hashSalt;
5800 if (hashSalt.IsNull())
5801 hashSalt = GetRandHash();
5802 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5803 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5804 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5808 vInvWait.push_back(inv);
5813 // returns true if wasn't already contained in the set
5814 if (pto->setInventoryKnown.insert(inv).second)
5816 vInv.push_back(inv);
5817 if (vInv.size() >= 1000)
5819 pto->PushMessage("inv", vInv);
5824 pto->vInventoryToSend = vInvWait;
5827 pto->PushMessage("inv", vInv);
5829 // Detect whether we're stalling
5830 int64_t nNow = GetTimeMicros();
5831 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5832 // Stalling only triggers when the block download window cannot move. During normal steady state,
5833 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5834 // should only happen during initial block download.
5835 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5836 pto->fDisconnect = true;
5838 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5839 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5840 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5841 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5842 // to unreasonably increase our timeout.
5843 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5844 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5845 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5846 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5847 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5848 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5849 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5850 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5851 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5852 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5853 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5855 if (queuedBlock.nTimeDisconnect < nNow) {
5856 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5857 pto->fDisconnect = true;
5862 // Message: getdata (blocks)
5864 vector<CInv> vGetData;
5865 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5866 vector<CBlockIndex*> vToDownload;
5867 NodeId staller = -1;
5868 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5869 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5870 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5871 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5872 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5873 pindex->nHeight, pto->id);
5875 if (state.nBlocksInFlight == 0 && staller != -1) {
5876 if (State(staller)->nStallingSince == 0) {
5877 State(staller)->nStallingSince = nNow;
5878 LogPrint("net", "Stall started peer=%d\n", staller);
5884 // Message: getdata (non-blocks)
5886 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5888 const CInv& inv = (*pto->mapAskFor.begin()).second;
5889 if (!AlreadyHave(inv))
5892 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5893 vGetData.push_back(inv);
5894 if (vGetData.size() >= 1000)
5896 pto->PushMessage("getdata", vGetData);
5900 //If we're not going to ask, don't expect a response.
5901 pto->setAskFor.erase(inv.hash);
5903 pto->mapAskFor.erase(pto->mapAskFor.begin());
5905 if (!vGetData.empty())
5906 pto->PushMessage("getdata", vGetData);
5912 std::string CBlockFileInfo::ToString() const {
5913 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));
5924 BlockMap::iterator it1 = mapBlockIndex.begin();
5925 for (; it1 != mapBlockIndex.end(); it1++)
5926 delete (*it1).second;
5927 mapBlockIndex.clear();
5929 // orphan transactions
5930 mapOrphanTransactions.clear();
5931 mapOrphanTransactionsByPrev.clear();
5933 } instance_of_cmaincleanup;
5936 // Set default values of new CMutableTransaction based on consensus rules at given height.
5937 CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight)
5939 CMutableTransaction mtx;
5941 bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER);
5942 if (isOverwintered) {
5943 mtx.fOverwintered = true;
5944 mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID;
5946 // Expiry height is not set. Only fields required for a parser to treat as a valid Overwinter V3 tx.
5948 // TODO: In future, when moving from Overwinter to Sapling, it will be useful
5949 // to set the expiry height to: min(activation_height - 1, default_expiry_height)