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"
22 #include "txmempool.h"
23 #include "ui_interface.h"
26 #include "utilmoneystr.h"
27 #include "validationinterface.h"
31 #include <boost/algorithm/string/replace.hpp>
32 #include <boost/filesystem.hpp>
33 #include <boost/filesystem/fstream.hpp>
34 #include <boost/math/distributions/poisson.hpp>
35 #include <boost/thread.hpp>
36 #include <boost/static_assert.hpp>
41 # error "Bitcoin cannot be compiled without assertions."
48 CCriticalSection cs_main;
50 BlockMap mapBlockIndex;
52 CBlockIndex *pindexBestHeader = NULL;
53 int64_t nTimeBestReceived = 0;
54 CWaitableCriticalSection csBestBlock;
55 CConditionVariable cvBlockChange;
56 int nScriptCheckThreads = 0;
57 bool fImporting = false;
58 bool fReindex = false;
59 bool fTxIndex = false;
60 bool fHavePruned = false;
61 bool fPruneMode = false;
62 bool fIsBareMultisigStd = true;
63 bool fCheckBlockIndex = false;
64 bool fCheckpointsEnabled = true;
65 size_t nCoinCacheUsage = 5000 * 300;
66 uint64_t nPruneTarget = 0;
67 bool fAlerts = DEFAULT_ALERTS;
69 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
70 CFeeRate minRelayTxFee = CFeeRate(5000);
72 CTxMemPool mempool(::minRelayTxFee);
78 map<uint256, COrphanTx> mapOrphanTransactions;
79 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
80 void EraseOrphansFor(NodeId peer);
83 * Returns true if there are nRequired or more blocks of minVersion or above
84 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
86 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
87 static void CheckBlockIndex();
89 /** Constant stuff for coinbase transactions we create: */
90 CScript COINBASE_FLAGS;
92 const string strMessageMagic = "Bitcoin Signed Message:\n";
97 struct CBlockIndexWorkComparator
99 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
100 // First sort by most total work, ...
101 if (pa->nChainWork > pb->nChainWork) return false;
102 if (pa->nChainWork < pb->nChainWork) return true;
104 // ... then by earliest time received, ...
105 if (pa->nSequenceId < pb->nSequenceId) return false;
106 if (pa->nSequenceId > pb->nSequenceId) return true;
108 // Use pointer address as tie breaker (should only happen with blocks
109 // loaded from disk, as those all have id 0).
110 if (pa < pb) return false;
111 if (pa > pb) return true;
118 CBlockIndex *pindexBestInvalid;
121 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
122 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
123 * missing the data for the block.
125 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
126 /** Number of nodes with fSyncStarted. */
127 int nSyncStarted = 0;
128 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
129 * Pruned nodes may have entries where B is missing data.
131 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
133 CCriticalSection cs_LastBlockFile;
134 std::vector<CBlockFileInfo> vinfoBlockFile;
135 int nLastBlockFile = 0;
136 /** Global flag to indicate we should check to see if there are
137 * block/undo files that should be deleted. Set on startup
138 * or if we allocate more file space when we're in prune mode
140 bool fCheckForPruning = false;
143 * Every received block is assigned a unique and increasing identifier, so we
144 * know which one to give priority in case of a fork.
146 CCriticalSection cs_nBlockSequenceId;
147 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
148 uint32_t nBlockSequenceId = 1;
151 * Sources of received blocks, saved to be able to send them reject
152 * messages or ban them when processing happens afterwards. Protected by
155 map<uint256, NodeId> mapBlockSource;
158 * Filter for transactions that were recently rejected by
159 * AcceptToMemoryPool. These are not rerequested until the chain tip
160 * changes, at which point the entire filter is reset. Protected by
163 * Without this filter we'd be re-requesting txs from each of our peers,
164 * increasing bandwidth consumption considerably. For instance, with 100
165 * peers, half of which relay a tx we don't accept, that might be a 50x
166 * bandwidth increase. A flooding attacker attempting to roll-over the
167 * filter using minimum-sized, 60byte, transactions might manage to send
168 * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
169 * two minute window to send invs to us.
171 * Decreasing the false positive rate is fairly cheap, so we pick one in a
172 * million to make it highly unlikely for users to have issues with this
177 boost::scoped_ptr<CRollingBloomFilter> recentRejects;
178 uint256 hashRecentRejectsChainTip;
180 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
183 CBlockIndex *pindex; //! Optional.
184 int64_t nTime; //! Time of "getdata" request in microseconds.
185 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
186 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
188 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
190 /** Number of blocks in flight with validated headers. */
191 int nQueuedValidatedHeaders = 0;
193 /** Number of preferable block download peers. */
194 int nPreferredDownload = 0;
196 /** Dirty block index entries. */
197 set<CBlockIndex*> setDirtyBlockIndex;
199 /** Dirty block file entries. */
200 set<int> setDirtyFileInfo;
203 //////////////////////////////////////////////////////////////////////////////
205 // Registration of network node signals.
210 struct CBlockReject {
211 unsigned char chRejectCode;
212 string strRejectReason;
217 * Maintain validation-specific state about nodes, protected by cs_main, instead
218 * by CNode's own locks. This simplifies asynchronous operation, where
219 * processing of incoming data is done after the ProcessMessage call returns,
220 * and we're no longer holding the node's locks.
223 //! The peer's address
225 //! Whether we have a fully established connection.
226 bool fCurrentlyConnected;
227 //! Accumulated misbehaviour score for this peer.
229 //! Whether this peer should be disconnected and banned (unless whitelisted).
231 //! String name of this peer (debugging/logging purposes).
233 //! List of asynchronously-determined block rejections to notify this peer about.
234 std::vector<CBlockReject> rejects;
235 //! The best known block we know this peer has announced.
236 CBlockIndex *pindexBestKnownBlock;
237 //! The hash of the last unknown block this peer has announced.
238 uint256 hashLastUnknownBlock;
239 //! The last full block we both have.
240 CBlockIndex *pindexLastCommonBlock;
241 //! Whether we've started headers synchronization with this peer.
243 //! Since when we're stalling block download progress (in microseconds), or 0.
244 int64_t nStallingSince;
245 list<QueuedBlock> vBlocksInFlight;
247 int nBlocksInFlightValidHeaders;
248 //! Whether we consider this a preferred download peer.
249 bool fPreferredDownload;
252 fCurrentlyConnected = false;
255 pindexBestKnownBlock = NULL;
256 hashLastUnknownBlock.SetNull();
257 pindexLastCommonBlock = NULL;
258 fSyncStarted = false;
261 nBlocksInFlightValidHeaders = 0;
262 fPreferredDownload = false;
266 /** Map maintaining per-node state. Requires cs_main. */
267 map<NodeId, CNodeState> mapNodeState;
270 CNodeState *State(NodeId pnode) {
271 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
272 if (it == mapNodeState.end())
280 return chainActive.Height();
283 void UpdatePreferredDownload(CNode* node, CNodeState* state)
285 nPreferredDownload -= state->fPreferredDownload;
287 // Whether this node should be marked as a preferred download node.
288 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
290 nPreferredDownload += state->fPreferredDownload;
293 // Returns time at which to timeout block request (nTime in microseconds)
294 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams)
296 return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore);
299 void InitializeNode(NodeId nodeid, const CNode *pnode) {
301 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
302 state.name = pnode->addrName;
303 state.address = pnode->addr;
306 void FinalizeNode(NodeId nodeid) {
308 CNodeState *state = State(nodeid);
310 if (state->fSyncStarted)
313 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
314 AddressCurrentlyConnected(state->address);
317 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
318 mapBlocksInFlight.erase(entry.hash);
319 EraseOrphansFor(nodeid);
320 nPreferredDownload -= state->fPreferredDownload;
322 mapNodeState.erase(nodeid);
326 // Returns a bool indicating whether we requested this block.
327 bool MarkBlockAsReceived(const uint256& hash) {
328 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
329 if (itInFlight != mapBlocksInFlight.end()) {
330 CNodeState *state = State(itInFlight->second.first);
331 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
332 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
333 state->vBlocksInFlight.erase(itInFlight->second.second);
334 state->nBlocksInFlight--;
335 state->nStallingSince = 0;
336 mapBlocksInFlight.erase(itInFlight);
343 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) {
344 CNodeState *state = State(nodeid);
345 assert(state != NULL);
347 // Make sure it's not listed somewhere already.
348 MarkBlockAsReceived(hash);
350 int64_t nNow = GetTimeMicros();
351 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)};
352 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
353 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
354 state->nBlocksInFlight++;
355 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
356 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
359 /** Check whether the last unknown block a peer advertized is not yet known. */
360 void ProcessBlockAvailability(NodeId nodeid) {
361 CNodeState *state = State(nodeid);
362 assert(state != NULL);
364 if (!state->hashLastUnknownBlock.IsNull()) {
365 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
366 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
367 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
368 state->pindexBestKnownBlock = itOld->second;
369 state->hashLastUnknownBlock.SetNull();
374 /** Update tracking information about which blocks a peer is assumed to have. */
375 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
376 CNodeState *state = State(nodeid);
377 assert(state != NULL);
379 ProcessBlockAvailability(nodeid);
381 BlockMap::iterator it = mapBlockIndex.find(hash);
382 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
383 // An actually better block was announced.
384 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
385 state->pindexBestKnownBlock = it->second;
387 // An unknown block was announced; just assume that the latest one is the best one.
388 state->hashLastUnknownBlock = hash;
392 /** Find the last common ancestor two blocks have.
393 * Both pa and pb must be non-NULL. */
394 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
395 if (pa->nHeight > pb->nHeight) {
396 pa = pa->GetAncestor(pb->nHeight);
397 } else if (pb->nHeight > pa->nHeight) {
398 pb = pb->GetAncestor(pa->nHeight);
401 while (pa != pb && pa && pb) {
406 // Eventually all chain branches meet at the genesis block.
411 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
412 * at most count entries. */
413 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
417 vBlocks.reserve(vBlocks.size() + count);
418 CNodeState *state = State(nodeid);
419 assert(state != NULL);
421 // Make sure pindexBestKnownBlock is up to date, we'll need it.
422 ProcessBlockAvailability(nodeid);
424 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
425 // This peer has nothing interesting.
429 if (state->pindexLastCommonBlock == NULL) {
430 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
431 // Guessing wrong in either direction is not a problem.
432 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
435 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
436 // of its current tip anymore. Go back enough to fix that.
437 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
438 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
441 std::vector<CBlockIndex*> vToFetch;
442 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
443 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
444 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
445 // download that next block if the window were 1 larger.
446 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
447 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
448 NodeId waitingfor = -1;
449 while (pindexWalk->nHeight < nMaxHeight) {
450 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
451 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
452 // as iterating over ~100 CBlockIndex* entries anyway.
453 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
454 vToFetch.resize(nToFetch);
455 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
456 vToFetch[nToFetch - 1] = pindexWalk;
457 for (unsigned int i = nToFetch - 1; i > 0; i--) {
458 vToFetch[i - 1] = vToFetch[i]->pprev;
461 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
462 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
463 // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
464 // already part of our chain (and therefore don't need it even if pruned).
465 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
466 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
467 // We consider the chain that this peer is on invalid.
470 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
471 if (pindex->nChainTx)
472 state->pindexLastCommonBlock = pindex;
473 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
474 // The block is not already downloaded, and not yet in flight.
475 if (pindex->nHeight > nWindowEnd) {
476 // We reached the end of the window.
477 if (vBlocks.size() == 0 && waitingfor != nodeid) {
478 // We aren't able to fetch anything, but we would be if the download window was one larger.
479 nodeStaller = waitingfor;
483 vBlocks.push_back(pindex);
484 if (vBlocks.size() == count) {
487 } else if (waitingfor == -1) {
488 // This is the first already-in-flight block.
489 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
497 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
499 CNodeState *state = State(nodeid);
502 stats.nMisbehavior = state->nMisbehavior;
503 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
504 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
505 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
507 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
512 void RegisterNodeSignals(CNodeSignals& nodeSignals)
514 nodeSignals.GetHeight.connect(&GetHeight);
515 nodeSignals.ProcessMessages.connect(&ProcessMessages);
516 nodeSignals.SendMessages.connect(&SendMessages);
517 nodeSignals.InitializeNode.connect(&InitializeNode);
518 nodeSignals.FinalizeNode.connect(&FinalizeNode);
521 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
523 nodeSignals.GetHeight.disconnect(&GetHeight);
524 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
525 nodeSignals.SendMessages.disconnect(&SendMessages);
526 nodeSignals.InitializeNode.disconnect(&InitializeNode);
527 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
530 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
532 // Find the first block the caller has in the main chain
533 BOOST_FOREACH(const uint256& hash, locator.vHave) {
534 BlockMap::iterator mi = mapBlockIndex.find(hash);
535 if (mi != mapBlockIndex.end())
537 CBlockIndex* pindex = (*mi).second;
538 if (chain.Contains(pindex))
542 return chain.Genesis();
545 CCoinsViewCache *pcoinsTip = NULL;
546 CBlockTreeDB *pblocktree = NULL;
548 //////////////////////////////////////////////////////////////////////////////
550 // mapOrphanTransactions
553 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
555 uint256 hash = tx.GetHash();
556 if (mapOrphanTransactions.count(hash))
559 // Ignore big transactions, to avoid a
560 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
561 // large transaction with a missing parent then we assume
562 // it will rebroadcast it later, after the parent transaction(s)
563 // have been mined or received.
564 // 10,000 orphans, each of which is at most 5,000 bytes big is
565 // at most 500 megabytes of orphans:
566 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
569 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
573 mapOrphanTransactions[hash].tx = tx;
574 mapOrphanTransactions[hash].fromPeer = peer;
575 BOOST_FOREACH(const CTxIn& txin, tx.vin)
576 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
578 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
579 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
583 void static EraseOrphanTx(uint256 hash)
585 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
586 if (it == mapOrphanTransactions.end())
588 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
590 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
591 if (itPrev == mapOrphanTransactionsByPrev.end())
593 itPrev->second.erase(hash);
594 if (itPrev->second.empty())
595 mapOrphanTransactionsByPrev.erase(itPrev);
597 mapOrphanTransactions.erase(it);
600 void EraseOrphansFor(NodeId peer)
603 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
604 while (iter != mapOrphanTransactions.end())
606 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
607 if (maybeErase->second.fromPeer == peer)
609 EraseOrphanTx(maybeErase->second.tx.GetHash());
613 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
617 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
619 unsigned int nEvicted = 0;
620 while (mapOrphanTransactions.size() > nMaxOrphans)
622 // Evict a random orphan:
623 uint256 randomhash = GetRandHash();
624 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
625 if (it == mapOrphanTransactions.end())
626 it = mapOrphanTransactions.begin();
627 EraseOrphanTx(it->first);
639 bool IsStandardTx(const CTransaction& tx, string& reason)
641 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
646 // Extremely large transactions with lots of inputs can cost the network
647 // almost as much to process as they cost the sender in fees, because
648 // computing signature hashes is O(ninputs*txsize). Limiting transactions
649 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
650 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
651 if (sz >= MAX_STANDARD_TX_SIZE) {
656 BOOST_FOREACH(const CTxIn& txin, tx.vin)
658 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
659 // keys. (remember the 520 byte limit on redeemScript size) That works
660 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
661 // bytes of scriptSig, which we round off to 1650 bytes for some minor
662 // future-proofing. That's also enough to spend a 20-of-20
663 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
664 // considered standard)
665 if (txin.scriptSig.size() > 1650) {
666 reason = "scriptsig-size";
669 if (!txin.scriptSig.IsPushOnly()) {
670 reason = "scriptsig-not-pushonly";
675 unsigned int nDataOut = 0;
676 txnouttype whichType;
677 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
678 if (!::IsStandard(txout.scriptPubKey, whichType)) {
679 reason = "scriptpubkey";
683 if (whichType == TX_NULL_DATA)
685 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
686 reason = "bare-multisig";
688 } else if (txout.IsDust(::minRelayTxFee)) {
694 // only one OP_RETURN txout is permitted
696 reason = "multi-op-return";
703 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
705 if (tx.nLockTime == 0)
707 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
709 BOOST_FOREACH(const CTxIn& txin, tx.vin)
715 bool CheckFinalTx(const CTransaction &tx, int flags)
717 AssertLockHeld(cs_main);
719 // By convention a negative value for flags indicates that the
720 // current network-enforced consensus rules should be used. In
721 // a future soft-fork scenario that would mean checking which
722 // rules would be enforced for the next block and setting the
723 // appropriate flags. At the present time no soft-forks are
724 // scheduled, so no flags are set.
725 flags = std::max(flags, 0);
727 // CheckFinalTx() uses chainActive.Height()+1 to evaluate
728 // nLockTime because when IsFinalTx() is called within
729 // CBlock::AcceptBlock(), the height of the block *being*
730 // evaluated is what is used. Thus if we want to know if a
731 // transaction can be part of the *next* block, we need to call
732 // IsFinalTx() with one more than chainActive.Height().
733 const int nBlockHeight = chainActive.Height() + 1;
735 // Timestamps on the other hand don't get any special treatment,
736 // because we can't know what timestamp the next block will have,
737 // and there aren't timestamp applications where it matters.
738 // However this changes once median past time-locks are enforced:
739 const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
740 ? chainActive.Tip()->GetMedianTimePast()
743 return IsFinalTx(tx, nBlockHeight, nBlockTime);
747 * Check transaction inputs to mitigate two
748 * potential denial-of-service attacks:
750 * 1. scriptSigs with extra data stuffed into them,
751 * not consumed by scriptPubKey (or P2SH script)
752 * 2. P2SH scripts with a crazy number of expensive
753 * CHECKSIG/CHECKMULTISIG operations
755 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
758 return true; // Coinbases don't use vin normally
760 for (unsigned int i = 0; i < tx.vin.size(); i++)
762 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
764 vector<vector<unsigned char> > vSolutions;
765 txnouttype whichType;
766 // get the scriptPubKey corresponding to this input:
767 const CScript& prevScript = prev.scriptPubKey;
768 if (!Solver(prevScript, whichType, vSolutions))
770 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
771 if (nArgsExpected < 0)
774 // Transactions with extra stuff in their scriptSigs are
775 // non-standard. Note that this EvalScript() call will
776 // be quick, because if there are any operations
777 // beside "push data" in the scriptSig
778 // IsStandardTx() will have already returned false
779 // and this method isn't called.
780 vector<vector<unsigned char> > stack;
781 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
784 if (whichType == TX_SCRIPTHASH)
788 CScript subscript(stack.back().begin(), stack.back().end());
789 vector<vector<unsigned char> > vSolutions2;
790 txnouttype whichType2;
791 if (Solver(subscript, whichType2, vSolutions2))
793 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
796 nArgsExpected += tmpExpected;
800 // Any other Script with less than 15 sigops OK:
801 unsigned int sigops = subscript.GetSigOpCount(true);
802 // ... extra data left on the stack after execution is OK, too:
803 return (sigops <= MAX_P2SH_SIGOPS);
807 if (stack.size() != (unsigned int)nArgsExpected)
814 unsigned int GetLegacySigOpCount(const CTransaction& tx)
816 unsigned int nSigOps = 0;
817 BOOST_FOREACH(const CTxIn& txin, tx.vin)
819 nSigOps += txin.scriptSig.GetSigOpCount(false);
821 BOOST_FOREACH(const CTxOut& txout, tx.vout)
823 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
828 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
833 unsigned int nSigOps = 0;
834 for (unsigned int i = 0; i < tx.vin.size(); i++)
836 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
837 if (prevout.scriptPubKey.IsPayToScriptHash())
838 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
847 // https://github.com/jedisct1/libsodium/commit/4099618de2cce5099ac2ec5ce8f2d80f4585606e
848 // which was removed to maintain backwards compatibility in
849 // https://github.com/jedisct1/libsodium/commit/cb07df046f19ee0d5ad600c579df97aaa4295cc3
851 crypto_sign_check_S_lt_l(const unsigned char *S)
853 static const unsigned char l[32] =
854 { 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
855 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
856 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
857 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 };
864 c |= ((S[i] - l[i]) >> 8) & n;
865 n &= ((S[i] ^ l[i]) - 1) >> 8;
873 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
875 // Basic checks that don't depend on any context
877 // Transactions can contain empty `vin` and `vout` so long as
878 // `vpour` is non-empty.
879 if (tx.vin.empty() && tx.vpour.empty())
880 return state.DoS(10, error("CheckTransaction(): vin empty"),
881 REJECT_INVALID, "bad-txns-vin-empty");
882 if (tx.vout.empty() && tx.vpour.empty())
883 return state.DoS(10, error("CheckTransaction(): vout empty"),
884 REJECT_INVALID, "bad-txns-vout-empty");
887 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
888 return state.DoS(100, error("CheckTransaction(): size limits failed"),
889 REJECT_INVALID, "bad-txns-oversize");
891 // Check for negative or overflow output values
892 CAmount nValueOut = 0;
893 BOOST_FOREACH(const CTxOut& txout, tx.vout)
895 if (txout.nValue < 0)
896 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
897 REJECT_INVALID, "bad-txns-vout-negative");
898 if (txout.nValue > MAX_MONEY)
899 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
900 REJECT_INVALID, "bad-txns-vout-toolarge");
901 nValueOut += txout.nValue;
902 if (!MoneyRange(nValueOut))
903 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
904 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
907 // Ensure that pour values are well-formed
908 BOOST_FOREACH(const CPourTx& pour, tx.vpour)
910 if (pour.vpub_old < 0) {
911 return state.DoS(100, error("CheckTransaction(): pour.vpub_old negative"),
912 REJECT_INVALID, "bad-txns-vpub_old-negative");
915 if (pour.vpub_new < 0) {
916 return state.DoS(100, error("CheckTransaction(): pour.vpub_new negative"),
917 REJECT_INVALID, "bad-txns-vpub_new-negative");
920 if (pour.vpub_old > MAX_MONEY) {
921 return state.DoS(100, error("CheckTransaction(): pour.vpub_old too high"),
922 REJECT_INVALID, "bad-txns-vpub_old-toolarge");
925 if (pour.vpub_new > MAX_MONEY) {
926 return state.DoS(100, error("CheckTransaction(): pour.vpub_new too high"),
927 REJECT_INVALID, "bad-txns-vpub_new-toolarge");
930 if (pour.vpub_new != 0 && pour.vpub_old != 0) {
931 return state.DoS(100, error("CheckTransaction(): pour.vpub_new and pour.vpub_old both nonzero"),
932 REJECT_INVALID, "bad-txns-vpubs-both-nonzero");
935 nValueOut += pour.vpub_new;
936 if (!MoneyRange(nValueOut)) {
937 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
938 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
943 // Check for duplicate inputs
944 set<COutPoint> vInOutPoints;
945 BOOST_FOREACH(const CTxIn& txin, tx.vin)
947 if (vInOutPoints.count(txin.prevout))
948 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
949 REJECT_INVALID, "bad-txns-inputs-duplicate");
950 vInOutPoints.insert(txin.prevout);
953 // Check for duplicate pour serials in this transaction
954 set<uint256> vPourSerials;
955 BOOST_FOREACH(const CPourTx& pour, tx.vpour)
957 BOOST_FOREACH(const uint256& serial, pour.serials)
959 if (vPourSerials.count(serial))
960 return state.DoS(100, error("CheckTransaction(): duplicate serials"),
961 REJECT_INVALID, "bad-pours-serials-duplicate");
963 vPourSerials.insert(serial);
969 // There should be no pours in a coinbase transaction
970 if (tx.vpour.size() > 0)
971 return state.DoS(100, error("CheckTransaction(): coinbase has pours"),
972 REJECT_INVALID, "bad-cb-has-pours");
974 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
975 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
976 REJECT_INVALID, "bad-cb-length");
980 BOOST_FOREACH(const CTxIn& txin, tx.vin)
981 if (txin.prevout.IsNull())
982 return state.DoS(10, error("CheckTransaction(): prevout is null"),
983 REJECT_INVALID, "bad-txns-prevout-null");
985 if (tx.vpour.size() > 0) {
987 static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
988 // Empty output script.
990 uint256 dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL);
991 if (dataToBeSigned == one) {
992 return state.DoS(100, error("CheckTransaction(): error computing signature hash"),
993 REJECT_INVALID, "error-computing-signature-hash");
996 BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32);
998 if (crypto_sign_verify_detached(&tx.joinSplitSig[0],
999 dataToBeSigned.begin(), 32,
1000 tx.joinSplitPubKey.begin()
1002 return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"),
1003 REJECT_INVALID, "bad-txns-invalid-joinsplit-signature");
1006 if (crypto_sign_check_S_lt_l(&tx.joinSplitSig[32]) != 0) {
1007 return state.DoS(100, error("CheckTransaction(): non-canonical ed25519 signature"),
1008 REJECT_INVALID, "non-canonical-ed25519-signature");
1011 if (state.PerformPourVerification()) {
1012 // Ensure that zk-SNARKs verify
1013 BOOST_FOREACH(const CPourTx &pour, tx.vpour) {
1014 if (!pour.Verify(*pzcashParams, tx.joinSplitPubKey)) {
1015 return state.DoS(100, error("CheckTransaction(): pour does not verify"),
1016 REJECT_INVALID, "bad-txns-pour-verification-failed");
1026 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
1030 uint256 hash = tx.GetHash();
1031 double dPriorityDelta = 0;
1032 CAmount nFeeDelta = 0;
1033 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
1034 if (dPriorityDelta > 0 || nFeeDelta > 0)
1038 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
1042 // There is a free transaction area in blocks created by most miners,
1043 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
1044 // to be considered to fall into this category. We don't want to encourage sending
1045 // multiple transactions instead of one big transaction to avoid fees.
1046 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
1050 if (!MoneyRange(nMinFee))
1051 nMinFee = MAX_MONEY;
1056 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
1057 bool* pfMissingInputs, bool fRejectAbsurdFee)
1059 AssertLockHeld(cs_main);
1060 if (pfMissingInputs)
1061 *pfMissingInputs = false;
1063 if (!CheckTransaction(tx, state))
1064 return error("AcceptToMemoryPool: CheckTransaction failed");
1066 // Coinbase is only valid in a block, not as a loose transaction
1067 if (tx.IsCoinBase())
1068 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
1069 REJECT_INVALID, "coinbase");
1071 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
1073 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
1075 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
1076 REJECT_NONSTANDARD, reason);
1078 // Only accept nLockTime-using transactions that can be mined in the next
1079 // block; we don't want our mempool filled up with transactions that can't
1081 if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
1082 return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
1084 // is it already in the memory pool?
1085 uint256 hash = tx.GetHash();
1086 if (pool.exists(hash))
1089 // Check for conflicts with in-memory transactions
1091 LOCK(pool.cs); // protect pool.mapNextTx
1092 for (unsigned int i = 0; i < tx.vin.size(); i++)
1094 COutPoint outpoint = tx.vin[i].prevout;
1095 if (pool.mapNextTx.count(outpoint))
1097 // Disable replacement feature for now
1101 BOOST_FOREACH(const CPourTx &pour, tx.vpour) {
1102 BOOST_FOREACH(const uint256 &serial, pour.serials) {
1103 if (pool.mapSerials.count(serial))
1113 CCoinsViewCache view(&dummy);
1115 CAmount nValueIn = 0;
1118 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
1119 view.SetBackend(viewMemPool);
1121 // do we already have it?
1122 if (view.HaveCoins(hash))
1125 // do all inputs exist?
1126 // Note that this does not check for the presence of actual outputs (see the next check for that),
1127 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
1128 BOOST_FOREACH(const CTxIn txin, tx.vin) {
1129 if (!view.HaveCoins(txin.prevout.hash)) {
1130 if (pfMissingInputs)
1131 *pfMissingInputs = true;
1136 // are the actual inputs available?
1137 if (!view.HaveInputs(tx))
1138 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1139 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1141 // are the pour's requirements met?
1142 if (!view.HavePourRequirements(tx))
1143 return state.Invalid(error("AcceptToMemoryPool: pour requirements not met"),
1144 REJECT_DUPLICATE, "bad-txns-pour-requirements-not-met");
1146 // Bring the best block into scope
1147 view.GetBestBlock();
1149 nValueIn = view.GetValueIn(tx);
1151 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1152 view.SetBackend(dummy);
1155 // Check for non-standard pay-to-script-hash in inputs
1156 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1157 return error("AcceptToMemoryPool: nonstandard transaction input");
1159 // Check that the transaction doesn't have an excessive number of
1160 // sigops, making it impossible to mine. Since the coinbase transaction
1161 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1162 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1163 // merely non-standard transaction.
1164 unsigned int nSigOps = GetLegacySigOpCount(tx);
1165 nSigOps += GetP2SHSigOpCount(tx, view);
1166 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1168 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1169 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1170 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1172 CAmount nValueOut = tx.GetValueOut();
1173 CAmount nFees = nValueIn-nValueOut;
1174 double dPriority = view.GetPriority(tx, chainActive.Height());
1176 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1177 unsigned int nSize = entry.GetTxSize();
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");
1186 // Require that free transactions have sufficient priority to be mined in the next block.
1187 if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1188 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1191 // Continuously rate-limit free (really, very-low-fee) transactions
1192 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1193 // be annoying or make others' transactions take longer to confirm.
1194 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1196 static CCriticalSection csFreeLimiter;
1197 static double dFreeCount;
1198 static int64_t nLastTime;
1199 int64_t nNow = GetTime();
1201 LOCK(csFreeLimiter);
1203 // Use an exponentially decaying ~10-minute window:
1204 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1206 // -limitfreerelay unit is thousand-bytes-per-minute
1207 // At default rate it would take over a month to fill 1GB
1208 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1209 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1210 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1211 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1212 dFreeCount += nSize;
1215 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1216 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1218 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1220 // Check against previous transactions
1221 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1222 if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1224 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1227 // Check again against just the consensus-critical mandatory script
1228 // verification flags, in case of bugs in the standard flags that cause
1229 // transactions to pass as valid when they're actually invalid. For
1230 // instance the STRICTENC flag was incorrectly allowing certain
1231 // CHECKSIG NOT scripts to pass, even though they were invalid.
1233 // There is a similar check in CreateNewBlock() to prevent creating
1234 // invalid blocks, however allowing such transactions into the mempool
1235 // can be exploited as a DoS attack.
1236 if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1238 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1241 // Store transaction in memory
1242 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1245 SyncWithWallets(tx, NULL);
1250 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1251 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1253 CBlockIndex *pindexSlow = NULL;
1257 if (mempool.lookup(hash, txOut))
1264 if (pblocktree->ReadTxIndex(hash, postx)) {
1265 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1267 return error("%s: OpenBlockFile failed", __func__);
1268 CBlockHeader header;
1271 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1273 } catch (const std::exception& e) {
1274 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1276 hashBlock = header.GetHash();
1277 if (txOut.GetHash() != hash)
1278 return error("%s: txid mismatch", __func__);
1283 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1286 CCoinsViewCache &view = *pcoinsTip;
1287 const CCoins* coins = view.AccessCoins(hash);
1289 nHeight = coins->nHeight;
1292 pindexSlow = chainActive[nHeight];
1297 if (ReadBlockFromDisk(block, pindexSlow)) {
1298 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1299 if (tx.GetHash() == hash) {
1301 hashBlock = pindexSlow->GetBlockHash();
1316 //////////////////////////////////////////////////////////////////////////////
1318 // CBlock and CBlockIndex
1321 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1323 // Open history file to append
1324 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1325 if (fileout.IsNull())
1326 return error("WriteBlockToDisk: OpenBlockFile failed");
1328 // Write index header
1329 unsigned int nSize = fileout.GetSerializeSize(block);
1330 fileout << FLATDATA(messageStart) << nSize;
1333 long fileOutPos = ftell(fileout.Get());
1335 return error("WriteBlockToDisk: ftell failed");
1336 pos.nPos = (unsigned int)fileOutPos;
1342 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1346 // Open history file to read
1347 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1348 if (filein.IsNull())
1349 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1355 catch (const std::exception& e) {
1356 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1360 if (!(CheckEquihashSolution(&block, Params()) &&
1361 CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus())))
1362 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1367 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1369 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1371 if (block.GetHash() != pindex->GetBlockHash())
1372 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1373 pindex->ToString(), pindex->GetBlockPos().ToString());
1377 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1379 CAmount nSubsidy = 12.5 * COIN;
1381 // Mining slow start
1382 // The subsidy is ramped up linearly, skipping the middle payout of
1383 // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start.
1384 if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) {
1385 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1386 nSubsidy *= nHeight;
1388 } else if (nHeight < consensusParams.nSubsidySlowStartInterval) {
1389 nSubsidy /= consensusParams.nSubsidySlowStartInterval;
1390 nSubsidy *= (nHeight+1);
1394 assert(nHeight > consensusParams.SubsidySlowStartShift());
1395 int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;
1396 // Force block reward to zero when right shift is undefined.
1400 // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years.
1401 nSubsidy >>= halvings;
1405 bool IsInitialBlockDownload()
1407 const CChainParams& chainParams = Params();
1409 if (fImporting || fReindex)
1411 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1413 static bool lockIBDState = false;
1416 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1417 pindexBestHeader->GetBlockTime() < GetTime() - chainParams.MaxTipAge());
1419 lockIBDState = true;
1423 bool fLargeWorkForkFound = false;
1424 bool fLargeWorkInvalidChainFound = false;
1425 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1427 void CheckForkWarningConditions()
1429 AssertLockHeld(cs_main);
1430 // Before we get past initial download, we cannot reliably alert about forks
1431 // (we assume we don't get stuck on a fork before the last checkpoint)
1432 if (IsInitialBlockDownload())
1435 // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it)
1436 // of our head, drop it
1437 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288)
1438 pindexBestForkTip = NULL;
1440 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1442 if (!fLargeWorkForkFound && pindexBestForkBase)
1444 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1445 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1446 CAlert::Notify(warning, true);
1448 if (pindexBestForkTip && pindexBestForkBase)
1450 LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
1451 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1452 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1453 fLargeWorkForkFound = true;
1457 std::string warning = std::string("Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.");
1458 LogPrintf("%s: %s\n", warning.c_str(), __func__);
1459 CAlert::Notify(warning, true);
1460 fLargeWorkInvalidChainFound = true;
1465 fLargeWorkForkFound = false;
1466 fLargeWorkInvalidChainFound = false;
1470 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1472 AssertLockHeld(cs_main);
1473 // If we are on a fork that is sufficiently large, set a warning flag
1474 CBlockIndex* pfork = pindexNewForkTip;
1475 CBlockIndex* plonger = chainActive.Tip();
1476 while (pfork && pfork != plonger)
1478 while (plonger && plonger->nHeight > pfork->nHeight)
1479 plonger = plonger->pprev;
1480 if (pfork == plonger)
1482 pfork = pfork->pprev;
1485 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1486 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1487 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1488 // hash rate operating on the fork.
1489 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1490 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1491 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1492 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1493 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1494 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1496 pindexBestForkTip = pindexNewForkTip;
1497 pindexBestForkBase = pfork;
1500 CheckForkWarningConditions();
1503 // Requires cs_main.
1504 void Misbehaving(NodeId pnode, int howmuch)
1509 CNodeState *state = State(pnode);
1513 state->nMisbehavior += howmuch;
1514 int banscore = GetArg("-banscore", 100);
1515 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1517 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1518 state->fShouldBan = true;
1520 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1523 void static InvalidChainFound(CBlockIndex* pindexNew)
1525 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1526 pindexBestInvalid = pindexNew;
1528 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1529 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1530 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1531 pindexNew->GetBlockTime()));
1532 CBlockIndex *tip = chainActive.Tip();
1534 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1535 tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
1536 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
1537 CheckForkWarningConditions();
1540 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1542 if (state.IsInvalid(nDoS)) {
1543 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1544 if (it != mapBlockSource.end() && State(it->second)) {
1545 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1546 State(it->second)->rejects.push_back(reject);
1548 Misbehaving(it->second, nDoS);
1551 if (!state.CorruptionPossible()) {
1552 pindex->nStatus |= BLOCK_FAILED_VALID;
1553 setDirtyBlockIndex.insert(pindex);
1554 setBlockIndexCandidates.erase(pindex);
1555 InvalidChainFound(pindex);
1559 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1561 // mark inputs spent
1562 if (!tx.IsCoinBase()) {
1563 txundo.vprevout.reserve(tx.vin.size());
1564 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1565 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1566 unsigned nPos = txin.prevout.n;
1568 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1570 // mark an outpoint spent, and construct undo information
1571 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1573 if (coins->vout.size() == 0) {
1574 CTxInUndo& undo = txundo.vprevout.back();
1575 undo.nHeight = coins->nHeight;
1576 undo.fCoinBase = coins->fCoinBase;
1577 undo.nVersion = coins->nVersion;
1583 BOOST_FOREACH(const CPourTx &pour, tx.vpour) {
1584 BOOST_FOREACH(const uint256 &serial, pour.serials) {
1585 inputs.SetSerial(serial, true);
1590 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1593 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1596 UpdateCoins(tx, state, inputs, txundo, nHeight);
1599 bool CScriptCheck::operator()() {
1600 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1601 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1602 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1607 bool NonContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1609 if (!tx.IsCoinBase())
1612 pvChecks->reserve(tx.vin.size());
1614 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1615 // for an attacker to attempt to split the network.
1616 if (!inputs.HaveInputs(tx))
1617 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1619 // are the pour's requirements met?
1620 if (!inputs.HavePourRequirements(tx))
1621 return state.Invalid(error("CheckInputs(): %s pour requirements not met", tx.GetHash().ToString()));
1623 CAmount nValueIn = 0;
1625 for (unsigned int i = 0; i < tx.vin.size(); i++)
1627 const COutPoint &prevout = tx.vin[i].prevout;
1628 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1631 if (coins->IsCoinBase()) {
1632 // Ensure that coinbases cannot be spent to transparent outputs
1633 if (!tx.vout.empty()) {
1634 return state.Invalid(
1635 error("CheckInputs(): tried to spend coinbase with transparent outputs"),
1636 REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs");
1640 // Check for negative or overflow input values
1641 nValueIn += coins->vout[prevout.n].nValue;
1642 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1643 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1644 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1648 nValueIn += tx.GetPourValueIn();
1649 if (!MoneyRange(nValueIn))
1650 return state.DoS(100, error("CheckInputs(): vpub_old values out of range"),
1651 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1653 if (nValueIn < tx.GetValueOut())
1654 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1655 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1656 REJECT_INVALID, "bad-txns-in-belowout");
1658 // Tally transaction fees
1659 CAmount nTxFee = nValueIn - tx.GetValueOut();
1661 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1662 REJECT_INVALID, "bad-txns-fee-negative");
1664 if (!MoneyRange(nFees))
1665 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1666 REJECT_INVALID, "bad-txns-fee-outofrange");
1668 // The first loop above does all the inexpensive checks.
1669 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1670 // Helps prevent CPU exhaustion attacks.
1672 // Skip ECDSA signature verification when connecting blocks
1673 // before the last block chain checkpoint. This is safe because block merkle hashes are
1674 // still computed and checked, and any change will be caught at the next checkpoint.
1675 if (fScriptChecks) {
1676 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1677 const COutPoint &prevout = tx.vin[i].prevout;
1678 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1682 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1684 pvChecks->push_back(CScriptCheck());
1685 check.swap(pvChecks->back());
1686 } else if (!check()) {
1687 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1688 // Check whether the failure was caused by a
1689 // non-mandatory script verification check, such as
1690 // non-standard DER encodings or non-null dummy
1691 // arguments; if so, don't trigger DoS protection to
1692 // avoid splitting the network between upgraded and
1693 // non-upgraded nodes.
1694 CScriptCheck check(*coins, tx, i,
1695 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1697 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1699 // Failures of other flags indicate a transaction that is
1700 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1701 // such nodes as they are not following the protocol. That
1702 // said during an upgrade careful thought should be taken
1703 // as to the correct behavior - we may want to continue
1704 // peering with non-upgraded nodes even after a soft-fork
1705 // super-majority vote has passed.
1706 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1715 bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1717 if (!tx.IsCoinBase())
1719 // While checking, GetBestBlock() refers to the parent block.
1720 // This is also true for mempool checks.
1721 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1722 int nSpendHeight = pindexPrev->nHeight + 1;
1723 for (unsigned int i = 0; i < tx.vin.size(); i++)
1725 const COutPoint &prevout = tx.vin[i].prevout;
1726 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1729 // If prev is coinbase, check that it's matured
1730 if (coins->IsCoinBase()) {
1731 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1732 return state.Invalid(
1733 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1734 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1739 return NonContextualCheckInputs(
1740 tx, state, inputs, fScriptChecks, flags, cacheStore, pvChecks
1746 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1748 // Open history file to append
1749 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1750 if (fileout.IsNull())
1751 return error("%s: OpenUndoFile failed", __func__);
1753 // Write index header
1754 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1755 fileout << FLATDATA(messageStart) << nSize;
1758 long fileOutPos = ftell(fileout.Get());
1760 return error("%s: ftell failed", __func__);
1761 pos.nPos = (unsigned int)fileOutPos;
1762 fileout << blockundo;
1764 // calculate & write checksum
1765 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1766 hasher << hashBlock;
1767 hasher << blockundo;
1768 fileout << hasher.GetHash();
1773 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1775 // Open history file to read
1776 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1777 if (filein.IsNull())
1778 return error("%s: OpenBlockFile failed", __func__);
1781 uint256 hashChecksum;
1783 filein >> blockundo;
1784 filein >> hashChecksum;
1786 catch (const std::exception& e) {
1787 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1791 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1792 hasher << hashBlock;
1793 hasher << blockundo;
1794 if (hashChecksum != hasher.GetHash())
1795 return error("%s: Checksum mismatch", __func__);
1800 /** Abort with a message */
1801 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1803 strMiscWarning = strMessage;
1804 LogPrintf("*** %s\n", strMessage);
1805 uiInterface.ThreadSafeMessageBox(
1806 userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
1807 "", CClientUIInterface::MSG_ERROR);
1812 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1814 AbortNode(strMessage, userMessage);
1815 return state.Error(strMessage);
1821 * Apply the undo operation of a CTxInUndo to the given chain state.
1822 * @param undo The undo object.
1823 * @param view The coins view to which to apply the changes.
1824 * @param out The out point that corresponds to the tx input.
1825 * @return True on success.
1827 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1831 CCoinsModifier coins = view.ModifyCoins(out.hash);
1832 if (undo.nHeight != 0) {
1833 // undo data contains height: this is the last output of the prevout tx being spent
1834 if (!coins->IsPruned())
1835 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1837 coins->fCoinBase = undo.fCoinBase;
1838 coins->nHeight = undo.nHeight;
1839 coins->nVersion = undo.nVersion;
1841 if (coins->IsPruned())
1842 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1844 if (coins->IsAvailable(out.n))
1845 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1846 if (coins->vout.size() < out.n+1)
1847 coins->vout.resize(out.n+1);
1848 coins->vout[out.n] = undo.txout;
1853 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1855 assert(pindex->GetBlockHash() == view.GetBestBlock());
1862 CBlockUndo blockUndo;
1863 CDiskBlockPos pos = pindex->GetUndoPos();
1865 return error("DisconnectBlock(): no undo data available");
1866 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1867 return error("DisconnectBlock(): failure reading undo data");
1869 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1870 return error("DisconnectBlock(): block and undo data inconsistent");
1872 // undo transactions in reverse order
1873 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1874 const CTransaction &tx = block.vtx[i];
1875 uint256 hash = tx.GetHash();
1877 // Check that all outputs are available and match the outputs in the block itself
1880 CCoinsModifier outs = view.ModifyCoins(hash);
1881 outs->ClearUnspendable();
1883 CCoins outsBlock(tx, pindex->nHeight);
1884 // The CCoins serialization does not serialize negative numbers.
1885 // No network rules currently depend on the version here, so an inconsistency is harmless
1886 // but it must be corrected before txout nversion ever influences a network rule.
1887 if (outsBlock.nVersion < 0)
1888 outs->nVersion = outsBlock.nVersion;
1889 if (*outs != outsBlock)
1890 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1897 BOOST_FOREACH(const CPourTx &pour, tx.vpour) {
1898 BOOST_FOREACH(const uint256 &serial, pour.serials) {
1899 view.SetSerial(serial, false);
1904 if (i > 0) { // not coinbases
1905 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1906 if (txundo.vprevout.size() != tx.vin.size())
1907 return error("DisconnectBlock(): transaction and undo data inconsistent");
1908 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1909 const COutPoint &out = tx.vin[j].prevout;
1910 const CTxInUndo &undo = txundo.vprevout[j];
1911 if (!ApplyTxInUndo(undo, view, out))
1917 // set the old best anchor back
1918 view.PopAnchor(blockUndo.old_tree_root);
1920 // move best block pointer to prevout block
1921 view.SetBestBlock(pindex->pprev->GetBlockHash());
1931 void static FlushBlockFile(bool fFinalize = false)
1933 LOCK(cs_LastBlockFile);
1935 CDiskBlockPos posOld(nLastBlockFile, 0);
1937 FILE *fileOld = OpenBlockFile(posOld);
1940 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1941 FileCommit(fileOld);
1945 fileOld = OpenUndoFile(posOld);
1948 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1949 FileCommit(fileOld);
1954 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1956 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1958 void ThreadScriptCheck() {
1959 RenameThread("bitcoin-scriptch");
1960 scriptcheckqueue.Thread();
1964 // Called periodically asynchronously; alerts if it smells like
1965 // we're being fed a bad chain (blocks being generated much
1966 // too slowly or too quickly).
1968 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CBlockIndex *const &bestHeader,
1969 int64_t nPowTargetSpacing)
1971 if (bestHeader == NULL || initialDownloadCheck()) return;
1973 static int64_t lastAlertTime = 0;
1974 int64_t now = GetAdjustedTime();
1975 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1977 const int SPAN_HOURS=4;
1978 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1979 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1981 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1983 std::string strWarning;
1984 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1987 const CBlockIndex* i = bestHeader;
1989 while (i->GetBlockTime() >= startTime) {
1992 if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed
1995 // How likely is it to find that many by chance?
1996 double p = boost::math::pdf(poisson, nBlocks);
1998 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1999 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
2001 // Aim for one false-positive about every fifty years of normal running:
2002 const int FIFTY_YEARS = 50*365*24*60*60;
2003 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
2005 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
2007 // Many fewer blocks than expected: alert!
2008 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
2009 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2011 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
2013 // Many more blocks than expected: alert!
2014 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
2015 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
2017 if (!strWarning.empty())
2019 strMiscWarning = strWarning;
2020 CAlert::Notify(strWarning, true);
2021 lastAlertTime = now;
2025 static int64_t nTimeVerify = 0;
2026 static int64_t nTimeConnect = 0;
2027 static int64_t nTimeIndex = 0;
2028 static int64_t nTimeCallbacks = 0;
2029 static int64_t nTimeTotal = 0;
2031 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
2033 const CChainParams& chainparams = Params();
2034 AssertLockHeld(cs_main);
2035 // Check it again in case a previous version let a bad block in
2036 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
2039 // verify that the view's current state corresponds to the previous block
2040 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
2041 assert(hashPrevBlock == view.GetBestBlock());
2043 // Special case for the genesis block, skipping connection of its transactions
2044 // (its coinbase is unspendable)
2045 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
2047 view.SetBestBlock(pindex->GetBlockHash());
2051 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
2053 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
2054 // unless those are already completely spent.
2055 // If such overwrites are allowed, coinbases and transactions depending upon those
2056 // can be duplicated to remove the ability to spend the first instance -- even after
2057 // being sent to another address.
2058 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
2059 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
2060 // already refuses previously-known transaction ids entirely.
2061 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
2062 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
2063 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
2064 // initial block download.
2065 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
2066 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
2067 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
2068 if (fEnforceBIP30) {
2069 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
2070 const CCoins* coins = view.AccessCoins(tx.GetHash());
2071 if (coins && !coins->IsPruned())
2072 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
2073 REJECT_INVALID, "bad-txns-BIP30");
2077 // BIP16 didn't become active until Apr 1 2012
2078 int64_t nBIP16SwitchTime = 1333238400;
2079 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
2081 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
2083 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks,
2084 // when 75% of the network has upgraded:
2085 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
2086 flags |= SCRIPT_VERIFY_DERSIG;
2089 // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
2090 // blocks, when 75% of the network has upgraded:
2091 if (block.nVersion >= 4 && IsSuperMajority(4, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
2092 flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
2095 CBlockUndo blockundo;
2097 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
2099 int64_t nTimeStart = GetTimeMicros();
2102 unsigned int nSigOps = 0;
2103 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
2104 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
2105 vPos.reserve(block.vtx.size());
2106 blockundo.vtxundo.reserve(block.vtx.size() - 1);
2108 // Construct the incremental merkle tree at the current
2110 auto old_tree_root = view.GetBestAnchor();
2111 ZCIncrementalMerkleTree tree;
2112 // This should never fail: we should always be able to get the root
2113 // that is on the tip of our chain
2114 assert(view.GetAnchorAt(old_tree_root, tree));
2117 // Consistency check: the root of the tree we're given should
2118 // match what we asked for.
2119 assert(tree.root() == old_tree_root);
2122 for (unsigned int i = 0; i < block.vtx.size(); i++)
2124 const CTransaction &tx = block.vtx[i];
2126 nInputs += tx.vin.size();
2127 nSigOps += GetLegacySigOpCount(tx);
2128 if (nSigOps > MAX_BLOCK_SIGOPS)
2129 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2130 REJECT_INVALID, "bad-blk-sigops");
2132 if (!tx.IsCoinBase())
2134 if (!view.HaveInputs(tx))
2135 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
2136 REJECT_INVALID, "bad-txns-inputs-missingorspent");
2138 // are the pour's requirements met?
2139 if (!view.HavePourRequirements(tx))
2140 return state.DoS(100, error("ConnectBlock(): pour requirements not met"),
2141 REJECT_INVALID, "bad-txns-pour-requirements-not-met");
2143 if (fStrictPayToScriptHash)
2145 // Add in sigops done by pay-to-script-hash inputs;
2146 // this is to prevent a "rogue miner" from creating
2147 // an incredibly-expensive-to-validate block.
2148 nSigOps += GetP2SHSigOpCount(tx, view);
2149 if (nSigOps > MAX_BLOCK_SIGOPS)
2150 return state.DoS(100, error("ConnectBlock(): too many sigops"),
2151 REJECT_INVALID, "bad-blk-sigops");
2154 nFees += view.GetValueIn(tx)-tx.GetValueOut();
2156 std::vector<CScriptCheck> vChecks;
2157 if (!ContextualCheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
2159 control.Add(vChecks);
2164 blockundo.vtxundo.push_back(CTxUndo());
2166 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
2168 BOOST_FOREACH(const CPourTx &pour, tx.vpour) {
2169 BOOST_FOREACH(const uint256 &bucket_commitment, pour.commitments) {
2170 // Insert the bucket commitments into our temporary tree.
2172 tree.append(bucket_commitment);
2176 vPos.push_back(std::make_pair(tx.GetHash(), pos));
2177 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
2180 view.PushAnchor(tree);
2181 blockundo.old_tree_root = old_tree_root;
2183 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
2184 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);
2186 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
2187 if (block.vtx[0].GetValueOut() > blockReward)
2188 return state.DoS(100,
2189 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
2190 block.vtx[0].GetValueOut(), blockReward),
2191 REJECT_INVALID, "bad-cb-amount");
2193 if (!control.Wait())
2194 return state.DoS(100, false);
2195 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
2196 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);
2201 // Write undo information to disk
2202 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
2204 if (pindex->GetUndoPos().IsNull()) {
2206 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
2207 return error("ConnectBlock(): FindUndoPos failed");
2208 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
2209 return AbortNode(state, "Failed to write undo data");
2211 // update nUndoPos in block index
2212 pindex->nUndoPos = pos.nPos;
2213 pindex->nStatus |= BLOCK_HAVE_UNDO;
2216 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
2217 setDirtyBlockIndex.insert(pindex);
2221 if (!pblocktree->WriteTxIndex(vPos))
2222 return AbortNode(state, "Failed to write transaction index");
2224 // add this block to the view's block chain
2225 view.SetBestBlock(pindex->GetBlockHash());
2227 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
2228 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
2230 // Watch for changes to the previous coinbase transaction.
2231 static uint256 hashPrevBestCoinBase;
2232 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
2233 hashPrevBestCoinBase = block.vtx[0].GetHash();
2235 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
2236 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
2241 enum FlushStateMode {
2243 FLUSH_STATE_IF_NEEDED,
2244 FLUSH_STATE_PERIODIC,
2249 * Update the on-disk chain state.
2250 * The caches and indexes are flushed depending on the mode we're called with
2251 * if they're too large, if it's been a while since the last write,
2252 * or always and in all cases if we're in prune mode and are deleting files.
2254 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
2255 LOCK2(cs_main, cs_LastBlockFile);
2256 static int64_t nLastWrite = 0;
2257 static int64_t nLastFlush = 0;
2258 static int64_t nLastSetChain = 0;
2259 std::set<int> setFilesToPrune;
2260 bool fFlushForPrune = false;
2262 if (fPruneMode && fCheckForPruning && !fReindex) {
2263 FindFilesToPrune(setFilesToPrune);
2264 fCheckForPruning = false;
2265 if (!setFilesToPrune.empty()) {
2266 fFlushForPrune = true;
2268 pblocktree->WriteFlag("prunedblockfiles", true);
2273 int64_t nNow = GetTimeMicros();
2274 // Avoid writing/flushing immediately after startup.
2275 if (nLastWrite == 0) {
2278 if (nLastFlush == 0) {
2281 if (nLastSetChain == 0) {
2282 nLastSetChain = nNow;
2284 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
2285 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
2286 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2287 // The cache is over the limit, we have to write now.
2288 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2289 // 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.
2290 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2291 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2292 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2293 // Combine all conditions that result in a full cache flush.
2294 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2295 // Write blocks and block index to disk.
2296 if (fDoFullFlush || fPeriodicWrite) {
2297 // Depend on nMinDiskSpace to ensure we can write block index
2298 if (!CheckDiskSpace(0))
2299 return state.Error("out of disk space");
2300 // First make sure all block and undo data is flushed to disk.
2302 // Then update all block file information (which may refer to block and undo files).
2304 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2305 vFiles.reserve(setDirtyFileInfo.size());
2306 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2307 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2308 setDirtyFileInfo.erase(it++);
2310 std::vector<const CBlockIndex*> vBlocks;
2311 vBlocks.reserve(setDirtyBlockIndex.size());
2312 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2313 vBlocks.push_back(*it);
2314 setDirtyBlockIndex.erase(it++);
2316 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2317 return AbortNode(state, "Files to write to block index database");
2320 // Finally remove any pruned files
2322 UnlinkPrunedFiles(setFilesToPrune);
2325 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2327 // Typical CCoins structures on disk are around 128 bytes in size.
2328 // Pushing a new one to the database can cause it to be written
2329 // twice (once in the log, and once in the tables). This is already
2330 // an overestimation, as most will delete an existing entry or
2331 // overwrite one. Still, use a conservative safety factor of 2.
2332 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2333 return state.Error("out of disk space");
2334 // Flush the chainstate (which may refer to block index entries).
2335 if (!pcoinsTip->Flush())
2336 return AbortNode(state, "Failed to write to coin database");
2339 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2340 // Update best block in wallet (so we can detect restored wallets).
2341 GetMainSignals().SetBestChain(chainActive.GetLocator());
2342 nLastSetChain = nNow;
2344 } catch (const std::runtime_error& e) {
2345 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2350 void FlushStateToDisk() {
2351 CValidationState state;
2352 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2355 void PruneAndFlush() {
2356 CValidationState state;
2357 fCheckForPruning = true;
2358 FlushStateToDisk(state, FLUSH_STATE_NONE);
2361 /** Update chainActive and related internal data structures. */
2362 void static UpdateTip(CBlockIndex *pindexNew) {
2363 const CChainParams& chainParams = Params();
2364 chainActive.SetTip(pindexNew);
2367 nTimeBestReceived = GetTime();
2368 mempool.AddTransactionsUpdated(1);
2370 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2371 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2372 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2373 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2375 cvBlockChange.notify_all();
2377 // Check the version of the last 100 blocks to see if we need to upgrade:
2378 static bool fWarned = false;
2379 if (!IsInitialBlockDownload() && !fWarned)
2382 const CBlockIndex* pindex = chainActive.Tip();
2383 for (int i = 0; i < 100 && pindex != NULL; i++)
2385 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2387 pindex = pindex->pprev;
2390 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2391 if (nUpgraded > 100/2)
2393 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2394 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2395 CAlert::Notify(strMiscWarning, true);
2401 /** Disconnect chainActive's tip. */
2402 bool static DisconnectTip(CValidationState &state) {
2403 CBlockIndex *pindexDelete = chainActive.Tip();
2404 assert(pindexDelete);
2405 mempool.check(pcoinsTip);
2406 // Read block from disk.
2408 if (!ReadBlockFromDisk(block, pindexDelete))
2409 return AbortNode(state, "Failed to read block");
2410 // Apply the block atomically to the chain state.
2411 uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor();
2412 int64_t nStart = GetTimeMicros();
2414 CCoinsViewCache view(pcoinsTip);
2415 if (!DisconnectBlock(block, state, pindexDelete, view))
2416 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2417 assert(view.Flush());
2419 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2420 uint256 anchorAfterDisconnect = pcoinsTip->GetBestAnchor();
2421 // Write the chain state to disk, if necessary.
2422 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2424 // Resurrect mempool transactions from the disconnected block.
2425 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2426 // ignore validation errors in resurrected transactions
2427 list<CTransaction> removed;
2428 CValidationState stateDummy;
2429 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2430 mempool.remove(tx, removed, true);
2432 if (anchorBeforeDisconnect != anchorAfterDisconnect) {
2433 // The anchor may not change between block disconnects,
2434 // in which case we don't want to evict from the mempool yet!
2435 mempool.removeWithAnchor(anchorBeforeDisconnect);
2437 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2438 mempool.check(pcoinsTip);
2439 // Update chainActive and related variables.
2440 UpdateTip(pindexDelete->pprev);
2441 // Let wallets know transactions went from 1-confirmed to
2442 // 0-confirmed or conflicted:
2443 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2444 SyncWithWallets(tx, NULL);
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 // Apply the block atomically to the chain state.
2471 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2473 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2475 CCoinsViewCache view(pcoinsTip);
2476 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2477 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2478 GetMainSignals().BlockChecked(*pblock, state);
2480 if (state.IsInvalid())
2481 InvalidBlockFound(pindexNew, state);
2482 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2484 mapBlockSource.erase(inv.hash);
2485 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2486 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2487 assert(view.Flush());
2489 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2490 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2491 // Write the chain state to disk, if necessary.
2492 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2494 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2495 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2496 // Remove conflicting transactions from the mempool.
2497 list<CTransaction> txConflicted;
2498 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2499 mempool.check(pcoinsTip);
2500 // Update chainActive & related variables.
2501 UpdateTip(pindexNew);
2502 // Tell wallet about transactions that went from mempool
2504 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2505 SyncWithWallets(tx, NULL);
2507 // ... and about transactions that got confirmed:
2508 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2509 SyncWithWallets(tx, pblock);
2512 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2513 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2514 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2519 * Return the tip of the chain with the most work in it, that isn't
2520 * known to be invalid (it's however far from certain to be valid).
2522 static CBlockIndex* FindMostWorkChain() {
2524 CBlockIndex *pindexNew = NULL;
2526 // Find the best candidate header.
2528 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2529 if (it == setBlockIndexCandidates.rend())
2534 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2535 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2536 CBlockIndex *pindexTest = pindexNew;
2537 bool fInvalidAncestor = false;
2538 while (pindexTest && !chainActive.Contains(pindexTest)) {
2539 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2541 // Pruned nodes may have entries in setBlockIndexCandidates for
2542 // which block files have been deleted. Remove those as candidates
2543 // for the most work chain if we come across them; we can't switch
2544 // to a chain unless we have all the non-active-chain parent blocks.
2545 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2546 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2547 if (fFailedChain || fMissingData) {
2548 // Candidate chain is not usable (either invalid or missing data)
2549 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2550 pindexBestInvalid = pindexNew;
2551 CBlockIndex *pindexFailed = pindexNew;
2552 // Remove the entire chain from the set.
2553 while (pindexTest != pindexFailed) {
2555 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2556 } else if (fMissingData) {
2557 // If we're missing data, then add back to mapBlocksUnlinked,
2558 // so that if the block arrives in the future we can try adding
2559 // to setBlockIndexCandidates again.
2560 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2562 setBlockIndexCandidates.erase(pindexFailed);
2563 pindexFailed = pindexFailed->pprev;
2565 setBlockIndexCandidates.erase(pindexTest);
2566 fInvalidAncestor = true;
2569 pindexTest = pindexTest->pprev;
2571 if (!fInvalidAncestor)
2576 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2577 static void PruneBlockIndexCandidates() {
2578 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2579 // reorganization to a better block fails.
2580 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2581 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2582 setBlockIndexCandidates.erase(it++);
2584 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2585 assert(!setBlockIndexCandidates.empty());
2589 * Try to make some progress towards making pindexMostWork the active block.
2590 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2592 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2593 AssertLockHeld(cs_main);
2594 bool fInvalidFound = false;
2595 const CBlockIndex *pindexOldTip = chainActive.Tip();
2596 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2598 // Disconnect active blocks which are no longer in the best chain.
2599 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2600 if (!DisconnectTip(state))
2604 // Build list of new blocks to connect.
2605 std::vector<CBlockIndex*> vpindexToConnect;
2606 bool fContinue = true;
2607 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2608 while (fContinue && nHeight != pindexMostWork->nHeight) {
2609 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2610 // a few blocks along the way.
2611 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2612 vpindexToConnect.clear();
2613 vpindexToConnect.reserve(nTargetHeight - nHeight);
2614 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2615 while (pindexIter && pindexIter->nHeight != nHeight) {
2616 vpindexToConnect.push_back(pindexIter);
2617 pindexIter = pindexIter->pprev;
2619 nHeight = nTargetHeight;
2621 // Connect new blocks.
2622 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2623 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2624 if (state.IsInvalid()) {
2625 // The block violates a consensus rule.
2626 if (!state.CorruptionPossible())
2627 InvalidChainFound(vpindexToConnect.back());
2628 state = CValidationState();
2629 fInvalidFound = true;
2633 // A system error occurred (disk space, database error, ...).
2637 PruneBlockIndexCandidates();
2638 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2639 // We're in a better position than we were. Return temporarily to release the lock.
2647 // Callbacks/notifications for a new best chain.
2649 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2651 CheckForkWarningConditions();
2657 * Make the best chain active, in multiple steps. The result is either failure
2658 * or an activated best chain. pblock is either NULL or a pointer to a block
2659 * that is already loaded (to avoid loading it again from disk).
2661 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2662 CBlockIndex *pindexNewTip = NULL;
2663 CBlockIndex *pindexMostWork = NULL;
2664 const CChainParams& chainParams = Params();
2666 boost::this_thread::interruption_point();
2668 bool fInitialDownload;
2671 pindexMostWork = FindMostWorkChain();
2673 // Whether we have anything to do at all.
2674 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2677 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2680 pindexNewTip = chainActive.Tip();
2681 fInitialDownload = IsInitialBlockDownload();
2683 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2685 // Notifications/callbacks that can run without cs_main
2686 if (!fInitialDownload) {
2687 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2688 // Relay inventory, but don't relay old inventory during initial block download.
2689 int nBlockEstimate = 0;
2690 if (fCheckpointsEnabled)
2691 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2692 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2693 // in a stalled download if the block file is pruned before the request.
2694 if (nLocalServices & NODE_NETWORK) {
2696 BOOST_FOREACH(CNode* pnode, vNodes)
2697 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2698 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2700 // Notify external listeners about the new tip.
2701 uiInterface.NotifyBlockTip(hashNewTip);
2703 } while(pindexMostWork != chainActive.Tip());
2706 // Write changes periodically to disk, after relay.
2707 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2714 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2715 AssertLockHeld(cs_main);
2717 // Mark the block itself as invalid.
2718 pindex->nStatus |= BLOCK_FAILED_VALID;
2719 setDirtyBlockIndex.insert(pindex);
2720 setBlockIndexCandidates.erase(pindex);
2722 while (chainActive.Contains(pindex)) {
2723 CBlockIndex *pindexWalk = chainActive.Tip();
2724 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2725 setDirtyBlockIndex.insert(pindexWalk);
2726 setBlockIndexCandidates.erase(pindexWalk);
2727 // ActivateBestChain considers blocks already in chainActive
2728 // unconditionally valid already, so force disconnect away from it.
2729 if (!DisconnectTip(state)) {
2734 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2736 BlockMap::iterator it = mapBlockIndex.begin();
2737 while (it != mapBlockIndex.end()) {
2738 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2739 setBlockIndexCandidates.insert(it->second);
2744 InvalidChainFound(pindex);
2748 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2749 AssertLockHeld(cs_main);
2751 int nHeight = pindex->nHeight;
2753 // Remove the invalidity flag from this block and all its descendants.
2754 BlockMap::iterator it = mapBlockIndex.begin();
2755 while (it != mapBlockIndex.end()) {
2756 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2757 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2758 setDirtyBlockIndex.insert(it->second);
2759 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2760 setBlockIndexCandidates.insert(it->second);
2762 if (it->second == pindexBestInvalid) {
2763 // Reset invalid block marker if it was pointing to one of those.
2764 pindexBestInvalid = NULL;
2770 // Remove the invalidity flag from all ancestors too.
2771 while (pindex != NULL) {
2772 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2773 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2774 setDirtyBlockIndex.insert(pindex);
2776 pindex = pindex->pprev;
2781 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2783 // Check for duplicate
2784 uint256 hash = block.GetHash();
2785 BlockMap::iterator it = mapBlockIndex.find(hash);
2786 if (it != mapBlockIndex.end())
2789 // Construct new block index object
2790 CBlockIndex* pindexNew = new CBlockIndex(block);
2792 // We assign the sequence id to blocks only when the full data is available,
2793 // to avoid miners withholding blocks but broadcasting headers, to get a
2794 // competitive advantage.
2795 pindexNew->nSequenceId = 0;
2796 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2797 pindexNew->phashBlock = &((*mi).first);
2798 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2799 if (miPrev != mapBlockIndex.end())
2801 pindexNew->pprev = (*miPrev).second;
2802 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2803 pindexNew->BuildSkip();
2805 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2806 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2807 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2808 pindexBestHeader = pindexNew;
2810 setDirtyBlockIndex.insert(pindexNew);
2815 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2816 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2818 pindexNew->nTx = block.vtx.size();
2819 pindexNew->nChainTx = 0;
2820 pindexNew->nFile = pos.nFile;
2821 pindexNew->nDataPos = pos.nPos;
2822 pindexNew->nUndoPos = 0;
2823 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2824 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2825 setDirtyBlockIndex.insert(pindexNew);
2827 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2828 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2829 deque<CBlockIndex*> queue;
2830 queue.push_back(pindexNew);
2832 // Recursively process any descendant blocks that now may be eligible to be connected.
2833 while (!queue.empty()) {
2834 CBlockIndex *pindex = queue.front();
2836 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2838 LOCK(cs_nBlockSequenceId);
2839 pindex->nSequenceId = nBlockSequenceId++;
2841 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2842 setBlockIndexCandidates.insert(pindex);
2844 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2845 while (range.first != range.second) {
2846 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2847 queue.push_back(it->second);
2849 mapBlocksUnlinked.erase(it);
2853 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2854 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2861 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2863 LOCK(cs_LastBlockFile);
2865 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2866 if (vinfoBlockFile.size() <= nFile) {
2867 vinfoBlockFile.resize(nFile + 1);
2871 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2873 if (vinfoBlockFile.size() <= nFile) {
2874 vinfoBlockFile.resize(nFile + 1);
2878 pos.nPos = vinfoBlockFile[nFile].nSize;
2881 if (nFile != nLastBlockFile) {
2883 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2885 FlushBlockFile(!fKnown);
2886 nLastBlockFile = nFile;
2889 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2891 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2893 vinfoBlockFile[nFile].nSize += nAddSize;
2896 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2897 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2898 if (nNewChunks > nOldChunks) {
2900 fCheckForPruning = true;
2901 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2902 FILE *file = OpenBlockFile(pos);
2904 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2905 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2910 return state.Error("out of disk space");
2914 setDirtyFileInfo.insert(nFile);
2918 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2922 LOCK(cs_LastBlockFile);
2924 unsigned int nNewSize;
2925 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2926 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2927 setDirtyFileInfo.insert(nFile);
2929 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2930 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2931 if (nNewChunks > nOldChunks) {
2933 fCheckForPruning = true;
2934 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2935 FILE *file = OpenUndoFile(pos);
2937 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2938 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2943 return state.Error("out of disk space");
2949 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2951 // Check Equihash solution is valid
2952 if (fCheckPOW && !CheckEquihashSolution(&block, Params()))
2953 return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),
2954 REJECT_INVALID, "invalid-solution");
2956 // Check proof of work matches claimed amount
2957 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2958 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2959 REJECT_INVALID, "high-hash");
2962 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2963 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2964 REJECT_INVALID, "time-too-new");
2969 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2971 // These are checks that are independent of context.
2973 // Check that the header is valid (particularly PoW). This is mostly
2974 // redundant with the call in AcceptBlockHeader.
2975 if (!CheckBlockHeader(block, state, fCheckPOW))
2978 // Check the merkle root.
2979 if (fCheckMerkleRoot) {
2981 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2982 if (block.hashMerkleRoot != hashMerkleRoot2)
2983 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2984 REJECT_INVALID, "bad-txnmrklroot", true);
2986 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2987 // of transactions in a block without affecting the merkle root of a block,
2988 // while still invalidating it.
2990 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2991 REJECT_INVALID, "bad-txns-duplicate", true);
2994 // All potential-corruption validation must be done before we do any
2995 // transaction validation, as otherwise we may mark the header as invalid
2996 // because we receive the wrong transactions for it.
2999 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
3000 return state.DoS(100, error("CheckBlock(): size limits failed"),
3001 REJECT_INVALID, "bad-blk-length");
3003 // First transaction must be coinbase, the rest must not be
3004 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
3005 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
3006 REJECT_INVALID, "bad-cb-missing");
3007 for (unsigned int i = 1; i < block.vtx.size(); i++)
3008 if (block.vtx[i].IsCoinBase())
3009 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
3010 REJECT_INVALID, "bad-cb-multiple");
3012 // Check transactions
3013 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3014 if (!CheckTransaction(tx, state))
3015 return error("CheckBlock(): CheckTransaction failed");
3017 unsigned int nSigOps = 0;
3018 BOOST_FOREACH(const CTransaction& tx, block.vtx)
3020 nSigOps += GetLegacySigOpCount(tx);
3022 if (nSigOps > MAX_BLOCK_SIGOPS)
3023 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
3024 REJECT_INVALID, "bad-blk-sigops", true);
3029 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
3031 const CChainParams& chainParams = Params();
3032 const Consensus::Params& consensusParams = chainParams.GetConsensus();
3033 uint256 hash = block.GetHash();
3034 if (hash == consensusParams.hashGenesisBlock)
3039 int nHeight = pindexPrev->nHeight+1;
3041 // Check proof of work
3042 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
3043 return state.DoS(100, error("%s: incorrect proof of work", __func__),
3044 REJECT_INVALID, "bad-diffbits");
3046 // Check timestamp against prev
3047 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
3048 return state.Invalid(error("%s: block's timestamp is too early", __func__),
3049 REJECT_INVALID, "time-too-old");
3051 if(fCheckpointsEnabled)
3053 // Check that the block chain matches the known block chain up to a checkpoint
3054 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
3055 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
3056 REJECT_CHECKPOINT, "checkpoint mismatch");
3058 // Don't accept any forks from the main chain prior to last checkpoint
3059 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
3060 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
3061 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
3064 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
3065 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
3066 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
3067 REJECT_OBSOLETE, "bad-version");
3069 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
3070 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
3071 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
3072 REJECT_OBSOLETE, "bad-version");
3074 // Reject block.nVersion=3 blocks when 95% (75% on testnet) of the network has upgraded:
3075 if (block.nVersion < 4 && IsSuperMajority(4, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
3076 return state.Invalid(error("%s : rejected nVersion=3 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 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
3102 CScript expect = CScript() << nHeight;
3103 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
3104 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
3105 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
3109 // Coinbase transaction must include an output sending 20% of
3110 // the block reward to `FOUNDERS_REWARD_SCRIPT` until the first
3111 // subsidy halving block, with exception to the genesis block.
3112 if ((nHeight > 0) && (nHeight < consensusParams.nSubsidyHalvingInterval)) {
3115 BOOST_FOREACH(const CTxOut& output, block.vtx[0].vout) {
3116 if (output.scriptPubKey == ParseHex(FOUNDERS_REWARD_SCRIPT)) {
3117 if (output.nValue == (GetBlockSubsidy(nHeight, consensusParams) / 5)) {
3125 return state.DoS(100, error("%s: founders reward missing", __func__), REJECT_INVALID, "cb-no-founders-reward");
3132 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
3134 const CChainParams& chainparams = Params();
3135 AssertLockHeld(cs_main);
3136 // Check for duplicate
3137 uint256 hash = block.GetHash();
3138 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
3139 CBlockIndex *pindex = NULL;
3140 if (miSelf != mapBlockIndex.end()) {
3141 // Block header is already known.
3142 pindex = miSelf->second;
3145 if (pindex->nStatus & BLOCK_FAILED_MASK)
3146 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
3150 if (!CheckBlockHeader(block, state))
3153 // Get prev block index
3154 CBlockIndex* pindexPrev = NULL;
3155 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
3156 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
3157 if (mi == mapBlockIndex.end())
3158 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
3159 pindexPrev = (*mi).second;
3160 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
3161 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
3164 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3168 pindex = AddToBlockIndex(block);
3176 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, bool fRequested, CDiskBlockPos* dbp)
3178 const CChainParams& chainparams = Params();
3179 AssertLockHeld(cs_main);
3181 CBlockIndex *&pindex = *ppindex;
3183 if (!AcceptBlockHeader(block, state, &pindex))
3186 // Try to process all requested blocks that we don't have, but only
3187 // process an unrequested block if it's new and has enough work to
3188 // advance our tip, and isn't too many blocks ahead.
3189 bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
3190 bool fHasMoreWork = (chainActive.Tip() ? pindex->nChainWork > chainActive.Tip()->nChainWork : true);
3191 // Blocks that are too out-of-order needlessly limit the effectiveness of
3192 // pruning, because pruning will not delete block files that contain any
3193 // blocks which are too close in height to the tip. Apply this test
3194 // regardless of whether pruning is enabled; it should generally be safe to
3195 // not process unrequested blocks.
3196 bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
3198 // TODO: deal better with return value and error conditions for duplicate
3199 // and unrequested blocks.
3200 if (fAlreadyHave) return true;
3201 if (!fRequested) { // If we didn't ask for it:
3202 if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
3203 if (!fHasMoreWork) return true; // Don't process less-work chains
3204 if (fTooFarAhead) return true; // Block height is too high
3207 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
3208 if (state.IsInvalid() && !state.CorruptionPossible()) {
3209 pindex->nStatus |= BLOCK_FAILED_VALID;
3210 setDirtyBlockIndex.insert(pindex);
3215 int nHeight = pindex->nHeight;
3217 // Write block to history file
3219 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3220 CDiskBlockPos blockPos;
3223 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
3224 return error("AcceptBlock(): FindBlockPos failed");
3226 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3227 AbortNode(state, "Failed to write block");
3228 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3229 return error("AcceptBlock(): ReceivedBlockTransactions failed");
3230 } catch (const std::runtime_error& e) {
3231 return AbortNode(state, std::string("System error: ") + e.what());
3234 if (fCheckForPruning)
3235 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
3240 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
3242 unsigned int nFound = 0;
3243 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
3245 if (pstart->nVersion >= minVersion)
3247 pstart = pstart->pprev;
3249 return (nFound >= nRequired);
3253 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp)
3255 // Preliminary checks
3256 bool checked = CheckBlock(*pblock, state);
3260 bool fRequested = MarkBlockAsReceived(pblock->GetHash());
3261 fRequested |= fForceProcessing;
3263 return error("%s: CheckBlock FAILED", __func__);
3267 CBlockIndex *pindex = NULL;
3268 bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp);
3269 if (pindex && pfrom) {
3270 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
3274 return error("%s: AcceptBlock FAILED", __func__);
3277 if (!ActivateBestChain(state, pblock))
3278 return error("%s: ActivateBestChain failed", __func__);
3283 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
3285 AssertLockHeld(cs_main);
3286 assert(pindexPrev == chainActive.Tip());
3288 CCoinsViewCache viewNew(pcoinsTip);
3289 CBlockIndex indexDummy(block);
3290 indexDummy.pprev = pindexPrev;
3291 indexDummy.nHeight = pindexPrev->nHeight + 1;
3293 // NOTE: CheckBlockHeader is called by CheckBlock
3294 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
3296 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
3298 if (!ContextualCheckBlock(block, state, pindexPrev))
3300 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
3302 assert(state.IsValid());
3308 * BLOCK PRUNING CODE
3311 /* Calculate the amount of disk space the block & undo files currently use */
3312 uint64_t CalculateCurrentUsage()
3314 uint64_t retval = 0;
3315 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
3316 retval += file.nSize + file.nUndoSize;
3321 /* Prune a block file (modify associated database entries)*/
3322 void PruneOneBlockFile(const int fileNumber)
3324 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
3325 CBlockIndex* pindex = it->second;
3326 if (pindex->nFile == fileNumber) {
3327 pindex->nStatus &= ~BLOCK_HAVE_DATA;
3328 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
3330 pindex->nDataPos = 0;
3331 pindex->nUndoPos = 0;
3332 setDirtyBlockIndex.insert(pindex);
3334 // Prune from mapBlocksUnlinked -- any block we prune would have
3335 // to be downloaded again in order to consider its chain, at which
3336 // point it would be considered as a candidate for
3337 // mapBlocksUnlinked or setBlockIndexCandidates.
3338 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
3339 while (range.first != range.second) {
3340 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
3342 if (it->second == pindex) {
3343 mapBlocksUnlinked.erase(it);
3349 vinfoBlockFile[fileNumber].SetNull();
3350 setDirtyFileInfo.insert(fileNumber);
3354 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3356 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3357 CDiskBlockPos pos(*it, 0);
3358 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3359 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3360 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3364 /* Calculate the block/rev files that should be deleted to remain under target*/
3365 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3367 LOCK2(cs_main, cs_LastBlockFile);
3368 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3371 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3375 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3376 uint64_t nCurrentUsage = CalculateCurrentUsage();
3377 // We don't check to prune until after we've allocated new space for files
3378 // So we should leave a buffer under our target to account for another allocation
3379 // before the next pruning.
3380 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3381 uint64_t nBytesToPrune;
3384 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3385 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3386 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3388 if (vinfoBlockFile[fileNumber].nSize == 0)
3391 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3394 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
3395 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3398 PruneOneBlockFile(fileNumber);
3399 // Queue up the files for removal
3400 setFilesToPrune.insert(fileNumber);
3401 nCurrentUsage -= nBytesToPrune;
3406 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3407 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3408 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3409 nLastBlockWeCanPrune, count);
3412 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3414 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3416 // Check for nMinDiskSpace bytes (currently 50MB)
3417 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3418 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3423 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3427 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3428 boost::filesystem::create_directories(path.parent_path());
3429 FILE* file = fopen(path.string().c_str(), "rb+");
3430 if (!file && !fReadOnly)
3431 file = fopen(path.string().c_str(), "wb+");
3433 LogPrintf("Unable to open file %s\n", path.string());
3437 if (fseek(file, pos.nPos, SEEK_SET)) {
3438 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3446 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3447 return OpenDiskFile(pos, "blk", fReadOnly);
3450 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3451 return OpenDiskFile(pos, "rev", fReadOnly);
3454 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3456 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3459 CBlockIndex * InsertBlockIndex(uint256 hash)
3465 BlockMap::iterator mi = mapBlockIndex.find(hash);
3466 if (mi != mapBlockIndex.end())
3467 return (*mi).second;
3470 CBlockIndex* pindexNew = new CBlockIndex();
3472 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3473 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3474 pindexNew->phashBlock = &((*mi).first);
3479 bool static LoadBlockIndexDB()
3481 const CChainParams& chainparams = Params();
3482 if (!pblocktree->LoadBlockIndexGuts())
3485 boost::this_thread::interruption_point();
3487 // Calculate nChainWork
3488 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3489 vSortedByHeight.reserve(mapBlockIndex.size());
3490 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3492 CBlockIndex* pindex = item.second;
3493 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3495 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3496 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3498 CBlockIndex* pindex = item.second;
3499 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3500 // We can link the chain of blocks for which we've received transactions at some point.
3501 // Pruned nodes may have deleted the block.
3502 if (pindex->nTx > 0) {
3503 if (pindex->pprev) {
3504 if (pindex->pprev->nChainTx) {
3505 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3507 pindex->nChainTx = 0;
3508 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3511 pindex->nChainTx = pindex->nTx;
3514 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3515 setBlockIndexCandidates.insert(pindex);
3516 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3517 pindexBestInvalid = pindex;
3519 pindex->BuildSkip();
3520 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3521 pindexBestHeader = pindex;
3524 // Load block file info
3525 pblocktree->ReadLastBlockFile(nLastBlockFile);
3526 vinfoBlockFile.resize(nLastBlockFile + 1);
3527 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3528 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3529 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3531 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3532 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3533 CBlockFileInfo info;
3534 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3535 vinfoBlockFile.push_back(info);
3541 // Check presence of blk files
3542 LogPrintf("Checking all blk files are present...\n");
3543 set<int> setBlkDataFiles;
3544 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3546 CBlockIndex* pindex = item.second;
3547 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3548 setBlkDataFiles.insert(pindex->nFile);
3551 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3553 CDiskBlockPos pos(*it, 0);
3554 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3559 // Check whether we have ever pruned block & undo files
3560 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3562 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3564 // Check whether we need to continue reindexing
3565 bool fReindexing = false;
3566 pblocktree->ReadReindexing(fReindexing);
3567 fReindex |= fReindexing;
3569 // Check whether we have a transaction index
3570 pblocktree->ReadFlag("txindex", fTxIndex);
3571 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3573 // Load pointer to end of best chain
3574 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3575 if (it == mapBlockIndex.end())
3577 chainActive.SetTip(it->second);
3579 PruneBlockIndexCandidates();
3581 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3582 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3583 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3584 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3589 CVerifyDB::CVerifyDB()
3591 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3594 CVerifyDB::~CVerifyDB()
3596 uiInterface.ShowProgress("", 100);
3599 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3602 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3605 // Verify blocks in the best chain
3606 if (nCheckDepth <= 0)
3607 nCheckDepth = 1000000000; // suffices until the year 19000
3608 if (nCheckDepth > chainActive.Height())
3609 nCheckDepth = chainActive.Height();
3610 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3611 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3612 CCoinsViewCache coins(coinsview);
3613 CBlockIndex* pindexState = chainActive.Tip();
3614 CBlockIndex* pindexFailure = NULL;
3615 int nGoodTransactions = 0;
3616 CValidationState state;
3617 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3619 boost::this_thread::interruption_point();
3620 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3621 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3624 // check level 0: read from disk
3625 if (!ReadBlockFromDisk(block, pindex))
3626 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3627 // check level 1: verify block validity
3628 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3629 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3630 // check level 2: verify undo validity
3631 if (nCheckLevel >= 2 && pindex) {
3633 CDiskBlockPos pos = pindex->GetUndoPos();
3634 if (!pos.IsNull()) {
3635 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3636 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3639 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3640 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3642 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3643 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3644 pindexState = pindex->pprev;
3646 nGoodTransactions = 0;
3647 pindexFailure = pindex;
3649 nGoodTransactions += block.vtx.size();
3651 if (ShutdownRequested())
3655 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3657 // check level 4: try reconnecting blocks
3658 if (nCheckLevel >= 4) {
3659 CBlockIndex *pindex = pindexState;
3660 while (pindex != chainActive.Tip()) {
3661 boost::this_thread::interruption_point();
3662 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3663 pindex = chainActive.Next(pindex);
3665 if (!ReadBlockFromDisk(block, pindex))
3666 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3667 if (!ConnectBlock(block, state, pindex, coins))
3668 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3672 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3677 void UnloadBlockIndex()
3680 setBlockIndexCandidates.clear();
3681 chainActive.SetTip(NULL);
3682 pindexBestInvalid = NULL;
3683 pindexBestHeader = NULL;
3685 mapOrphanTransactions.clear();
3686 mapOrphanTransactionsByPrev.clear();
3688 mapBlocksUnlinked.clear();
3689 vinfoBlockFile.clear();
3691 nBlockSequenceId = 1;
3692 mapBlockSource.clear();
3693 mapBlocksInFlight.clear();
3694 nQueuedValidatedHeaders = 0;
3695 nPreferredDownload = 0;
3696 setDirtyBlockIndex.clear();
3697 setDirtyFileInfo.clear();
3698 mapNodeState.clear();
3699 recentRejects.reset(NULL);
3701 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3702 delete entry.second;
3704 mapBlockIndex.clear();
3705 fHavePruned = false;
3708 bool LoadBlockIndex()
3710 // Load block index from databases
3711 if (!fReindex && !LoadBlockIndexDB())
3717 bool InitBlockIndex() {
3718 const CChainParams& chainparams = Params();
3721 // Initialize global variables that cannot be constructed at startup.
3722 recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
3724 // Check whether we're already initialized
3725 if (chainActive.Genesis() != NULL)
3728 // Use the provided setting for -txindex in the new database
3729 fTxIndex = GetBoolArg("-txindex", false);
3730 pblocktree->WriteFlag("txindex", fTxIndex);
3731 LogPrintf("Initializing databases...\n");
3733 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3736 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3737 // Start new block file
3738 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3739 CDiskBlockPos blockPos;
3740 CValidationState state;
3741 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3742 return error("LoadBlockIndex(): FindBlockPos failed");
3743 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3744 return error("LoadBlockIndex(): writing genesis block to disk failed");
3745 CBlockIndex *pindex = AddToBlockIndex(block);
3746 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3747 return error("LoadBlockIndex(): genesis block not accepted");
3748 if (!ActivateBestChain(state, &block))
3749 return error("LoadBlockIndex(): genesis block cannot be activated");
3750 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3751 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3752 } catch (const std::runtime_error& e) {
3753 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3762 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3764 const CChainParams& chainparams = Params();
3765 // Map of disk positions for blocks with unknown parent (only used for reindex)
3766 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3767 int64_t nStart = GetTimeMillis();
3771 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3772 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3773 uint64_t nRewind = blkdat.GetPos();
3774 while (!blkdat.eof()) {
3775 boost::this_thread::interruption_point();
3777 blkdat.SetPos(nRewind);
3778 nRewind++; // start one byte further next time, in case of failure
3779 blkdat.SetLimit(); // remove former limit
3780 unsigned int nSize = 0;
3783 unsigned char buf[MESSAGE_START_SIZE];
3784 blkdat.FindByte(Params().MessageStart()[0]);
3785 nRewind = blkdat.GetPos()+1;
3786 blkdat >> FLATDATA(buf);
3787 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3791 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3793 } catch (const std::exception&) {
3794 // no valid block header found; don't complain
3799 uint64_t nBlockPos = blkdat.GetPos();
3801 dbp->nPos = nBlockPos;
3802 blkdat.SetLimit(nBlockPos + nSize);
3803 blkdat.SetPos(nBlockPos);
3806 nRewind = blkdat.GetPos();
3808 // detect out of order blocks, and store them for later
3809 uint256 hash = block.GetHash();
3810 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3811 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3812 block.hashPrevBlock.ToString());
3814 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3818 // process in case the block isn't known yet
3819 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3820 CValidationState state;
3821 if (ProcessNewBlock(state, NULL, &block, true, dbp))
3823 if (state.IsError())
3825 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3826 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3829 // Recursively process earlier encountered successors of this block
3830 deque<uint256> queue;
3831 queue.push_back(hash);
3832 while (!queue.empty()) {
3833 uint256 head = queue.front();
3835 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3836 while (range.first != range.second) {
3837 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3838 if (ReadBlockFromDisk(block, it->second))
3840 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3842 CValidationState dummy;
3843 if (ProcessNewBlock(dummy, NULL, &block, true, &it->second))
3846 queue.push_back(block.GetHash());
3850 mapBlocksUnknownParent.erase(it);
3853 } catch (const std::exception& e) {
3854 LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
3857 } catch (const std::runtime_error& e) {
3858 AbortNode(std::string("System error: ") + e.what());
3861 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3865 void static CheckBlockIndex()
3867 const Consensus::Params& consensusParams = Params().GetConsensus();
3868 if (!fCheckBlockIndex) {
3874 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3875 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3876 // iterating the block tree require that chainActive has been initialized.)
3877 if (chainActive.Height() < 0) {
3878 assert(mapBlockIndex.size() <= 1);
3882 // Build forward-pointing map of the entire block tree.
3883 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3884 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3885 forward.insert(std::make_pair(it->second->pprev, it->second));
3888 assert(forward.size() == mapBlockIndex.size());
3890 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3891 CBlockIndex *pindex = rangeGenesis.first->second;
3892 rangeGenesis.first++;
3893 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3895 // Iterate over the entire block tree, using depth-first search.
3896 // Along the way, remember whether there are blocks on the path from genesis
3897 // block being explored which are the first to have certain properties.
3900 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3901 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3902 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3903 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3904 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3905 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3906 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3907 while (pindex != NULL) {
3909 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3910 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3911 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3912 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3913 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3914 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3915 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3917 // Begin: actual consistency checks.
3918 if (pindex->pprev == NULL) {
3919 // Genesis block checks.
3920 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3921 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3923 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3924 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3925 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3927 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3928 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3929 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3931 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3932 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3934 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3935 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3936 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3937 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3938 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3939 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3940 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.
3941 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3942 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3943 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3944 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3945 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3946 if (pindexFirstInvalid == NULL) {
3947 // Checks for not-invalid blocks.
3948 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3950 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3951 if (pindexFirstInvalid == NULL) {
3952 // If this block sorts at least as good as the current tip and
3953 // is valid and we have all data for its parents, it must be in
3954 // setBlockIndexCandidates. chainActive.Tip() must also be there
3955 // even if some data has been pruned.
3956 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3957 assert(setBlockIndexCandidates.count(pindex));
3959 // If some parent is missing, then it could be that this block was in
3960 // setBlockIndexCandidates but had to be removed because of the missing data.
3961 // In this case it must be in mapBlocksUnlinked -- see test below.
3963 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3964 assert(setBlockIndexCandidates.count(pindex) == 0);
3966 // Check whether this block is in mapBlocksUnlinked.
3967 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3968 bool foundInUnlinked = false;
3969 while (rangeUnlinked.first != rangeUnlinked.second) {
3970 assert(rangeUnlinked.first->first == pindex->pprev);
3971 if (rangeUnlinked.first->second == pindex) {
3972 foundInUnlinked = true;
3975 rangeUnlinked.first++;
3977 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3978 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3979 assert(foundInUnlinked);
3981 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3982 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3983 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3984 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3985 assert(fHavePruned); // We must have pruned.
3986 // This block may have entered mapBlocksUnlinked if:
3987 // - it has a descendant that at some point had more work than the
3989 // - we tried switching to that descendant but were missing
3990 // data for some intermediate block between chainActive and the
3992 // So if this block is itself better than chainActive.Tip() and it wasn't in
3993 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3994 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3995 if (pindexFirstInvalid == NULL) {
3996 assert(foundInUnlinked);
4000 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
4001 // End: actual consistency checks.
4003 // Try descending into the first subnode.
4004 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
4005 if (range.first != range.second) {
4006 // A subnode was found.
4007 pindex = range.first->second;
4011 // This is a leaf node.
4012 // Move upwards until we reach a node of which we have not yet visited the last child.
4014 // We are going to either move to a parent or a sibling of pindex.
4015 // If pindex was the first with a certain property, unset the corresponding variable.
4016 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
4017 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
4018 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
4019 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
4020 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
4021 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
4022 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
4024 CBlockIndex* pindexPar = pindex->pprev;
4025 // Find which child we just visited.
4026 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
4027 while (rangePar.first->second != pindex) {
4028 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
4031 // Proceed to the next one.
4033 if (rangePar.first != rangePar.second) {
4034 // Move to the sibling.
4035 pindex = rangePar.first->second;
4046 // Check that we actually traversed the entire map.
4047 assert(nNodes == forward.size());
4050 //////////////////////////////////////////////////////////////////////////////
4055 string GetWarnings(string strFor)
4058 string strStatusBar;
4061 if (!CLIENT_VERSION_IS_RELEASE)
4062 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
4064 if (GetBoolArg("-testsafemode", false))
4065 strStatusBar = strRPC = "testsafemode enabled";
4067 // Misc warnings like out of disk space and clock is wrong
4068 if (strMiscWarning != "")
4071 strStatusBar = strMiscWarning;
4074 if (fLargeWorkForkFound)
4077 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
4079 else if (fLargeWorkInvalidChainFound)
4082 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.");
4088 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4090 const CAlert& alert = item.second;
4091 if (alert.AppliesToMe() && alert.nPriority > nPriority)
4093 nPriority = alert.nPriority;
4094 strStatusBar = alert.strStatusBar;
4099 if (strFor == "statusbar")
4100 return strStatusBar;
4101 else if (strFor == "rpc")
4103 assert(!"GetWarnings(): invalid parameter");
4114 //////////////////////////////////////////////////////////////////////////////
4120 bool static AlreadyHave(const CInv& inv)
4126 assert(recentRejects);
4127 if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
4129 // If the chain tip has changed previously rejected transactions
4130 // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
4131 // or a double-spend. Reset the rejects filter and give those
4132 // txs a second chance.
4133 hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
4134 recentRejects->reset();
4137 return recentRejects->contains(inv.hash) ||
4138 mempool.exists(inv.hash) ||
4139 mapOrphanTransactions.count(inv.hash) ||
4140 pcoinsTip->HaveCoins(inv.hash);
4143 return mapBlockIndex.count(inv.hash);
4145 // Don't know what it is, just say we already got one
4149 void static ProcessGetData(CNode* pfrom)
4151 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
4153 vector<CInv> vNotFound;
4157 while (it != pfrom->vRecvGetData.end()) {
4158 // Don't bother if send buffer is too full to respond anyway
4159 if (pfrom->nSendSize >= SendBufferSize())
4162 const CInv &inv = *it;
4164 boost::this_thread::interruption_point();
4167 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4170 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
4171 if (mi != mapBlockIndex.end())
4173 if (chainActive.Contains(mi->second)) {
4176 static const int nOneMonth = 30 * 24 * 60 * 60;
4177 // To prevent fingerprinting attacks, only send blocks outside of the active
4178 // chain if they are valid, and no more than a month older (both in time, and in
4179 // best equivalent proof of work) than the best header chain we know about.
4180 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
4181 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
4182 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
4184 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
4188 // Pruned nodes may have deleted the block, so check whether
4189 // it's available before trying to send.
4190 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
4192 // Send block from disk
4194 if (!ReadBlockFromDisk(block, (*mi).second))
4195 assert(!"cannot load block from disk");
4196 if (inv.type == MSG_BLOCK)
4197 pfrom->PushMessage("block", block);
4198 else // MSG_FILTERED_BLOCK)
4200 LOCK(pfrom->cs_filter);
4203 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
4204 pfrom->PushMessage("merkleblock", merkleBlock);
4205 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
4206 // This avoids hurting performance by pointlessly requiring a round-trip
4207 // Note that there is currently no way for a node to request any single transactions we didn't send here -
4208 // they must either disconnect and retry or request the full block.
4209 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
4210 // however we MUST always provide at least what the remote peer needs
4211 typedef std::pair<unsigned int, uint256> PairType;
4212 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
4213 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
4214 pfrom->PushMessage("tx", block.vtx[pair.first]);
4220 // Trigger the peer node to send a getblocks request for the next batch of inventory
4221 if (inv.hash == pfrom->hashContinue)
4223 // Bypass PushInventory, this must send even if redundant,
4224 // and we want it right after the last block so they don't
4225 // wait for other stuff first.
4227 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
4228 pfrom->PushMessage("inv", vInv);
4229 pfrom->hashContinue.SetNull();
4233 else if (inv.IsKnownType())
4235 // Send stream from relay memory
4236 bool pushed = false;
4239 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
4240 if (mi != mapRelay.end()) {
4241 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
4245 if (!pushed && inv.type == MSG_TX) {
4247 if (mempool.lookup(inv.hash, tx)) {
4248 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
4251 pfrom->PushMessage("tx", ss);
4256 vNotFound.push_back(inv);
4260 // Track requests for our stuff.
4261 GetMainSignals().Inventory(inv.hash);
4263 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
4268 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
4270 if (!vNotFound.empty()) {
4271 // Let the peer know that we didn't find what it asked for, so it doesn't
4272 // have to wait around forever. Currently only SPV clients actually care
4273 // about this message: it's needed when they are recursively walking the
4274 // dependencies of relevant unconfirmed transactions. SPV clients want to
4275 // do that because they want to know about (and store and rebroadcast and
4276 // risk analyze) the dependencies of transactions relevant to them, without
4277 // having to download the entire memory pool.
4278 pfrom->PushMessage("notfound", vNotFound);
4282 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
4284 const CChainParams& chainparams = Params();
4285 RandAddSeedPerfmon();
4286 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
4287 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
4289 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
4296 if (strCommand == "version")
4298 // Each connection can only send one version message
4299 if (pfrom->nVersion != 0)
4301 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
4302 Misbehaving(pfrom->GetId(), 1);
4309 uint64_t nNonce = 1;
4310 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
4311 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
4313 // disconnect from peers older than this proto version
4314 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
4315 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
4316 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
4317 pfrom->fDisconnect = true;
4321 if (pfrom->nVersion == 10300)
4322 pfrom->nVersion = 300;
4324 vRecv >> addrFrom >> nNonce;
4325 if (!vRecv.empty()) {
4326 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
4327 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
4330 vRecv >> pfrom->nStartingHeight;
4332 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
4334 pfrom->fRelayTxes = true;
4336 // Disconnect if we connected to ourself
4337 if (nNonce == nLocalHostNonce && nNonce > 1)
4339 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
4340 pfrom->fDisconnect = true;
4344 pfrom->addrLocal = addrMe;
4345 if (pfrom->fInbound && addrMe.IsRoutable())
4350 // Be shy and don't send version until we hear
4351 if (pfrom->fInbound)
4352 pfrom->PushVersion();
4354 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
4356 // Potentially mark this peer as a preferred download peer.
4357 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
4360 pfrom->PushMessage("verack");
4361 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4363 if (!pfrom->fInbound)
4365 // Advertise our address
4366 if (fListen && !IsInitialBlockDownload())
4368 CAddress addr = GetLocalAddress(&pfrom->addr);
4369 if (addr.IsRoutable())
4371 pfrom->PushAddress(addr);
4372 } else if (IsPeerAddrLocalGood(pfrom)) {
4373 addr.SetIP(pfrom->addrLocal);
4374 pfrom->PushAddress(addr);
4378 // Get recent addresses
4379 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4381 pfrom->PushMessage("getaddr");
4382 pfrom->fGetAddr = true;
4384 addrman.Good(pfrom->addr);
4386 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4388 addrman.Add(addrFrom, addrFrom);
4389 addrman.Good(addrFrom);
4396 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4397 item.second.RelayTo(pfrom);
4400 pfrom->fSuccessfullyConnected = true;
4404 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4406 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4407 pfrom->cleanSubVer, pfrom->nVersion,
4408 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4411 int64_t nTimeOffset = nTime - GetTime();
4412 pfrom->nTimeOffset = nTimeOffset;
4413 AddTimeData(pfrom->addr, nTimeOffset);
4417 else if (pfrom->nVersion == 0)
4419 // Must have a version message before anything else
4420 Misbehaving(pfrom->GetId(), 1);
4425 else if (strCommand == "verack")
4427 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4429 // Mark this node as currently connected, so we update its timestamp later.
4430 if (pfrom->fNetworkNode) {
4432 State(pfrom->GetId())->fCurrentlyConnected = true;
4437 else if (strCommand == "addr")
4439 vector<CAddress> vAddr;
4442 // Don't want addr from older versions unless seeding
4443 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4445 if (vAddr.size() > 1000)
4447 Misbehaving(pfrom->GetId(), 20);
4448 return error("message addr size() = %u", vAddr.size());
4451 // Store the new addresses
4452 vector<CAddress> vAddrOk;
4453 int64_t nNow = GetAdjustedTime();
4454 int64_t nSince = nNow - 10 * 60;
4455 BOOST_FOREACH(CAddress& addr, vAddr)
4457 boost::this_thread::interruption_point();
4459 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4460 addr.nTime = nNow - 5 * 24 * 60 * 60;
4461 pfrom->AddAddressKnown(addr);
4462 bool fReachable = IsReachable(addr);
4463 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4465 // Relay to a limited number of other nodes
4468 // Use deterministic randomness to send to the same nodes for 24 hours
4469 // at a time so the addrKnowns of the chosen nodes prevent repeats
4470 static uint256 hashSalt;
4471 if (hashSalt.IsNull())
4472 hashSalt = GetRandHash();
4473 uint64_t hashAddr = addr.GetHash();
4474 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4475 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4476 multimap<uint256, CNode*> mapMix;
4477 BOOST_FOREACH(CNode* pnode, vNodes)
4479 if (pnode->nVersion < CADDR_TIME_VERSION)
4481 unsigned int nPointer;
4482 memcpy(&nPointer, &pnode, sizeof(nPointer));
4483 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4484 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4485 mapMix.insert(make_pair(hashKey, pnode));
4487 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4488 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4489 ((*mi).second)->PushAddress(addr);
4492 // Do not store addresses outside our network
4494 vAddrOk.push_back(addr);
4496 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4497 if (vAddr.size() < 1000)
4498 pfrom->fGetAddr = false;
4499 if (pfrom->fOneShot)
4500 pfrom->fDisconnect = true;
4504 else if (strCommand == "inv")
4508 if (vInv.size() > MAX_INV_SZ)
4510 Misbehaving(pfrom->GetId(), 20);
4511 return error("message inv size() = %u", vInv.size());
4516 std::vector<CInv> vToFetch;
4518 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4520 const CInv &inv = vInv[nInv];
4522 boost::this_thread::interruption_point();
4523 pfrom->AddInventoryKnown(inv);
4525 bool fAlreadyHave = AlreadyHave(inv);
4526 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4528 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4531 if (inv.type == MSG_BLOCK) {
4532 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4533 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4534 // First request the headers preceding the announced block. In the normal fully-synced
4535 // case where a new block is announced that succeeds the current tip (no reorganization),
4536 // there are no such headers.
4537 // Secondly, and only when we are close to being synced, we request the announced block directly,
4538 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4539 // time the block arrives, the header chain leading up to it is already validated. Not
4540 // doing this will result in the received block being rejected as an orphan in case it is
4541 // not a direct successor.
4542 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4543 CNodeState *nodestate = State(pfrom->GetId());
4544 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4545 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4546 vToFetch.push_back(inv);
4547 // Mark block as in flight already, even though the actual "getdata" message only goes out
4548 // later (within the same cs_main lock, though).
4549 MarkBlockAsInFlight(pfrom->GetId(), inv.hash, chainparams.GetConsensus());
4551 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4555 // Track requests for our stuff
4556 GetMainSignals().Inventory(inv.hash);
4558 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4559 Misbehaving(pfrom->GetId(), 50);
4560 return error("send buffer size() = %u", pfrom->nSendSize);
4564 if (!vToFetch.empty())
4565 pfrom->PushMessage("getdata", vToFetch);
4569 else if (strCommand == "getdata")
4573 if (vInv.size() > MAX_INV_SZ)
4575 Misbehaving(pfrom->GetId(), 20);
4576 return error("message getdata size() = %u", vInv.size());
4579 if (fDebug || (vInv.size() != 1))
4580 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4582 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4583 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4585 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4586 ProcessGetData(pfrom);
4590 else if (strCommand == "getblocks")
4592 CBlockLocator locator;
4594 vRecv >> locator >> hashStop;
4598 // Find the last block the caller has in the main chain
4599 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4601 // Send the rest of the chain
4603 pindex = chainActive.Next(pindex);
4605 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4606 for (; pindex; pindex = chainActive.Next(pindex))
4608 if (pindex->GetBlockHash() == hashStop)
4610 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4613 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4616 // When this block is requested, we'll send an inv that'll
4617 // trigger the peer to getblocks the next batch of inventory.
4618 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4619 pfrom->hashContinue = pindex->GetBlockHash();
4626 else if (strCommand == "getheaders")
4628 CBlockLocator locator;
4630 vRecv >> locator >> hashStop;
4634 if (IsInitialBlockDownload())
4637 CBlockIndex* pindex = NULL;
4638 if (locator.IsNull())
4640 // If locator is null, return the hashStop block
4641 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4642 if (mi == mapBlockIndex.end())
4644 pindex = (*mi).second;
4648 // Find the last block the caller has in the main chain
4649 pindex = FindForkInGlobalIndex(chainActive, locator);
4651 pindex = chainActive.Next(pindex);
4654 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4655 vector<CBlock> vHeaders;
4656 int nLimit = MAX_HEADERS_RESULTS;
4657 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4658 for (; pindex; pindex = chainActive.Next(pindex))
4660 vHeaders.push_back(pindex->GetBlockHeader());
4661 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4664 pfrom->PushMessage("headers", vHeaders);
4668 else if (strCommand == "tx")
4670 vector<uint256> vWorkQueue;
4671 vector<uint256> vEraseQueue;
4675 CInv inv(MSG_TX, tx.GetHash());
4676 pfrom->AddInventoryKnown(inv);
4680 bool fMissingInputs = false;
4681 CValidationState state;
4683 mapAlreadyAskedFor.erase(inv);
4685 // Check for recently rejected (and do other quick existence checks)
4686 if (AlreadyHave(inv))
4689 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4691 mempool.check(pcoinsTip);
4692 RelayTransaction(tx);
4693 vWorkQueue.push_back(inv.hash);
4695 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4696 pfrom->id, pfrom->cleanSubVer,
4697 tx.GetHash().ToString(),
4698 mempool.mapTx.size());
4700 // Recursively process any orphan transactions that depended on this one
4701 set<NodeId> setMisbehaving;
4702 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4704 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4705 if (itByPrev == mapOrphanTransactionsByPrev.end())
4707 for (set<uint256>::iterator mi = itByPrev->second.begin();
4708 mi != itByPrev->second.end();
4711 const uint256& orphanHash = *mi;
4712 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4713 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4714 bool fMissingInputs2 = false;
4715 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4716 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4717 // anyone relaying LegitTxX banned)
4718 CValidationState stateDummy;
4721 if (setMisbehaving.count(fromPeer))
4723 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4725 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4726 RelayTransaction(orphanTx);
4727 vWorkQueue.push_back(orphanHash);
4728 vEraseQueue.push_back(orphanHash);
4730 else if (!fMissingInputs2)
4733 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4735 // Punish peer that gave us an invalid orphan tx
4736 Misbehaving(fromPeer, nDos);
4737 setMisbehaving.insert(fromPeer);
4738 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4740 // Has inputs but not accepted to mempool
4741 // Probably non-standard or insufficient fee/priority
4742 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4743 vEraseQueue.push_back(orphanHash);
4744 assert(recentRejects);
4745 recentRejects->insert(orphanHash);
4747 mempool.check(pcoinsTip);
4751 BOOST_FOREACH(uint256 hash, vEraseQueue)
4752 EraseOrphanTx(hash);
4754 // TODO: currently, prohibit pours from entering mapOrphans
4755 else if (fMissingInputs && tx.vpour.size() == 0)
4757 AddOrphanTx(tx, pfrom->GetId());
4759 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4760 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4761 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4763 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4765 assert(recentRejects);
4766 recentRejects->insert(tx.GetHash());
4768 if (pfrom->fWhitelisted) {
4769 // Always relay transactions received from whitelisted peers, even
4770 // if they were rejected from the mempool, allowing the node to
4771 // function as a gateway for nodes hidden behind it.
4773 // FIXME: This includes invalid transactions, which means a
4774 // whitelisted peer could get us banned! We may want to change
4776 RelayTransaction(tx);
4780 if (state.IsInvalid(nDoS))
4782 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4783 pfrom->id, pfrom->cleanSubVer,
4784 state.GetRejectReason());
4785 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4786 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4788 Misbehaving(pfrom->GetId(), nDoS);
4793 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4795 std::vector<CBlockHeader> headers;
4797 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4798 unsigned int nCount = ReadCompactSize(vRecv);
4799 if (nCount > MAX_HEADERS_RESULTS) {
4800 Misbehaving(pfrom->GetId(), 20);
4801 return error("headers message size = %u", nCount);
4803 headers.resize(nCount);
4804 for (unsigned int n = 0; n < nCount; n++) {
4805 vRecv >> headers[n];
4806 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4812 // Nothing interesting. Stop asking this peers for more headers.
4816 CBlockIndex *pindexLast = NULL;
4817 BOOST_FOREACH(const CBlockHeader& header, headers) {
4818 CValidationState state;
4819 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4820 Misbehaving(pfrom->GetId(), 20);
4821 return error("non-continuous headers sequence");
4823 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4825 if (state.IsInvalid(nDoS)) {
4827 Misbehaving(pfrom->GetId(), nDoS);
4828 return error("invalid header received");
4834 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4836 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4837 // Headers message had its maximum size; the peer may have more headers.
4838 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4839 // from there instead.
4840 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4841 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4847 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4852 CInv inv(MSG_BLOCK, block.GetHash());
4853 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4855 pfrom->AddInventoryKnown(inv);
4857 CValidationState state;
4858 // Process all blocks from whitelisted peers, even if not requested,
4859 // unless we're still syncing with the network.
4860 // Such an unrequested block may still be processed, subject to the
4861 // conditions in AcceptBlock().
4862 bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
4863 ProcessNewBlock(state, pfrom, &block, forceProcessing, NULL);
4865 if (state.IsInvalid(nDoS)) {
4866 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4867 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4870 Misbehaving(pfrom->GetId(), nDoS);
4877 // This asymmetric behavior for inbound and outbound connections was introduced
4878 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4879 // to users' AddrMan and later request them by sending getaddr messages.
4880 // Making nodes which are behind NAT and can only make outgoing connections ignore
4881 // the getaddr message mitigates the attack.
4882 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4884 pfrom->vAddrToSend.clear();
4885 vector<CAddress> vAddr = addrman.GetAddr();
4886 BOOST_FOREACH(const CAddress &addr, vAddr)
4887 pfrom->PushAddress(addr);
4891 else if (strCommand == "mempool")
4893 LOCK2(cs_main, pfrom->cs_filter);
4895 std::vector<uint256> vtxid;
4896 mempool.queryHashes(vtxid);
4898 BOOST_FOREACH(uint256& hash, vtxid) {
4899 CInv inv(MSG_TX, hash);
4901 bool fInMemPool = mempool.lookup(hash, tx);
4902 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4903 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4905 vInv.push_back(inv);
4906 if (vInv.size() == MAX_INV_SZ) {
4907 pfrom->PushMessage("inv", vInv);
4911 if (vInv.size() > 0)
4912 pfrom->PushMessage("inv", vInv);
4916 else if (strCommand == "ping")
4918 if (pfrom->nVersion > BIP0031_VERSION)
4922 // Echo the message back with the nonce. This allows for two useful features:
4924 // 1) A remote node can quickly check if the connection is operational
4925 // 2) Remote nodes can measure the latency of the network thread. If this node
4926 // is overloaded it won't respond to pings quickly and the remote node can
4927 // avoid sending us more work, like chain download requests.
4929 // The nonce stops the remote getting confused between different pings: without
4930 // it, if the remote node sends a ping once per second and this node takes 5
4931 // seconds to respond to each, the 5th ping the remote sends would appear to
4932 // return very quickly.
4933 pfrom->PushMessage("pong", nonce);
4938 else if (strCommand == "pong")
4940 int64_t pingUsecEnd = nTimeReceived;
4942 size_t nAvail = vRecv.in_avail();
4943 bool bPingFinished = false;
4944 std::string sProblem;
4946 if (nAvail >= sizeof(nonce)) {
4949 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4950 if (pfrom->nPingNonceSent != 0) {
4951 if (nonce == pfrom->nPingNonceSent) {
4952 // Matching pong received, this ping is no longer outstanding
4953 bPingFinished = true;
4954 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4955 if (pingUsecTime > 0) {
4956 // Successful ping time measurement, replace previous
4957 pfrom->nPingUsecTime = pingUsecTime;
4959 // This should never happen
4960 sProblem = "Timing mishap";
4963 // Nonce mismatches are normal when pings are overlapping
4964 sProblem = "Nonce mismatch";
4966 // This is most likely a bug in another implementation somewhere; cancel this ping
4967 bPingFinished = true;
4968 sProblem = "Nonce zero";
4972 sProblem = "Unsolicited pong without ping";
4975 // This is most likely a bug in another implementation somewhere; cancel this ping
4976 bPingFinished = true;
4977 sProblem = "Short payload";
4980 if (!(sProblem.empty())) {
4981 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4985 pfrom->nPingNonceSent,
4989 if (bPingFinished) {
4990 pfrom->nPingNonceSent = 0;
4995 else if (fAlerts && strCommand == "alert")
5000 uint256 alertHash = alert.GetHash();
5001 if (pfrom->setKnown.count(alertHash) == 0)
5003 if (alert.ProcessAlert(Params().AlertKey()))
5006 pfrom->setKnown.insert(alertHash);
5009 BOOST_FOREACH(CNode* pnode, vNodes)
5010 alert.RelayTo(pnode);
5014 // Small DoS penalty so peers that send us lots of
5015 // duplicate/expired/invalid-signature/whatever alerts
5016 // eventually get banned.
5017 // This isn't a Misbehaving(100) (immediate ban) because the
5018 // peer might be an older or different implementation with
5019 // a different signature key, etc.
5020 Misbehaving(pfrom->GetId(), 10);
5026 else if (strCommand == "filterload")
5028 CBloomFilter filter;
5031 if (!filter.IsWithinSizeConstraints())
5032 // There is no excuse for sending a too-large filter
5033 Misbehaving(pfrom->GetId(), 100);
5036 LOCK(pfrom->cs_filter);
5037 delete pfrom->pfilter;
5038 pfrom->pfilter = new CBloomFilter(filter);
5039 pfrom->pfilter->UpdateEmptyFull();
5041 pfrom->fRelayTxes = true;
5045 else if (strCommand == "filteradd")
5047 vector<unsigned char> vData;
5050 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
5051 // and thus, the maximum size any matched object can have) in a filteradd message
5052 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
5054 Misbehaving(pfrom->GetId(), 100);
5056 LOCK(pfrom->cs_filter);
5058 pfrom->pfilter->insert(vData);
5060 Misbehaving(pfrom->GetId(), 100);
5065 else if (strCommand == "filterclear")
5067 LOCK(pfrom->cs_filter);
5068 delete pfrom->pfilter;
5069 pfrom->pfilter = new CBloomFilter();
5070 pfrom->fRelayTxes = true;
5074 else if (strCommand == "reject")
5078 string strMsg; unsigned char ccode; string strReason;
5079 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
5082 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
5084 if (strMsg == "block" || strMsg == "tx")
5088 ss << ": hash " << hash.ToString();
5090 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
5091 } catch (const std::ios_base::failure&) {
5092 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
5093 LogPrint("net", "Unparseable reject message received\n");
5100 // Ignore unknown commands for extensibility
5101 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
5109 // requires LOCK(cs_vRecvMsg)
5110 bool ProcessMessages(CNode* pfrom)
5113 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
5117 // (4) message start
5125 if (!pfrom->vRecvGetData.empty())
5126 ProcessGetData(pfrom);
5128 // this maintains the order of responses
5129 if (!pfrom->vRecvGetData.empty()) return fOk;
5131 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
5132 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
5133 // Don't bother if send buffer is too full to respond anyway
5134 if (pfrom->nSendSize >= SendBufferSize())
5138 CNetMessage& msg = *it;
5141 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
5142 // msg.hdr.nMessageSize, msg.vRecv.size(),
5143 // msg.complete() ? "Y" : "N");
5145 // end, if an incomplete message is found
5146 if (!msg.complete())
5149 // at this point, any failure means we can delete the current message
5152 // Scan for message start
5153 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
5154 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
5160 CMessageHeader& hdr = msg.hdr;
5161 if (!hdr.IsValid(Params().MessageStart()))
5163 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
5166 string strCommand = hdr.GetCommand();
5169 unsigned int nMessageSize = hdr.nMessageSize;
5172 CDataStream& vRecv = msg.vRecv;
5173 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
5174 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
5175 if (nChecksum != hdr.nChecksum)
5177 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
5178 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
5186 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
5187 boost::this_thread::interruption_point();
5189 catch (const std::ios_base::failure& e)
5191 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
5192 if (strstr(e.what(), "end of data"))
5194 // Allow exceptions from under-length message on vRecv
5195 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());
5197 else if (strstr(e.what(), "size too large"))
5199 // Allow exceptions from over-long size
5200 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
5204 PrintExceptionContinue(&e, "ProcessMessages()");
5207 catch (const boost::thread_interrupted&) {
5210 catch (const std::exception& e) {
5211 PrintExceptionContinue(&e, "ProcessMessages()");
5213 PrintExceptionContinue(NULL, "ProcessMessages()");
5217 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
5222 // In case the connection got shut down, its receive buffer was wiped
5223 if (!pfrom->fDisconnect)
5224 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
5230 bool SendMessages(CNode* pto, bool fSendTrickle)
5232 const Consensus::Params& consensusParams = Params().GetConsensus();
5234 // Don't send anything until we get its version message
5235 if (pto->nVersion == 0)
5241 bool pingSend = false;
5242 if (pto->fPingQueued) {
5243 // RPC ping request by user
5246 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
5247 // Ping automatically sent as a latency probe & keepalive.
5252 while (nonce == 0) {
5253 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
5255 pto->fPingQueued = false;
5256 pto->nPingUsecStart = GetTimeMicros();
5257 if (pto->nVersion > BIP0031_VERSION) {
5258 pto->nPingNonceSent = nonce;
5259 pto->PushMessage("ping", nonce);
5261 // Peer is too old to support ping command with nonce, pong will never arrive.
5262 pto->nPingNonceSent = 0;
5263 pto->PushMessage("ping");
5267 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
5271 // Address refresh broadcast
5272 static int64_t nLastRebroadcast;
5273 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
5276 BOOST_FOREACH(CNode* pnode, vNodes)
5278 // Periodically clear addrKnown to allow refresh broadcasts
5279 if (nLastRebroadcast)
5280 pnode->addrKnown.reset();
5282 // Rebroadcast our address
5283 AdvertizeLocal(pnode);
5285 if (!vNodes.empty())
5286 nLastRebroadcast = GetTime();
5294 vector<CAddress> vAddr;
5295 vAddr.reserve(pto->vAddrToSend.size());
5296 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
5298 if (!pto->addrKnown.contains(addr.GetKey()))
5300 pto->addrKnown.insert(addr.GetKey());
5301 vAddr.push_back(addr);
5302 // receiver rejects addr messages larger than 1000
5303 if (vAddr.size() >= 1000)
5305 pto->PushMessage("addr", vAddr);
5310 pto->vAddrToSend.clear();
5312 pto->PushMessage("addr", vAddr);
5315 CNodeState &state = *State(pto->GetId());
5316 if (state.fShouldBan) {
5317 if (pto->fWhitelisted)
5318 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
5320 pto->fDisconnect = true;
5321 if (pto->addr.IsLocal())
5322 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
5325 CNode::Ban(pto->addr);
5328 state.fShouldBan = false;
5331 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
5332 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
5333 state.rejects.clear();
5336 if (pindexBestHeader == NULL)
5337 pindexBestHeader = chainActive.Tip();
5338 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.
5339 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
5340 // Only actively request headers from a single peer, unless we're close to today.
5341 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
5342 state.fSyncStarted = true;
5344 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
5345 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
5346 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
5350 // Resend wallet transactions that haven't gotten in a block yet
5351 // Except during reindex, importing and IBD, when old wallet
5352 // transactions become unconfirmed and spams other nodes.
5353 if (!fReindex && !fImporting && !IsInitialBlockDownload())
5355 GetMainSignals().Broadcast(nTimeBestReceived);
5359 // Message: inventory
5362 vector<CInv> vInvWait;
5364 LOCK(pto->cs_inventory);
5365 vInv.reserve(pto->vInventoryToSend.size());
5366 vInvWait.reserve(pto->vInventoryToSend.size());
5367 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
5369 if (pto->setInventoryKnown.count(inv))
5372 // trickle out tx inv to protect privacy
5373 if (inv.type == MSG_TX && !fSendTrickle)
5375 // 1/4 of tx invs blast to all immediately
5376 static uint256 hashSalt;
5377 if (hashSalt.IsNull())
5378 hashSalt = GetRandHash();
5379 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
5380 hashRand = Hash(BEGIN(hashRand), END(hashRand));
5381 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
5385 vInvWait.push_back(inv);
5390 // returns true if wasn't already contained in the set
5391 if (pto->setInventoryKnown.insert(inv).second)
5393 vInv.push_back(inv);
5394 if (vInv.size() >= 1000)
5396 pto->PushMessage("inv", vInv);
5401 pto->vInventoryToSend = vInvWait;
5404 pto->PushMessage("inv", vInv);
5406 // Detect whether we're stalling
5407 int64_t nNow = GetTimeMicros();
5408 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5409 // Stalling only triggers when the block download window cannot move. During normal steady state,
5410 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5411 // should only happen during initial block download.
5412 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5413 pto->fDisconnect = true;
5415 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5416 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5417 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5418 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5419 // to unreasonably increase our timeout.
5420 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5421 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5422 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5423 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5424 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5425 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5426 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5427 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders, consensusParams);
5428 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5429 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5430 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5432 if (queuedBlock.nTimeDisconnect < nNow) {
5433 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5434 pto->fDisconnect = true;
5439 // Message: getdata (blocks)
5441 vector<CInv> vGetData;
5442 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5443 vector<CBlockIndex*> vToDownload;
5444 NodeId staller = -1;
5445 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5446 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5447 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5448 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
5449 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5450 pindex->nHeight, pto->id);
5452 if (state.nBlocksInFlight == 0 && staller != -1) {
5453 if (State(staller)->nStallingSince == 0) {
5454 State(staller)->nStallingSince = nNow;
5455 LogPrint("net", "Stall started peer=%d\n", staller);
5461 // Message: getdata (non-blocks)
5463 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5465 const CInv& inv = (*pto->mapAskFor.begin()).second;
5466 if (!AlreadyHave(inv))
5469 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5470 vGetData.push_back(inv);
5471 if (vGetData.size() >= 1000)
5473 pto->PushMessage("getdata", vGetData);
5477 pto->mapAskFor.erase(pto->mapAskFor.begin());
5479 if (!vGetData.empty())
5480 pto->PushMessage("getdata", vGetData);
5486 std::string CBlockFileInfo::ToString() const {
5487 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));
5498 BlockMap::iterator it1 = mapBlockIndex.begin();
5499 for (; it1 != mapBlockIndex.end(); it1++)
5500 delete (*it1).second;
5501 mapBlockIndex.clear();
5503 // orphan transactions
5504 mapOrphanTransactions.clear();
5505 mapOrphanTransactionsByPrev.clear();
5507 } instance_of_cmaincleanup;