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 auto verifier = libzcash::ProofVerifier::Strict();
848 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
849 if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) {
850 return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"),
851 REJECT_INVALID, "bad-txns-joinsplit-verification-failed");
858 bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state)
860 // Basic checks that don't depend on any context
862 // Check transaction version
863 if (tx.nVersion < MIN_TX_VERSION) {
864 return state.DoS(100, error("CheckTransaction(): version too low"),
865 REJECT_INVALID, "bad-txns-version-too-low");
868 // Transactions can contain empty `vin` and `vout` so long as
869 // `vjoinsplit` is non-empty.
870 if (tx.vin.empty() && tx.vjoinsplit.empty())
871 return state.DoS(10, error("CheckTransaction(): vin empty"),
872 REJECT_INVALID, "bad-txns-vin-empty");
873 if (tx.vout.empty() && tx.vjoinsplit.empty())
874 return state.DoS(10, error("CheckTransaction(): vout empty"),
875 REJECT_INVALID, "bad-txns-vout-empty");
878 BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity
879 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE)
880 return state.DoS(100, error("CheckTransaction(): size limits failed"),
881 REJECT_INVALID, "bad-txns-oversize");
883 // Check for negative or overflow output values
884 CAmount nValueOut = 0;
885 BOOST_FOREACH(const CTxOut& txout, tx.vout)
887 if (txout.nValue < 0)
888 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
889 REJECT_INVALID, "bad-txns-vout-negative");
890 if (txout.nValue > MAX_MONEY)
891 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
892 REJECT_INVALID, "bad-txns-vout-toolarge");
893 nValueOut += txout.nValue;
894 if (!MoneyRange(nValueOut))
895 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
896 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
899 // Ensure that joinsplit values are well-formed
900 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
902 if (joinsplit.vpub_old < 0) {
903 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"),
904 REJECT_INVALID, "bad-txns-vpub_old-negative");
907 if (joinsplit.vpub_new < 0) {
908 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"),
909 REJECT_INVALID, "bad-txns-vpub_new-negative");
912 if (joinsplit.vpub_old > MAX_MONEY) {
913 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"),
914 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
917 if (joinsplit.vpub_new > MAX_MONEY) {
918 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"),
919 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
922 if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) {
923 return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"),
924 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
927 nValueOut += joinsplit.vpub_old;
928 if (!MoneyRange(nValueOut)) {
929 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
930 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
934 // Ensure input values do not exceed MAX_MONEY
935 // We have not resolved the txin values at this stage,
936 // but we do know what the joinsplits claim to add
937 // to the value pool.
939 CAmount nValueIn = 0;
940 for (std::vector<JSDescription>::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it)
942 nValueIn += it->vpub_new;
944 if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) {
945 return state.DoS(100, error("CheckTransaction(): txin total out of range"),
946 REJECT_INVALID, "bad-txns-txintotal-toolarge");
952 // Check for duplicate inputs
953 set<COutPoint> vInOutPoints;
954 BOOST_FOREACH(const CTxIn& txin, tx.vin)
956 if (vInOutPoints.count(txin.prevout))
957 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
958 REJECT_INVALID, "bad-txns-inputs-duplicate");
959 vInOutPoints.insert(txin.prevout);
962 // Check for duplicate joinsplit nullifiers in this transaction
963 set<uint256> vJoinSplitNullifiers;
964 BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit)
966 BOOST_FOREACH(const uint256& nf, joinsplit.nullifiers)
968 if (vJoinSplitNullifiers.count(nf))
969 return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"),
970 REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate");
972 vJoinSplitNullifiers.insert(nf);
978 // There should be no joinsplits in a coinbase transaction
979 if (tx.vjoinsplit.size() > 0)
980 return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"),
981 REJECT_INVALID, "bad-cb-has-joinsplits");
983 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
984 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
985 REJECT_INVALID, "bad-cb-length");
989 BOOST_FOREACH(const CTxIn& txin, tx.vin)
990 if (txin.prevout.IsNull())
991 return state.DoS(10, error("CheckTransaction(): prevout is null"),
992 REJECT_INVALID, "bad-txns-prevout-null");
994 if (tx.vjoinsplit.size() > 0) {
995 // Empty output script.
997 uint256 dataToBeSigned;
999 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
1000 } catch (std::logic_error ex) {
1001 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
1002 REJECT_INVALID, "error-computing-signature-hash");
1005 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
1007 // We rely on libsodium to check that the signature is canonical.
1008 // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0
1009 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
1010 dataToBeSigned.begin(), 32,
1011 tx.joinSplitPubKey.begin()
1013 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1014 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1022 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1026 uint256 hash = tx.GetHash();
1027 double dPriorityDelta = 0;
1028 CAmount nFeeDelta = 0;
1029 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1030 if (dPriorityDelta > 0 || nFeeDelta > 0)
1034 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1038 // There is a free transaction area in blocks created by most miners,
1039 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1040 // to be considered to fall into this category. We don't want to encourage sending
1041 // multiple transactions instead of one big transaction to avoid fees.
1042 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1046 if (!MoneyRange(nMinFee))
1047 nMinFee = MAX_MONEY;
1052 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1053 bool* pfMissingInputs, bool fRejectAbsurdFee)
1055 AssertLockHeld(cs_main);
1056 if (pfMissingInputs)
1057 *pfMissingInputs = false;
1059 if (!CheckTransaction(tx, state))
1060 return error("AcceptToMemoryPool: CheckTransaction failed");
1062 // Coinbase is only valid in a block, not as a loose transaction
1063 if (tx.IsCoinBase())
1064 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1065 REJECT_INVALID, "coinbase");
1067 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1069 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1071 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1072 REJECT_NONSTANDARD, reason);
1074 // Only accept nLockTime-using transactions that can be mined in the next
1075 // block; we don't want our mempool filled up with transactions that can't
1077 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1078 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1080 // is it already in the memory pool?
1081 uint256 hash = tx.GetHash();
1082 if (pool.exists(hash))
1085 // Check for conflicts with in-memory transactions
1087 LOCK(pool.cs); // protect pool.mapNextTx
1088 for (unsigned int i = 0; i < tx.vin.size(); i++)
1090 COutPoint outpoint = tx.vin[i].prevout;
1091 if (pool.mapNextTx.count(outpoint))
1093 // Disable replacement feature for now
1097 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1098 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1099 if (pool.mapNullifiers.count(nf))
1109 CCoinsViewCache view(&dummy);
1111 CAmount nValueIn = 0;
1114 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1115 view.SetBackend(viewMemPool);
1117 // do we already have it?
1118 if (view.HaveCoins(hash))
1121 // do all inputs exist?
1122 // Note that this does not check for the presence of actual outputs (see the next check for that),
1123 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1124 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1125 if (!view.HaveCoins(txin.prevout.hash)) {
1126 if (pfMissingInputs)
1127 *pfMissingInputs = true;
1132 // are the actual inputs available?
1133 if (!view.HaveInputs(tx))
1134 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1135 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1137 // are the joinsplit's requirements met?
1138 if (!view.HaveJoinSplitRequirements(tx))
1139 return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),
1140 REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met");
1142 // Bring the best block into scope
1143 view.GetBestBlock();
1145 nValueIn = view.GetValueIn(tx);
1147 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1148 view.SetBackend(dummy);
1151 // Check for non-standard pay-to-script-hash in inputs
1152 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1153 return error("AcceptToMemoryPool: nonstandard transaction input");
1155 // Check that the transaction doesn't have an excessive number of
1156 // sigops, making it impossible to mine. Since the coinbase transaction
1157 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1158 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1159 // merely non-standard transaction.
1160 unsigned int nSigOps = GetLegacySigOpCount(tx);
1161 nSigOps += GetP2SHSigOpCount(tx, view);
1162 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1164 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1165 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1166 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1168 CAmount nValueOut = tx.GetValueOut();
1169 CAmount nFees = nValueIn-nValueOut;
1170 double dPriority = view.GetPriority(tx, chainActive.Height());
1172 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1173 unsigned int nSize = entry.GetTxSize();
1175 // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany.
1176 if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) {
1177 // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits.
1179 // Don't accept it if it can't get into a block
1180 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1181 if (fLimitFree && nFees < txMinFee)
1182 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1183 hash.ToString(), nFees, txMinFee),
1184 REJECT_INSUFFICIENTFEE, "insufficient fee");
1187 // Require that free transactions have sufficient priority to be mined in the next block.
1188 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1189 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1192 // Continuously rate-limit free (really, very-low-fee) transactions
1193 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1194 // be annoying or make others' transactions take longer to confirm.
1195 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1197 static CCriticalSection csFreeLimiter;
1198 static double dFreeCount;
1199 static int64_t nLastTime;
1200 int64_t nNow = GetTime();
1202 LOCK(csFreeLimiter);
1204 // Use an exponentially decaying ~10-minute window:
1205 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1207 // -limitfreerelay unit is thousand-bytes-per-minute
1208 // At default rate it would take over a month to fill 1GB
1209 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1210 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1211 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1212 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1213 dFreeCount += nSize;
1216 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1217 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1219 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1221 // Check against previous transactions
1222 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1223 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1225 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1228 // Check again against just the consensus-critical mandatory script
1229 // verification flags, in case of bugs in the standard flags that cause
1230 // transactions to pass as valid when they're actually invalid. For
1231 // instance the STRICTENC flag was incorrectly allowing certain
1232 // CHECKSIG NOT scripts to pass, even though they were invalid.
1234 // There is a similar check in CreateNewBlock() to prevent creating
1235 // invalid blocks, however allowing such transactions into the mempool
1236 // can be exploited as a DoS attack.
1237 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus()))
1239 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1242 // Store transaction in memory
1243 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1246 SyncWithWallets(tx, NULL);
1251 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1252 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1254 CBlockIndex *pindexSlow = NULL;
1258 if (mempool.lookup(hash, txOut))
1265 if (pblocktree->ReadTxIndex(hash, postx)) {
1266 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1268 return error("%s: OpenBlockFile failed", __func__);
1269 CBlockHeader header;
1272 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1274 } catch (const std::exception& e) {
1275 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1277 hashBlock = header.GetHash();
1278 if (txOut.GetHash() != hash)
1279 return error("%s: txid mismatch", __func__);
1284 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1287 CCoinsViewCache &view = *pcoinsTip;
1288 const CCoins* coins = view.AccessCoins(hash);
1290 nHeight = coins->nHeight;
1293 pindexSlow = chainActive[nHeight];
1298 if (ReadBlockFromDisk(block, pindexSlow)) {
1299 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1300 if (tx.GetHash() == hash) {
1302 hashBlock = pindexSlow->GetBlockHash();
1317 //////////////////////////////////////////////////////////////////////////////
1319 // CBlock and CBlockIndex
1322 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1324 // Open history file to append
1325 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1326 if (fileout.IsNull())
1327 return error("WriteBlockToDisk: OpenBlockFile failed");
1329 // Write index header
1330 unsigned int nSize = fileout.GetSerializeSize(block);
1331 fileout << FLATDATA(messageStart) << nSize;
1334 long fileOutPos = ftell(fileout.Get());
1336 return error("WriteBlockToDisk: ftell failed");
1337 pos.nPos = (unsigned int)fileOutPos;
1343 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1347 // Open history file to read
1348 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1349 if (filein.IsNull())
1350 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1356 catch (const std::exception& e) {
1357 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1361 if (!(CheckEquihashSolution(&block, Params()) &&
1362 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1363 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1368 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1370 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1372 if (block.GetHash() != pindex->GetBlockHash())
1373 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1374 pindex->ToString(), pindex->GetBlockPos().ToString());
1378 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1380 CAmount nSubsidy = 12.5 * COIN;
1382 // Mining slow start
1383 // The subsidy is ramped up linearly, skipping the middle payout of
1384 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1385 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1386 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1387 nSubsidy *= nHeight;
1389 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1390 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1391 nSubsidy *= (nHeight+1);
1395 assert(nHeight > consensusParams.SubsidySlowStartShift());
1396 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1397 // Force block reward to zero when right shift is undefined.
1401 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1402 nSubsidy >>= halvings;
1406 bool IsInitialBlockDownload()
1408 const CChainParams& chainParams = Params();
1410 if (fImporting || fReindex)
1412 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1414 static bool lockIBDState = false;
1417 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1418 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1420 lockIBDState = true;
1424 bool fLargeWorkForkFound = false;
1425 bool fLargeWorkInvalidChainFound = false;
1426 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1428 void CheckForkWarningConditions()
1430 AssertLockHeld(cs_main);
1431 // Before we get past initial download, we cannot reliably alert about forks
1432 // (we assume we don't get stuck on a fork before the last checkpoint)
1433 if (IsInitialBlockDownload())
1436 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1437 // of our head, drop it
1438 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1439 pindexBestForkTip = NULL;
1441 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1443 if (!fLargeWorkForkFound && pindexBestForkBase)
1445 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1446 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1447 CAlert::Notify(warning, true);
1449 if (pindexBestForkTip && pindexBestForkBase)
1451 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__,
1452 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1453 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1454 fLargeWorkForkFound = true;
1458 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1459 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1460 CAlert::Notify(warning, true);
1461 fLargeWorkInvalidChainFound = true;
1466 fLargeWorkForkFound = false;
1467 fLargeWorkInvalidChainFound = false;
1471 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1473 AssertLockHeld(cs_main);
1474 // If we are on a fork that is sufficiently large, set a warning flag
1475 CBlockIndex* pfork = pindexNewForkTip;
1476 CBlockIndex* plonger = chainActive.Tip();
1477 while (pfork && pfork != plonger)
1479 while (plonger && plonger->nHeight > pfork->nHeight)
1480 plonger = plonger->pprev;
1481 if (pfork == plonger)
1483 pfork = pfork->pprev;
1486 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1487 // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours
1488 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1489 // hash rate operating on the fork.
1490 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1491 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1492 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1493 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1494 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1495 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1497 pindexBestForkTip = pindexNewForkTip;
1498 pindexBestForkBase = pfork;
1501 CheckForkWarningConditions();
1504 // Requires cs_main.
1505 void Misbehaving(NodeId pnode, int howmuch)
1510 CNodeState *state = State(pnode);
1514 state->nMisbehavior += howmuch;
1515 int banscore = GetArg("-banscore", 100);
1516 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1518 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1519 state->fShouldBan = true;
1521 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1524 void static InvalidChainFound(CBlockIndex* pindexNew)
1526 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1527 pindexBestInvalid = pindexNew;
1529 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1530 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1531 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1532 pindexNew->GetBlockTime()));
1533 CBlockIndex *tip = chainActive.Tip();
1535 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1536 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1537 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1538 CheckForkWarningConditions();
1541 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1543 if (state.IsInvalid(nDoS)) {
1544 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1545 if (it != mapBlockSource.end() && State(it->second)) {
1546 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1547 State(it->second)->rejects.push_back(reject);
1549 Misbehaving(it->second, nDoS);
1552 if (!state.CorruptionPossible()) {
1553 pindex->nStatus |= BLOCK_FAILED_VALID;
1554 setDirtyBlockIndex.insert(pindex);
1555 setBlockIndexCandidates.erase(pindex);
1556 InvalidChainFound(pindex);
1560 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1562 // mark inputs spent
1563 if (!tx.IsCoinBase()) {
1564 txundo.vprevout.reserve(tx.vin.size());
1565 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1566 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1567 unsigned nPos = txin.prevout.n;
1569 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1571 // mark an outpoint spent, and construct undo information
1572 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1574 if (coins->vout.size() == 0) {
1575 CTxInUndo& undo = txundo.vprevout.back();
1576 undo.nHeight = coins->nHeight;
1577 undo.fCoinBase = coins->fCoinBase;
1578 undo.nVersion = coins->nVersion;
1584 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1585 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1586 inputs.SetNullifier(nf, true);
1591 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1594 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1597 UpdateCoins(tx, state, inputs, txundo, nHeight);
1600 bool CScriptCheck::operator()() {
1601 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1602 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1603 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1608 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)
1610 if (!tx.IsCoinBase())
1613 pvChecks->reserve(tx.vin.size());
1615 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1616 // for an attacker to attempt to split the network.
1617 if (!inputs.HaveInputs(tx))
1618 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1620 // are the JoinSplit's requirements met?
1621 if (!inputs.HaveJoinSplitRequirements(tx))
1622 return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString()));
1624 CAmount nValueIn = 0;
1626 for (unsigned int i = 0; i < tx.vin.size(); i++)
1628 const COutPoint &prevout = tx.vin[i].prevout;
1629 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1632 if (coins->IsCoinBase()) {
1633 // Ensure that coinbases cannot be spent to transparent outputs
1634 // Disabled on regtest
1635 if (fCoinbaseEnforcedProtectionEnabled &&
1636 consensusParams.fCoinbaseMustBeProtected &&
1638 return state.Invalid(
1639 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1640 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1644 // Check for negative or overflow input values
1645 nValueIn += coins->vout[prevout.n].nValue;
1646 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1647 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1648 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1652 nValueIn += tx.GetJoinSplitValueIn();
1653 if (!MoneyRange(nValueIn))
1654 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1655 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1657 if (nValueIn < tx.GetValueOut())
1658 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1659 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1660 REJECT_INVALID, "bad-txns-in-belowout");
1662 // Tally transaction fees
1663 CAmount nTxFee = nValueIn - tx.GetValueOut();
1665 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1666 REJECT_INVALID, "bad-txns-fee-negative");
1668 if (!MoneyRange(nFees))
1669 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1670 REJECT_INVALID, "bad-txns-fee-outofrange");
1672 // The first loop above does all the inexpensive checks.
1673 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1674 // Helps prevent CPU exhaustion attacks.
1676 // Skip ECDSA signature verification when connecting blocks
1677 // before the last block chain checkpoint. This is safe because block merkle hashes are
1678 // still computed and checked, and any change will be caught at the next checkpoint.
1679 if (fScriptChecks) {
1680 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1681 const COutPoint &prevout = tx.vin[i].prevout;
1682 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1686 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1688 pvChecks->push_back(CScriptCheck());
1689 check.swap(pvChecks->back());
1690 } else if (!check()) {
1691 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1692 // Check whether the failure was caused by a
1693 // non-mandatory script verification check, such as
1694 // non-standard DER encodings or non-null dummy
1695 // arguments; if so, don't trigger DoS protection to
1696 // avoid splitting the network between upgraded and
1697 // non-upgraded nodes.
1698 CScriptCheck check(*coins, tx, i,
1699 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1701 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1703 // Failures of other flags indicate a transaction that is
1704 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1705 // such nodes as they are not following the protocol. That
1706 // said during an upgrade careful thought should be taken
1707 // as to the correct behavior - we may want to continue
1708 // peering with non-upgraded nodes even after a soft-fork
1709 // super-majority vote has passed.
1710 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1719 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)
1721 if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) {
1725 if (!tx.IsCoinBase())
1727 // While checking, GetBestBlock() refers to the parent block.
1728 // This is also true for mempool checks.
1729 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1730 int nSpendHeight = pindexPrev->nHeight + 1;
1731 for (unsigned int i = 0; i < tx.vin.size(); i++)
1733 const COutPoint &prevout = tx.vin[i].prevout;
1734 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1735 // Assertion is okay because NonContextualCheckInputs ensures the inputs
1739 // If prev is coinbase, check that it's matured
1740 if (coins->IsCoinBase()) {
1741 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) {
1742 return state.Invalid(
1743 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1744 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1755 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1757 // Open history file to append
1758 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1759 if (fileout.IsNull())
1760 return error("%s: OpenUndoFile failed", __func__);
1762 // Write index header
1763 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1764 fileout << FLATDATA(messageStart) << nSize;
1767 long fileOutPos = ftell(fileout.Get());
1769 return error("%s: ftell failed", __func__);
1770 pos.nPos = (unsigned int)fileOutPos;
1771 fileout << blockundo;
1773 // calculate & write checksum
1774 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1775 hasher << hashBlock;
1776 hasher << blockundo;
1777 fileout << hasher.GetHash();
1782 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1784 // Open history file to read
1785 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1786 if (filein.IsNull())
1787 return error("%s: OpenBlockFile failed", __func__);
1790 uint256 hashChecksum;
1792 filein >> blockundo;
1793 filein >> hashChecksum;
1795 catch (const std::exception& e) {
1796 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1800 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1801 hasher << hashBlock;
1802 hasher << blockundo;
1803 if (hashChecksum != hasher.GetHash())
1804 return error("%s: Checksum mismatch", __func__);
1809 /** Abort with a message */
1810 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1812 strMiscWarning = strMessage;
1813 LogPrintf("*** %s\n", strMessage);
1814 uiInterface.ThreadSafeMessageBox(
1815 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1816 "", CClientUIInterface::MSG_ERROR);
1821 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1823 AbortNode(strMessage, userMessage);
1824 return state.Error(strMessage);
1830 * Apply the undo operation of a CTxInUndo to the given chain state.
1831 * @param undo The undo object.
1832 * @param view The coins view to which to apply the changes.
1833 * @param out The out point that corresponds to the tx input.
1834 * @return True on success.
1836 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1840 CCoinsModifier coins = view.ModifyCoins(out.hash);
1841 if (undo.nHeight != 0) {
1842 // undo data contains height: this is the last output of the prevout tx being spent
1843 if (!coins->IsPruned())
1844 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1846 coins->fCoinBase = undo.fCoinBase;
1847 coins->nHeight = undo.nHeight;
1848 coins->nVersion = undo.nVersion;
1850 if (coins->IsPruned())
1851 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1853 if (coins->IsAvailable(out.n))
1854 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1855 if (coins->vout.size() < out.n+1)
1856 coins->vout.resize(out.n+1);
1857 coins->vout[out.n] = undo.txout;
1862 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1864 assert(pindex->GetBlockHash() == view.GetBestBlock());
1871 CBlockUndo blockUndo;
1872 CDiskBlockPos pos = pindex->GetUndoPos();
1874 return error("DisconnectBlock(): no undo data available");
1875 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1876 return error("DisconnectBlock(): failure reading undo data");
1878 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1879 return error("DisconnectBlock(): block and undo data inconsistent");
1881 // undo transactions in reverse order
1882 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1883 const CTransaction &tx = block.vtx[i];
1884 uint256 hash = tx.GetHash();
1886 // Check that all outputs are available and match the outputs in the block itself
1889 CCoinsModifier outs = view.ModifyCoins(hash);
1890 outs->ClearUnspendable();
1892 CCoins outsBlock(tx, pindex->nHeight);
1893 // The CCoins serialization does not serialize negative numbers.
1894 // No network rules currently depend on the version here, so an inconsistency is harmless
1895 // but it must be corrected before txout nversion ever influences a network rule.
1896 if (outsBlock.nVersion < 0)
1897 outs->nVersion = outsBlock.nVersion;
1898 if (*outs != outsBlock)
1899 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1905 // unspend nullifiers
1906 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
1907 BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
1908 view.SetNullifier(nf, false);
1913 if (i > 0) { // not coinbases
1914 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1915 if (txundo.vprevout.size() != tx.vin.size())
1916 return error("DisconnectBlock(): transaction and undo data inconsistent");
1917 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1918 const COutPoint &out = tx.vin[j].prevout;
1919 const CTxInUndo &undo = txundo.vprevout[j];
1920 if (!ApplyTxInUndo(undo, view, out))
1926 // set the old best anchor back
1927 view.PopAnchor(blockUndo.old_tree_root);
1929 // move best block pointer to prevout block
1930 view.SetBestBlock(pindex->pprev->GetBlockHash());
1940 void static FlushBlockFile(bool fFinalize = false)
1942 LOCK(cs_LastBlockFile);
1944 CDiskBlockPos posOld(nLastBlockFile, 0);
1946 FILE *fileOld = OpenBlockFile(posOld);
1949 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1950 FileCommit(fileOld);
1954 fileOld = OpenUndoFile(posOld);
1957 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1958 FileCommit(fileOld);
1963 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1965 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1967 void ThreadScriptCheck() {
1968 RenameThread("zcash-scriptch");
1969 scriptcheckqueue.Thread();
1973 // Called periodically asynchronously; alerts if it smells like
1974 // we're being fed a bad chain (blocks being generated much
1975 // too slowly or too quickly).
1977 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1978 int64_t nPowTargetSpacing)
1980 if (bestHeader == NULL || initialDownloadCheck()) return;
1982 static int64_t lastAlertTime = 0;
1983 int64_t now = GetAdjustedTime();
1984 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1986 const int SPAN_HOURS=4;
1987 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1988 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1990 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1992 std::string strWarning;
1993 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1996 const CBlockIndex* i = bestHeader;
1998 while (i->GetBlockTime() >= startTime) {
2001 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
2004 // How likely is it to find that many by chance?
2005 double p = boost::math::pdf(poisson, nBlocks);
2007 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
2008 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2010 // Aim for one false-positive about every fifty years of normal running:
2011 const int FIFTY_YEARS = 50*365*24*60*60;
2012 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2014 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2016 // Many fewer blocks than expected: alert!
2017 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2018 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2020 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2022 // Many more blocks than expected: alert!
2023 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2024 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2026 if (!strWarning.empty())
2028 strMiscWarning = strWarning;
2029 CAlert::Notify(strWarning, true);
2030 lastAlertTime = now;
2034 static int64_t nTimeVerify = 0;
2035 static int64_t nTimeConnect = 0;
2036 static int64_t nTimeIndex = 0;
2037 static int64_t nTimeCallbacks = 0;
2038 static int64_t nTimeTotal = 0;
2040 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2042 const CChainParams& chainparams = Params();
2043 AssertLockHeld(cs_main);
2044 // Check it again in case a previous version let a bad block in
2045 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
2048 // verify that the view's current state corresponds to the previous block
2049 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2050 assert(hashPrevBlock == view.GetBestBlock());
2052 // Special case for the genesis block, skipping connection of its transactions
2053 // (its coinbase is unspendable)
2054 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2056 view.SetBestBlock(pindex->GetBlockHash());
2057 // Before the genesis block, there was an empty tree
2058 ZCIncrementalMerkleTree tree;
2059 pindex->hashAnchor = tree.root();
2064 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2066 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2067 // unless those are already completely spent.
2068 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2069 const CCoins* coins = view.AccessCoins(tx.GetHash());
2070 if (coins && !coins->IsPruned())
2071 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2072 REJECT_INVALID, "bad-txns-BIP30");
2075 unsigned int flags = SCRIPT_VERIFY_P2SH;
2077 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2078 // when 75% of the network has upgraded:
2079 if (block.nVersion >= 3) {
2080 flags |= SCRIPT_VERIFY_DERSIG;
2083 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2084 // blocks, when 75% of the network has upgraded:
2085 if (block.nVersion >= 4) {
2086 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2089 CBlockUndo blockundo;
2091 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2093 int64_t nTimeStart = GetTimeMicros();
2096 unsigned int nSigOps = 0;
2097 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2098 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2099 vPos.reserve(block.vtx.size());
2100 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2102 // Construct the incremental merkle tree at the current
2104 auto old_tree_root = view.GetBestAnchor();
2105 // saving the top anchor in the block index as we go.
2107 pindex->hashAnchor = old_tree_root;
2109 ZCIncrementalMerkleTree tree;
2110 // This should never fail: we should always be able to get the root
2111 // that is on the tip of our chain
2112 assert(view.GetAnchorAt(old_tree_root, tree));
2115 // Consistency check: the root of the tree we're given should
2116 // match what we asked for.
2117 assert(tree.root() == old_tree_root);
2120 for (unsigned int i = 0; i < block.vtx.size(); i++)
2122 const CTransaction &tx = block.vtx[i];
2124 nInputs += tx.vin.size();
2125 nSigOps += GetLegacySigOpCount(tx);
2126 if (nSigOps > MAX_BLOCK_SIGOPS)
2127 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2128 REJECT_INVALID, "bad-blk-sigops");
2130 if (!tx.IsCoinBase())
2132 if (!view.HaveInputs(tx))
2133 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2134 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2136 // are the JoinSplit's requirements met?
2137 if (!view.HaveJoinSplitRequirements(tx))
2138 return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"),
2139 REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met");
2141 // Add in sigops done by pay-to-script-hash inputs;
2142 // this is to prevent a "rogue miner" from creating
2143 // an incredibly-expensive-to-validate block.
2144 nSigOps += GetP2SHSigOpCount(tx, view);
2145 if (nSigOps > MAX_BLOCK_SIGOPS)
2146 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2147 REJECT_INVALID, "bad-blk-sigops");
2149 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2151 std::vector<CScriptCheck> vChecks;
2152 if (!ContextualCheckInputs(tx, state, view, fScriptChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
2154 control.Add(vChecks);
2159 blockundo.vtxundo.push_back(CTxUndo());
2161 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2163 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) {
2164 BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) {
2165 // Insert the note commitments into our temporary tree.
2167 tree.append(note_commitment);
2171 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2172 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2175 view.PushAnchor(tree);
2176 blockundo.old_tree_root = old_tree_root;
2178 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2179 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);
2181 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2182 if (block.vtx[0].GetValueOut() > blockReward)
2183 return state.DoS(100,
2184 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2185 block.vtx[0].GetValueOut(), blockReward),
2186 REJECT_INVALID, "bad-cb-amount");
2188 if (!control.Wait())
2189 return state.DoS(100, false);
2190 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2191 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);
2196 // Write undo information to disk
2197 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2199 if (pindex->GetUndoPos().IsNull()) {
2201 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2202 return error("ConnectBlock(): FindUndoPos failed");
2203 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2204 return AbortNode(state, "Failed to write undo data");
2206 // update nUndoPos in block index
2207 pindex->nUndoPos = pos.nPos;
2208 pindex->nStatus |= BLOCK_HAVE_UNDO;
2211 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2212 setDirtyBlockIndex.insert(pindex);
2216 if (!pblocktree->WriteTxIndex(vPos))
2217 return AbortNode(state, "Failed to write transaction index");
2219 // add this block to the view's block chain
2220 view.SetBestBlock(pindex->GetBlockHash());
2222 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2223 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2225 // Watch for changes to the previous coinbase transaction.
2226 static uint256 hashPrevBestCoinBase;
2227 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2228 hashPrevBestCoinBase = block.vtx[0].GetHash();
2230 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2231 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2236 enum FlushStateMode {
2238 FLUSH_STATE_IF_NEEDED,
2239 FLUSH_STATE_PERIODIC,
2244 * Update the on-disk chain state.
2245 * The caches and indexes are flushed depending on the mode we're called with
2246 * if they're too large, if it's been a while since the last write,
2247 * or always and in all cases if we're in prune mode and are deleting files.
2249 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2250 LOCK2(cs_main, cs_LastBlockFile);
2251 static int64_t nLastWrite = 0;
2252 static int64_t nLastFlush = 0;
2253 static int64_t nLastSetChain = 0;
2254 std::set<int> setFilesToPrune;
2255 bool fFlushForPrune = false;
2257 if (fPruneMode && fCheckForPruning && !fReindex) {
2258 FindFilesToPrune(setFilesToPrune);
2259 fCheckForPruning = false;
2260 if (!setFilesToPrune.empty()) {
2261 fFlushForPrune = true;
2263 pblocktree->WriteFlag("prunedblockfiles", true);
2268 int64_t nNow = GetTimeMicros();
2269 // Avoid writing/flushing immediately after startup.
2270 if (nLastWrite == 0) {
2273 if (nLastFlush == 0) {
2276 if (nLastSetChain == 0) {
2277 nLastSetChain = nNow;
2279 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2280 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2281 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2282 // The cache is over the limit, we have to write now.
2283 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2284 // 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.
2285 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2286 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2287 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2288 // Combine all conditions that result in a full cache flush.
2289 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2290 // Write blocks and block index to disk.
2291 if (fDoFullFlush || fPeriodicWrite) {
2292 // Depend on nMinDiskSpace to ensure we can write block index
2293 if (!CheckDiskSpace(0))
2294 return state.Error("out of disk space");
2295 // First make sure all block and undo data is flushed to disk.
2297 // Then update all block file information (which may refer to block and undo files).
2299 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2300 vFiles.reserve(setDirtyFileInfo.size());
2301 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2302 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2303 setDirtyFileInfo.erase(it++);
2305 std::vector<const CBlockIndex*> vBlocks;
2306 vBlocks.reserve(setDirtyBlockIndex.size());
2307 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2308 vBlocks.push_back(*it);
2309 setDirtyBlockIndex.erase(it++);
2311 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2312 return AbortNode(state, "Files to write to block index database");
2315 // Finally remove any pruned files
2317 UnlinkPrunedFiles(setFilesToPrune);
2320 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2322 // Typical CCoins structures on disk are around 128 bytes in size.
2323 // Pushing a new one to the database can cause it to be written
2324 // twice (once in the log, and once in the tables). This is already
2325 // an overestimation, as most will delete an existing entry or
2326 // overwrite one. Still, use a conservative safety factor of 2.
2327 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2328 return state.Error("out of disk space");
2329 // Flush the chainstate (which may refer to block index entries).
2330 if (!pcoinsTip->Flush())
2331 return AbortNode(state, "Failed to write to coin database");
2334 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2335 // Update best block in wallet (so we can detect restored wallets).
2336 GetMainSignals().SetBestChain(chainActive.GetLocator());
2337 nLastSetChain = nNow;
2339 } catch (const std::runtime_error& e) {
2340 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2345 void FlushStateToDisk() {
2346 CValidationState state;
2347 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2350 void PruneAndFlush() {
2351 CValidationState state;
2352 fCheckForPruning = true;
2353 FlushStateToDisk(state, FLUSH_STATE_NONE);
2356 /** Update chainActive and related internal data structures. */
2357 void static UpdateTip(CBlockIndex *pindexNew) {
2358 const CChainParams& chainParams = Params();
2359 chainActive.SetTip(pindexNew);
2362 nTimeBestReceived = GetTime();
2363 mempool.AddTransactionsUpdated(1);
2365 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2366 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2367 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2368 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2370 cvBlockChange.notify_all();
2372 // Check the version of the last 100 blocks to see if we need to upgrade:
2373 static bool fWarned = false;
2374 if (!IsInitialBlockDownload() && !fWarned)
2377 const CBlockIndex* pindex = chainActive.Tip();
2378 for (int i = 0; i < 100 && pindex != NULL; i++)
2380 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2382 pindex = pindex->pprev;
2385 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2386 if (nUpgraded > 100/2)
2388 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2389 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2390 CAlert::Notify(strMiscWarning, true);
2396 /** Disconnect chainActive's tip. */
2397 bool static DisconnectTip(CValidationState &state) {
2398 CBlockIndex *pindexDelete = chainActive.Tip();
2399 assert(pindexDelete);
2400 mempool.check(pcoinsTip);
2401 // Read block from disk.
2403 if (!ReadBlockFromDisk(block, pindexDelete))
2404 return AbortNode(state, "Failed to read block");
2405 // Apply the block atomically to the chain state.
2406 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2407 int64_t nStart = GetTimeMicros();
2409 CCoinsViewCache view(pcoinsTip);
2410 if (!DisconnectBlock(block, state, pindexDelete, view))
2411 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2412 assert(view.Flush());
2414 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2415 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2416 // Write the chain state to disk, if necessary.
2417 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2419 // Resurrect mempool transactions from the disconnected block.
2420 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2421 // ignore validation errors in resurrected transactions
2422 list<CTransaction> removed;
2423 CValidationState stateDummy;
2424 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2425 mempool.remove(tx, removed, true);
2427 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2428 // The anchor may not change between block disconnects,
2429 // in which case we don't want to evict from the mempool yet!
2430 mempool.removeWithAnchor(anchorBeforeDisconnect);
2432 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2433 mempool.check(pcoinsTip);
2434 // Update chainActive and related variables.
2435 UpdateTip(pindexDelete->pprev);
2436 // Get the current commitment tree
2437 ZCIncrementalMerkleTree newTree;
2438 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), newTree));
2439 // Let wallets know transactions went from 1-confirmed to
2440 // 0-confirmed or conflicted:
2441 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2442 SyncWithWallets(tx, NULL);
2444 // Update cached incremental witnesses
2445 GetMainSignals().ChainTip(pindexDelete, &block, newTree, false);
2449 static int64_t nTimeReadFromDisk = 0;
2450 static int64_t nTimeConnectTotal = 0;
2451 static int64_t nTimeFlush = 0;
2452 static int64_t nTimeChainState = 0;
2453 static int64_t nTimePostConnect = 0;
2456 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2457 * corresponding to pindexNew, to bypass loading it again from disk.
2459 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2460 assert(pindexNew->pprev == chainActive.Tip());
2461 mempool.check(pcoinsTip);
2462 // Read block from disk.
2463 int64_t nTime1 = GetTimeMicros();
2466 if (!ReadBlockFromDisk(block, pindexNew))
2467 return AbortNode(state, "Failed to read block");
2470 // Get the current commitment tree
2471 ZCIncrementalMerkleTree oldTree;
2472 assert(pcoinsTip->GetAnchorAt(pcoinsTip->GetBestAnchor(), oldTree));
2473 // Apply the block atomically to the chain state.
2474 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2476 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2478 CCoinsViewCache view(pcoinsTip);
2479 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2480 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2481 GetMainSignals().BlockChecked(*pblock, state);
2483 if (state.IsInvalid())
2484 InvalidBlockFound(pindexNew, state);
2485 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2487 mapBlockSource.erase(inv.hash);
2488 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2489 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2490 assert(view.Flush());
2492 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2493 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2494 // Write the chain state to disk, if necessary.
2495 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2497 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2498 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2499 // Remove conflicting transactions from the mempool.
2500 list<CTransaction> txConflicted;
2501 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2502 mempool.check(pcoinsTip);
2503 // Update chainActive & related variables.
2504 UpdateTip(pindexNew);
2505 // Tell wallet about transactions that went from mempool
2507 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2508 SyncWithWallets(tx, NULL);
2510 // ... and about transactions that got confirmed:
2511 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2512 SyncWithWallets(tx, pblock);
2514 // Update cached incremental witnesses
2515 GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true);
2517 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2518 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2519 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2524 * Return the tip of the chain with the most work in it, that isn't
2525 * known to be invalid (it's however far from certain to be valid).
2527 static CBlockIndex* FindMostWorkChain() {
2529 CBlockIndex *pindexNew = NULL;
2531 // Find the best candidate header.
2533 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2534 if (it == setBlockIndexCandidates.rend())
2539 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2540 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2541 CBlockIndex *pindexTest = pindexNew;
2542 bool fInvalidAncestor = false;
2543 while (pindexTest && !chainActive.Contains(pindexTest)) {
2544 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2546 // Pruned nodes may have entries in setBlockIndexCandidates for
2547 // which block files have been deleted. Remove those as candidates
2548 // for the most work chain if we come across them; we can't switch
2549 // to a chain unless we have all the non-active-chain parent blocks.
2550 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2551 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2552 if (fFailedChain || fMissingData) {
2553 // Candidate chain is not usable (either invalid or missing data)
2554 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2555 pindexBestInvalid = pindexNew;
2556 CBlockIndex *pindexFailed = pindexNew;
2557 // Remove the entire chain from the set.
2558 while (pindexTest != pindexFailed) {
2560 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2561 } else if (fMissingData) {
2562 // If we're missing data, then add back to mapBlocksUnlinked,
2563 // so that if the block arrives in the future we can try adding
2564 // to setBlockIndexCandidates again.
2565 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2567 setBlockIndexCandidates.erase(pindexFailed);
2568 pindexFailed = pindexFailed->pprev;
2570 setBlockIndexCandidates.erase(pindexTest);
2571 fInvalidAncestor = true;
2574 pindexTest = pindexTest->pprev;
2576 if (!fInvalidAncestor)
2581 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2582 static void PruneBlockIndexCandidates() {
2583 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2584 // reorganization to a better block fails.
2585 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2586 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2587 setBlockIndexCandidates.erase(it++);
2589 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2590 assert(!setBlockIndexCandidates.empty());
2594 * Try to make some progress towards making pindexMostWork the active block.
2595 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2597 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2598 AssertLockHeld(cs_main);
2599 bool fInvalidFound = false;
2600 const CBlockIndex *pindexOldTip = chainActive.Tip();
2601 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2603 // Disconnect active blocks which are no longer in the best chain.
2604 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2605 if (!DisconnectTip(state))
2609 // Build list of new blocks to connect.
2610 std::vector<CBlockIndex*> vpindexToConnect;
2611 bool fContinue = true;
2612 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2613 while (fContinue && nHeight != pindexMostWork->nHeight) {
2614 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2615 // a few blocks along the way.
2616 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2617 vpindexToConnect.clear();
2618 vpindexToConnect.reserve(nTargetHeight - nHeight);
2619 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2620 while (pindexIter && pindexIter->nHeight != nHeight) {
2621 vpindexToConnect.push_back(pindexIter);
2622 pindexIter = pindexIter->pprev;
2624 nHeight = nTargetHeight;
2626 // Connect new blocks.
2627 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2628 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2629 if (state.IsInvalid()) {
2630 // The block violates a consensus rule.
2631 if (!state.CorruptionPossible())
2632 InvalidChainFound(vpindexToConnect.back());
2633 state = CValidationState();
2634 fInvalidFound = true;
2638 // A system error occurred (disk space, database error, ...).
2642 PruneBlockIndexCandidates();
2643 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2644 // We're in a better position than we were. Return temporarily to release the lock.
2652 // Callbacks/notifications for a new best chain.
2654 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2656 CheckForkWarningConditions();
2662 * Make the best chain active, in multiple steps. The result is either failure
2663 * or an activated best chain. pblock is either NULL or a pointer to a block
2664 * that is already loaded (to avoid loading it again from disk).
2666 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2667 CBlockIndex *pindexNewTip = NULL;
2668 CBlockIndex *pindexMostWork = NULL;
2669 const CChainParams& chainParams = Params();
2671 boost::this_thread::interruption_point();
2673 bool fInitialDownload;
2676 pindexMostWork = FindMostWorkChain();
2678 // Whether we have anything to do at all.
2679 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2682 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2685 pindexNewTip = chainActive.Tip();
2686 fInitialDownload = IsInitialBlockDownload();
2688 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2690 // Notifications/callbacks that can run without cs_main
2691 if (!fInitialDownload) {
2692 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2693 // Relay inventory, but don't relay old inventory during initial block download.
2694 int nBlockEstimate = 0;
2695 if (fCheckpointsEnabled)
2696 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2697 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2698 // in a stalled download if the block file is pruned before the request.
2699 if (nLocalServices & NODE_NETWORK) {
2701 BOOST_FOREACH(CNode* pnode, vNodes)
2702 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2703 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2705 // Notify external listeners about the new tip.
2706 uiInterface.NotifyBlockTip(hashNewTip);
2708 } while(pindexMostWork != chainActive.Tip());
2711 // Write changes periodically to disk, after relay.
2712 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2719 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2720 AssertLockHeld(cs_main);
2722 // Mark the block itself as invalid.
2723 pindex->nStatus |= BLOCK_FAILED_VALID;
2724 setDirtyBlockIndex.insert(pindex);
2725 setBlockIndexCandidates.erase(pindex);
2727 while (chainActive.Contains(pindex)) {
2728 CBlockIndex *pindexWalk = chainActive.Tip();
2729 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2730 setDirtyBlockIndex.insert(pindexWalk);
2731 setBlockIndexCandidates.erase(pindexWalk);
2732 // ActivateBestChain considers blocks already in chainActive
2733 // unconditionally valid already, so force disconnect away from it.
2734 if (!DisconnectTip(state)) {
2739 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2741 BlockMap::iterator it = mapBlockIndex.begin();
2742 while (it != mapBlockIndex.end()) {
2743 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2744 setBlockIndexCandidates.insert(it->second);
2749 InvalidChainFound(pindex);
2753 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2754 AssertLockHeld(cs_main);
2756 int nHeight = pindex->nHeight;
2758 // Remove the invalidity flag from this block and all its descendants.
2759 BlockMap::iterator it = mapBlockIndex.begin();
2760 while (it != mapBlockIndex.end()) {
2761 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2762 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2763 setDirtyBlockIndex.insert(it->second);
2764 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2765 setBlockIndexCandidates.insert(it->second);
2767 if (it->second == pindexBestInvalid) {
2768 // Reset invalid block marker if it was pointing to one of those.
2769 pindexBestInvalid = NULL;
2775 // Remove the invalidity flag from all ancestors too.
2776 while (pindex != NULL) {
2777 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2778 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2779 setDirtyBlockIndex.insert(pindex);
2781 pindex = pindex->pprev;
2786 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2788 // Check for duplicate
2789 uint256 hash = block.GetHash();
2790 BlockMap::iterator it = mapBlockIndex.find(hash);
2791 if (it != mapBlockIndex.end())
2794 // Construct new block index object
2795 CBlockIndex* pindexNew = new CBlockIndex(block);
2797 // We assign the sequence id to blocks only when the full data is available,
2798 // to avoid miners withholding blocks but broadcasting headers, to get a
2799 // competitive advantage.
2800 pindexNew->nSequenceId = 0;
2801 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2802 pindexNew->phashBlock = &((*mi).first);
2803 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2804 if (miPrev != mapBlockIndex.end())
2806 pindexNew->pprev = (*miPrev).second;
2807 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2808 pindexNew->BuildSkip();
2810 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2811 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2812 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2813 pindexBestHeader = pindexNew;
2815 setDirtyBlockIndex.insert(pindexNew);
2820 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2821 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2823 pindexNew->nTx = block.vtx.size();
2824 pindexNew->nChainTx = 0;
2825 pindexNew->nFile = pos.nFile;
2826 pindexNew->nDataPos = pos.nPos;
2827 pindexNew->nUndoPos = 0;
2828 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2829 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2830 setDirtyBlockIndex.insert(pindexNew);
2832 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2833 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2834 deque<CBlockIndex*> queue;
2835 queue.push_back(pindexNew);
2837 // Recursively process any descendant blocks that now may be eligible to be connected.
2838 while (!queue.empty()) {
2839 CBlockIndex *pindex = queue.front();
2841 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2843 LOCK(cs_nBlockSequenceId);
2844 pindex->nSequenceId = nBlockSequenceId++;
2846 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2847 setBlockIndexCandidates.insert(pindex);
2849 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2850 while (range.first != range.second) {
2851 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2852 queue.push_back(it->second);
2854 mapBlocksUnlinked.erase(it);
2858 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2859 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2866 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2868 LOCK(cs_LastBlockFile);
2870 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2871 if (vinfoBlockFile.size() <= nFile) {
2872 vinfoBlockFile.resize(nFile + 1);
2876 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2878 if (vinfoBlockFile.size() <= nFile) {
2879 vinfoBlockFile.resize(nFile + 1);
2883 pos.nPos = vinfoBlockFile[nFile].nSize;
2886 if (nFile != nLastBlockFile) {
2888 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2890 FlushBlockFile(!fKnown);
2891 nLastBlockFile = nFile;
2894 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2896 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2898 vinfoBlockFile[nFile].nSize += nAddSize;
2901 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2902 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2903 if (nNewChunks > nOldChunks) {
2905 fCheckForPruning = true;
2906 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2907 FILE *file = OpenBlockFile(pos);
2909 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2910 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2915 return state.Error("out of disk space");
2919 setDirtyFileInfo.insert(nFile);
2923 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2927 LOCK(cs_LastBlockFile);
2929 unsigned int nNewSize;
2930 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2931 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2932 setDirtyFileInfo.insert(nFile);
2934 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2935 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2936 if (nNewChunks > nOldChunks) {
2938 fCheckForPruning = true;
2939 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2940 FILE *file = OpenUndoFile(pos);
2942 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2943 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2948 return state.Error("out of disk space");
2954 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2956 // Check block version
2957 if (block.nVersion < MIN_BLOCK_VERSION)
2958 return state.DoS(100, error("CheckBlockHeader(): block version too low"),
2959 REJECT_INVALID, "version-too-low");
2961 // Check Equihash solution is valid
2962 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2963 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2964 REJECT_INVALID, "invalid-solution");
2966 // Check proof of work matches claimed amount
2967 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2968 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2969 REJECT_INVALID, "high-hash");
2972 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2973 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2974 REJECT_INVALID, "time-too-new");
2979 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2981 // These are checks that are independent of context.
2983 // Check that the header is valid (particularly PoW). This is mostly
2984 // redundant with the call in AcceptBlockHeader.
2985 if (!CheckBlockHeader(block, state, fCheckPOW))
2988 // Check the merkle root.
2989 if (fCheckMerkleRoot) {
2991 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2992 if (block.hashMerkleRoot != hashMerkleRoot2)
2993 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2994 REJECT_INVALID, "bad-txnmrklroot", true);
2996 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2997 // of transactions in a block without affecting the merkle root of a block,
2998 // while still invalidating it.
3000 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
3001 REJECT_INVALID, "bad-txns-duplicate", true);
3004 // All potential-corruption validation must be done before we do any
3005 // transaction validation, as otherwise we may mark the header as invalid
3006 // because we receive the wrong transactions for it.
3009 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3010 return state.DoS(100, error("CheckBlock(): size limits failed"),
3011 REJECT_INVALID, "bad-blk-length");
3013 // First transaction must be coinbase, the rest must not be
3014 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3015 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3016 REJECT_INVALID, "bad-cb-missing");
3017 for (unsigned int i = 1; i < block.vtx.size(); i++)
3018 if (block.vtx[i].IsCoinBase())
3019 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3020 REJECT_INVALID, "bad-cb-multiple");
3022 // Check transactions
3023 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3024 if (!CheckTransaction(tx, state))
3025 return error("CheckBlock(): CheckTransaction failed");
3027 unsigned int nSigOps = 0;
3028 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3030 nSigOps += GetLegacySigOpCount(tx);
3032 if (nSigOps > MAX_BLOCK_SIGOPS)
3033 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3034 REJECT_INVALID, "bad-blk-sigops", true);
3039 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3041 const CChainParams& chainParams = Params();
3042 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3043 uint256 hash = block.GetHash();
3044 if (hash == consensusParams.hashGenesisBlock)
3049 int nHeight = pindexPrev->nHeight+1;
3051 // Check proof of work
3052 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3053 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3054 REJECT_INVALID, "bad-diffbits");
3056 // Check timestamp against prev
3057 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3058 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3059 REJECT_INVALID, "time-too-old");
3061 if(fCheckpointsEnabled)
3063 // Check that the block chain matches the known block chain up to a checkpoint
3064 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3065 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
3066 REJECT_CHECKPOINT, "checkpoint mismatch");
3068 // Don't accept any forks from the main chain prior to last checkpoint
3069 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3070 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3071 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3074 // Reject block.nVersion < 4 blocks
3075 if (block.nVersion < 4)
3076 return state.Invalid(error("%s : rejected nVersion<4 block", __func__),
3077 REJECT_OBSOLETE, "bad-version");
3082 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
3084 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
3085 const Consensus::Params& consensusParams = Params().GetConsensus();
3087 // Check that all transactions are finalized
3088 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
3089 int nLockTimeFlags = 0;
3090 int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
3091 ? pindexPrev->GetMedianTimePast()
3092 : block.GetBlockTime();
3093 if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) {
3094 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
3098 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
3099 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
3100 // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this.
3101 // This rule is not applied to the genesis block, which didn't include the height
3105 CScript expect = CScript() << nHeight;
3106 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3107 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3108 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3112 // Coinbase transaction must include an output sending 20% of
3113 // the block reward to a founders reward script, until the last founders
3114 // reward block is reached, with exception of the genesis block.
3115 // The last founders reward block is defined as the block just before the
3116 // first subsidy halving block, which occurs at halving_interval + slow_start_shift
3117 if ((nHeight > 0) && (nHeight <= consensusParams.GetLastFoundersRewardBlockHeight())) {
3120 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3121 if (output.scriptPubKey == Params().GetFoundersRewardScriptAtHeight(nHeight)) {
3122 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3130 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3137 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3139 const CChainParams& chainparams = Params();
3140 AssertLockHeld(cs_main);
3141 // Check for duplicate
3142 uint256 hash = block.GetHash();
3143 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3144 CBlockIndex *pindex = NULL;
3145 if (miSelf != mapBlockIndex.end()) {
3146 // Block header is already known.
3147 pindex = miSelf->second;
3150 if (pindex->nStatus & BLOCK_FAILED_MASK)
3151 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3155 if (!CheckBlockHeader(block, state))
3158 // Get prev block index
3159 CBlockIndex* pindexPrev = NULL;
3160 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3161 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3162 if (mi == mapBlockIndex.end())
3163 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3164 pindexPrev = (*mi).second;
3165 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3166 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3169 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3173 pindex = AddToBlockIndex(block);
3181 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3183 const CChainParams& chainparams = Params();
3184 AssertLockHeld(cs_main);
3186 CBlockIndex *&pindex = *ppindex;
3188 if (!AcceptBlockHeader(block, state, &pindex))
3191 // Try to process all requested blocks that we don't have, but only
3192 // process an unrequested block if it's new and has enough work to
3193 // advance our tip, and isn't too many blocks ahead.
3194 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3195 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3196 // Blocks that are too out-of-order needlessly limit the effectiveness of
3197 // pruning, because pruning will not delete block files that contain any
3198 // blocks which are too close in height to the tip. Apply this test
3199 // regardless of whether pruning is enabled; it should generally be safe to
3200 // not process unrequested blocks.
3201 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3203 // TODO: deal better with return value and error conditions for duplicate
3204 // and unrequested blocks.
3205 if (fAlreadyHave) return true;
3206 if (!fRequested) { // If we didn't ask for it:
3207 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3208 if (!fHasMoreWork) return true; // Don't process less-work chains
3209 if (fTooFarAhead) return true; // Block height is too high
3212 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3213 if (state.IsInvalid() && !state.CorruptionPossible()) {
3214 pindex->nStatus |= BLOCK_FAILED_VALID;
3215 setDirtyBlockIndex.insert(pindex);
3220 int nHeight = pindex->nHeight;
3222 // Write block to history file
3224 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3225 CDiskBlockPos blockPos;
3228 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3229 return error("AcceptBlock(): FindBlockPos failed");
3231 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3232 AbortNode(state, "Failed to write block");
3233 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3234 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3235 } catch (const std::runtime_error& e) {
3236 return AbortNode(state, std::string("System error: ") + e.what());
3239 if (fCheckForPruning)
3240 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3245 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3247 unsigned int nFound = 0;
3248 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3250 if (pstart->nVersion >= minVersion)
3252 pstart = pstart->pprev;
3254 return (nFound >= nRequired);
3258 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3260 // Preliminary checks
3261 bool checked = CheckBlock(*pblock, state);
3265 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3266 fRequested |= fForceProcessing;
3268 return error("%s: CheckBlock FAILED", __func__);
3272 CBlockIndex *pindex = NULL;
3273 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3274 if (pindex && pfrom) {
3275 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3279 return error("%s: AcceptBlock FAILED", __func__);
3282 if (!ActivateBestChain(state, pblock))
3283 return error("%s: ActivateBestChain failed", __func__);
3288 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3290 AssertLockHeld(cs_main);
3291 assert(pindexPrev == chainActive.Tip());
3293 CCoinsViewCache viewNew(pcoinsTip);
3294 CBlockIndex indexDummy(block);
3295 indexDummy.pprev = pindexPrev;
3296 indexDummy.nHeight = pindexPrev->nHeight + 1;
3298 // NOTE: CheckBlockHeader is called by CheckBlock
3299 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3301 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3303 if (!ContextualCheckBlock(block, state, pindexPrev))
3305 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3307 assert(state.IsValid());
3313 * BLOCK PRUNING CODE
3316 /* Calculate the amount of disk space the block & undo files currently use */
3317 uint64_t CalculateCurrentUsage()
3319 uint64_t retval = 0;
3320 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3321 retval += file.nSize + file.nUndoSize;
3326 /* Prune a block file (modify associated database entries)*/
3327 void PruneOneBlockFile(const int fileNumber)
3329 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3330 CBlockIndex* pindex = it->second;
3331 if (pindex->nFile == fileNumber) {
3332 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3333 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3335 pindex->nDataPos = 0;
3336 pindex->nUndoPos = 0;
3337 setDirtyBlockIndex.insert(pindex);
3339 // Prune from mapBlocksUnlinked -- any block we prune would have
3340 // to be downloaded again in order to consider its chain, at which
3341 // point it would be considered as a candidate for
3342 // mapBlocksUnlinked or setBlockIndexCandidates.
3343 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3344 while (range.first != range.second) {
3345 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3347 if (it->second == pindex) {
3348 mapBlocksUnlinked.erase(it);
3354 vinfoBlockFile[fileNumber].SetNull();
3355 setDirtyFileInfo.insert(fileNumber);
3359 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3361 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3362 CDiskBlockPos pos(*it, 0);
3363 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3364 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3365 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3369 /* Calculate the block/rev files that should be deleted to remain under target*/
3370 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3372 LOCK2(cs_main, cs_LastBlockFile);
3373 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3376 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3380 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3381 uint64_t nCurrentUsage = CalculateCurrentUsage();
3382 // We don't check to prune until after we've allocated new space for files
3383 // So we should leave a buffer under our target to account for another allocation
3384 // before the next pruning.
3385 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3386 uint64_t nBytesToPrune;
3389 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3390 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3391 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3393 if (vinfoBlockFile[fileNumber].nSize == 0)
3396 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3399 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3400 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3403 PruneOneBlockFile(fileNumber);
3404 // Queue up the files for removal
3405 setFilesToPrune.insert(fileNumber);
3406 nCurrentUsage -= nBytesToPrune;
3411 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3412 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3413 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3414 nLastBlockWeCanPrune, count);
3417 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3419 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3421 // Check for nMinDiskSpace bytes (currently 50MB)
3422 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3423 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3428 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3432 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3433 boost::filesystem::create_directories(path.parent_path());
3434 FILE* file = fopen(path.string().c_str(), "rb+");
3435 if (!file && !fReadOnly)
3436 file = fopen(path.string().c_str(), "wb+");
3438 LogPrintf("Unable to open file %s\n", path.string());
3442 if (fseek(file, pos.nPos, SEEK_SET)) {
3443 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3451 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3452 return OpenDiskFile(pos, "blk", fReadOnly);
3455 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3456 return OpenDiskFile(pos, "rev", fReadOnly);
3459 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3461 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3464 CBlockIndex * InsertBlockIndex(uint256 hash)
3470 BlockMap::iterator mi = mapBlockIndex.find(hash);
3471 if (mi != mapBlockIndex.end())
3472 return (*mi).second;
3475 CBlockIndex* pindexNew = new CBlockIndex();
3477 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3478 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3479 pindexNew->phashBlock = &((*mi).first);
3484 bool static LoadBlockIndexDB()
3486 const CChainParams& chainparams = Params();
3487 if (!pblocktree->LoadBlockIndexGuts())
3490 boost::this_thread::interruption_point();
3492 // Calculate nChainWork
3493 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3494 vSortedByHeight.reserve(mapBlockIndex.size());
3495 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3497 CBlockIndex* pindex = item.second;
3498 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3500 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3501 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3503 CBlockIndex* pindex = item.second;
3504 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3505 // We can link the chain of blocks for which we've received transactions at some point.
3506 // Pruned nodes may have deleted the block.
3507 if (pindex->nTx > 0) {
3508 if (pindex->pprev) {
3509 if (pindex->pprev->nChainTx) {
3510 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3512 pindex->nChainTx = 0;
3513 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3516 pindex->nChainTx = pindex->nTx;
3519 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3520 setBlockIndexCandidates.insert(pindex);
3521 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3522 pindexBestInvalid = pindex;
3524 pindex->BuildSkip();
3525 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3526 pindexBestHeader = pindex;
3529 // Load block file info
3530 pblocktree->ReadLastBlockFile(nLastBlockFile);
3531 vinfoBlockFile.resize(nLastBlockFile + 1);
3532 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3533 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3534 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3536 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3537 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3538 CBlockFileInfo info;
3539 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3540 vinfoBlockFile.push_back(info);
3546 // Check presence of blk files
3547 LogPrintf("Checking all blk files are present...\n");
3548 set<int> setBlkDataFiles;
3549 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3551 CBlockIndex* pindex = item.second;
3552 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3553 setBlkDataFiles.insert(pindex->nFile);
3556 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3558 CDiskBlockPos pos(*it, 0);
3559 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3564 // Check whether we have ever pruned block & undo files
3565 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3567 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3569 // Check whether we need to continue reindexing
3570 bool fReindexing = false;
3571 pblocktree->ReadReindexing(fReindexing);
3572 fReindex |= fReindexing;
3574 // Check whether we have a transaction index
3575 pblocktree->ReadFlag("txindex", fTxIndex);
3576 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3578 // Load pointer to end of best chain
3579 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3580 if (it == mapBlockIndex.end())
3582 chainActive.SetTip(it->second);
3584 PruneBlockIndexCandidates();
3586 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3587 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3588 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3589 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3594 CVerifyDB::CVerifyDB()
3596 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3599 CVerifyDB::~CVerifyDB()
3601 uiInterface.ShowProgress("", 100);
3604 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3607 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3610 // Verify blocks in the best chain
3611 if (nCheckDepth <= 0)
3612 nCheckDepth = 1000000000; // suffices until the year 19000
3613 if (nCheckDepth > chainActive.Height())
3614 nCheckDepth = chainActive.Height();
3615 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3616 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3617 CCoinsViewCache coins(coinsview);
3618 CBlockIndex* pindexState = chainActive.Tip();
3619 CBlockIndex* pindexFailure = NULL;
3620 int nGoodTransactions = 0;
3621 CValidationState state;
3622 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3624 boost::this_thread::interruption_point();
3625 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3626 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3629 // check level 0: read from disk
3630 if (!ReadBlockFromDisk(block, pindex))
3631 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3632 // check level 1: verify block validity
3633 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3634 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3635 // check level 2: verify undo validity
3636 if (nCheckLevel >= 2 && pindex) {
3638 CDiskBlockPos pos = pindex->GetUndoPos();
3639 if (!pos.IsNull()) {
3640 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3641 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3644 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3645 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3647 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3648 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3649 pindexState = pindex->pprev;
3651 nGoodTransactions = 0;
3652 pindexFailure = pindex;
3654 nGoodTransactions += block.vtx.size();
3656 if (ShutdownRequested())
3660 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3662 // check level 4: try reconnecting blocks
3663 if (nCheckLevel >= 4) {
3664 CBlockIndex *pindex = pindexState;
3665 while (pindex != chainActive.Tip()) {
3666 boost::this_thread::interruption_point();
3667 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3668 pindex = chainActive.Next(pindex);
3670 if (!ReadBlockFromDisk(block, pindex))
3671 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3672 if (!ConnectBlock(block, state, pindex, coins))
3673 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3677 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3682 void UnloadBlockIndex()
3685 setBlockIndexCandidates.clear();
3686 chainActive.SetTip(NULL);
3687 pindexBestInvalid = NULL;
3688 pindexBestHeader = NULL;
3690 mapOrphanTransactions.clear();
3691 mapOrphanTransactionsByPrev.clear();
3693 mapBlocksUnlinked.clear();
3694 vinfoBlockFile.clear();
3696 nBlockSequenceId = 1;
3697 mapBlockSource.clear();
3698 mapBlocksInFlight.clear();
3699 nQueuedValidatedHeaders = 0;
3700 nPreferredDownload = 0;
3701 setDirtyBlockIndex.clear();
3702 setDirtyFileInfo.clear();
3703 mapNodeState.clear();
3704 recentRejects.reset(NULL);
3706 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3707 delete entry.second;
3709 mapBlockIndex.clear();
3710 fHavePruned = false;
3713 bool LoadBlockIndex()
3715 // Load block index from databases
3716 if (!fReindex && !LoadBlockIndexDB())
3722 bool InitBlockIndex() {
3723 const CChainParams& chainparams = Params();
3726 // Initialize global variables that cannot be constructed at startup.
3727 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3729 // Check whether we're already initialized
3730 if (chainActive.Genesis() != NULL)
3733 // Use the provided setting for -txindex in the new database
3734 fTxIndex = GetBoolArg("-txindex", false);
3735 pblocktree->WriteFlag("txindex", fTxIndex);
3736 LogPrintf("Initializing databases...\n");
3738 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3741 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3742 // Start new block file
3743 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3744 CDiskBlockPos blockPos;
3745 CValidationState state;
3746 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3747 return error("LoadBlockIndex(): FindBlockPos failed");
3748 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3749 return error("LoadBlockIndex(): writing genesis block to disk failed");
3750 CBlockIndex *pindex = AddToBlockIndex(block);
3751 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3752 return error("LoadBlockIndex(): genesis block not accepted");
3753 if (!ActivateBestChain(state, &block))
3754 return error("LoadBlockIndex(): genesis block cannot be activated");
3755 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3756 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3757 } catch (const std::runtime_error& e) {
3758 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3767 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3769 const CChainParams& chainparams = Params();
3770 // Map of disk positions for blocks with unknown parent (only used for reindex)
3771 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3772 int64_t nStart = GetTimeMillis();
3776 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3777 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3778 uint64_t nRewind = blkdat.GetPos();
3779 while (!blkdat.eof()) {
3780 boost::this_thread::interruption_point();
3782 blkdat.SetPos(nRewind);
3783 nRewind++; // start one byte further next time, in case of failure
3784 blkdat.SetLimit(); // remove former limit
3785 unsigned int nSize = 0;
3788 unsigned char buf[MESSAGE_START_SIZE];
3789 blkdat.FindByte(Params().MessageStart()[0]);
3790 nRewind = blkdat.GetPos()+1;
3791 blkdat >> FLATDATA(buf);
3792 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3796 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3798 } catch (const std::exception&) {
3799 // no valid block header found; don't complain
3804 uint64_t nBlockPos = blkdat.GetPos();
3806 dbp->nPos = nBlockPos;
3807 blkdat.SetLimit(nBlockPos + nSize);
3808 blkdat.SetPos(nBlockPos);
3811 nRewind = blkdat.GetPos();
3813 // detect out of order blocks, and store them for later
3814 uint256 hash = block.GetHash();
3815 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3816 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3817 block.hashPrevBlock.ToString());
3819 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3823 // process in case the block isn't known yet
3824 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3825 CValidationState state;
3826 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3828 if (state.IsError())
3830 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3831 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3834 // Recursively process earlier encountered successors of this block
3835 deque<uint256> queue;
3836 queue.push_back(hash);
3837 while (!queue.empty()) {
3838 uint256 head = queue.front();
3840 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3841 while (range.first != range.second) {
3842 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3843 if (ReadBlockFromDisk(block, it->second))
3845 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3847 CValidationState dummy;
3848 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3851 queue.push_back(block.GetHash());
3855 mapBlocksUnknownParent.erase(it);
3858 } catch (const std::exception& e) {
3859 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3862 } catch (const std::runtime_error& e) {
3863 AbortNode(std::string("System error: ") + e.what());
3866 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3870 void static CheckBlockIndex()
3872 const Consensus::Params& consensusParams = Params().GetConsensus();
3873 if (!fCheckBlockIndex) {
3879 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3880 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3881 // iterating the block tree require that chainActive has been initialized.)
3882 if (chainActive.Height() < 0) {
3883 assert(mapBlockIndex.size() <= 1);
3887 // Build forward-pointing map of the entire block tree.
3888 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3889 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3890 forward.insert(std::make_pair(it->second->pprev, it->second));
3893 assert(forward.size() == mapBlockIndex.size());
3895 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3896 CBlockIndex *pindex = rangeGenesis.first->second;
3897 rangeGenesis.first++;
3898 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3900 // Iterate over the entire block tree, using depth-first search.
3901 // Along the way, remember whether there are blocks on the path from genesis
3902 // block being explored which are the first to have certain properties.
3905 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3906 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3907 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3908 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3909 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3910 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3911 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3912 while (pindex != NULL) {
3914 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3915 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3916 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3917 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3918 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3919 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3920 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3922 // Begin: actual consistency checks.
3923 if (pindex->pprev == NULL) {
3924 // Genesis block checks.
3925 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3926 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3928 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3929 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3930 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3932 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3933 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3934 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3936 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3937 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3939 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3940 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3941 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3942 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3943 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3944 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3945 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.
3946 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3947 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3948 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3949 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3950 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3951 if (pindexFirstInvalid == NULL) {
3952 // Checks for not-invalid blocks.
3953 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3955 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3956 if (pindexFirstInvalid == NULL) {
3957 // If this block sorts at least as good as the current tip and
3958 // is valid and we have all data for its parents, it must be in
3959 // setBlockIndexCandidates. chainActive.Tip() must also be there
3960 // even if some data has been pruned.
3961 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3962 assert(setBlockIndexCandidates.count(pindex));
3964 // If some parent is missing, then it could be that this block was in
3965 // setBlockIndexCandidates but had to be removed because of the missing data.
3966 // In this case it must be in mapBlocksUnlinked -- see test below.
3968 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3969 assert(setBlockIndexCandidates.count(pindex) == 0);
3971 // Check whether this block is in mapBlocksUnlinked.
3972 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3973 bool foundInUnlinked = false;
3974 while (rangeUnlinked.first != rangeUnlinked.second) {
3975 assert(rangeUnlinked.first->first == pindex->pprev);
3976 if (rangeUnlinked.first->second == pindex) {
3977 foundInUnlinked = true;
3980 rangeUnlinked.first++;
3982 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3983 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3984 assert(foundInUnlinked);
3986 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3987 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3988 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3989 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3990 assert(fHavePruned); // We must have pruned.
3991 // This block may have entered mapBlocksUnlinked if:
3992 // - it has a descendant that at some point had more work than the
3994 // - we tried switching to that descendant but were missing
3995 // data for some intermediate block between chainActive and the
3997 // So if this block is itself better than chainActive.Tip() and it wasn't in
3998 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3999 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
4000 if (pindexFirstInvalid == NULL) {
4001 assert(foundInUnlinked);
4005 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4006 // End: actual consistency checks.
4008 // Try descending into the first subnode.
4009 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4010 if (range.first != range.second) {
4011 // A subnode was found.
4012 pindex = range.first->second;
4016 // This is a leaf node.
4017 // Move upwards until we reach a node of which we have not yet visited the last child.
4019 // We are going to either move to a parent or a sibling of pindex.
4020 // If pindex was the first with a certain property, unset the corresponding variable.
4021 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4022 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4023 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4024 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4025 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4026 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4027 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4029 CBlockIndex* pindexPar = pindex->pprev;
4030 // Find which child we just visited.
4031 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4032 while (rangePar.first->second != pindex) {
4033 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4036 // Proceed to the next one.
4038 if (rangePar.first != rangePar.second) {
4039 // Move to the sibling.
4040 pindex = rangePar.first->second;
4051 // Check that we actually traversed the entire map.
4052 assert(nNodes == forward.size());
4055 //////////////////////////////////////////////////////////////////////////////
4060 string GetWarnings(string strFor)
4063 string strStatusBar;
4066 if (!CLIENT_VERSION_IS_RELEASE)
4067 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4069 if (GetBoolArg("-testsafemode", false))
4070 strStatusBar = strRPC = "testsafemode enabled";
4072 // Misc warnings like out of disk space and clock is wrong
4073 if (strMiscWarning != "")
4076 strStatusBar = strMiscWarning;
4079 if (fLargeWorkForkFound)
4082 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4084 else if (fLargeWorkInvalidChainFound)
4087 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.");
4093 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4095 const CAlert& alert = item.second;
4096 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4098 nPriority = alert.nPriority;
4099 strStatusBar = alert.strStatusBar;
4100 if (alert.nPriority >= ALERT_PRIORITY_SAFE_MODE) {
4101 strRPC = alert.strRPCError;
4107 if (strFor == "statusbar")
4108 return strStatusBar;
4109 else if (strFor == "rpc")
4111 assert(!"GetWarnings(): invalid parameter");
4122 //////////////////////////////////////////////////////////////////////////////
4128 bool static AlreadyHave(const CInv& inv)
4134 assert(recentRejects);
4135 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4137 // If the chain tip has changed previously rejected transactions
4138 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4139 // or a double-spend. Reset the rejects filter and give those
4140 // txs a second chance.
4141 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4142 recentRejects->reset();
4145 return recentRejects->contains(inv.hash) ||
4146 mempool.exists(inv.hash) ||
4147 mapOrphanTransactions.count(inv.hash) ||
4148 pcoinsTip->HaveCoins(inv.hash);
4151 return mapBlockIndex.count(inv.hash);
4153 // Don't know what it is, just say we already got one
4157 void static ProcessGetData(CNode* pfrom)
4159 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4161 vector<CInv> vNotFound;
4165 while (it != pfrom->vRecvGetData.end()) {
4166 // Don't bother if send buffer is too full to respond anyway
4167 if (pfrom->nSendSize >= SendBufferSize())
4170 const CInv &inv = *it;
4172 boost::this_thread::interruption_point();
4175 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4178 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4179 if (mi != mapBlockIndex.end())
4181 if (chainActive.Contains(mi->second)) {
4184 static const int nOneMonth = 30 * 24 * 60 * 60;
4185 // To prevent fingerprinting attacks, only send blocks outside of the active
4186 // chain if they are valid, and no more than a month older (both in time, and in
4187 // best equivalent proof of work) than the best header chain we know about.
4188 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4189 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4190 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4192 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4196 // Pruned nodes may have deleted the block, so check whether
4197 // it's available before trying to send.
4198 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4200 // Send block from disk
4202 if (!ReadBlockFromDisk(block, (*mi).second))
4203 assert(!"cannot load block from disk");
4204 if (inv.type == MSG_BLOCK)
4205 pfrom->PushMessage("block", block);
4206 else // MSG_FILTERED_BLOCK)
4208 LOCK(pfrom->cs_filter);
4211 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4212 pfrom->PushMessage("merkleblock", merkleBlock);
4213 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4214 // This avoids hurting performance by pointlessly requiring a round-trip
4215 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4216 // they must either disconnect and retry or request the full block.
4217 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4218 // however we MUST always provide at least what the remote peer needs
4219 typedef std::pair<unsigned int, uint256> PairType;
4220 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4221 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4222 pfrom->PushMessage("tx", block.vtx[pair.first]);
4228 // Trigger the peer node to send a getblocks request for the next batch of inventory
4229 if (inv.hash == pfrom->hashContinue)
4231 // Bypass PushInventory, this must send even if redundant,
4232 // and we want it right after the last block so they don't
4233 // wait for other stuff first.
4235 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4236 pfrom->PushMessage("inv", vInv);
4237 pfrom->hashContinue.SetNull();
4241 else if (inv.IsKnownType())
4243 // Send stream from relay memory
4244 bool pushed = false;
4247 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4248 if (mi != mapRelay.end()) {
4249 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4253 if (!pushed && inv.type == MSG_TX) {
4255 if (mempool.lookup(inv.hash, tx)) {
4256 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4259 pfrom->PushMessage("tx", ss);
4264 vNotFound.push_back(inv);
4268 // Track requests for our stuff.
4269 GetMainSignals().Inventory(inv.hash);
4271 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4276 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4278 if (!vNotFound.empty()) {
4279 // Let the peer know that we didn't find what it asked for, so it doesn't
4280 // have to wait around forever. Currently only SPV clients actually care
4281 // about this message: it's needed when they are recursively walking the
4282 // dependencies of relevant unconfirmed transactions. SPV clients want to
4283 // do that because they want to know about (and store and rebroadcast and
4284 // risk analyze) the dependencies of transactions relevant to them, without
4285 // having to download the entire memory pool.
4286 pfrom->PushMessage("notfound", vNotFound);
4290 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4292 const CChainParams& chainparams = Params();
4293 RandAddSeedPerfmon();
4294 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4295 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4297 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4304 if (strCommand == "version")
4306 // Each connection can only send one version message
4307 if (pfrom->nVersion != 0)
4309 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4310 Misbehaving(pfrom->GetId(), 1);
4317 uint64_t nNonce = 1;
4318 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4319 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4321 // disconnect from peers older than this proto version
4322 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4323 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4324 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4325 pfrom->fDisconnect = true;
4329 if (pfrom->nVersion == 10300)
4330 pfrom->nVersion = 300;
4332 vRecv >> addrFrom >> nNonce;
4333 if (!vRecv.empty()) {
4334 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4335 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4338 vRecv >> pfrom->nStartingHeight;
4340 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4342 pfrom->fRelayTxes = true;
4344 // Disconnect if we connected to ourself
4345 if (nNonce == nLocalHostNonce && nNonce > 1)
4347 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4348 pfrom->fDisconnect = true;
4352 pfrom->addrLocal = addrMe;
4353 if (pfrom->fInbound && addrMe.IsRoutable())
4358 // Be shy and don't send version until we hear
4359 if (pfrom->fInbound)
4360 pfrom->PushVersion();
4362 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4364 // Potentially mark this peer as a preferred download peer.
4365 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4368 pfrom->PushMessage("verack");
4369 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4371 if (!pfrom->fInbound)
4373 // Advertise our address
4374 if (fListen && !IsInitialBlockDownload())
4376 CAddress addr = GetLocalAddress(&pfrom->addr);
4377 if (addr.IsRoutable())
4379 pfrom->PushAddress(addr);
4380 } else if (IsPeerAddrLocalGood(pfrom)) {
4381 addr.SetIP(pfrom->addrLocal);
4382 pfrom->PushAddress(addr);
4386 // Get recent addresses
4387 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4389 pfrom->PushMessage("getaddr");
4390 pfrom->fGetAddr = true;
4392 addrman.Good(pfrom->addr);
4394 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4396 addrman.Add(addrFrom, addrFrom);
4397 addrman.Good(addrFrom);
4404 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4405 item.second.RelayTo(pfrom);
4408 pfrom->fSuccessfullyConnected = true;
4412 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4414 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4415 pfrom->cleanSubVer, pfrom->nVersion,
4416 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4419 int64_t nTimeOffset = nTime - GetTime();
4420 pfrom->nTimeOffset = nTimeOffset;
4421 AddTimeData(pfrom->addr, nTimeOffset);
4425 else if (pfrom->nVersion == 0)
4427 // Must have a version message before anything else
4428 Misbehaving(pfrom->GetId(), 1);
4433 else if (strCommand == "verack")
4435 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4437 // Mark this node as currently connected, so we update its timestamp later.
4438 if (pfrom->fNetworkNode) {
4440 State(pfrom->GetId())->fCurrentlyConnected = true;
4445 else if (strCommand == "addr")
4447 vector<CAddress> vAddr;
4450 // Don't want addr from older versions unless seeding
4451 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4453 if (vAddr.size() > 1000)
4455 Misbehaving(pfrom->GetId(), 20);
4456 return error("message addr size() = %u", vAddr.size());
4459 // Store the new addresses
4460 vector<CAddress> vAddrOk;
4461 int64_t nNow = GetAdjustedTime();
4462 int64_t nSince = nNow - 10 * 60;
4463 BOOST_FOREACH(CAddress& addr, vAddr)
4465 boost::this_thread::interruption_point();
4467 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4468 addr.nTime = nNow - 5 * 24 * 60 * 60;
4469 pfrom->AddAddressKnown(addr);
4470 bool fReachable = IsReachable(addr);
4471 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4473 // Relay to a limited number of other nodes
4476 // Use deterministic randomness to send to the same nodes for 24 hours
4477 // at a time so the addrKnowns of the chosen nodes prevent repeats
4478 static uint256 hashSalt;
4479 if (hashSalt.IsNull())
4480 hashSalt = GetRandHash();
4481 uint64_t hashAddr = addr.GetHash();
4482 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4483 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4484 multimap<uint256, CNode*> mapMix;
4485 BOOST_FOREACH(CNode* pnode, vNodes)
4487 if (pnode->nVersion < CADDR_TIME_VERSION)
4489 unsigned int nPointer;
4490 memcpy(&nPointer, &pnode, sizeof(nPointer));
4491 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4492 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4493 mapMix.insert(make_pair(hashKey, pnode));
4495 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4496 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4497 ((*mi).second)->PushAddress(addr);
4500 // Do not store addresses outside our network
4502 vAddrOk.push_back(addr);
4504 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4505 if (vAddr.size() < 1000)
4506 pfrom->fGetAddr = false;
4507 if (pfrom->fOneShot)
4508 pfrom->fDisconnect = true;
4512 else if (strCommand == "inv")
4516 if (vInv.size() > MAX_INV_SZ)
4518 Misbehaving(pfrom->GetId(), 20);
4519 return error("message inv size() = %u", vInv.size());
4524 std::vector<CInv> vToFetch;
4526 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4528 const CInv &inv = vInv[nInv];
4530 boost::this_thread::interruption_point();
4531 pfrom->AddInventoryKnown(inv);
4533 bool fAlreadyHave = AlreadyHave(inv);
4534 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4536 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4539 if (inv.type == MSG_BLOCK) {
4540 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4541 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4542 // First request the headers preceding the announced block. In the normal fully-synced
4543 // case where a new block is announced that succeeds the current tip (no reorganization),
4544 // there are no such headers.
4545 // Secondly, and only when we are close to being synced, we request the announced block directly,
4546 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4547 // time the block arrives, the header chain leading up to it is already validated. Not
4548 // doing this will result in the received block being rejected as an orphan in case it is
4549 // not a direct successor.
4550 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4551 CNodeState *nodestate = State(pfrom->GetId());
4552 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4553 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4554 vToFetch.push_back(inv);
4555 // Mark block as in flight already, even though the actual "getdata" message only goes out
4556 // later (within the same cs_main lock, though).
4557 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4559 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4563 // Track requests for our stuff
4564 GetMainSignals().Inventory(inv.hash);
4566 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4567 Misbehaving(pfrom->GetId(), 50);
4568 return error("send buffer size() = %u", pfrom->nSendSize);
4572 if (!vToFetch.empty())
4573 pfrom->PushMessage("getdata", vToFetch);
4577 else if (strCommand == "getdata")
4581 if (vInv.size() > MAX_INV_SZ)
4583 Misbehaving(pfrom->GetId(), 20);
4584 return error("message getdata size() = %u", vInv.size());
4587 if (fDebug || (vInv.size() != 1))
4588 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4590 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4591 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4593 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4594 ProcessGetData(pfrom);
4598 else if (strCommand == "getblocks")
4600 CBlockLocator locator;
4602 vRecv >> locator >> hashStop;
4606 // Find the last block the caller has in the main chain
4607 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4609 // Send the rest of the chain
4611 pindex = chainActive.Next(pindex);
4613 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4614 for (; pindex; pindex = chainActive.Next(pindex))
4616 if (pindex->GetBlockHash() == hashStop)
4618 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4621 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4624 // When this block is requested, we'll send an inv that'll
4625 // trigger the peer to getblocks the next batch of inventory.
4626 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4627 pfrom->hashContinue = pindex->GetBlockHash();
4634 else if (strCommand == "getheaders")
4636 CBlockLocator locator;
4638 vRecv >> locator >> hashStop;
4642 if (IsInitialBlockDownload())
4645 CBlockIndex* pindex = NULL;
4646 if (locator.IsNull())
4648 // If locator is null, return the hashStop block
4649 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4650 if (mi == mapBlockIndex.end())
4652 pindex = (*mi).second;
4656 // Find the last block the caller has in the main chain
4657 pindex = FindForkInGlobalIndex(chainActive, locator);
4659 pindex = chainActive.Next(pindex);
4662 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4663 vector<CBlock> vHeaders;
4664 int nLimit = MAX_HEADERS_RESULTS;
4665 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4666 for (; pindex; pindex = chainActive.Next(pindex))
4668 vHeaders.push_back(pindex->GetBlockHeader());
4669 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4672 pfrom->PushMessage("headers", vHeaders);
4676 else if (strCommand == "tx")
4678 vector<uint256> vWorkQueue;
4679 vector<uint256> vEraseQueue;
4683 CInv inv(MSG_TX, tx.GetHash());
4684 pfrom->AddInventoryKnown(inv);
4688 bool fMissingInputs = false;
4689 CValidationState state;
4691 pfrom->setAskFor.erase(inv.hash);
4692 mapAlreadyAskedFor.erase(inv);
4694 if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4696 mempool.check(pcoinsTip);
4697 RelayTransaction(tx);
4698 vWorkQueue.push_back(inv.hash);
4700 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4701 pfrom->id, pfrom->cleanSubVer,
4702 tx.GetHash().ToString(),
4703 mempool.mapTx.size());
4705 // Recursively process any orphan transactions that depended on this one
4706 set<NodeId> setMisbehaving;
4707 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4709 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4710 if (itByPrev == mapOrphanTransactionsByPrev.end())
4712 for (set<uint256>::iterator mi = itByPrev->second.begin();
4713 mi != itByPrev->second.end();
4716 const uint256& orphanHash = *mi;
4717 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4718 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4719 bool fMissingInputs2 = false;
4720 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4721 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4722 // anyone relaying LegitTxX banned)
4723 CValidationState stateDummy;
4726 if (setMisbehaving.count(fromPeer))
4728 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4730 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4731 RelayTransaction(orphanTx);
4732 vWorkQueue.push_back(orphanHash);
4733 vEraseQueue.push_back(orphanHash);
4735 else if (!fMissingInputs2)
4738 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4740 // Punish peer that gave us an invalid orphan tx
4741 Misbehaving(fromPeer, nDos);
4742 setMisbehaving.insert(fromPeer);
4743 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4745 // Has inputs but not accepted to mempool
4746 // Probably non-standard or insufficient fee/priority
4747 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4748 vEraseQueue.push_back(orphanHash);
4749 assert(recentRejects);
4750 recentRejects->insert(orphanHash);
4752 mempool.check(pcoinsTip);
4756 BOOST_FOREACH(uint256 hash, vEraseQueue)
4757 EraseOrphanTx(hash);
4759 // TODO: currently, prohibit joinsplits from entering mapOrphans
4760 else if (fMissingInputs && tx.vjoinsplit.size() == 0)
4762 AddOrphanTx(tx, pfrom->GetId());
4764 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4765 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4766 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4768 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4770 assert(recentRejects);
4771 recentRejects->insert(tx.GetHash());
4773 if (pfrom->fWhitelisted) {
4774 // Always relay transactions received from whitelisted peers, even
4775 // if they were already in the mempool or rejected from it due
4776 // to policy, allowing the node to function as a gateway for
4777 // nodes hidden behind it.
4779 // Never relay transactions that we would assign a non-zero DoS
4780 // score for, as we expect peers to do the same with us in that
4783 if (!state.IsInvalid(nDoS) || nDoS == 0) {
4784 LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
4785 RelayTransaction(tx);
4787 LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n",
4788 tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode());
4793 if (state.IsInvalid(nDoS))
4795 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4796 pfrom->id, pfrom->cleanSubVer,
4797 state.GetRejectReason());
4798 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4799 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4801 Misbehaving(pfrom->GetId(), nDoS);
4806 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4808 std::vector<CBlockHeader> headers;
4810 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4811 unsigned int nCount = ReadCompactSize(vRecv);
4812 if (nCount > MAX_HEADERS_RESULTS) {
4813 Misbehaving(pfrom->GetId(), 20);
4814 return error("headers message size = %u", nCount);
4816 headers.resize(nCount);
4817 for (unsigned int n = 0; n < nCount; n++) {
4818 vRecv >> headers[n];
4819 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4825 // Nothing interesting. Stop asking this peers for more headers.
4829 CBlockIndex *pindexLast = NULL;
4830 BOOST_FOREACH(const CBlockHeader& header, headers) {
4831 CValidationState state;
4832 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4833 Misbehaving(pfrom->GetId(), 20);
4834 return error("non-continuous headers sequence");
4836 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4838 if (state.IsInvalid(nDoS)) {
4840 Misbehaving(pfrom->GetId(), nDoS);
4841 return error("invalid header received");
4847 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4849 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4850 // Headers message had its maximum size; the peer may have more headers.
4851 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4852 // from there instead.
4853 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4854 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4860 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4865 CInv inv(MSG_BLOCK, block.GetHash());
4866 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4868 pfrom->AddInventoryKnown(inv);
4870 CValidationState state;
4871 // Process all blocks from whitelisted peers, even if not requested,
4872 // unless we're still syncing with the network.
4873 // Such an unrequested block may still be processed, subject to the
4874 // conditions in AcceptBlock().
4875 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4876 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4878 if (state.IsInvalid(nDoS)) {
4879 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4880 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4883 Misbehaving(pfrom->GetId(), nDoS);
4890 // This asymmetric behavior for inbound and outbound connections was introduced
4891 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4892 // to users' AddrMan and later request them by sending getaddr messages.
4893 // Making nodes which are behind NAT and can only make outgoing connections ignore
4894 // the getaddr message mitigates the attack.
4895 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4897 // Only send one GetAddr response per connection to reduce resource waste
4898 // and discourage addr stamping of INV announcements.
4899 if (pfrom->fSentAddr) {
4900 LogPrint("net", "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
4903 pfrom->fSentAddr = true;
4905 pfrom->vAddrToSend.clear();
4906 vector<CAddress> vAddr = addrman.GetAddr();
4907 BOOST_FOREACH(const CAddress &addr, vAddr)
4908 pfrom->PushAddress(addr);
4912 else if (strCommand == "mempool")
4914 LOCK2(cs_main, pfrom->cs_filter);
4916 std::vector<uint256> vtxid;
4917 mempool.queryHashes(vtxid);
4919 BOOST_FOREACH(uint256& hash, vtxid) {
4920 CInv inv(MSG_TX, hash);
4922 bool fInMemPool = mempool.lookup(hash, tx);
4923 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4924 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4926 vInv.push_back(inv);
4927 if (vInv.size() == MAX_INV_SZ) {
4928 pfrom->PushMessage("inv", vInv);
4932 if (vInv.size() > 0)
4933 pfrom->PushMessage("inv", vInv);
4937 else if (strCommand == "ping")
4939 if (pfrom->nVersion > BIP0031_VERSION)
4943 // Echo the message back with the nonce. This allows for two useful features:
4945 // 1) A remote node can quickly check if the connection is operational
4946 // 2) Remote nodes can measure the latency of the network thread. If this node
4947 // is overloaded it won't respond to pings quickly and the remote node can
4948 // avoid sending us more work, like chain download requests.
4950 // The nonce stops the remote getting confused between different pings: without
4951 // it, if the remote node sends a ping once per second and this node takes 5
4952 // seconds to respond to each, the 5th ping the remote sends would appear to
4953 // return very quickly.
4954 pfrom->PushMessage("pong", nonce);
4959 else if (strCommand == "pong")
4961 int64_t pingUsecEnd = nTimeReceived;
4963 size_t nAvail = vRecv.in_avail();
4964 bool bPingFinished = false;
4965 std::string sProblem;
4967 if (nAvail >= sizeof(nonce)) {
4970 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4971 if (pfrom->nPingNonceSent != 0) {
4972 if (nonce == pfrom->nPingNonceSent) {
4973 // Matching pong received, this ping is no longer outstanding
4974 bPingFinished = true;
4975 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4976 if (pingUsecTime > 0) {
4977 // Successful ping time measurement, replace previous
4978 pfrom->nPingUsecTime = pingUsecTime;
4979 pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime, pingUsecTime);
4981 // This should never happen
4982 sProblem = "Timing mishap";
4985 // Nonce mismatches are normal when pings are overlapping
4986 sProblem = "Nonce mismatch";
4988 // This is most likely a bug in another implementation somewhere; cancel this ping
4989 bPingFinished = true;
4990 sProblem = "Nonce zero";
4994 sProblem = "Unsolicited pong without ping";
4997 // This is most likely a bug in another implementation somewhere; cancel this ping
4998 bPingFinished = true;
4999 sProblem = "Short payload";
5002 if (!(sProblem.empty())) {
5003 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
5007 pfrom->nPingNonceSent,
5011 if (bPingFinished) {
5012 pfrom->nPingNonceSent = 0;
5017 else if (fAlerts && strCommand == "alert")
5022 uint256 alertHash = alert.GetHash();
5023 if (pfrom->setKnown.count(alertHash) == 0)
5025 if (alert.ProcessAlert(Params().AlertKey()))
5028 pfrom->setKnown.insert(alertHash);
5031 BOOST_FOREACH(CNode* pnode, vNodes)
5032 alert.RelayTo(pnode);
5036 // Small DoS penalty so peers that send us lots of
5037 // duplicate/expired/invalid-signature/whatever alerts
5038 // eventually get banned.
5039 // This isn't a Misbehaving(100) (immediate ban) because the
5040 // peer might be an older or different implementation with
5041 // a different signature key, etc.
5042 Misbehaving(pfrom->GetId(), 10);
5048 else if (strCommand == "filterload")
5050 CBloomFilter filter;
5053 if (!filter.IsWithinSizeConstraints())
5054 // There is no excuse for sending a too-large filter
5055 Misbehaving(pfrom->GetId(), 100);
5058 LOCK(pfrom->cs_filter);
5059 delete pfrom->pfilter;
5060 pfrom->pfilter = new CBloomFilter(filter);
5061 pfrom->pfilter->UpdateEmptyFull();
5063 pfrom->fRelayTxes = true;
5067 else if (strCommand == "filteradd")
5069 vector<unsigned char> vData;
5072 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5073 // and thus, the maximum size any matched object can have) in a filteradd message
5074 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5076 Misbehaving(pfrom->GetId(), 100);
5078 LOCK(pfrom->cs_filter);
5080 pfrom->pfilter->insert(vData);
5082 Misbehaving(pfrom->GetId(), 100);
5087 else if (strCommand == "filterclear")
5089 LOCK(pfrom->cs_filter);
5090 delete pfrom->pfilter;
5091 pfrom->pfilter = new CBloomFilter();
5092 pfrom->fRelayTxes = true;
5096 else if (strCommand == "reject")
5100 string strMsg; unsigned char ccode; string strReason;
5101 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5104 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5106 if (strMsg == "block" || strMsg == "tx")
5110 ss << ": hash " << hash.ToString();
5112 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5113 } catch (const std::ios_base::failure&) {
5114 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5115 LogPrint("net", "Unparseable reject message received\n");
5120 else if (strCommand == "notfound") {
5121 // We do not care about the NOTFOUND message, but logging an Unknown Command
5122 // message would be undesirable as we transmit it ourselves.
5126 // Ignore unknown commands for extensibility
5127 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5135 // requires LOCK(cs_vRecvMsg)
5136 bool ProcessMessages(CNode* pfrom)
5139 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5143 // (4) message start
5151 if (!pfrom->vRecvGetData.empty())
5152 ProcessGetData(pfrom);
5154 // this maintains the order of responses
5155 if (!pfrom->vRecvGetData.empty()) return fOk;
5157 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5158 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5159 // Don't bother if send buffer is too full to respond anyway
5160 if (pfrom->nSendSize >= SendBufferSize())
5164 CNetMessage& msg = *it;
5167 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5168 // msg.hdr.nMessageSize, msg.vRecv.size(),
5169 // msg.complete() ? "Y" : "N");
5171 // end, if an incomplete message is found
5172 if (!msg.complete())
5175 // at this point, any failure means we can delete the current message
5178 // Scan for message start
5179 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5180 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5186 CMessageHeader& hdr = msg.hdr;
5187 if (!hdr.IsValid(Params().MessageStart()))
5189 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5192 string strCommand = hdr.GetCommand();
5195 unsigned int nMessageSize = hdr.nMessageSize;
5198 CDataStream& vRecv = msg.vRecv;
5199 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5200 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5201 if (nChecksum != hdr.nChecksum)
5203 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5204 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5212 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5213 boost::this_thread::interruption_point();
5215 catch (const std::ios_base::failure& e)
5217 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5218 if (strstr(e.what(), "end of data"))
5220 // Allow exceptions from under-length message on vRecv
5221 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());
5223 else if (strstr(e.what(), "size too large"))
5225 // Allow exceptions from over-long size
5226 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5230 PrintExceptionContinue(&e, "ProcessMessages()");
5233 catch (const boost::thread_interrupted&) {
5236 catch (const std::exception& e) {
5237 PrintExceptionContinue(&e, "ProcessMessages()");
5239 PrintExceptionContinue(NULL, "ProcessMessages()");
5243 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5248 // In case the connection got shut down, its receive buffer was wiped
5249 if (!pfrom->fDisconnect)
5250 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5256 bool SendMessages(CNode* pto, bool fSendTrickle)
5258 const Consensus::Params& consensusParams = Params().GetConsensus();
5260 // Don't send anything until we get its version message
5261 if (pto->nVersion == 0)
5267 bool pingSend = false;
5268 if (pto->fPingQueued) {
5269 // RPC ping request by user
5272 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5273 // Ping automatically sent as a latency probe & keepalive.
5278 while (nonce == 0) {
5279 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5281 pto->fPingQueued = false;
5282 pto->nPingUsecStart = GetTimeMicros();
5283 if (pto->nVersion > BIP0031_VERSION) {
5284 pto->nPingNonceSent = nonce;
5285 pto->PushMessage("ping", nonce);
5287 // Peer is too old to support ping command with nonce, pong will never arrive.
5288 pto->nPingNonceSent = 0;
5289 pto->PushMessage("ping");
5293 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5297 // Address refresh broadcast
5298 static int64_t nLastRebroadcast;
5299 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5302 BOOST_FOREACH(CNode* pnode, vNodes)
5304 // Periodically clear addrKnown to allow refresh broadcasts
5305 if (nLastRebroadcast)
5306 pnode->addrKnown.reset();
5308 // Rebroadcast our address
5309 AdvertizeLocal(pnode);
5311 if (!vNodes.empty())
5312 nLastRebroadcast = GetTime();
5320 vector<CAddress> vAddr;
5321 vAddr.reserve(pto->vAddrToSend.size());
5322 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5324 if (!pto->addrKnown.contains(addr.GetKey()))
5326 pto->addrKnown.insert(addr.GetKey());
5327 vAddr.push_back(addr);
5328 // receiver rejects addr messages larger than 1000
5329 if (vAddr.size() >= 1000)
5331 pto->PushMessage("addr", vAddr);
5336 pto->vAddrToSend.clear();
5338 pto->PushMessage("addr", vAddr);
5341 CNodeState &state = *State(pto->GetId());
5342 if (state.fShouldBan) {
5343 if (pto->fWhitelisted)
5344 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5346 pto->fDisconnect = true;
5347 if (pto->addr.IsLocal())
5348 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5351 CNode::Ban(pto->addr);
5354 state.fShouldBan = false;
5357 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5358 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5359 state.rejects.clear();
5362 if (pindexBestHeader == NULL)
5363 pindexBestHeader = chainActive.Tip();
5364 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.
5365 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5366 // Only actively request headers from a single peer, unless we're close to today.
5367 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5368 state.fSyncStarted = true;
5370 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5371 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5372 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5376 // Resend wallet transactions that haven't gotten in a block yet
5377 // Except during reindex, importing and IBD, when old wallet
5378 // transactions become unconfirmed and spams other nodes.
5379 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5381 GetMainSignals().Broadcast(nTimeBestReceived);
5385 // Message: inventory
5388 vector<CInv> vInvWait;
5390 LOCK(pto->cs_inventory);
5391 vInv.reserve(pto->vInventoryToSend.size());
5392 vInvWait.reserve(pto->vInventoryToSend.size());
5393 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5395 if (pto->setInventoryKnown.count(inv))
5398 // trickle out tx inv to protect privacy
5399 if (inv.type == MSG_TX && !fSendTrickle)
5401 // 1/4 of tx invs blast to all immediately
5402 static uint256 hashSalt;
5403 if (hashSalt.IsNull())
5404 hashSalt = GetRandHash();
5405 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5406 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5407 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5411 vInvWait.push_back(inv);
5416 // returns true if wasn't already contained in the set
5417 if (pto->setInventoryKnown.insert(inv).second)
5419 vInv.push_back(inv);
5420 if (vInv.size() >= 1000)
5422 pto->PushMessage("inv", vInv);
5427 pto->vInventoryToSend = vInvWait;
5430 pto->PushMessage("inv", vInv);
5432 // Detect whether we're stalling
5433 int64_t nNow = GetTimeMicros();
5434 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5435 // Stalling only triggers when the block download window cannot move. During normal steady state,
5436 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5437 // should only happen during initial block download.
5438 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5439 pto->fDisconnect = true;
5441 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5442 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5443 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5444 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5445 // to unreasonably increase our timeout.
5446 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5447 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5448 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5449 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5450 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5451 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5452 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5453 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5454 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5455 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5456 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5458 if (queuedBlock.nTimeDisconnect < nNow) {
5459 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5460 pto->fDisconnect = true;
5465 // Message: getdata (blocks)
5467 vector<CInv> vGetData;
5468 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5469 vector<CBlockIndex*> vToDownload;
5470 NodeId staller = -1;
5471 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5472 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5473 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5474 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5475 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5476 pindex->nHeight, pto->id);
5478 if (state.nBlocksInFlight == 0 && staller != -1) {
5479 if (State(staller)->nStallingSince == 0) {
5480 State(staller)->nStallingSince = nNow;
5481 LogPrint("net", "Stall started peer=%d\n", staller);
5487 // Message: getdata (non-blocks)
5489 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5491 const CInv& inv = (*pto->mapAskFor.begin()).second;
5492 if (!AlreadyHave(inv))
5495 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5496 vGetData.push_back(inv);
5497 if (vGetData.size() >= 1000)
5499 pto->PushMessage("getdata", vGetData);
5503 //If we're not going to ask, don't expect a response.
5504 pto->setAskFor.erase(inv.hash);
5506 pto->mapAskFor.erase(pto->mapAskFor.begin());
5508 if (!vGetData.empty())
5509 pto->PushMessage("getdata", vGetData);
5515 std::string CBlockFileInfo::ToString() const {
5516 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));
5527 BlockMap::iterator it1 = mapBlockIndex.begin();
5528 for (; it1 != mapBlockIndex.end(); it1++)
5529 delete (*it1).second;
5530 mapBlockIndex.clear();
5532 // orphan transactions
5533 mapOrphanTransactions.clear();
5534 mapOrphanTransactionsByPrev.clear();
5536 } instance_of_cmaincleanup;