1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "arith_uint256.h"
13 #include "chainparams.h"
14 #include "checkpoints.h"
15 #include "checkqueue.h"
16 #include "consensus/validation.h"
18 #include "merkleblock.h"
23 #include "txmempool.h"
24 #include "ui_interface.h"
27 #include "utilmoneystr.h"
28 #include "validationinterface.h"
29 #include "wallet/asyncrpcoperation_sendmany.h"
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/filesystem/fstream.hpp>
36 #include <boost/math/distributions/poisson.hpp>
37 #include <boost/thread.hpp>
38 #include <boost/static_assert.hpp>
43 # error "Zcash cannot be compiled without assertions."
50 CCriticalSection cs_main;
52 BlockMap mapBlockIndex;
54 CBlockIndex *pindexBestHeader = NULL;
55 int64_t nTimeBestReceived = 0;
56 CWaitableCriticalSection csBestBlock;
57 CConditionVariable cvBlockChange;
58 int nScriptCheckThreads = 0;
59 bool fImporting = false;
60 bool fReindex = false;
61 bool fTxIndex = false;
62 bool fHavePruned = false;
63 bool fPruneMode = false;
64 bool fIsBareMultisigStd = true;
65 bool fCheckBlockIndex = false;
66 bool fCheckpointsEnabled = true;
67 bool fCoinbaseEnforcedProtectionEnabled = true;
68 size_t nCoinCacheUsage = 5000 * 300;
69 uint64_t nPruneTarget = 0;
70 bool fAlerts = DEFAULT_ALERTS;
72 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
73 CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
75 CTxMemPool mempool(::minRelayTxFee);
81 map<uint256, COrphanTx> mapOrphanTransactions;
82 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
83 void EraseOrphansFor(NodeId peer);
86 * Returns true if there are nRequired or more blocks of minVersion or above
87 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
89 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
90 static void CheckBlockIndex();
92 /** Constant stuff for coinbase transactions we create: */
93 CScript COINBASE_FLAGS;
95 const string strMessageMagic = "Zcash Signed Message:\n";
100 struct CBlockIndexWorkComparator
102 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
103 // First sort by most total work, ...
104 if (pa->nChainWork > pb->nChainWork) return false;
105 if (pa->nChainWork < pb->nChainWork) return true;
107 // ... then by earliest time received, ...
108 if (pa->nSequenceId < pb->nSequenceId) return false;
109 if (pa->nSequenceId > pb->nSequenceId) return true;
111 // Use pointer address as tie breaker (should only happen with blocks
112 // loaded from disk, as those all have id 0).
113 if (pa < pb) return false;
114 if (pa > pb) return true;
121 CBlockIndex *pindexBestInvalid;
124 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
125 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
126 * missing the data for the block.
128 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
129 /** Number of nodes with fSyncStarted. */
130 int nSyncStarted = 0;
131 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
132 * Pruned nodes may have entries where B is missing data.
134 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
136 CCriticalSection cs_LastBlockFile;
137 std::vector<CBlockFileInfo> vinfoBlockFile;
138 int nLastBlockFile = 0;
139 /** Global flag to indicate we should check to see if there are
140 * block/undo files that should be deleted. Set on startup
141 * or if we allocate more file space when we're in prune mode
143 bool fCheckForPruning = false;
146 * Every received block is assigned a unique and increasing identifier, so we
147 * know which one to give priority in case of a fork.
149 CCriticalSection cs_nBlockSequenceId;
150 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
151 uint32_t nBlockSequenceId = 1;
154 * Sources of received blocks, saved to be able to send them reject
155 * messages or ban them when processing happens afterwards. Protected by
158 map<uint256, NodeId> mapBlockSource;
161 * Filter for transactions that were recently rejected by
162 * AcceptToMemoryPool. These are not rerequested until the chain tip
163 * changes, at which point the entire filter is reset. Protected by
166 * Without this filter we'd be re-requesting txs from each of our peers,
167 * increasing bandwidth consumption considerably. For instance, with 100
168 * peers, half of which relay a tx we don't accept, that might be a 50x
169 * bandwidth increase. A flooding attacker attempting to roll-over the
170 * filter using minimum-sized, 60byte, transactions might manage to send
171 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
172 * two minute window to send invs to us.
174 * Decreasing the false positive rate is fairly cheap, so we pick one in a
175 * million to make it highly unlikely for users to have issues with this
180 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
181 uint256 hashRecentRejectsChainTip;
183 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
186 CBlockIndex *pindex; //! Optional.
187 int64_t nTime; //! Time of "getdata" request in microseconds.
188 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
189 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
191 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
193 /** Number of blocks in flight with validated headers. */
194 int nQueuedValidatedHeaders = 0;
196 /** Number of preferable block download peers. */
197 int nPreferredDownload = 0;
199 /** Dirty block index entries. */
200 set<CBlockIndex*> setDirtyBlockIndex;
202 /** Dirty block file entries. */
203 set<int> setDirtyFileInfo;
206 //////////////////////////////////////////////////////////////////////////////
208 // Registration of network node signals.
213 struct CBlockReject {
214 unsigned char chRejectCode;
215 string strRejectReason;
220 * Maintain validation-specific state about nodes, protected by cs_main, instead
221 * by CNode's own locks. This simplifies asynchronous operation, where
222 * processing of incoming data is done after the ProcessMessage call returns,
223 * and we're no longer holding the node's locks.
226 //! The peer's address
228 //! Whether we have a fully established connection.
229 bool fCurrentlyConnected;
230 //! Accumulated misbehaviour score for this peer.
232 //! Whether this peer should be disconnected and banned (unless whitelisted).
234 //! String name of this peer (debugging/logging purposes).
236 //! List of asynchronously-determined block rejections to notify this peer about.
237 std::vector<CBlockReject> rejects;
238 //! The best known block we know this peer has announced.
239 CBlockIndex *pindexBestKnownBlock;
240 //! The hash of the last unknown block this peer has announced.
241 uint256 hashLastUnknownBlock;
242 //! The last full block we both have.
243 CBlockIndex *pindexLastCommonBlock;
244 //! Whether we've started headers synchronization with this peer.
246 //! Since when we're stalling block download progress (in microseconds), or 0.
247 int64_t nStallingSince;
248 list<QueuedBlock> vBlocksInFlight;
250 int nBlocksInFlightValidHeaders;
251 //! Whether we consider this a preferred download peer.
252 bool fPreferredDownload;
255 fCurrentlyConnected = false;
258 pindexBestKnownBlock = NULL;
259 hashLastUnknownBlock.SetNull();
260 pindexLastCommonBlock = NULL;
261 fSyncStarted = false;
264 nBlocksInFlightValidHeaders = 0;
265 fPreferredDownload = false;
269 /** Map maintaining per-node state. Requires cs_main. */
270 map<NodeId, CNodeState> mapNodeState;
273 CNodeState *State(NodeId pnode) {
274 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
275 if (it == mapNodeState.end())
283 return chainActive.Height();
286 void UpdatePreferredDownload(CNode* node, CNodeState* state)
288 nPreferredDownload -= state->fPreferredDownload;
290 // Whether this node should be marked as a preferred download node.
291 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
293 nPreferredDownload += state->fPreferredDownload;
296 // Returns time at which to timeout block request (nTime in microseconds)
297 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
299 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
302 void InitializeNode(NodeId nodeid, const CNode *pnode) {
304 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
305 state.name = pnode->addrName;
306 state.address = pnode->addr;
309 void FinalizeNode(NodeId nodeid) {
311 CNodeState *state = State(nodeid);
313 if (state->fSyncStarted)
316 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
317 AddressCurrentlyConnected(state->address);
320 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
321 mapBlocksInFlight.erase(entry.hash);
322 EraseOrphansFor(nodeid);
323 nPreferredDownload -= state->fPreferredDownload;
325 mapNodeState.erase(nodeid);
329 // Returns a bool indicating whether we requested this block.
330 bool MarkBlockAsReceived(const uint256& hash) {
331 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
332 if (itInFlight != mapBlocksInFlight.end()) {
333 CNodeState *state = State(itInFlight->second.first);
334 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
335 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
336 state->vBlocksInFlight.erase(itInFlight->second.second);
337 state->nBlocksInFlight--;
338 state->nStallingSince = 0;
339 mapBlocksInFlight.erase(itInFlight);
346 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
347 CNodeState *state = State(nodeid);
348 assert(state != NULL);
350 // Make sure it's not listed somewhere already.
351 MarkBlockAsReceived(hash);
353 int64_t nNow = GetTimeMicros();
354 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
355 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
356 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
357 state->nBlocksInFlight++;
358 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
359 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
362 /** Check whether the last unknown block a peer advertized is not yet known. */
363 void ProcessBlockAvailability(NodeId nodeid) {
364 CNodeState *state = State(nodeid);
365 assert(state != NULL);
367 if (!state->hashLastUnknownBlock.IsNull()) {
368 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
369 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
370 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
371 state->pindexBestKnownBlock = itOld->second;
372 state->hashLastUnknownBlock.SetNull();
377 /** Update tracking information about which blocks a peer is assumed to have. */
378 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
379 CNodeState *state = State(nodeid);
380 assert(state != NULL);
382 ProcessBlockAvailability(nodeid);
384 BlockMap::iterator it = mapBlockIndex.find(hash);
385 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
386 // An actually better block was announced.
387 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
388 state->pindexBestKnownBlock = it->second;
390 // An unknown block was announced; just assume that the latest one is the best one.
391 state->hashLastUnknownBlock = hash;
395 /** Find the last common ancestor two blocks have.
396 * Both pa and pb must be non-NULL. */
397 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
398 if (pa->nHeight > pb->nHeight) {
399 pa = pa->GetAncestor(pb->nHeight);
400 } else if (pb->nHeight > pa->nHeight) {
401 pb = pb->GetAncestor(pa->nHeight);
404 while (pa != pb && pa && pb) {
409 // Eventually all chain branches meet at the genesis block.
414 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
415 * at most count entries. */
416 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
420 vBlocks.reserve(vBlocks.size() + count);
421 CNodeState *state = State(nodeid);
422 assert(state != NULL);
424 // Make sure pindexBestKnownBlock is up to date, we'll need it.
425 ProcessBlockAvailability(nodeid);
427 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
428 // This peer has nothing interesting.
432 if (state->pindexLastCommonBlock == NULL) {
433 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
434 // Guessing wrong in either direction is not a problem.
435 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
438 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
439 // of its current tip anymore. Go back enough to fix that.
440 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
441 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
444 std::vector<CBlockIndex*> vToFetch;
445 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
446 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
447 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
448 // download that next block if the window were 1 larger.
449 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
450 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
451 NodeId waitingfor = -1;
452 while (pindexWalk->nHeight < nMaxHeight) {
453 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
454 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
455 // as iterating over ~100 CBlockIndex* entries anyway.
456 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
457 vToFetch.resize(nToFetch);
458 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
459 vToFetch[nToFetch - 1] = pindexWalk;
460 for (unsigned int i = nToFetch - 1; i > 0; i--) {
461 vToFetch[i - 1] = vToFetch[i]->pprev;
464 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
465 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
466 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
467 // already part of our chain (and therefore don't need it even if pruned).
468 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
469 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
470 // We consider the chain that this peer is on invalid.
473 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
474 if (pindex->nChainTx)
475 state->pindexLastCommonBlock = pindex;
476 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
477 // The block is not already downloaded, and not yet in flight.
478 if (pindex->nHeight > nWindowEnd) {
479 // We reached the end of the window.
480 if (vBlocks.size() == 0 && waitingfor != nodeid) {
481 // We aren't able to fetch anything, but we would be if the download window was one larger.
482 nodeStaller = waitingfor;
486 vBlocks.push_back(pindex);
487 if (vBlocks.size() == count) {
490 } else if (waitingfor == -1) {
491 // This is the first already-in-flight block.
492 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
500 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
502 CNodeState *state = State(nodeid);
505 stats.nMisbehavior = state->nMisbehavior;
506 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
507 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
508 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
510 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
515 void RegisterNodeSignals(CNodeSignals& nodeSignals)
517 nodeSignals.GetHeight.connect(&GetHeight);
518 nodeSignals.ProcessMessages.connect(&ProcessMessages);
519 nodeSignals.SendMessages.connect(&SendMessages);
520 nodeSignals.InitializeNode.connect(&InitializeNode);
521 nodeSignals.FinalizeNode.connect(&FinalizeNode);
524 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
526 nodeSignals.GetHeight.disconnect(&GetHeight);
527 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
528 nodeSignals.SendMessages.disconnect(&SendMessages);
529 nodeSignals.InitializeNode.disconnect(&InitializeNode);
530 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
533 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
535 // Find the first block the caller has in the main chain
536 BOOST_FOREACH(const uint256& hash, locator.vHave) {
537 BlockMap::iterator mi = mapBlockIndex.find(hash);
538 if (mi != mapBlockIndex.end())
540 CBlockIndex* pindex = (*mi).second;
541 if (chain.Contains(pindex))
545 return chain.Genesis();
548 CCoinsViewCache *pcoinsTip = NULL;
549 CBlockTreeDB *pblocktree = NULL;
551 //////////////////////////////////////////////////////////////////////////////
553 // mapOrphanTransactions
556 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
558 uint256 hash = tx.GetHash();
559 if (mapOrphanTransactions.count(hash))
562 // Ignore big transactions, to avoid a
563 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
564 // large transaction with a missing parent then we assume
565 // it will rebroadcast it later, after the parent transaction(s)
566 // have been mined or received.
567 // 10,000 orphans, each of which is at most 5,000 bytes big is
568 // at most 500 megabytes of orphans:
569 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, tx.nVersion);
572 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
576 mapOrphanTransactions[hash].tx = tx;
577 mapOrphanTransactions[hash].fromPeer = peer;
578 BOOST_FOREACH(const CTxIn& txin, tx.vin)
579 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
581 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
582 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
586 void static EraseOrphanTx(uint256 hash)
588 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
589 if (it == mapOrphanTransactions.end())
591 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
593 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
594 if (itPrev == mapOrphanTransactionsByPrev.end())
596 itPrev->second.erase(hash);
597 if (itPrev->second.empty())
598 mapOrphanTransactionsByPrev.erase(itPrev);
600 mapOrphanTransactions.erase(it);
603 void EraseOrphansFor(NodeId peer)
606 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
607 while (iter != mapOrphanTransactions.end())
609 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
610 if (maybeErase->second.fromPeer == peer)
612 EraseOrphanTx(maybeErase->second.tx.GetHash());
616 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
620 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
622 unsigned int nEvicted = 0;
623 while (mapOrphanTransactions.size() > nMaxOrphans)
625 // Evict a random orphan:
626 uint256 randomhash = GetRandHash();
627 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
628 if (it == mapOrphanTransactions.end())
629 it = mapOrphanTransactions.begin();
630 EraseOrphanTx(it->first);
642 bool IsStandardTx(const CTransaction& tx, string& reason)
644 if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) {
649 BOOST_FOREACH(const CTxIn& txin, tx.vin)
651 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
652 // keys. (remember the 520 byte limit on redeemScript size) That works
653 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
654 // bytes of scriptSig, which we round off to 1650 bytes for some minor
655 // future-proofing. That's also enough to spend a 20-of-20
656 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
657 // considered standard)
658 if (txin.scriptSig.size() > 1650) {
659 reason = "scriptsig-size";
662 if (!txin.scriptSig.IsPushOnly()) {
663 reason = "scriptsig-not-pushonly";
668 unsigned int nDataOut = 0;
669 txnouttype whichType;
670 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
671 if (!::IsStandard(txout.scriptPubKey, whichType)) {
672 reason = "scriptpubkey";
676 if (whichType == TX_NULL_DATA)
678 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
679 reason = "bare-multisig";
681 } else if (txout.IsDust(::minRelayTxFee)) {
687 // only one OP_RETURN txout is permitted
689 reason = "multi-op-return";
696 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
698 if (tx.nLockTime == 0)
700 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
702 BOOST_FOREACH(const CTxIn& txin, tx.vin)
708 bool CheckFinalTx(const CTransaction &tx, int flags)
710 AssertLockHeld(cs_main);
712 // By convention a negative value for flags indicates that the
713 // current network-enforced consensus rules should be used. In
714 // a future soft-fork scenario that would mean checking which
715 // rules would be enforced for the next block and setting the
716 // appropriate flags. At the present time no soft-forks are
717 // scheduled, so no flags are set.
718 flags = std::max(flags, 0);
720 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
721 // nLockTime because when IsFinalTx() is called within
722 // CBlock::AcceptBlock(), the height of the block *being*
723 // evaluated is what is used. Thus if we want to know if a
724 // transaction can be part of the *next* block, we need to call
725 // IsFinalTx() with one more than chainActive.Height().
726 const int nBlockHeight = chainActive.Height() + 1;
728 // Timestamps on the other hand don't get any special treatment,
729 // because we can't know what timestamp the next block will have,
730 // and there aren't timestamp applications where it matters.
731 // However this changes once median past time-locks are enforced:
732 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
733 ? chainActive.Tip()->GetMedianTimePast()
736 return IsFinalTx(tx, nBlockHeight, nBlockTime);
740 * Check transaction inputs to mitigate two
741 * potential denial-of-service attacks:
743 * 1. scriptSigs with extra data stuffed into them,
744 * not consumed by scriptPubKey (or P2SH script)
745 * 2. P2SH scripts with a crazy number of expensive
746 * CHECKSIG/CHECKMULTISIG operations
748 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
751 return true; // Coinbases don't use vin normally
753 for (unsigned int i = 0; i < tx.vin.size(); i++)
755 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
757 vector<vector<unsigned char> > vSolutions;
758 txnouttype whichType;
759 // get the scriptPubKey corresponding to this input:
760 const CScript& prevScript = prev.scriptPubKey;
761 if (!Solver(prevScript, whichType, vSolutions))
763 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
764 if (nArgsExpected < 0)
767 // Transactions with extra stuff in their scriptSigs are
768 // non-standard. Note that this EvalScript() call will
769 // be quick, because if there are any operations
770 // beside "push data" in the scriptSig
771 // IsStandardTx() will have already returned false
772 // and this method isn't called.
773 vector<vector<unsigned char> > stack;
774 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
777 if (whichType == TX_SCRIPTHASH)
781 CScript subscript(stack.back().begin(), stack.back().end());
782 vector<vector<unsigned char> > vSolutions2;
783 txnouttype whichType2;
784 if (Solver(subscript, whichType2, vSolutions2))
786 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
789 nArgsExpected += tmpExpected;
793 // Any other Script with less than 15 sigops OK:
794 unsigned int sigops = subscript.GetSigOpCount(true);
795 // ... extra data left on the stack after execution is OK, too:
796 return (sigops <= MAX_P2SH_SIGOPS);
800 if (stack.size() != (unsigned int)nArgsExpected)
807 unsigned int GetLegacySigOpCount(const CTransaction& tx)
809 unsigned int nSigOps = 0;
810 BOOST_FOREACH(const CTxIn& txin, tx.vin)
812 nSigOps += txin.scriptSig.GetSigOpCount(false);
814 BOOST_FOREACH(const CTxOut& txout, tx.vout)
816 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
821 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
826 unsigned int nSigOps = 0;
827 for (unsigned int i = 0; i < tx.vin.size(); i++)
829 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
830 if (prevout.scriptPubKey.IsPayToScriptHash())
831 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
836 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
838 // Don't count coinbase transactions because mining skews the count
839 if (!tx.IsCoinBase()) {
840 transactionsValidated.increment();
843 if (!CheckTransactionWithoutProofVerification(tx, state)) {
846 // Ensure that zk-SNARKs verify
847 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
848 if (!joinsplit.Verify(*pzcashParams, tx.joinSplitPubKey)) {
849 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
850 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
857 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
859 // Basic checks that don't depend on any context
861 // Check transaction version
862 if (tx.nVersion < MIN_TX_VERSION) {
863 return state.DoS(100, error("CheckTransaction(): version too low"),
864 REJECT_INVALID, "bad-txns-version-too-low");
867 // Transactions can contain empty `vin` and `vout` so long as
868 // `vjoinsplit` is non-empty.
869 if (tx.vin.empty() && tx.vjoinsplit.empty())
870 return state.DoS(10, error("CheckTransaction(): vin empty"),
871 REJECT_INVALID, "bad-txns-vin-empty");
872 if (tx.vout.empty() && tx.vjoinsplit.empty())
873 return state.DoS(10, error("CheckTransaction(): vout empty"),
874 REJECT_INVALID, "bad-txns-vout-empty");
877 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
878 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
879 return state.DoS(100, error("CheckTransaction(): size limits failed"),
880 REJECT_INVALID, "bad-txns-oversize");
882 // Check for negative or overflow output values
883 CAmount nValueOut = 0;
884 BOOST_FOREACH(const CTxOut& txout, tx.vout)
886 if (txout.nValue < 0)
887 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
888 REJECT_INVALID, "bad-txns-vout-negative");
889 if (txout.nValue > MAX_MONEY)
890 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
891 REJECT_INVALID, "bad-txns-vout-toolarge");
892 nValueOut += txout.nValue;
893 if (!MoneyRange(nValueOut))
894 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
895 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
898 // Ensure that joinsplit values are well-formed
899 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
901 if (joinsplit.vpub_old < 0) {
902 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
903 REJECT_INVALID, "bad-txns-vpub_old-negative");
906 if (joinsplit.vpub_new < 0) {
907 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
908 REJECT_INVALID, "bad-txns-vpub_new-negative");
911 if (joinsplit.vpub_old > MAX_MONEY) {
912 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
913 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
916 if (joinsplit.vpub_new > MAX_MONEY) {
917 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
918 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
921 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
922 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
923 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
926 nValueOut += joinsplit.vpub_old;
927 if (!MoneyRange(nValueOut)) {
928 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
929 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
933 // Ensure input values do not exceed MAX_MONEY
934 // We have not resolved the txin values at this stage,
935 // but we do know what the joinsplits claim to add
936 // to the value pool.
938 CAmount nValueIn = 0;
939 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
941 nValueIn += it->vpub_new;
943 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
944 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
945 REJECT_INVALID, "bad-txns-txintotal-toolarge");
951 // Check for duplicate inputs
952 set<COutPoint> vInOutPoints;
953 BOOST_FOREACH(const CTxIn& txin, tx.vin)
955 if (vInOutPoints.count(txin.prevout))
956 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
957 REJECT_INVALID, "bad-txns-inputs-duplicate");
958 vInOutPoints.insert(txin.prevout);
961 // Check for duplicate joinsplit nullifiers in this transaction
962 set<uint256> vJoinSplitNullifiers;
963 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
965 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
967 if (vJoinSplitNullifiers.count(nf))
968 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
969 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
971 vJoinSplitNullifiers.insert(nf);
977 // There should be no joinsplits in a coinbase transaction
978 if (tx.vjoinsplit.size() > 0)
979 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
980 REJECT_INVALID, "bad-cb-has-joinsplits");
982 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
983 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
984 REJECT_INVALID, "bad-cb-length");
988 BOOST_FOREACH(const CTxIn& txin, tx.vin)
989 if (txin.prevout.IsNull())
990 return state.DoS(10, error("CheckTransaction(): prevout is null"),
991 REJECT_INVALID, "bad-txns-prevout-null");
993 if (tx.vjoinsplit.size() > 0) {
994 // Empty output script.
996 uint256 dataToBeSigned;
998 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
999 } catch (std::logic_error ex) {
1000 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1001 REJECT_INVALID, "error-computing-signature-hash");
1004 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1006 // We rely on libsodium to check that the signature is canonical.
1007 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1008 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1009 dataToBeSigned.begin(), 32,
1010 tx.joinSplitPubKey.begin()
1012 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1013 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1021 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1025 uint256 hash = tx.GetHash();
1026 double dPriorityDelta = 0;
1027 CAmount nFeeDelta = 0;
1028 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1029 if (dPriorityDelta > 0 || nFeeDelta > 0)
1033 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1037 // There is a free transaction area in blocks created by most miners,
1038 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1039 // to be considered to fall into this category. We don't want to encourage sending
1040 // multiple transactions instead of one big transaction to avoid fees.
1041 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1045 if (!MoneyRange(nMinFee))
1046 nMinFee = MAX_MONEY;
1051 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1052 bool* pfMissingInputs, bool fRejectAbsurdFee)
1054 AssertLockHeld(cs_main);
1055 if (pfMissingInputs)
1056 *pfMissingInputs = false;
1058 if (!CheckTransaction(tx, state))
1059 return error("AcceptToMemoryPool: CheckTransaction failed");
1061 // Coinbase is only valid in a block, not as a loose transaction
1062 if (tx.IsCoinBase())
1063 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1064 REJECT_INVALID, "coinbase");
1066 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1068 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1070 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1071 REJECT_NONSTANDARD, reason);
1073 // Only accept nLockTime-using transactions that can be mined in the next
1074 // block; we don't want our mempool filled up with transactions that can't
1076 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1077 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1079 // is it already in the memory pool?
1080 uint256 hash = tx.GetHash();
1081 if (pool.exists(hash))
1084 // Check for conflicts with in-memory transactions
1086 LOCK(pool.cs); // protect pool.mapNextTx
1087 for (unsigned int i = 0; i < tx.vin.size(); i++)
1089 COutPoint outpoint = tx.vin[i].prevout;
1090 if (pool.mapNextTx.count(outpoint))
1092 // Disable replacement feature for now
1096 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1097 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1098 if (pool.mapNullifiers.count(nf))
1108 CCoinsViewCache view(&dummy);
1110 CAmount nValueIn = 0;
1113 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1114 view.SetBackend(viewMemPool);
1116 // do we already have it?
1117 if (view.HaveCoins(hash))
1120 // do all inputs exist?
1121 // Note that this does not check for the presence of actual outputs (see the next check for that),
1122 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1123 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1124 if (!view.HaveCoins(txin.prevout.hash)) {
1125 if (pfMissingInputs)
1126 *pfMissingInputs = true;
1131 // are the actual inputs available?
1132 if (!view.HaveInputs(tx))
1133 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1134 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1136 // are the joinsplit's requirements met?
1137 if (!view.HaveJoinSplitRequirements(tx))
1138 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1139 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1141 // Bring the best block into scope
1142 view.GetBestBlock();
1144 nValueIn = view.GetValueIn(tx);
1146 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1147 view.SetBackend(dummy);
1150 // Check for non-standard pay-to-script-hash in inputs
1151 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1152 return error("AcceptToMemoryPool: nonstandard transaction input");
1154 // Check that the transaction doesn't have an excessive number of
1155 // sigops, making it impossible to mine. Since the coinbase transaction
1156 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1157 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1158 // merely non-standard transaction.
1159 unsigned int nSigOps = GetLegacySigOpCount(tx);
1160 nSigOps += GetP2SHSigOpCount(tx, view);
1161 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1163 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1164 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1165 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1167 CAmount nValueOut = tx.GetValueOut();
1168 CAmount nFees = nValueIn-nValueOut;
1169 double dPriority = view.GetPriority(tx, chainActive.Height());
1171 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1172 unsigned int nSize = entry.GetTxSize();
1174 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1175 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1176 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1178 // Don't accept it if it can't get into a block
1179 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1180 if (fLimitFree && nFees < txMinFee)
1181 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1182 hash.ToString(), nFees, txMinFee),
1183 REJECT_INSUFFICIENTFEE, "insufficient fee");
1186 // Require that free transactions have sufficient priority to be mined in the next block.
1187 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1188 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1191 // Continuously rate-limit free (really, very-low-fee) transactions
1192 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1193 // be annoying or make others' transactions take longer to confirm.
1194 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1196 static CCriticalSection csFreeLimiter;
1197 static double dFreeCount;
1198 static int64_t nLastTime;
1199 int64_t nNow = GetTime();
1201 LOCK(csFreeLimiter);
1203 // Use an exponentially decaying ~10-minute window:
1204 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1206 // -limitfreerelay unit is thousand-bytes-per-minute
1207 // At default rate it would take over a month to fill 1GB
1208 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1209 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1210 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1211 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1212 dFreeCount += nSize;
1215 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1216 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1218 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1220 // Check against previous transactions
1221 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1222 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1224 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1227 // Check again against just the consensus-critical mandatory script
1228 // verification flags, in case of bugs in the standard flags that cause
1229 // transactions to pass as valid when they're actually invalid. For
1230 // instance the STRICTENC flag was incorrectly allowing certain
1231 // CHECKSIG NOT scripts to pass, even though they were invalid.
1233 // There is a similar check in CreateNewBlock() to prevent creating
1234 // invalid blocks, however allowing such transactions into the mempool
1235 // can be exploited as a DoS attack.
1236 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1238 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1241 // Store transaction in memory
1242 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1245 SyncWithWallets(tx, NULL);
1250 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1251 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1253 CBlockIndex *pindexSlow = NULL;
1257 if (mempool.lookup(hash, txOut))
1264 if (pblocktree->ReadTxIndex(hash, postx)) {
1265 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1267 return error("%s: OpenBlockFile failed", __func__);
1268 CBlockHeader header;
1271 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1273 } catch (const std::exception& e) {
1274 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1276 hashBlock = header.GetHash();
1277 if (txOut.GetHash() != hash)
1278 return error("%s: txid mismatch", __func__);
1283 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1286 CCoinsViewCache &view = *pcoinsTip;
1287 const CCoins* coins = view.AccessCoins(hash);
1289 nHeight = coins->nHeight;
1292 pindexSlow = chainActive[nHeight];
1297 if (ReadBlockFromDisk(block, pindexSlow)) {
1298 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1299 if (tx.GetHash() == hash) {
1301 hashBlock = pindexSlow->GetBlockHash();
1316 //////////////////////////////////////////////////////////////////////////////
1318 // CBlock and CBlockIndex
1321 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1323 // Open history file to append
1324 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1325 if (fileout.IsNull())
1326 return error("WriteBlockToDisk: OpenBlockFile failed");
1328 // Write index header
1329 unsigned int nSize = fileout.GetSerializeSize(block);
1330 fileout << FLATDATA(messageStart) << nSize;
1333 long fileOutPos = ftell(fileout.Get());
1335 return error("WriteBlockToDisk: ftell failed");
1336 pos.nPos = (unsigned int)fileOutPos;
1342 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1346 // Open history file to read
1347 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1348 if (filein.IsNull())
1349 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1355 catch (const std::exception& e) {
1356 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1360 if (!(CheckEquihashSolution(&block, Params()) &&
1361 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1362 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1367 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1369 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1371 if (block.GetHash() != pindex->GetBlockHash())
1372 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1373 pindex->ToString(), pindex->GetBlockPos().ToString());
1377 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1379 CAmount nSubsidy = 12.5 * COIN;
1381 // Mining slow start
1382 // The subsidy is ramped up linearly, skipping the middle payout of
1383 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1384 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1385 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1386 nSubsidy *= nHeight;
1388 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1389 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1390 nSubsidy *= (nHeight+1);
1394 assert(nHeight > consensusParams.SubsidySlowStartShift());
1395 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1396 // Force block reward to zero when right shift is undefined.
1400 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1401 nSubsidy >>= halvings;
1405 bool IsInitialBlockDownload()
1407 const CChainParams& chainParams = Params();
1409 if (fImporting || fReindex)
1411 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1413 static bool lockIBDState = false;
1416 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1417 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1419 lockIBDState = true;
1423 bool fLargeWorkForkFound = false;
1424 bool fLargeWorkInvalidChainFound = false;
1425 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1427 void CheckForkWarningConditions()
1429 AssertLockHeld(cs_main);
1430 // Before we get past initial download, we cannot reliably alert about forks
1431 // (we assume we don't get stuck on a fork before the last checkpoint)
1432 if (IsInitialBlockDownload())
1435 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1436 // of our head, drop it
1437 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1438 pindexBestForkTip = NULL;
1440 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1442 if (!fLargeWorkForkFound && pindexBestForkBase)
1444 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1445 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1446 CAlert::Notify(warning, true);
1448 if (pindexBestForkTip && pindexBestForkBase)
1450 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__,
1451 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1452 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1453 fLargeWorkForkFound = true;
1457 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1458 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1459 CAlert::Notify(warning, true);
1460 fLargeWorkInvalidChainFound = true;
1465 fLargeWorkForkFound = false;
1466 fLargeWorkInvalidChainFound = false;
1470 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1472 AssertLockHeld(cs_main);
1473 // If we are on a fork that is sufficiently large, set a warning flag
1474 CBlockIndex* pfork = pindexNewForkTip;
1475 CBlockIndex* plonger = chainActive.Tip();
1476 while (pfork && pfork != plonger)
1478 while (plonger && plonger->nHeight > pfork->nHeight)
1479 plonger = plonger->pprev;
1480 if (pfork == plonger)
1482 pfork = pfork->pprev;
1485 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1486 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1487 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1488 // hash rate operating on the fork.
1489 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1490 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1491 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1492 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1493 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1494 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1496 pindexBestForkTip = pindexNewForkTip;
1497 pindexBestForkBase = pfork;
1500 CheckForkWarningConditions();
1503 // Requires cs_main.
1504 void Misbehaving(NodeId pnode, int howmuch)
1509 CNodeState *state = State(pnode);
1513 state->nMisbehavior += howmuch;
1514 int banscore = GetArg("-banscore", 100);
1515 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1517 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1518 state->fShouldBan = true;
1520 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1523 void static InvalidChainFound(CBlockIndex* pindexNew)
1525 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1526 pindexBestInvalid = pindexNew;
1528 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1529 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1530 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1531 pindexNew->GetBlockTime()));
1532 CBlockIndex *tip = chainActive.Tip();
1534 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1535 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1536 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1537 CheckForkWarningConditions();
1540 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1542 if (state.IsInvalid(nDoS)) {
1543 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1544 if (it != mapBlockSource.end() && State(it->second)) {
1545 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1546 State(it->second)->rejects.push_back(reject);
1548 Misbehaving(it->second, nDoS);
1551 if (!state.CorruptionPossible()) {
1552 pindex->nStatus |= BLOCK_FAILED_VALID;
1553 setDirtyBlockIndex.insert(pindex);
1554 setBlockIndexCandidates.erase(pindex);
1555 InvalidChainFound(pindex);
1559 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1561 // mark inputs spent
1562 if (!tx.IsCoinBase()) {
1563 txundo.vprevout.reserve(tx.vin.size());
1564 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1565 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1566 unsigned nPos = txin.prevout.n;
1568 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1570 // mark an outpoint spent, and construct undo information
1571 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1573 if (coins->vout.size() == 0) {
1574 CTxInUndo& undo = txundo.vprevout.back();
1575 undo.nHeight = coins->nHeight;
1576 undo.fCoinBase = coins->fCoinBase;
1577 undo.nVersion = coins->nVersion;
1583 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1584 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1585 inputs.SetNullifier(nf, true);
1590 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1593 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1596 UpdateCoins(tx, state, inputs, txundo, nHeight);
1599 bool CScriptCheck::operator()() {
1600 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1601 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1602 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1607 bool NonContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1609 if (!tx.IsCoinBase())
1612 pvChecks->reserve(tx.vin.size());
1614 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1615 // for an attacker to attempt to split the network.
1616 if (!inputs.HaveInputs(tx))
1617 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1619 // are the JoinSplit's requirements met?
1620 if (!inputs.HaveJoinSplitRequirements(tx))
1621 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1623 CAmount nValueIn = 0;
1625 for (unsigned int i = 0; i < tx.vin.size(); i++)
1627 const COutPoint &prevout = tx.vin[i].prevout;
1628 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1631 if (coins->IsCoinBase()) {
1632 // Ensure that coinbases cannot be spent to transparent outputs
1633 // Disabled on regtest
1634 if (fCoinbaseEnforcedProtectionEnabled &&
1635 consensusParams.fCoinbaseMustBeProtected &&
1637 return state.Invalid(
1638 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1639 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1643 // Check for negative or overflow input values
1644 nValueIn += coins->vout[prevout.n].nValue;
1645 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1646 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1647 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1651 nValueIn += tx.GetJoinSplitValueIn();
1652 if (!MoneyRange(nValueIn))
1653 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1654 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1656 if (nValueIn < tx.GetValueOut())
1657 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1658 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1659 REJECT_INVALID, "bad-txns-in-belowout");
1661 // Tally transaction fees
1662 CAmount nTxFee = nValueIn - tx.GetValueOut();
1664 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1665 REJECT_INVALID, "bad-txns-fee-negative");
1667 if (!MoneyRange(nFees))
1668 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1669 REJECT_INVALID, "bad-txns-fee-outofrange");
1671 // The first loop above does all the inexpensive checks.
1672 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1673 // Helps prevent CPU exhaustion attacks.
1675 // Skip ECDSA signature verification when connecting blocks
1676 // before the last block chain checkpoint. This is safe because block merkle hashes are
1677 // still computed and checked, and any change will be caught at the next checkpoint.
1678 if (fScriptChecks) {
1679 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1680 const COutPoint &prevout = tx.vin[i].prevout;
1681 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1685 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1687 pvChecks->push_back(CScriptCheck());
1688 check.swap(pvChecks->back());
1689 } else if (!check()) {
1690 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1691 // Check whether the failure was caused by a
1692 // non-mandatory script verification check, such as
1693 // non-standard DER encodings or non-null dummy
1694 // arguments; if so, don't trigger DoS protection to
1695 // avoid splitting the network between upgraded and
1696 // non-upgraded nodes.
1697 CScriptCheck check(*coins, tx, i,
1698 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1700 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1702 // Failures of other flags indicate a transaction that is
1703 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1704 // such nodes as they are not following the protocol. That
1705 // said during an upgrade careful thought should be taken
1706 // as to the correct behavior - we may want to continue
1707 // peering with non-upgraded nodes even after a soft-fork
1708 // super-majority vote has passed.
1709 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1718 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector<CScriptCheck> *pvChecks)
1720 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1724 if (!tx.IsCoinBase())
1726 // While checking, GetBestBlock() refers to the parent block.
1727 // This is also true for mempool checks.
1728 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1729 int nSpendHeight = pindexPrev->nHeight + 1;
1730 for (unsigned int i = 0; i < tx.vin.size(); i++)
1732 const COutPoint &prevout = tx.vin[i].prevout;
1733 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1734 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1738 // If prev is coinbase, check that it's matured
1739 if (coins->IsCoinBase()) {
1740 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1741 return state.Invalid(
1742 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1743 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1754 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1756 // Open history file to append
1757 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1758 if (fileout.IsNull())
1759 return error("%s: OpenUndoFile failed", __func__);
1761 // Write index header
1762 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1763 fileout << FLATDATA(messageStart) << nSize;
1766 long fileOutPos = ftell(fileout.Get());
1768 return error("%s: ftell failed", __func__);
1769 pos.nPos = (unsigned int)fileOutPos;
1770 fileout << blockundo;
1772 // calculate & write checksum
1773 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1774 hasher << hashBlock;
1775 hasher << blockundo;
1776 fileout << hasher.GetHash();
1781 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1783 // Open history file to read
1784 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1785 if (filein.IsNull())
1786 return error("%s: OpenBlockFile failed", __func__);
1789 uint256 hashChecksum;
1791 filein >> blockundo;
1792 filein >> hashChecksum;
1794 catch (const std::exception& e) {
1795 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1799 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1800 hasher << hashBlock;
1801 hasher << blockundo;
1802 if (hashChecksum != hasher.GetHash())
1803 return error("%s: Checksum mismatch", __func__);
1808 /** Abort with a message */
1809 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1811 strMiscWarning = strMessage;
1812 LogPrintf("*** %s\n", strMessage);
1813 uiInterface.ThreadSafeMessageBox(
1814 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1815 "", CClientUIInterface::MSG_ERROR);
1820 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1822 AbortNode(strMessage, userMessage);
1823 return state.Error(strMessage);
1829 * Apply the undo operation of a CTxInUndo to the given chain state.
1830 * @param undo The undo object.
1831 * @param view The coins view to which to apply the changes.
1832 * @param out The out point that corresponds to the tx input.
1833 * @return True on success.
1835 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1839 CCoinsModifier coins = view.ModifyCoins(out.hash);
1840 if (undo.nHeight != 0) {
1841 // undo data contains height: this is the last output of the prevout tx being spent
1842 if (!coins->IsPruned())
1843 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1845 coins->fCoinBase = undo.fCoinBase;
1846 coins->nHeight = undo.nHeight;
1847 coins->nVersion = undo.nVersion;
1849 if (coins->IsPruned())
1850 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1852 if (coins->IsAvailable(out.n))
1853 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1854 if (coins->vout.size() < out.n+1)
1855 coins->vout.resize(out.n+1);
1856 coins->vout[out.n] = undo.txout;
1861 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1863 assert(pindex->GetBlockHash() == view.GetBestBlock());
1870 CBlockUndo blockUndo;
1871 CDiskBlockPos pos = pindex->GetUndoPos();
1873 return error("DisconnectBlock(): no undo data available");
1874 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1875 return error("DisconnectBlock(): failure reading undo data");
1877 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1878 return error("DisconnectBlock(): block and undo data inconsistent");
1880 // undo transactions in reverse order
1881 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1882 const CTransaction &tx = block.vtx[i];
1883 uint256 hash = tx.GetHash();
1885 // Check that all outputs are available and match the outputs in the block itself
1888 CCoinsModifier outs = view.ModifyCoins(hash);
1889 outs->ClearUnspendable();
1891 CCoins outsBlock(tx, pindex->nHeight);
1892 // The CCoins serialization does not serialize negative numbers.
1893 // No network rules currently depend on the version here, so an inconsistency is harmless
1894 // but it must be corrected before txout nversion ever influences a network rule.
1895 if (outsBlock.nVersion < 0)
1896 outs->nVersion = outsBlock.nVersion;
1897 if (*outs != outsBlock)
1898 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1904 // unspend nullifiers
1905 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1906 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1907 view.SetNullifier(nf, false);
1912 if (i > 0) { // not coinbases
1913 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1914 if (txundo.vprevout.size() != tx.vin.size())
1915 return error("DisconnectBlock(): transaction and undo data inconsistent");
1916 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1917 const COutPoint &out = tx.vin[j].prevout;
1918 const CTxInUndo &undo = txundo.vprevout[j];
1919 if (!ApplyTxInUndo(undo, view, out))
1925 // set the old best anchor back
1926 view.PopAnchor(blockUndo.old_tree_root);
1928 // move best block pointer to prevout block
1929 view.SetBestBlock(pindex->pprev->GetBlockHash());
1939 void static FlushBlockFile(bool fFinalize = false)
1941 LOCK(cs_LastBlockFile);
1943 CDiskBlockPos posOld(nLastBlockFile, 0);
1945 FILE *fileOld = OpenBlockFile(posOld);
1948 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1949 FileCommit(fileOld);
1953 fileOld = OpenUndoFile(posOld);
1956 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1957 FileCommit(fileOld);
1962 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1964 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1966 void ThreadScriptCheck() {
1967 RenameThread("zcash-scriptch");
1968 scriptcheckqueue.Thread();
1972 // Called periodically asynchronously; alerts if it smells like
1973 // we're being fed a bad chain (blocks being generated much
1974 // too slowly or too quickly).
1976 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1977 int64_t nPowTargetSpacing)
1979 if (bestHeader == NULL || initialDownloadCheck()) return;
1981 static int64_t lastAlertTime = 0;
1982 int64_t now = GetAdjustedTime();
1983 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1985 const int SPAN_HOURS=4;
1986 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1987 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1989 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1991 std::string strWarning;
1992 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1995 const CBlockIndex* i = bestHeader;
1997 while (i->GetBlockTime() >= startTime) {
2000 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2003 // How likely is it to find that many by chance?
2004 double p = boost::math::pdf(poisson, nBlocks);
2006 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2007 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2009 // Aim for one false-positive about every fifty years of normal running:
2010 const int FIFTY_YEARS = 50*365*24*60*60;
2011 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2013 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2015 // Many fewer blocks than expected: alert!
2016 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2017 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2019 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2021 // Many more blocks than expected: alert!
2022 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2023 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2025 if (!strWarning.empty())
2027 strMiscWarning = strWarning;
2028 CAlert::Notify(strWarning, true);
2029 lastAlertTime = now;
2033 static int64_t nTimeVerify = 0;
2034 static int64_t nTimeConnect = 0;
2035 static int64_t nTimeIndex = 0;
2036 static int64_t nTimeCallbacks = 0;
2037 static int64_t nTimeTotal = 0;
2039 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2041 const CChainParams& chainparams = Params();
2042 AssertLockHeld(cs_main);
2043 // Check it again in case a previous version let a bad block in
2044 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
2047 // verify that the view's current state corresponds to the previous block
2048 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2049 assert(hashPrevBlock == view.GetBestBlock());
2051 // Special case for the genesis block, skipping connection of its transactions
2052 // (its coinbase is unspendable)
2053 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2055 view.SetBestBlock(pindex->GetBlockHash());
2056 // Before the genesis block, there was an empty tree
2057 ZCIncrementalMerkleTree tree;
2058 pindex->hashAnchor = tree.root();
2063 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2065 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2066 // unless those are already completely spent.
2067 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2068 const CCoins* coins = view.AccessCoins(tx.GetHash());
2069 if (coins && !coins->IsPruned())
2070 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2071 REJECT_INVALID, "bad-txns-BIP30");
2074 unsigned int flags = SCRIPT_VERIFY_P2SH;
2076 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2077 // when 75% of the network has upgraded:
2078 if (block.nVersion >= 3) {
2079 flags |= SCRIPT_VERIFY_DERSIG;
2082 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2083 // blocks, when 75% of the network has upgraded:
2084 if (block.nVersion >= 4) {
2085 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2088 CBlockUndo blockundo;
2090 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2092 int64_t nTimeStart = GetTimeMicros();
2095 unsigned int nSigOps = 0;
2096 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2097 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2098 vPos.reserve(block.vtx.size());
2099 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2101 // Construct the incremental merkle tree at the current
2103 auto old_tree_root = view.GetBestAnchor();
2104 // saving the top anchor in the block index as we go.
2106 pindex->hashAnchor = old_tree_root;
2108 ZCIncrementalMerkleTree tree;
2109 // This should never fail: we should always be able to get the root
2110 // that is on the tip of our chain
2111 assert(view.GetAnchorAt(old_tree_root, tree));
2114 // Consistency check: the root of the tree we're given should
2115 // match what we asked for.
2116 assert(tree.root() == old_tree_root);
2119 for (unsigned int i = 0; i < block.vtx.size(); i++)
2121 const CTransaction &tx = block.vtx[i];
2123 nInputs += tx.vin.size();
2124 nSigOps += GetLegacySigOpCount(tx);
2125 if (nSigOps > MAX_BLOCK_SIGOPS)
2126 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2127 REJECT_INVALID, "bad-blk-sigops");
2129 if (!tx.IsCoinBase())
2131 if (!view.HaveInputs(tx))
2132 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2133 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2135 // are the JoinSplit's requirements met?
2136 if (!view.HaveJoinSplitRequirements(tx))
2137 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2138 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2140 // Add in sigops done by pay-to-script-hash inputs;
2141 // this is to prevent a "rogue miner" from creating
2142 // an incredibly-expensive-to-validate block.
2143 nSigOps += GetP2SHSigOpCount(tx, view);
2144 if (nSigOps > MAX_BLOCK_SIGOPS)
2145 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2146 REJECT_INVALID, "bad-blk-sigops");
2148 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2150 std::vector<CScriptCheck> vChecks;
2151 if (!ContextualCheckInputs(tx, state, view, fScriptChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2153 control.Add(vChecks);
2158 blockundo.vtxundo.push_back(CTxUndo());
2160 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2162 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2163 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2164 // Insert the note commitments into our temporary tree.
2166 tree.append(note_commitment);
2170 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2171 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2174 view.PushAnchor(tree);
2175 blockundo.old_tree_root = old_tree_root;
2177 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2178 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);
2180 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2181 if (block.vtx[0].GetValueOut() > blockReward)
2182 return state.DoS(100,
2183 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2184 block.vtx[0].GetValueOut(), blockReward),
2185 REJECT_INVALID, "bad-cb-amount");
2187 if (!control.Wait())
2188 return state.DoS(100, false);
2189 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2190 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);
2195 // Write undo information to disk
2196 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2198 if (pindex->GetUndoPos().IsNull()) {
2200 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2201 return error("ConnectBlock(): FindUndoPos failed");
2202 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2203 return AbortNode(state, "Failed to write undo data");
2205 // update nUndoPos in block index
2206 pindex->nUndoPos = pos.nPos;
2207 pindex->nStatus |= BLOCK_HAVE_UNDO;
2210 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2211 setDirtyBlockIndex.insert(pindex);
2215 if (!pblocktree->WriteTxIndex(vPos))
2216 return AbortNode(state, "Failed to write transaction index");
2218 // add this block to the view's block chain
2219 view.SetBestBlock(pindex->GetBlockHash());
2221 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2222 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2224 // Watch for changes to the previous coinbase transaction.
2225 static uint256 hashPrevBestCoinBase;
2226 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2227 hashPrevBestCoinBase = block.vtx[0].GetHash();
2229 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2230 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2235 enum FlushStateMode {
2237 FLUSH_STATE_IF_NEEDED,
2238 FLUSH_STATE_PERIODIC,
2243 * Update the on-disk chain state.
2244 * The caches and indexes are flushed depending on the mode we're called with
2245 * if they're too large, if it's been a while since the last write,
2246 * or always and in all cases if we're in prune mode and are deleting files.
2248 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2249 LOCK2(cs_main, cs_LastBlockFile);
2250 static int64_t nLastWrite = 0;
2251 static int64_t nLastFlush = 0;
2252 static int64_t nLastSetChain = 0;
2253 std::set<int> setFilesToPrune;
2254 bool fFlushForPrune = false;
2256 if (fPruneMode && fCheckForPruning && !fReindex) {
2257 FindFilesToPrune(setFilesToPrune);
2258 fCheckForPruning = false;
2259 if (!setFilesToPrune.empty()) {
2260 fFlushForPrune = true;
2262 pblocktree->WriteFlag("prunedblockfiles", true);
2267 int64_t nNow = GetTimeMicros();
2268 // Avoid writing/flushing immediately after startup.
2269 if (nLastWrite == 0) {
2272 if (nLastFlush == 0) {
2275 if (nLastSetChain == 0) {
2276 nLastSetChain = nNow;
2278 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2279 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2280 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2281 // The cache is over the limit, we have to write now.
2282 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2283 // 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.
2284 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2285 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2286 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2287 // Combine all conditions that result in a full cache flush.
2288 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2289 // Write blocks and block index to disk.
2290 if (fDoFullFlush || fPeriodicWrite) {
2291 // Depend on nMinDiskSpace to ensure we can write block index
2292 if (!CheckDiskSpace(0))
2293 return state.Error("out of disk space");
2294 // First make sure all block and undo data is flushed to disk.
2296 // Then update all block file information (which may refer to block and undo files).
2298 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2299 vFiles.reserve(setDirtyFileInfo.size());
2300 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2301 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2302 setDirtyFileInfo.erase(it++);
2304 std::vector<const CBlockIndex*> vBlocks;
2305 vBlocks.reserve(setDirtyBlockIndex.size());
2306 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2307 vBlocks.push_back(*it);
2308 setDirtyBlockIndex.erase(it++);
2310 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2311 return AbortNode(state, "Files to write to block index database");
2314 // Finally remove any pruned files
2316 UnlinkPrunedFiles(setFilesToPrune);
2319 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2321 // Typical CCoins structures on disk are around 128 bytes in size.
2322 // Pushing a new one to the database can cause it to be written
2323 // twice (once in the log, and once in the tables). This is already
2324 // an overestimation, as most will delete an existing entry or
2325 // overwrite one. Still, use a conservative safety factor of 2.
2326 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2327 return state.Error("out of disk space");
2328 // Flush the chainstate (which may refer to block index entries).
2329 if (!pcoinsTip->Flush())
2330 return AbortNode(state, "Failed to write to coin database");
2333 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2334 // Update best block in wallet (so we can detect restored wallets).
2335 GetMainSignals().SetBestChain(chainActive.GetLocator());
2336 nLastSetChain = nNow;
2338 } catch (const std::runtime_error& e) {
2339 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2344 void FlushStateToDisk() {
2345 CValidationState state;
2346 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2349 void PruneAndFlush() {
2350 CValidationState state;
2351 fCheckForPruning = true;
2352 FlushStateToDisk(state, FLUSH_STATE_NONE);
2355 /** Update chainActive and related internal data structures. */
2356 void static UpdateTip(CBlockIndex *pindexNew) {
2357 const CChainParams& chainParams = Params();
2358 chainActive.SetTip(pindexNew);
2361 nTimeBestReceived = GetTime();
2362 mempool.AddTransactionsUpdated(1);
2364 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2365 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2366 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2367 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2369 cvBlockChange.notify_all();
2371 // Check the version of the last 100 blocks to see if we need to upgrade:
2372 static bool fWarned = false;
2373 if (!IsInitialBlockDownload() && !fWarned)
2376 const CBlockIndex* pindex = chainActive.Tip();
2377 for (int i = 0; i < 100 && pindex != NULL; i++)
2379 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2381 pindex = pindex->pprev;
2384 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2385 if (nUpgraded > 100/2)
2387 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2388 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2389 CAlert::Notify(strMiscWarning, true);
2395 /** Disconnect chainActive's tip. */
2396 bool static DisconnectTip(CValidationState &state) {
2397 CBlockIndex *pindexDelete = chainActive.Tip();
2398 assert(pindexDelete);
2399 mempool.check(pcoinsTip);
2400 // Read block from disk.
2402 if (!ReadBlockFromDisk(block, pindexDelete))
2403 return AbortNode(state, "Failed to read block");
2404 // Apply the block atomically to the chain state.
2405 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2406 int64_t nStart = GetTimeMicros();
2408 CCoinsViewCache view(pcoinsTip);
2409 if (!DisconnectBlock(block, state, pindexDelete, view))
2410 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2411 assert(view.Flush());
2413 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2414 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2415 // Write the chain state to disk, if necessary.
2416 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2418 // Resurrect mempool transactions from the disconnected block.
2419 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2420 // ignore validation errors in resurrected transactions
2421 list<CTransaction> removed;
2422 CValidationState stateDummy;
2423 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2424 mempool.remove(tx, removed, true);
2426 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2427 // The anchor may not change between block disconnects,
2428 // in which case we don't want to evict from the mempool yet!
2429 mempool.removeWithAnchor(anchorBeforeDisconnect);
2431 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2432 mempool.check(pcoinsTip);
2433 // Update chainActive and related variables.
2434 UpdateTip(pindexDelete->pprev);
2435 // Get the current commitment tree
2436 ZCIncrementalMerkleTree newTree;
2437 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2438 // Let wallets know transactions went from 1-confirmed to
2439 // 0-confirmed or conflicted:
2440 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2441 SyncWithWallets(tx, NULL);
2443 // Update cached incremental witnesses
2444 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2448 static int64_t nTimeReadFromDisk = 0;
2449 static int64_t nTimeConnectTotal = 0;
2450 static int64_t nTimeFlush = 0;
2451 static int64_t nTimeChainState = 0;
2452 static int64_t nTimePostConnect = 0;
2455 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2456 * corresponding to pindexNew, to bypass loading it again from disk.
2458 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2459 assert(pindexNew->pprev == chainActive.Tip());
2460 mempool.check(pcoinsTip);
2461 // Read block from disk.
2462 int64_t nTime1 = GetTimeMicros();
2465 if (!ReadBlockFromDisk(block, pindexNew))
2466 return AbortNode(state, "Failed to read block");
2469 // Get the current commitment tree
2470 ZCIncrementalMerkleTree oldTree;
2471 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2472 // Apply the block atomically to the chain state.
2473 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2475 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2477 CCoinsViewCache view(pcoinsTip);
2478 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2479 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2480 GetMainSignals().BlockChecked(*pblock, state);
2482 if (state.IsInvalid())
2483 InvalidBlockFound(pindexNew, state);
2484 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2486 mapBlockSource.erase(inv.hash);
2487 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2488 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2489 assert(view.Flush());
2491 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2492 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2493 // Write the chain state to disk, if necessary.
2494 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2496 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2497 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2498 // Remove conflicting transactions from the mempool.
2499 list<CTransaction> txConflicted;
2500 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2501 mempool.check(pcoinsTip);
2502 // Update chainActive & related variables.
2503 UpdateTip(pindexNew);
2504 // Tell wallet about transactions that went from mempool
2506 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2507 SyncWithWallets(tx, NULL);
2509 // ... and about transactions that got confirmed:
2510 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2511 SyncWithWallets(tx, pblock);
2513 // Update cached incremental witnesses
2514 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2516 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2517 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2518 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2523 * Return the tip of the chain with the most work in it, that isn't
2524 * known to be invalid (it's however far from certain to be valid).
2526 static CBlockIndex* FindMostWorkChain() {
2528 CBlockIndex *pindexNew = NULL;
2530 // Find the best candidate header.
2532 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2533 if (it == setBlockIndexCandidates.rend())
2538 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2539 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2540 CBlockIndex *pindexTest = pindexNew;
2541 bool fInvalidAncestor = false;
2542 while (pindexTest && !chainActive.Contains(pindexTest)) {
2543 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2545 // Pruned nodes may have entries in setBlockIndexCandidates for
2546 // which block files have been deleted. Remove those as candidates
2547 // for the most work chain if we come across them; we can't switch
2548 // to a chain unless we have all the non-active-chain parent blocks.
2549 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2550 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2551 if (fFailedChain || fMissingData) {
2552 // Candidate chain is not usable (either invalid or missing data)
2553 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2554 pindexBestInvalid = pindexNew;
2555 CBlockIndex *pindexFailed = pindexNew;
2556 // Remove the entire chain from the set.
2557 while (pindexTest != pindexFailed) {
2559 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2560 } else if (fMissingData) {
2561 // If we're missing data, then add back to mapBlocksUnlinked,
2562 // so that if the block arrives in the future we can try adding
2563 // to setBlockIndexCandidates again.
2564 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2566 setBlockIndexCandidates.erase(pindexFailed);
2567 pindexFailed = pindexFailed->pprev;
2569 setBlockIndexCandidates.erase(pindexTest);
2570 fInvalidAncestor = true;
2573 pindexTest = pindexTest->pprev;
2575 if (!fInvalidAncestor)
2580 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2581 static void PruneBlockIndexCandidates() {
2582 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2583 // reorganization to a better block fails.
2584 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2585 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2586 setBlockIndexCandidates.erase(it++);
2588 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2589 assert(!setBlockIndexCandidates.empty());
2593 * Try to make some progress towards making pindexMostWork the active block.
2594 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2596 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2597 AssertLockHeld(cs_main);
2598 bool fInvalidFound = false;
2599 const CBlockIndex *pindexOldTip = chainActive.Tip();
2600 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2602 // Disconnect active blocks which are no longer in the best chain.
2603 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2604 if (!DisconnectTip(state))
2608 // Build list of new blocks to connect.
2609 std::vector<CBlockIndex*> vpindexToConnect;
2610 bool fContinue = true;
2611 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2612 while (fContinue && nHeight != pindexMostWork->nHeight) {
2613 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2614 // a few blocks along the way.
2615 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2616 vpindexToConnect.clear();
2617 vpindexToConnect.reserve(nTargetHeight - nHeight);
2618 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2619 while (pindexIter && pindexIter->nHeight != nHeight) {
2620 vpindexToConnect.push_back(pindexIter);
2621 pindexIter = pindexIter->pprev;
2623 nHeight = nTargetHeight;
2625 // Connect new blocks.
2626 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2627 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2628 if (state.IsInvalid()) {
2629 // The block violates a consensus rule.
2630 if (!state.CorruptionPossible())
2631 InvalidChainFound(vpindexToConnect.back());
2632 state = CValidationState();
2633 fInvalidFound = true;
2637 // A system error occurred (disk space, database error, ...).
2641 PruneBlockIndexCandidates();
2642 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2643 // We're in a better position than we were. Return temporarily to release the lock.
2651 // Callbacks/notifications for a new best chain.
2653 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2655 CheckForkWarningConditions();
2661 * Make the best chain active, in multiple steps. The result is either failure
2662 * or an activated best chain. pblock is either NULL or a pointer to a block
2663 * that is already loaded (to avoid loading it again from disk).
2665 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2666 CBlockIndex *pindexNewTip = NULL;
2667 CBlockIndex *pindexMostWork = NULL;
2668 const CChainParams& chainParams = Params();
2670 boost::this_thread::interruption_point();
2672 bool fInitialDownload;
2675 pindexMostWork = FindMostWorkChain();
2677 // Whether we have anything to do at all.
2678 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2681 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2684 pindexNewTip = chainActive.Tip();
2685 fInitialDownload = IsInitialBlockDownload();
2687 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2689 // Notifications/callbacks that can run without cs_main
2690 if (!fInitialDownload) {
2691 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2692 // Relay inventory, but don't relay old inventory during initial block download.
2693 int nBlockEstimate = 0;
2694 if (fCheckpointsEnabled)
2695 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2696 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2697 // in a stalled download if the block file is pruned before the request.
2698 if (nLocalServices & NODE_NETWORK) {
2700 BOOST_FOREACH(CNode* pnode, vNodes)
2701 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2702 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2704 // Notify external listeners about the new tip.
2705 uiInterface.NotifyBlockTip(hashNewTip);
2707 } while(pindexMostWork != chainActive.Tip());
2710 // Write changes periodically to disk, after relay.
2711 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2718 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2719 AssertLockHeld(cs_main);
2721 // Mark the block itself as invalid.
2722 pindex->nStatus |= BLOCK_FAILED_VALID;
2723 setDirtyBlockIndex.insert(pindex);
2724 setBlockIndexCandidates.erase(pindex);
2726 while (chainActive.Contains(pindex)) {
2727 CBlockIndex *pindexWalk = chainActive.Tip();
2728 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2729 setDirtyBlockIndex.insert(pindexWalk);
2730 setBlockIndexCandidates.erase(pindexWalk);
2731 // ActivateBestChain considers blocks already in chainActive
2732 // unconditionally valid already, so force disconnect away from it.
2733 if (!DisconnectTip(state)) {
2738 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2740 BlockMap::iterator it = mapBlockIndex.begin();
2741 while (it != mapBlockIndex.end()) {
2742 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2743 setBlockIndexCandidates.insert(it->second);
2748 InvalidChainFound(pindex);
2752 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2753 AssertLockHeld(cs_main);
2755 int nHeight = pindex->nHeight;
2757 // Remove the invalidity flag from this block and all its descendants.
2758 BlockMap::iterator it = mapBlockIndex.begin();
2759 while (it != mapBlockIndex.end()) {
2760 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2761 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2762 setDirtyBlockIndex.insert(it->second);
2763 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2764 setBlockIndexCandidates.insert(it->second);
2766 if (it->second == pindexBestInvalid) {
2767 // Reset invalid block marker if it was pointing to one of those.
2768 pindexBestInvalid = NULL;
2774 // Remove the invalidity flag from all ancestors too.
2775 while (pindex != NULL) {
2776 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2777 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2778 setDirtyBlockIndex.insert(pindex);
2780 pindex = pindex->pprev;
2785 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2787 // Check for duplicate
2788 uint256 hash = block.GetHash();
2789 BlockMap::iterator it = mapBlockIndex.find(hash);
2790 if (it != mapBlockIndex.end())
2793 // Construct new block index object
2794 CBlockIndex* pindexNew = new CBlockIndex(block);
2796 // We assign the sequence id to blocks only when the full data is available,
2797 // to avoid miners withholding blocks but broadcasting headers, to get a
2798 // competitive advantage.
2799 pindexNew->nSequenceId = 0;
2800 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2801 pindexNew->phashBlock = &((*mi).first);
2802 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2803 if (miPrev != mapBlockIndex.end())
2805 pindexNew->pprev = (*miPrev).second;
2806 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2807 pindexNew->BuildSkip();
2809 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2810 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2811 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2812 pindexBestHeader = pindexNew;
2814 setDirtyBlockIndex.insert(pindexNew);
2819 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2820 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2822 pindexNew->nTx = block.vtx.size();
2823 pindexNew->nChainTx = 0;
2824 pindexNew->nFile = pos.nFile;
2825 pindexNew->nDataPos = pos.nPos;
2826 pindexNew->nUndoPos = 0;
2827 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2828 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2829 setDirtyBlockIndex.insert(pindexNew);
2831 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2832 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2833 deque<CBlockIndex*> queue;
2834 queue.push_back(pindexNew);
2836 // Recursively process any descendant blocks that now may be eligible to be connected.
2837 while (!queue.empty()) {
2838 CBlockIndex *pindex = queue.front();
2840 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2842 LOCK(cs_nBlockSequenceId);
2843 pindex->nSequenceId = nBlockSequenceId++;
2845 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2846 setBlockIndexCandidates.insert(pindex);
2848 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2849 while (range.first != range.second) {
2850 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2851 queue.push_back(it->second);
2853 mapBlocksUnlinked.erase(it);
2857 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2858 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2865 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2867 LOCK(cs_LastBlockFile);
2869 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2870 if (vinfoBlockFile.size() <= nFile) {
2871 vinfoBlockFile.resize(nFile + 1);
2875 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2877 if (vinfoBlockFile.size() <= nFile) {
2878 vinfoBlockFile.resize(nFile + 1);
2882 pos.nPos = vinfoBlockFile[nFile].nSize;
2885 if (nFile != nLastBlockFile) {
2887 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2889 FlushBlockFile(!fKnown);
2890 nLastBlockFile = nFile;
2893 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2895 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2897 vinfoBlockFile[nFile].nSize += nAddSize;
2900 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2901 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2902 if (nNewChunks > nOldChunks) {
2904 fCheckForPruning = true;
2905 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2906 FILE *file = OpenBlockFile(pos);
2908 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2909 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2914 return state.Error("out of disk space");
2918 setDirtyFileInfo.insert(nFile);
2922 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2926 LOCK(cs_LastBlockFile);
2928 unsigned int nNewSize;
2929 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2930 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2931 setDirtyFileInfo.insert(nFile);
2933 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2934 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2935 if (nNewChunks > nOldChunks) {
2937 fCheckForPruning = true;
2938 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2939 FILE *file = OpenUndoFile(pos);
2941 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2942 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2947 return state.Error("out of disk space");
2953 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2955 // Check block version
2956 if (block.nVersion < MIN_BLOCK_VERSION)
2957 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
2958 REJECT_INVALID, "version-too-low");
2960 // Check Equihash solution is valid
2961 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2962 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2963 REJECT_INVALID, "invalid-solution");
2965 // Check proof of work matches claimed amount
2966 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2967 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2968 REJECT_INVALID, "high-hash");
2971 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2972 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2973 REJECT_INVALID, "time-too-new");
2978 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2980 // These are checks that are independent of context.
2982 // Check that the header is valid (particularly PoW). This is mostly
2983 // redundant with the call in AcceptBlockHeader.
2984 if (!CheckBlockHeader(block, state, fCheckPOW))
2987 // Check the merkle root.
2988 if (fCheckMerkleRoot) {
2990 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2991 if (block.hashMerkleRoot != hashMerkleRoot2)
2992 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2993 REJECT_INVALID, "bad-txnmrklroot", true);
2995 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2996 // of transactions in a block without affecting the merkle root of a block,
2997 // while still invalidating it.
2999 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3000 REJECT_INVALID, "bad-txns-duplicate", true);
3003 // All potential-corruption validation must be done before we do any
3004 // transaction validation, as otherwise we may mark the header as invalid
3005 // because we receive the wrong transactions for it.
3008 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3009 return state.DoS(100, error("CheckBlock(): size limits failed"),
3010 REJECT_INVALID, "bad-blk-length");
3012 // First transaction must be coinbase, the rest must not be
3013 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3014 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3015 REJECT_INVALID, "bad-cb-missing");
3016 for (unsigned int i = 1; i < block.vtx.size(); i++)
3017 if (block.vtx[i].IsCoinBase())
3018 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3019 REJECT_INVALID, "bad-cb-multiple");
3021 // Check transactions
3022 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3023 if (!CheckTransaction(tx, state))
3024 return error("CheckBlock(): CheckTransaction failed");
3026 unsigned int nSigOps = 0;
3027 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3029 nSigOps += GetLegacySigOpCount(tx);
3031 if (nSigOps > MAX_BLOCK_SIGOPS)
3032 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3033 REJECT_INVALID, "bad-blk-sigops", true);
3038 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3040 const CChainParams& chainParams = Params();
3041 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3042 uint256 hash = block.GetHash();
3043 if (hash == consensusParams.hashGenesisBlock)
3048 int nHeight = pindexPrev->nHeight+1;
3050 // Check proof of work
3051 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3052 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3053 REJECT_INVALID, "bad-diffbits");
3055 // Check timestamp against prev
3056 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3057 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3058 REJECT_INVALID, "time-too-old");
3060 if(fCheckpointsEnabled)
3062 // Check that the block chain matches the known block chain up to a checkpoint
3063 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3064 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
3065 REJECT_CHECKPOINT, "checkpoint mismatch");
3067 // Don't accept any forks from the main chain prior to last checkpoint
3068 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3069 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3070 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3073 // Reject block.nVersion < 4 blocks
3074 if (block.nVersion < 4)
3075 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3076 REJECT_OBSOLETE, "bad-version");
3081 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3083 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3084 const Consensus::Params& consensusParams = Params().GetConsensus();
3086 // Check that all transactions are finalized
3087 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3088 int nLockTimeFlags = 0;
3089 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3090 ? pindexPrev->GetMedianTimePast()
3091 : block.GetBlockTime();
3092 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3093 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3097 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3098 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3099 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3100 // This rule is not applied to the genesis block, which didn't include the height
3104 CScript expect = CScript() << nHeight;
3105 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3106 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3107 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3111 // Coinbase transaction must include an output sending 20% of
3112 // the block reward to a founders reward script, until the last founders
3113 // reward block is reached, with exception of the genesis block.
3114 // The last founders reward block is defined as the block just before the
3115 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3116 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3119 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3120 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3121 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3129 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3136 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3138 const CChainParams& chainparams = Params();
3139 AssertLockHeld(cs_main);
3140 // Check for duplicate
3141 uint256 hash = block.GetHash();
3142 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3143 CBlockIndex *pindex = NULL;
3144 if (miSelf != mapBlockIndex.end()) {
3145 // Block header is already known.
3146 pindex = miSelf->second;
3149 if (pindex->nStatus & BLOCK_FAILED_MASK)
3150 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3154 if (!CheckBlockHeader(block, state))
3157 // Get prev block index
3158 CBlockIndex* pindexPrev = NULL;
3159 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3160 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3161 if (mi == mapBlockIndex.end())
3162 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3163 pindexPrev = (*mi).second;
3164 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3165 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3168 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3172 pindex = AddToBlockIndex(block);
3180 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3182 const CChainParams& chainparams = Params();
3183 AssertLockHeld(cs_main);
3185 CBlockIndex *&pindex = *ppindex;
3187 if (!AcceptBlockHeader(block, state, &pindex))
3190 // Try to process all requested blocks that we don't have, but only
3191 // process an unrequested block if it's new and has enough work to
3192 // advance our tip, and isn't too many blocks ahead.
3193 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3194 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3195 // Blocks that are too out-of-order needlessly limit the effectiveness of
3196 // pruning, because pruning will not delete block files that contain any
3197 // blocks which are too close in height to the tip. Apply this test
3198 // regardless of whether pruning is enabled; it should generally be safe to
3199 // not process unrequested blocks.
3200 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3202 // TODO: deal better with return value and error conditions for duplicate
3203 // and unrequested blocks.
3204 if (fAlreadyHave) return true;
3205 if (!fRequested) { // If we didn't ask for it:
3206 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3207 if (!fHasMoreWork) return true; // Don't process less-work chains
3208 if (fTooFarAhead) return true; // Block height is too high
3211 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3212 if (state.IsInvalid() && !state.CorruptionPossible()) {
3213 pindex->nStatus |= BLOCK_FAILED_VALID;
3214 setDirtyBlockIndex.insert(pindex);
3219 int nHeight = pindex->nHeight;
3221 // Write block to history file
3223 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3224 CDiskBlockPos blockPos;
3227 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3228 return error("AcceptBlock(): FindBlockPos failed");
3230 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3231 AbortNode(state, "Failed to write block");
3232 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3233 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3234 } catch (const std::runtime_error& e) {
3235 return AbortNode(state, std::string("System error: ") + e.what());
3238 if (fCheckForPruning)
3239 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3244 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3246 unsigned int nFound = 0;
3247 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3249 if (pstart->nVersion >= minVersion)
3251 pstart = pstart->pprev;
3253 return (nFound >= nRequired);
3257 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3259 // Preliminary checks
3260 bool checked = CheckBlock(*pblock, state);
3264 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3265 fRequested |= fForceProcessing;
3267 return error("%s: CheckBlock FAILED", __func__);
3271 CBlockIndex *pindex = NULL;
3272 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3273 if (pindex && pfrom) {
3274 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3278 return error("%s: AcceptBlock FAILED", __func__);
3281 if (!ActivateBestChain(state, pblock))
3282 return error("%s: ActivateBestChain failed", __func__);
3287 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3289 AssertLockHeld(cs_main);
3290 assert(pindexPrev == chainActive.Tip());
3292 CCoinsViewCache viewNew(pcoinsTip);
3293 CBlockIndex indexDummy(block);
3294 indexDummy.pprev = pindexPrev;
3295 indexDummy.nHeight = pindexPrev->nHeight + 1;
3297 // NOTE: CheckBlockHeader is called by CheckBlock
3298 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3300 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3302 if (!ContextualCheckBlock(block, state, pindexPrev))
3304 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3306 assert(state.IsValid());
3312 * BLOCK PRUNING CODE
3315 /* Calculate the amount of disk space the block & undo files currently use */
3316 uint64_t CalculateCurrentUsage()
3318 uint64_t retval = 0;
3319 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3320 retval += file.nSize + file.nUndoSize;
3325 /* Prune a block file (modify associated database entries)*/
3326 void PruneOneBlockFile(const int fileNumber)
3328 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3329 CBlockIndex* pindex = it->second;
3330 if (pindex->nFile == fileNumber) {
3331 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3332 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3334 pindex->nDataPos = 0;
3335 pindex->nUndoPos = 0;
3336 setDirtyBlockIndex.insert(pindex);
3338 // Prune from mapBlocksUnlinked -- any block we prune would have
3339 // to be downloaded again in order to consider its chain, at which
3340 // point it would be considered as a candidate for
3341 // mapBlocksUnlinked or setBlockIndexCandidates.
3342 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3343 while (range.first != range.second) {
3344 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3346 if (it->second == pindex) {
3347 mapBlocksUnlinked.erase(it);
3353 vinfoBlockFile[fileNumber].SetNull();
3354 setDirtyFileInfo.insert(fileNumber);
3358 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3360 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3361 CDiskBlockPos pos(*it, 0);
3362 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3363 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3364 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3368 /* Calculate the block/rev files that should be deleted to remain under target*/
3369 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3371 LOCK2(cs_main, cs_LastBlockFile);
3372 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3375 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3379 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3380 uint64_t nCurrentUsage = CalculateCurrentUsage();
3381 // We don't check to prune until after we've allocated new space for files
3382 // So we should leave a buffer under our target to account for another allocation
3383 // before the next pruning.
3384 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3385 uint64_t nBytesToPrune;
3388 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3389 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3390 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3392 if (vinfoBlockFile[fileNumber].nSize == 0)
3395 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3398 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3399 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3402 PruneOneBlockFile(fileNumber);
3403 // Queue up the files for removal
3404 setFilesToPrune.insert(fileNumber);
3405 nCurrentUsage -= nBytesToPrune;
3410 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3411 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3412 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3413 nLastBlockWeCanPrune, count);
3416 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3418 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3420 // Check for nMinDiskSpace bytes (currently 50MB)
3421 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3422 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3427 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3431 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3432 boost::filesystem::create_directories(path.parent_path());
3433 FILE* file = fopen(path.string().c_str(), "rb+");
3434 if (!file && !fReadOnly)
3435 file = fopen(path.string().c_str(), "wb+");
3437 LogPrintf("Unable to open file %s\n", path.string());
3441 if (fseek(file, pos.nPos, SEEK_SET)) {
3442 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3450 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3451 return OpenDiskFile(pos, "blk", fReadOnly);
3454 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3455 return OpenDiskFile(pos, "rev", fReadOnly);
3458 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3460 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3463 CBlockIndex * InsertBlockIndex(uint256 hash)
3469 BlockMap::iterator mi = mapBlockIndex.find(hash);
3470 if (mi != mapBlockIndex.end())
3471 return (*mi).second;
3474 CBlockIndex* pindexNew = new CBlockIndex();
3476 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3477 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3478 pindexNew->phashBlock = &((*mi).first);
3483 bool static LoadBlockIndexDB()
3485 const CChainParams& chainparams = Params();
3486 if (!pblocktree->LoadBlockIndexGuts())
3489 boost::this_thread::interruption_point();
3491 // Calculate nChainWork
3492 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3493 vSortedByHeight.reserve(mapBlockIndex.size());
3494 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3496 CBlockIndex* pindex = item.second;
3497 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3499 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3500 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3502 CBlockIndex* pindex = item.second;
3503 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3504 // We can link the chain of blocks for which we've received transactions at some point.
3505 // Pruned nodes may have deleted the block.
3506 if (pindex->nTx > 0) {
3507 if (pindex->pprev) {
3508 if (pindex->pprev->nChainTx) {
3509 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3511 pindex->nChainTx = 0;
3512 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3515 pindex->nChainTx = pindex->nTx;
3518 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3519 setBlockIndexCandidates.insert(pindex);
3520 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3521 pindexBestInvalid = pindex;
3523 pindex->BuildSkip();
3524 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3525 pindexBestHeader = pindex;
3528 // Load block file info
3529 pblocktree->ReadLastBlockFile(nLastBlockFile);
3530 vinfoBlockFile.resize(nLastBlockFile + 1);
3531 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3532 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3533 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3535 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3536 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3537 CBlockFileInfo info;
3538 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3539 vinfoBlockFile.push_back(info);
3545 // Check presence of blk files
3546 LogPrintf("Checking all blk files are present...\n");
3547 set<int> setBlkDataFiles;
3548 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3550 CBlockIndex* pindex = item.second;
3551 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3552 setBlkDataFiles.insert(pindex->nFile);
3555 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3557 CDiskBlockPos pos(*it, 0);
3558 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3563 // Check whether we have ever pruned block & undo files
3564 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3566 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3568 // Check whether we need to continue reindexing
3569 bool fReindexing = false;
3570 pblocktree->ReadReindexing(fReindexing);
3571 fReindex |= fReindexing;
3573 // Check whether we have a transaction index
3574 pblocktree->ReadFlag("txindex", fTxIndex);
3575 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3577 // Load pointer to end of best chain
3578 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3579 if (it == mapBlockIndex.end())
3581 chainActive.SetTip(it->second);
3583 PruneBlockIndexCandidates();
3585 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3586 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3587 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3588 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3593 CVerifyDB::CVerifyDB()
3595 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3598 CVerifyDB::~CVerifyDB()
3600 uiInterface.ShowProgress("", 100);
3603 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3606 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3609 // Verify blocks in the best chain
3610 if (nCheckDepth <= 0)
3611 nCheckDepth = 1000000000; // suffices until the year 19000
3612 if (nCheckDepth > chainActive.Height())
3613 nCheckDepth = chainActive.Height();
3614 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3615 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3616 CCoinsViewCache coins(coinsview);
3617 CBlockIndex* pindexState = chainActive.Tip();
3618 CBlockIndex* pindexFailure = NULL;
3619 int nGoodTransactions = 0;
3620 CValidationState state;
3621 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3623 boost::this_thread::interruption_point();
3624 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3625 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3628 // check level 0: read from disk
3629 if (!ReadBlockFromDisk(block, pindex))
3630 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3631 // check level 1: verify block validity
3632 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3633 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3634 // check level 2: verify undo validity
3635 if (nCheckLevel >= 2 && pindex) {
3637 CDiskBlockPos pos = pindex->GetUndoPos();
3638 if (!pos.IsNull()) {
3639 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3640 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3643 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3644 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3646 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3647 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3648 pindexState = pindex->pprev;
3650 nGoodTransactions = 0;
3651 pindexFailure = pindex;
3653 nGoodTransactions += block.vtx.size();
3655 if (ShutdownRequested())
3659 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3661 // check level 4: try reconnecting blocks
3662 if (nCheckLevel >= 4) {
3663 CBlockIndex *pindex = pindexState;
3664 while (pindex != chainActive.Tip()) {
3665 boost::this_thread::interruption_point();
3666 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3667 pindex = chainActive.Next(pindex);
3669 if (!ReadBlockFromDisk(block, pindex))
3670 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3671 if (!ConnectBlock(block, state, pindex, coins))
3672 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3676 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3681 void UnloadBlockIndex()
3684 setBlockIndexCandidates.clear();
3685 chainActive.SetTip(NULL);
3686 pindexBestInvalid = NULL;
3687 pindexBestHeader = NULL;
3689 mapOrphanTransactions.clear();
3690 mapOrphanTransactionsByPrev.clear();
3692 mapBlocksUnlinked.clear();
3693 vinfoBlockFile.clear();
3695 nBlockSequenceId = 1;
3696 mapBlockSource.clear();
3697 mapBlocksInFlight.clear();
3698 nQueuedValidatedHeaders = 0;
3699 nPreferredDownload = 0;
3700 setDirtyBlockIndex.clear();
3701 setDirtyFileInfo.clear();
3702 mapNodeState.clear();
3703 recentRejects.reset(NULL);
3705 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3706 delete entry.second;
3708 mapBlockIndex.clear();
3709 fHavePruned = false;
3712 bool LoadBlockIndex()
3714 // Load block index from databases
3715 if (!fReindex && !LoadBlockIndexDB())
3721 bool InitBlockIndex() {
3722 const CChainParams& chainparams = Params();
3725 // Initialize global variables that cannot be constructed at startup.
3726 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3728 // Check whether we're already initialized
3729 if (chainActive.Genesis() != NULL)
3732 // Use the provided setting for -txindex in the new database
3733 fTxIndex = GetBoolArg("-txindex", false);
3734 pblocktree->WriteFlag("txindex", fTxIndex);
3735 LogPrintf("Initializing databases...\n");
3737 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3740 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3741 // Start new block file
3742 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3743 CDiskBlockPos blockPos;
3744 CValidationState state;
3745 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3746 return error("LoadBlockIndex(): FindBlockPos failed");
3747 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3748 return error("LoadBlockIndex(): writing genesis block to disk failed");
3749 CBlockIndex *pindex = AddToBlockIndex(block);
3750 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3751 return error("LoadBlockIndex(): genesis block not accepted");
3752 if (!ActivateBestChain(state, &block))
3753 return error("LoadBlockIndex(): genesis block cannot be activated");
3754 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3755 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3756 } catch (const std::runtime_error& e) {
3757 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3766 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3768 const CChainParams& chainparams = Params();
3769 // Map of disk positions for blocks with unknown parent (only used for reindex)
3770 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3771 int64_t nStart = GetTimeMillis();
3775 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3776 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3777 uint64_t nRewind = blkdat.GetPos();
3778 while (!blkdat.eof()) {
3779 boost::this_thread::interruption_point();
3781 blkdat.SetPos(nRewind);
3782 nRewind++; // start one byte further next time, in case of failure
3783 blkdat.SetLimit(); // remove former limit
3784 unsigned int nSize = 0;
3787 unsigned char buf[MESSAGE_START_SIZE];
3788 blkdat.FindByte(Params().MessageStart()[0]);
3789 nRewind = blkdat.GetPos()+1;
3790 blkdat >> FLATDATA(buf);
3791 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3795 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3797 } catch (const std::exception&) {
3798 // no valid block header found; don't complain
3803 uint64_t nBlockPos = blkdat.GetPos();
3805 dbp->nPos = nBlockPos;
3806 blkdat.SetLimit(nBlockPos + nSize);
3807 blkdat.SetPos(nBlockPos);
3810 nRewind = blkdat.GetPos();
3812 // detect out of order blocks, and store them for later
3813 uint256 hash = block.GetHash();
3814 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3815 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3816 block.hashPrevBlock.ToString());
3818 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3822 // process in case the block isn't known yet
3823 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3824 CValidationState state;
3825 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3827 if (state.IsError())
3829 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3830 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3833 // Recursively process earlier encountered successors of this block
3834 deque<uint256> queue;
3835 queue.push_back(hash);
3836 while (!queue.empty()) {
3837 uint256 head = queue.front();
3839 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3840 while (range.first != range.second) {
3841 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3842 if (ReadBlockFromDisk(block, it->second))
3844 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3846 CValidationState dummy;
3847 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3850 queue.push_back(block.GetHash());
3854 mapBlocksUnknownParent.erase(it);
3857 } catch (const std::exception& e) {
3858 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3861 } catch (const std::runtime_error& e) {
3862 AbortNode(std::string("System error: ") + e.what());
3865 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3869 void static CheckBlockIndex()
3871 const Consensus::Params& consensusParams = Params().GetConsensus();
3872 if (!fCheckBlockIndex) {
3878 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3879 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3880 // iterating the block tree require that chainActive has been initialized.)
3881 if (chainActive.Height() < 0) {
3882 assert(mapBlockIndex.size() <= 1);
3886 // Build forward-pointing map of the entire block tree.
3887 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3888 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3889 forward.insert(std::make_pair(it->second->pprev, it->second));
3892 assert(forward.size() == mapBlockIndex.size());
3894 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3895 CBlockIndex *pindex = rangeGenesis.first->second;
3896 rangeGenesis.first++;
3897 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3899 // Iterate over the entire block tree, using depth-first search.
3900 // Along the way, remember whether there are blocks on the path from genesis
3901 // block being explored which are the first to have certain properties.
3904 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3905 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3906 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3907 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3908 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3909 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3910 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3911 while (pindex != NULL) {
3913 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3914 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3915 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3916 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3917 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3918 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3919 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3921 // Begin: actual consistency checks.
3922 if (pindex->pprev == NULL) {
3923 // Genesis block checks.
3924 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3925 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3927 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3928 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3929 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3931 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3932 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3933 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3935 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3936 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3938 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3939 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3940 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3941 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3942 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3943 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3944 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.
3945 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3946 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3947 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3948 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3949 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3950 if (pindexFirstInvalid == NULL) {
3951 // Checks for not-invalid blocks.
3952 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3954 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3955 if (pindexFirstInvalid == NULL) {
3956 // If this block sorts at least as good as the current tip and
3957 // is valid and we have all data for its parents, it must be in
3958 // setBlockIndexCandidates. chainActive.Tip() must also be there
3959 // even if some data has been pruned.
3960 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3961 assert(setBlockIndexCandidates.count(pindex));
3963 // If some parent is missing, then it could be that this block was in
3964 // setBlockIndexCandidates but had to be removed because of the missing data.
3965 // In this case it must be in mapBlocksUnlinked -- see test below.
3967 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3968 assert(setBlockIndexCandidates.count(pindex) == 0);
3970 // Check whether this block is in mapBlocksUnlinked.
3971 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3972 bool foundInUnlinked = false;
3973 while (rangeUnlinked.first != rangeUnlinked.second) {
3974 assert(rangeUnlinked.first->first == pindex->pprev);
3975 if (rangeUnlinked.first->second == pindex) {
3976 foundInUnlinked = true;
3979 rangeUnlinked.first++;
3981 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3982 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3983 assert(foundInUnlinked);
3985 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3986 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3987 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3988 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3989 assert(fHavePruned); // We must have pruned.
3990 // This block may have entered mapBlocksUnlinked if:
3991 // - it has a descendant that at some point had more work than the
3993 // - we tried switching to that descendant but were missing
3994 // data for some intermediate block between chainActive and the
3996 // So if this block is itself better than chainActive.Tip() and it wasn't in
3997 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3998 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3999 if (pindexFirstInvalid == NULL) {
4000 assert(foundInUnlinked);
4004 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4005 // End: actual consistency checks.
4007 // Try descending into the first subnode.
4008 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4009 if (range.first != range.second) {
4010 // A subnode was found.
4011 pindex = range.first->second;
4015 // This is a leaf node.
4016 // Move upwards until we reach a node of which we have not yet visited the last child.
4018 // We are going to either move to a parent or a sibling of pindex.
4019 // If pindex was the first with a certain property, unset the corresponding variable.
4020 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4021 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4022 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4023 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4024 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4025 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4026 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4028 CBlockIndex* pindexPar = pindex->pprev;
4029 // Find which child we just visited.
4030 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4031 while (rangePar.first->second != pindex) {
4032 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4035 // Proceed to the next one.
4037 if (rangePar.first != rangePar.second) {
4038 // Move to the sibling.
4039 pindex = rangePar.first->second;
4050 // Check that we actually traversed the entire map.
4051 assert(nNodes == forward.size());
4054 //////////////////////////////////////////////////////////////////////////////
4059 string GetWarnings(string strFor)
4062 string strStatusBar;
4065 if (!CLIENT_VERSION_IS_RELEASE)
4066 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4068 if (GetBoolArg("-testsafemode", false))
4069 strStatusBar = strRPC = "testsafemode enabled";
4071 // Misc warnings like out of disk space and clock is wrong
4072 if (strMiscWarning != "")
4075 strStatusBar = strMiscWarning;
4078 if (fLargeWorkForkFound)
4081 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4083 else if (fLargeWorkInvalidChainFound)
4086 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.");
4092 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4094 const CAlert& alert = item.second;
4095 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4097 nPriority = alert.nPriority;
4098 strStatusBar = alert.strStatusBar;
4099 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4100 strRPC = alert.strRPCError;
4106 if (strFor == "statusbar")
4107 return strStatusBar;
4108 else if (strFor == "rpc")
4110 assert(!"GetWarnings(): invalid parameter");
4121 //////////////////////////////////////////////////////////////////////////////
4127 bool static AlreadyHave(const CInv& inv)
4133 assert(recentRejects);
4134 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4136 // If the chain tip has changed previously rejected transactions
4137 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4138 // or a double-spend. Reset the rejects filter and give those
4139 // txs a second chance.
4140 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4141 recentRejects->reset();
4144 return recentRejects->contains(inv.hash) ||
4145 mempool.exists(inv.hash) ||
4146 mapOrphanTransactions.count(inv.hash) ||
4147 pcoinsTip->HaveCoins(inv.hash);
4150 return mapBlockIndex.count(inv.hash);
4152 // Don't know what it is, just say we already got one
4156 void static ProcessGetData(CNode* pfrom)
4158 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4160 vector<CInv> vNotFound;
4164 while (it != pfrom->vRecvGetData.end()) {
4165 // Don't bother if send buffer is too full to respond anyway
4166 if (pfrom->nSendSize >= SendBufferSize())
4169 const CInv &inv = *it;
4171 boost::this_thread::interruption_point();
4174 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4177 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4178 if (mi != mapBlockIndex.end())
4180 if (chainActive.Contains(mi->second)) {
4183 static const int nOneMonth = 30 * 24 * 60 * 60;
4184 // To prevent fingerprinting attacks, only send blocks outside of the active
4185 // chain if they are valid, and no more than a month older (both in time, and in
4186 // best equivalent proof of work) than the best header chain we know about.
4187 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4188 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4189 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4191 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4195 // Pruned nodes may have deleted the block, so check whether
4196 // it's available before trying to send.
4197 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4199 // Send block from disk
4201 if (!ReadBlockFromDisk(block, (*mi).second))
4202 assert(!"cannot load block from disk");
4203 if (inv.type == MSG_BLOCK)
4204 pfrom->PushMessage("block", block);
4205 else // MSG_FILTERED_BLOCK)
4207 LOCK(pfrom->cs_filter);
4210 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4211 pfrom->PushMessage("merkleblock", merkleBlock);
4212 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4213 // This avoids hurting performance by pointlessly requiring a round-trip
4214 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4215 // they must either disconnect and retry or request the full block.
4216 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4217 // however we MUST always provide at least what the remote peer needs
4218 typedef std::pair<unsigned int, uint256> PairType;
4219 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4220 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4221 pfrom->PushMessage("tx", block.vtx[pair.first]);
4227 // Trigger the peer node to send a getblocks request for the next batch of inventory
4228 if (inv.hash == pfrom->hashContinue)
4230 // Bypass PushInventory, this must send even if redundant,
4231 // and we want it right after the last block so they don't
4232 // wait for other stuff first.
4234 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4235 pfrom->PushMessage("inv", vInv);
4236 pfrom->hashContinue.SetNull();
4240 else if (inv.IsKnownType())
4242 // Send stream from relay memory
4243 bool pushed = false;
4246 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4247 if (mi != mapRelay.end()) {
4248 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4252 if (!pushed && inv.type == MSG_TX) {
4254 if (mempool.lookup(inv.hash, tx)) {
4255 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4258 pfrom->PushMessage("tx", ss);
4263 vNotFound.push_back(inv);
4267 // Track requests for our stuff.
4268 GetMainSignals().Inventory(inv.hash);
4270 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4275 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4277 if (!vNotFound.empty()) {
4278 // Let the peer know that we didn't find what it asked for, so it doesn't
4279 // have to wait around forever. Currently only SPV clients actually care
4280 // about this message: it's needed when they are recursively walking the
4281 // dependencies of relevant unconfirmed transactions. SPV clients want to
4282 // do that because they want to know about (and store and rebroadcast and
4283 // risk analyze) the dependencies of transactions relevant to them, without
4284 // having to download the entire memory pool.
4285 pfrom->PushMessage("notfound", vNotFound);
4289 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4291 const CChainParams& chainparams = Params();
4292 RandAddSeedPerfmon();
4293 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4294 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4296 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4303 if (strCommand == "version")
4305 // Each connection can only send one version message
4306 if (pfrom->nVersion != 0)
4308 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4309 Misbehaving(pfrom->GetId(), 1);
4316 uint64_t nNonce = 1;
4317 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4318 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4320 // disconnect from peers older than this proto version
4321 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4322 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4323 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4324 pfrom->fDisconnect = true;
4328 if (pfrom->nVersion == 10300)
4329 pfrom->nVersion = 300;
4331 vRecv >> addrFrom >> nNonce;
4332 if (!vRecv.empty()) {
4333 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4334 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4337 vRecv >> pfrom->nStartingHeight;
4339 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4341 pfrom->fRelayTxes = true;
4343 // Disconnect if we connected to ourself
4344 if (nNonce == nLocalHostNonce && nNonce > 1)
4346 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4347 pfrom->fDisconnect = true;
4351 pfrom->addrLocal = addrMe;
4352 if (pfrom->fInbound && addrMe.IsRoutable())
4357 // Be shy and don't send version until we hear
4358 if (pfrom->fInbound)
4359 pfrom->PushVersion();
4361 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4363 // Potentially mark this peer as a preferred download peer.
4364 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4367 pfrom->PushMessage("verack");
4368 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4370 if (!pfrom->fInbound)
4372 // Advertise our address
4373 if (fListen && !IsInitialBlockDownload())
4375 CAddress addr = GetLocalAddress(&pfrom->addr);
4376 if (addr.IsRoutable())
4378 pfrom->PushAddress(addr);
4379 } else if (IsPeerAddrLocalGood(pfrom)) {
4380 addr.SetIP(pfrom->addrLocal);
4381 pfrom->PushAddress(addr);
4385 // Get recent addresses
4386 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4388 pfrom->PushMessage("getaddr");
4389 pfrom->fGetAddr = true;
4391 addrman.Good(pfrom->addr);
4393 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4395 addrman.Add(addrFrom, addrFrom);
4396 addrman.Good(addrFrom);
4403 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4404 item.second.RelayTo(pfrom);
4407 pfrom->fSuccessfullyConnected = true;
4411 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4413 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4414 pfrom->cleanSubVer, pfrom->nVersion,
4415 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4418 int64_t nTimeOffset = nTime - GetTime();
4419 pfrom->nTimeOffset = nTimeOffset;
4420 AddTimeData(pfrom->addr, nTimeOffset);
4424 else if (pfrom->nVersion == 0)
4426 // Must have a version message before anything else
4427 Misbehaving(pfrom->GetId(), 1);
4432 else if (strCommand == "verack")
4434 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4436 // Mark this node as currently connected, so we update its timestamp later.
4437 if (pfrom->fNetworkNode) {
4439 State(pfrom->GetId())->fCurrentlyConnected = true;
4444 else if (strCommand == "addr")
4446 vector<CAddress> vAddr;
4449 // Don't want addr from older versions unless seeding
4450 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4452 if (vAddr.size() > 1000)
4454 Misbehaving(pfrom->GetId(), 20);
4455 return error("message addr size() = %u", vAddr.size());
4458 // Store the new addresses
4459 vector<CAddress> vAddrOk;
4460 int64_t nNow = GetAdjustedTime();
4461 int64_t nSince = nNow - 10 * 60;
4462 BOOST_FOREACH(CAddress& addr, vAddr)
4464 boost::this_thread::interruption_point();
4466 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4467 addr.nTime = nNow - 5 * 24 * 60 * 60;
4468 pfrom->AddAddressKnown(addr);
4469 bool fReachable = IsReachable(addr);
4470 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4472 // Relay to a limited number of other nodes
4475 // Use deterministic randomness to send to the same nodes for 24 hours
4476 // at a time so the addrKnowns of the chosen nodes prevent repeats
4477 static uint256 hashSalt;
4478 if (hashSalt.IsNull())
4479 hashSalt = GetRandHash();
4480 uint64_t hashAddr = addr.GetHash();
4481 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4482 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4483 multimap<uint256, CNode*> mapMix;
4484 BOOST_FOREACH(CNode* pnode, vNodes)
4486 if (pnode->nVersion < CADDR_TIME_VERSION)
4488 unsigned int nPointer;
4489 memcpy(&nPointer, &pnode, sizeof(nPointer));
4490 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4491 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4492 mapMix.insert(make_pair(hashKey, pnode));
4494 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4495 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4496 ((*mi).second)->PushAddress(addr);
4499 // Do not store addresses outside our network
4501 vAddrOk.push_back(addr);
4503 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4504 if (vAddr.size() < 1000)
4505 pfrom->fGetAddr = false;
4506 if (pfrom->fOneShot)
4507 pfrom->fDisconnect = true;
4511 else if (strCommand == "inv")
4515 if (vInv.size() > MAX_INV_SZ)
4517 Misbehaving(pfrom->GetId(), 20);
4518 return error("message inv size() = %u", vInv.size());
4523 std::vector<CInv> vToFetch;
4525 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4527 const CInv &inv = vInv[nInv];
4529 boost::this_thread::interruption_point();
4530 pfrom->AddInventoryKnown(inv);
4532 bool fAlreadyHave = AlreadyHave(inv);
4533 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4535 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4538 if (inv.type == MSG_BLOCK) {
4539 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4540 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4541 // First request the headers preceding the announced block. In the normal fully-synced
4542 // case where a new block is announced that succeeds the current tip (no reorganization),
4543 // there are no such headers.
4544 // Secondly, and only when we are close to being synced, we request the announced block directly,
4545 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4546 // time the block arrives, the header chain leading up to it is already validated. Not
4547 // doing this will result in the received block being rejected as an orphan in case it is
4548 // not a direct successor.
4549 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4550 CNodeState *nodestate = State(pfrom->GetId());
4551 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4552 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4553 vToFetch.push_back(inv);
4554 // Mark block as in flight already, even though the actual "getdata" message only goes out
4555 // later (within the same cs_main lock, though).
4556 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4558 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4562 // Track requests for our stuff
4563 GetMainSignals().Inventory(inv.hash);
4565 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4566 Misbehaving(pfrom->GetId(), 50);
4567 return error("send buffer size() = %u", pfrom->nSendSize);
4571 if (!vToFetch.empty())
4572 pfrom->PushMessage("getdata", vToFetch);
4576 else if (strCommand == "getdata")
4580 if (vInv.size() > MAX_INV_SZ)
4582 Misbehaving(pfrom->GetId(), 20);
4583 return error("message getdata size() = %u", vInv.size());
4586 if (fDebug || (vInv.size() != 1))
4587 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4589 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4590 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4592 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4593 ProcessGetData(pfrom);
4597 else if (strCommand == "getblocks")
4599 CBlockLocator locator;
4601 vRecv >> locator >> hashStop;
4605 // Find the last block the caller has in the main chain
4606 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4608 // Send the rest of the chain
4610 pindex = chainActive.Next(pindex);
4612 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4613 for (; pindex; pindex = chainActive.Next(pindex))
4615 if (pindex->GetBlockHash() == hashStop)
4617 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4620 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4623 // When this block is requested, we'll send an inv that'll
4624 // trigger the peer to getblocks the next batch of inventory.
4625 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4626 pfrom->hashContinue = pindex->GetBlockHash();
4633 else if (strCommand == "getheaders")
4635 CBlockLocator locator;
4637 vRecv >> locator >> hashStop;
4641 if (IsInitialBlockDownload())
4644 CBlockIndex* pindex = NULL;
4645 if (locator.IsNull())
4647 // If locator is null, return the hashStop block
4648 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4649 if (mi == mapBlockIndex.end())
4651 pindex = (*mi).second;
4655 // Find the last block the caller has in the main chain
4656 pindex = FindForkInGlobalIndex(chainActive, locator);
4658 pindex = chainActive.Next(pindex);
4661 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4662 vector<CBlock> vHeaders;
4663 int nLimit = MAX_HEADERS_RESULTS;
4664 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4665 for (; pindex; pindex = chainActive.Next(pindex))
4667 vHeaders.push_back(pindex->GetBlockHeader());
4668 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4671 pfrom->PushMessage("headers", vHeaders);
4675 else if (strCommand == "tx")
4677 vector<uint256> vWorkQueue;
4678 vector<uint256> vEraseQueue;
4682 CInv inv(MSG_TX, tx.GetHash());
4683 pfrom->AddInventoryKnown(inv);
4687 bool fMissingInputs = false;
4688 CValidationState state;
4690 pfrom->setAskFor.erase(inv.hash);
4691 mapAlreadyAskedFor.erase(inv);
4693 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4695 mempool.check(pcoinsTip);
4696 RelayTransaction(tx);
4697 vWorkQueue.push_back(inv.hash);
4699 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4700 pfrom->id, pfrom->cleanSubVer,
4701 tx.GetHash().ToString(),
4702 mempool.mapTx.size());
4704 // Recursively process any orphan transactions that depended on this one
4705 set<NodeId> setMisbehaving;
4706 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4708 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4709 if (itByPrev == mapOrphanTransactionsByPrev.end())
4711 for (set<uint256>::iterator mi = itByPrev->second.begin();
4712 mi != itByPrev->second.end();
4715 const uint256& orphanHash = *mi;
4716 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4717 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4718 bool fMissingInputs2 = false;
4719 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4720 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4721 // anyone relaying LegitTxX banned)
4722 CValidationState stateDummy;
4725 if (setMisbehaving.count(fromPeer))
4727 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4729 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4730 RelayTransaction(orphanTx);
4731 vWorkQueue.push_back(orphanHash);
4732 vEraseQueue.push_back(orphanHash);
4734 else if (!fMissingInputs2)
4737 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4739 // Punish peer that gave us an invalid orphan tx
4740 Misbehaving(fromPeer, nDos);
4741 setMisbehaving.insert(fromPeer);
4742 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4744 // Has inputs but not accepted to mempool
4745 // Probably non-standard or insufficient fee/priority
4746 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4747 vEraseQueue.push_back(orphanHash);
4748 assert(recentRejects);
4749 recentRejects->insert(orphanHash);
4751 mempool.check(pcoinsTip);
4755 BOOST_FOREACH(uint256 hash, vEraseQueue)
4756 EraseOrphanTx(hash);
4758 // TODO: currently, prohibit joinsplits from entering mapOrphans
4759 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4761 AddOrphanTx(tx, pfrom->GetId());
4763 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4764 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4765 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4767 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4769 assert(recentRejects);
4770 recentRejects->insert(tx.GetHash());
4772 if (pfrom->fWhitelisted) {
4773 // Always relay transactions received from whitelisted peers, even
4774 // if they were already in the mempool or rejected from it due
4775 // to policy, allowing the node to function as a gateway for
4776 // nodes hidden behind it.
4778 // Never relay transactions that we would assign a non-zero DoS
4779 // score for, as we expect peers to do the same with us in that
4782 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4783 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4784 RelayTransaction(tx);
4786 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4787 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4792 if (state.IsInvalid(nDoS))
4794 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4795 pfrom->id, pfrom->cleanSubVer,
4796 state.GetRejectReason());
4797 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4798 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4800 Misbehaving(pfrom->GetId(), nDoS);
4805 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4807 std::vector<CBlockHeader> headers;
4809 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4810 unsigned int nCount = ReadCompactSize(vRecv);
4811 if (nCount > MAX_HEADERS_RESULTS) {
4812 Misbehaving(pfrom->GetId(), 20);
4813 return error("headers message size = %u", nCount);
4815 headers.resize(nCount);
4816 for (unsigned int n = 0; n < nCount; n++) {
4817 vRecv >> headers[n];
4818 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4824 // Nothing interesting. Stop asking this peers for more headers.
4828 CBlockIndex *pindexLast = NULL;
4829 BOOST_FOREACH(const CBlockHeader& header, headers) {
4830 CValidationState state;
4831 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4832 Misbehaving(pfrom->GetId(), 20);
4833 return error("non-continuous headers sequence");
4835 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4837 if (state.IsInvalid(nDoS)) {
4839 Misbehaving(pfrom->GetId(), nDoS);
4840 return error("invalid header received");
4846 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4848 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4849 // Headers message had its maximum size; the peer may have more headers.
4850 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4851 // from there instead.
4852 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4853 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4859 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4864 CInv inv(MSG_BLOCK, block.GetHash());
4865 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4867 pfrom->AddInventoryKnown(inv);
4869 CValidationState state;
4870 // Process all blocks from whitelisted peers, even if not requested,
4871 // unless we're still syncing with the network.
4872 // Such an unrequested block may still be processed, subject to the
4873 // conditions in AcceptBlock().
4874 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4875 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4877 if (state.IsInvalid(nDoS)) {
4878 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4879 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4882 Misbehaving(pfrom->GetId(), nDoS);
4889 // This asymmetric behavior for inbound and outbound connections was introduced
4890 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4891 // to users' AddrMan and later request them by sending getaddr messages.
4892 // Making nodes which are behind NAT and can only make outgoing connections ignore
4893 // the getaddr message mitigates the attack.
4894 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4896 // Only send one GetAddr response per connection to reduce resource waste
4897 // and discourage addr stamping of INV announcements.
4898 if (pfrom->fSentAddr) {
4899 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4902 pfrom->fSentAddr = true;
4904 pfrom->vAddrToSend.clear();
4905 vector<CAddress> vAddr = addrman.GetAddr();
4906 BOOST_FOREACH(const CAddress &addr, vAddr)
4907 pfrom->PushAddress(addr);
4911 else if (strCommand == "mempool")
4913 LOCK2(cs_main, pfrom->cs_filter);
4915 std::vector<uint256> vtxid;
4916 mempool.queryHashes(vtxid);
4918 BOOST_FOREACH(uint256& hash, vtxid) {
4919 CInv inv(MSG_TX, hash);
4921 bool fInMemPool = mempool.lookup(hash, tx);
4922 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4923 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4925 vInv.push_back(inv);
4926 if (vInv.size() == MAX_INV_SZ) {
4927 pfrom->PushMessage("inv", vInv);
4931 if (vInv.size() > 0)
4932 pfrom->PushMessage("inv", vInv);
4936 else if (strCommand == "ping")
4938 if (pfrom->nVersion > BIP0031_VERSION)
4942 // Echo the message back with the nonce. This allows for two useful features:
4944 // 1) A remote node can quickly check if the connection is operational
4945 // 2) Remote nodes can measure the latency of the network thread. If this node
4946 // is overloaded it won't respond to pings quickly and the remote node can
4947 // avoid sending us more work, like chain download requests.
4949 // The nonce stops the remote getting confused between different pings: without
4950 // it, if the remote node sends a ping once per second and this node takes 5
4951 // seconds to respond to each, the 5th ping the remote sends would appear to
4952 // return very quickly.
4953 pfrom->PushMessage("pong", nonce);
4958 else if (strCommand == "pong")
4960 int64_t pingUsecEnd = nTimeReceived;
4962 size_t nAvail = vRecv.in_avail();
4963 bool bPingFinished = false;
4964 std::string sProblem;
4966 if (nAvail >= sizeof(nonce)) {
4969 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4970 if (pfrom->nPingNonceSent != 0) {
4971 if (nonce == pfrom->nPingNonceSent) {
4972 // Matching pong received, this ping is no longer outstanding
4973 bPingFinished = true;
4974 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4975 if (pingUsecTime > 0) {
4976 // Successful ping time measurement, replace previous
4977 pfrom->nPingUsecTime = pingUsecTime;
4978 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4980 // This should never happen
4981 sProblem = "Timing mishap";
4984 // Nonce mismatches are normal when pings are overlapping
4985 sProblem = "Nonce mismatch";
4987 // This is most likely a bug in another implementation somewhere; cancel this ping
4988 bPingFinished = true;
4989 sProblem = "Nonce zero";
4993 sProblem = "Unsolicited pong without ping";
4996 // This is most likely a bug in another implementation somewhere; cancel this ping
4997 bPingFinished = true;
4998 sProblem = "Short payload";
5001 if (!(sProblem.empty())) {
5002 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5006 pfrom->nPingNonceSent,
5010 if (bPingFinished) {
5011 pfrom->nPingNonceSent = 0;
5016 else if (fAlerts && strCommand == "alert")
5021 uint256 alertHash = alert.GetHash();
5022 if (pfrom->setKnown.count(alertHash) == 0)
5024 if (alert.ProcessAlert(Params().AlertKey()))
5027 pfrom->setKnown.insert(alertHash);
5030 BOOST_FOREACH(CNode* pnode, vNodes)
5031 alert.RelayTo(pnode);
5035 // Small DoS penalty so peers that send us lots of
5036 // duplicate/expired/invalid-signature/whatever alerts
5037 // eventually get banned.
5038 // This isn't a Misbehaving(100) (immediate ban) because the
5039 // peer might be an older or different implementation with
5040 // a different signature key, etc.
5041 Misbehaving(pfrom->GetId(), 10);
5047 else if (strCommand == "filterload")
5049 CBloomFilter filter;
5052 if (!filter.IsWithinSizeConstraints())
5053 // There is no excuse for sending a too-large filter
5054 Misbehaving(pfrom->GetId(), 100);
5057 LOCK(pfrom->cs_filter);
5058 delete pfrom->pfilter;
5059 pfrom->pfilter = new CBloomFilter(filter);
5060 pfrom->pfilter->UpdateEmptyFull();
5062 pfrom->fRelayTxes = true;
5066 else if (strCommand == "filteradd")
5068 vector<unsigned char> vData;
5071 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5072 // and thus, the maximum size any matched object can have) in a filteradd message
5073 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5075 Misbehaving(pfrom->GetId(), 100);
5077 LOCK(pfrom->cs_filter);
5079 pfrom->pfilter->insert(vData);
5081 Misbehaving(pfrom->GetId(), 100);
5086 else if (strCommand == "filterclear")
5088 LOCK(pfrom->cs_filter);
5089 delete pfrom->pfilter;
5090 pfrom->pfilter = new CBloomFilter();
5091 pfrom->fRelayTxes = true;
5095 else if (strCommand == "reject")
5099 string strMsg; unsigned char ccode; string strReason;
5100 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5103 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5105 if (strMsg == "block" || strMsg == "tx")
5109 ss << ": hash " << hash.ToString();
5111 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5112 } catch (const std::ios_base::failure&) {
5113 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5114 LogPrint("net", "Unparseable reject message received\n");
5119 else if (strCommand == "notfound") {
5120 // We do not care about the NOTFOUND message, but logging an Unknown Command
5121 // message would be undesirable as we transmit it ourselves.
5125 // Ignore unknown commands for extensibility
5126 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5134 // requires LOCK(cs_vRecvMsg)
5135 bool ProcessMessages(CNode* pfrom)
5138 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5142 // (4) message start
5150 if (!pfrom->vRecvGetData.empty())
5151 ProcessGetData(pfrom);
5153 // this maintains the order of responses
5154 if (!pfrom->vRecvGetData.empty()) return fOk;
5156 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5157 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5158 // Don't bother if send buffer is too full to respond anyway
5159 if (pfrom->nSendSize >= SendBufferSize())
5163 CNetMessage& msg = *it;
5166 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5167 // msg.hdr.nMessageSize, msg.vRecv.size(),
5168 // msg.complete() ? "Y" : "N");
5170 // end, if an incomplete message is found
5171 if (!msg.complete())
5174 // at this point, any failure means we can delete the current message
5177 // Scan for message start
5178 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5179 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5185 CMessageHeader& hdr = msg.hdr;
5186 if (!hdr.IsValid(Params().MessageStart()))
5188 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5191 string strCommand = hdr.GetCommand();
5194 unsigned int nMessageSize = hdr.nMessageSize;
5197 CDataStream& vRecv = msg.vRecv;
5198 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5199 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5200 if (nChecksum != hdr.nChecksum)
5202 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5203 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5211 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5212 boost::this_thread::interruption_point();
5214 catch (const std::ios_base::failure& e)
5216 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5217 if (strstr(e.what(), "end of data"))
5219 // Allow exceptions from under-length message on vRecv
5220 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());
5222 else if (strstr(e.what(), "size too large"))
5224 // Allow exceptions from over-long size
5225 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5229 PrintExceptionContinue(&e, "ProcessMessages()");
5232 catch (const boost::thread_interrupted&) {
5235 catch (const std::exception& e) {
5236 PrintExceptionContinue(&e, "ProcessMessages()");
5238 PrintExceptionContinue(NULL, "ProcessMessages()");
5242 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5247 // In case the connection got shut down, its receive buffer was wiped
5248 if (!pfrom->fDisconnect)
5249 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5255 bool SendMessages(CNode* pto, bool fSendTrickle)
5257 const Consensus::Params& consensusParams = Params().GetConsensus();
5259 // Don't send anything until we get its version message
5260 if (pto->nVersion == 0)
5266 bool pingSend = false;
5267 if (pto->fPingQueued) {
5268 // RPC ping request by user
5271 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5272 // Ping automatically sent as a latency probe & keepalive.
5277 while (nonce == 0) {
5278 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5280 pto->fPingQueued = false;
5281 pto->nPingUsecStart = GetTimeMicros();
5282 if (pto->nVersion > BIP0031_VERSION) {
5283 pto->nPingNonceSent = nonce;
5284 pto->PushMessage("ping", nonce);
5286 // Peer is too old to support ping command with nonce, pong will never arrive.
5287 pto->nPingNonceSent = 0;
5288 pto->PushMessage("ping");
5292 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5296 // Address refresh broadcast
5297 static int64_t nLastRebroadcast;
5298 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5301 BOOST_FOREACH(CNode* pnode, vNodes)
5303 // Periodically clear addrKnown to allow refresh broadcasts
5304 if (nLastRebroadcast)
5305 pnode->addrKnown.reset();
5307 // Rebroadcast our address
5308 AdvertizeLocal(pnode);
5310 if (!vNodes.empty())
5311 nLastRebroadcast = GetTime();
5319 vector<CAddress> vAddr;
5320 vAddr.reserve(pto->vAddrToSend.size());
5321 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5323 if (!pto->addrKnown.contains(addr.GetKey()))
5325 pto->addrKnown.insert(addr.GetKey());
5326 vAddr.push_back(addr);
5327 // receiver rejects addr messages larger than 1000
5328 if (vAddr.size() >= 1000)
5330 pto->PushMessage("addr", vAddr);
5335 pto->vAddrToSend.clear();
5337 pto->PushMessage("addr", vAddr);
5340 CNodeState &state = *State(pto->GetId());
5341 if (state.fShouldBan) {
5342 if (pto->fWhitelisted)
5343 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5345 pto->fDisconnect = true;
5346 if (pto->addr.IsLocal())
5347 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5350 CNode::Ban(pto->addr);
5353 state.fShouldBan = false;
5356 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5357 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5358 state.rejects.clear();
5361 if (pindexBestHeader == NULL)
5362 pindexBestHeader = chainActive.Tip();
5363 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.
5364 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5365 // Only actively request headers from a single peer, unless we're close to today.
5366 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5367 state.fSyncStarted = true;
5369 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5370 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5371 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5375 // Resend wallet transactions that haven't gotten in a block yet
5376 // Except during reindex, importing and IBD, when old wallet
5377 // transactions become unconfirmed and spams other nodes.
5378 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5380 GetMainSignals().Broadcast(nTimeBestReceived);
5384 // Message: inventory
5387 vector<CInv> vInvWait;
5389 LOCK(pto->cs_inventory);
5390 vInv.reserve(pto->vInventoryToSend.size());
5391 vInvWait.reserve(pto->vInventoryToSend.size());
5392 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5394 if (pto->setInventoryKnown.count(inv))
5397 // trickle out tx inv to protect privacy
5398 if (inv.type == MSG_TX && !fSendTrickle)
5400 // 1/4 of tx invs blast to all immediately
5401 static uint256 hashSalt;
5402 if (hashSalt.IsNull())
5403 hashSalt = GetRandHash();
5404 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5405 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5406 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5410 vInvWait.push_back(inv);
5415 // returns true if wasn't already contained in the set
5416 if (pto->setInventoryKnown.insert(inv).second)
5418 vInv.push_back(inv);
5419 if (vInv.size() >= 1000)
5421 pto->PushMessage("inv", vInv);
5426 pto->vInventoryToSend = vInvWait;
5429 pto->PushMessage("inv", vInv);
5431 // Detect whether we're stalling
5432 int64_t nNow = GetTimeMicros();
5433 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5434 // Stalling only triggers when the block download window cannot move. During normal steady state,
5435 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5436 // should only happen during initial block download.
5437 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5438 pto->fDisconnect = true;
5440 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5441 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5442 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5443 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5444 // to unreasonably increase our timeout.
5445 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5446 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5447 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5448 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5449 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5450 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5451 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5452 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5453 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5454 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5455 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5457 if (queuedBlock.nTimeDisconnect < nNow) {
5458 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5459 pto->fDisconnect = true;
5464 // Message: getdata (blocks)
5466 vector<CInv> vGetData;
5467 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5468 vector<CBlockIndex*> vToDownload;
5469 NodeId staller = -1;
5470 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5471 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5472 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5473 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5474 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5475 pindex->nHeight, pto->id);
5477 if (state.nBlocksInFlight == 0 && staller != -1) {
5478 if (State(staller)->nStallingSince == 0) {
5479 State(staller)->nStallingSince = nNow;
5480 LogPrint("net", "Stall started peer=%d\n", staller);
5486 // Message: getdata (non-blocks)
5488 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5490 const CInv& inv = (*pto->mapAskFor.begin()).second;
5491 if (!AlreadyHave(inv))
5494 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5495 vGetData.push_back(inv);
5496 if (vGetData.size() >= 1000)
5498 pto->PushMessage("getdata", vGetData);
5502 //If we're not going to ask, don't expect a response.
5503 pto->setAskFor.erase(inv.hash);
5505 pto->mapAskFor.erase(pto->mapAskFor.begin());
5507 if (!vGetData.empty())
5508 pto->PushMessage("getdata", vGetData);
5514 std::string CBlockFileInfo::ToString() const {
5515 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));
5526 BlockMap::iterator it1 = mapBlockIndex.begin();
5527 for (; it1 != mapBlockIndex.end(); it1++)
5528 delete (*it1).second;
5529 mapBlockIndex.clear();
5531 // orphan transactions
5532 mapOrphanTransactions.clear();
5533 mapOrphanTransactionsByPrev.clear();
5535 } instance_of_cmaincleanup;