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.
10 #include "arith_uint256.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "consensus/validation.h"
16 #include "merkleblock.h"
20 #include "txmempool.h"
21 #include "ui_interface.h"
24 #include "utilmoneystr.h"
25 #include "validationinterface.h"
29 #include <boost/algorithm/string/replace.hpp>
30 #include <boost/filesystem.hpp>
31 #include <boost/filesystem/fstream.hpp>
32 #include <boost/math/distributions/poisson.hpp>
33 #include <boost/thread.hpp>
38 # error "Bitcoin cannot be compiled without assertions."
45 CCriticalSection cs_main;
47 BlockMap mapBlockIndex;
49 CBlockIndex *pindexBestHeader = NULL;
50 int64_t nTimeBestReceived = 0;
51 CWaitableCriticalSection csBestBlock;
52 CConditionVariable cvBlockChange;
53 int nScriptCheckThreads = 0;
54 bool fImporting = false;
55 bool fReindex = false;
56 bool fTxIndex = false;
57 bool fHavePruned = false;
58 bool fPruneMode = false;
59 bool fIsBareMultisigStd = true;
60 bool fCheckBlockIndex = false;
61 bool fCheckpointsEnabled = true;
62 size_t nCoinCacheUsage = 5000 * 300;
63 uint64_t nPruneTarget = 0;
65 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
66 CFeeRate minRelayTxFee = CFeeRate(1000);
68 CTxMemPool mempool(::minRelayTxFee);
74 map<uint256, COrphanTx> mapOrphanTransactions;
75 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
76 void EraseOrphansFor(NodeId peer);
79 * Returns true if there are nRequired or more blocks of minVersion or above
80 * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
82 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
83 static void CheckBlockIndex();
85 /** Constant stuff for coinbase transactions we create: */
86 CScript COINBASE_FLAGS;
88 const string strMessageMagic = "Bitcoin Signed Message:\n";
93 struct CBlockIndexWorkComparator
95 bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
96 // First sort by most total work, ...
97 if (pa->nChainWork > pb->nChainWork) return false;
98 if (pa->nChainWork < pb->nChainWork) return true;
100 // ... then by earliest time received, ...
101 if (pa->nSequenceId < pb->nSequenceId) return false;
102 if (pa->nSequenceId > pb->nSequenceId) return true;
104 // Use pointer address as tie breaker (should only happen with blocks
105 // loaded from disk, as those all have id 0).
106 if (pa < pb) return false;
107 if (pa > pb) return true;
114 CBlockIndex *pindexBestInvalid;
117 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
118 * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
119 * missing the data for the block.
121 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
122 /** Number of nodes with fSyncStarted. */
123 int nSyncStarted = 0;
124 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
125 * Pruned nodes may have entries where B is missing data.
127 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
129 CCriticalSection cs_LastBlockFile;
130 std::vector<CBlockFileInfo> vinfoBlockFile;
131 int nLastBlockFile = 0;
132 /** Global flag to indicate we should check to see if there are
133 * block/undo files that should be deleted. Set on startup
134 * or if we allocate more file space when we're in prune mode
136 bool fCheckForPruning = false;
139 * Every received block is assigned a unique and increasing identifier, so we
140 * know which one to give priority in case of a fork.
142 CCriticalSection cs_nBlockSequenceId;
143 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
144 uint32_t nBlockSequenceId = 1;
147 * Sources of received blocks, saved to be able to send them reject
148 * messages or ban them when processing happens afterwards. Protected by
151 map<uint256, NodeId> mapBlockSource;
153 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
156 CBlockIndex *pindex; //! Optional.
157 int64_t nTime; //! Time of "getdata" request in microseconds.
158 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
159 int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
161 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
163 /** Number of blocks in flight with validated headers. */
164 int nQueuedValidatedHeaders = 0;
166 /** Number of preferable block download peers. */
167 int nPreferredDownload = 0;
169 /** Dirty block index entries. */
170 set<CBlockIndex*> setDirtyBlockIndex;
172 /** Dirty block file entries. */
173 set<int> setDirtyFileInfo;
176 //////////////////////////////////////////////////////////////////////////////
178 // Registration of network node signals.
183 struct CBlockReject {
184 unsigned char chRejectCode;
185 string strRejectReason;
190 * Maintain validation-specific state about nodes, protected by cs_main, instead
191 * by CNode's own locks. This simplifies asynchronous operation, where
192 * processing of incoming data is done after the ProcessMessage call returns,
193 * and we're no longer holding the node's locks.
196 //! The peer's address
198 //! Whether we have a fully established connection.
199 bool fCurrentlyConnected;
200 //! Accumulated misbehaviour score for this peer.
202 //! Whether this peer should be disconnected and banned (unless whitelisted).
204 //! String name of this peer (debugging/logging purposes).
206 //! List of asynchronously-determined block rejections to notify this peer about.
207 std::vector<CBlockReject> rejects;
208 //! The best known block we know this peer has announced.
209 CBlockIndex *pindexBestKnownBlock;
210 //! The hash of the last unknown block this peer has announced.
211 uint256 hashLastUnknownBlock;
212 //! The last full block we both have.
213 CBlockIndex *pindexLastCommonBlock;
214 //! Whether we've started headers synchronization with this peer.
216 //! Since when we're stalling block download progress (in microseconds), or 0.
217 int64_t nStallingSince;
218 list<QueuedBlock> vBlocksInFlight;
220 int nBlocksInFlightValidHeaders;
221 //! Whether we consider this a preferred download peer.
222 bool fPreferredDownload;
225 fCurrentlyConnected = false;
228 pindexBestKnownBlock = NULL;
229 hashLastUnknownBlock.SetNull();
230 pindexLastCommonBlock = NULL;
231 fSyncStarted = false;
234 nBlocksInFlightValidHeaders = 0;
235 fPreferredDownload = false;
239 /** Map maintaining per-node state. Requires cs_main. */
240 map<NodeId, CNodeState> mapNodeState;
243 CNodeState *State(NodeId pnode) {
244 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
245 if (it == mapNodeState.end())
253 return chainActive.Height();
256 void UpdatePreferredDownload(CNode* node, CNodeState* state)
258 nPreferredDownload -= state->fPreferredDownload;
260 // Whether this node should be marked as a preferred download node.
261 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
263 nPreferredDownload += state->fPreferredDownload;
266 // Returns time at which to timeout block request (nTime in microseconds)
267 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore)
269 return nTime + 500000 * Params().GetConsensus().nPowTargetSpacing * (4 + nValidatedQueuedBefore);
272 void InitializeNode(NodeId nodeid, const CNode *pnode) {
274 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
275 state.name = pnode->addrName;
276 state.address = pnode->addr;
279 void FinalizeNode(NodeId nodeid) {
281 CNodeState *state = State(nodeid);
283 if (state->fSyncStarted)
286 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
287 AddressCurrentlyConnected(state->address);
290 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
291 mapBlocksInFlight.erase(entry.hash);
292 EraseOrphansFor(nodeid);
293 nPreferredDownload -= state->fPreferredDownload;
295 mapNodeState.erase(nodeid);
299 void MarkBlockAsReceived(const uint256& hash) {
300 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
301 if (itInFlight != mapBlocksInFlight.end()) {
302 CNodeState *state = State(itInFlight->second.first);
303 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
304 state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
305 state->vBlocksInFlight.erase(itInFlight->second.second);
306 state->nBlocksInFlight--;
307 state->nStallingSince = 0;
308 mapBlocksInFlight.erase(itInFlight);
313 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
314 CNodeState *state = State(nodeid);
315 assert(state != NULL);
317 // Make sure it's not listed somewhere already.
318 MarkBlockAsReceived(hash);
320 int64_t nNow = GetTimeMicros();
321 QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders)};
322 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
323 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
324 state->nBlocksInFlight++;
325 state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
326 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
329 /** Check whether the last unknown block a peer advertized is not yet known. */
330 void ProcessBlockAvailability(NodeId nodeid) {
331 CNodeState *state = State(nodeid);
332 assert(state != NULL);
334 if (!state->hashLastUnknownBlock.IsNull()) {
335 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
336 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
337 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
338 state->pindexBestKnownBlock = itOld->second;
339 state->hashLastUnknownBlock.SetNull();
344 /** Update tracking information about which blocks a peer is assumed to have. */
345 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
346 CNodeState *state = State(nodeid);
347 assert(state != NULL);
349 ProcessBlockAvailability(nodeid);
351 BlockMap::iterator it = mapBlockIndex.find(hash);
352 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
353 // An actually better block was announced.
354 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
355 state->pindexBestKnownBlock = it->second;
357 // An unknown block was announced; just assume that the latest one is the best one.
358 state->hashLastUnknownBlock = hash;
362 /** Find the last common ancestor two blocks have.
363 * Both pa and pb must be non-NULL. */
364 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
365 if (pa->nHeight > pb->nHeight) {
366 pa = pa->GetAncestor(pb->nHeight);
367 } else if (pb->nHeight > pa->nHeight) {
368 pb = pb->GetAncestor(pa->nHeight);
371 while (pa != pb && pa && pb) {
376 // Eventually all chain branches meet at the genesis block.
381 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
382 * at most count entries. */
383 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
387 vBlocks.reserve(vBlocks.size() + count);
388 CNodeState *state = State(nodeid);
389 assert(state != NULL);
391 // Make sure pindexBestKnownBlock is up to date, we'll need it.
392 ProcessBlockAvailability(nodeid);
394 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
395 // This peer has nothing interesting.
399 if (state->pindexLastCommonBlock == NULL) {
400 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
401 // Guessing wrong in either direction is not a problem.
402 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
405 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
406 // of its current tip anymore. Go back enough to fix that.
407 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
408 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
411 std::vector<CBlockIndex*> vToFetch;
412 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
413 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
414 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
415 // download that next block if the window were 1 larger.
416 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
417 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
418 NodeId waitingfor = -1;
419 while (pindexWalk->nHeight < nMaxHeight) {
420 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
421 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
422 // as iterating over ~100 CBlockIndex* entries anyway.
423 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
424 vToFetch.resize(nToFetch);
425 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
426 vToFetch[nToFetch - 1] = pindexWalk;
427 for (unsigned int i = nToFetch - 1; i > 0; i--) {
428 vToFetch[i - 1] = vToFetch[i]->pprev;
431 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
432 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
433 // pindexLastCommonBlock as long as all ancestors are already downloaded.
434 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
435 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
436 // We consider the chain that this peer is on invalid.
439 if (pindex->nStatus & BLOCK_HAVE_DATA) {
440 if (pindex->nChainTx)
441 state->pindexLastCommonBlock = pindex;
442 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
443 // The block is not already downloaded, and not yet in flight.
444 if (pindex->nHeight > nWindowEnd) {
445 // We reached the end of the window.
446 if (vBlocks.size() == 0 && waitingfor != nodeid) {
447 // We aren't able to fetch anything, but we would be if the download window was one larger.
448 nodeStaller = waitingfor;
452 vBlocks.push_back(pindex);
453 if (vBlocks.size() == count) {
456 } else if (waitingfor == -1) {
457 // This is the first already-in-flight block.
458 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
466 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
468 CNodeState *state = State(nodeid);
471 stats.nMisbehavior = state->nMisbehavior;
472 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
473 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
474 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
476 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
481 void RegisterNodeSignals(CNodeSignals& nodeSignals)
483 nodeSignals.GetHeight.connect(&GetHeight);
484 nodeSignals.ProcessMessages.connect(&ProcessMessages);
485 nodeSignals.SendMessages.connect(&SendMessages);
486 nodeSignals.InitializeNode.connect(&InitializeNode);
487 nodeSignals.FinalizeNode.connect(&FinalizeNode);
490 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
492 nodeSignals.GetHeight.disconnect(&GetHeight);
493 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
494 nodeSignals.SendMessages.disconnect(&SendMessages);
495 nodeSignals.InitializeNode.disconnect(&InitializeNode);
496 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
499 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
501 // Find the first block the caller has in the main chain
502 BOOST_FOREACH(const uint256& hash, locator.vHave) {
503 BlockMap::iterator mi = mapBlockIndex.find(hash);
504 if (mi != mapBlockIndex.end())
506 CBlockIndex* pindex = (*mi).second;
507 if (chain.Contains(pindex))
511 return chain.Genesis();
514 CCoinsViewCache *pcoinsTip = NULL;
515 CBlockTreeDB *pblocktree = NULL;
517 //////////////////////////////////////////////////////////////////////////////
519 // mapOrphanTransactions
522 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
524 uint256 hash = tx.GetHash();
525 if (mapOrphanTransactions.count(hash))
528 // Ignore big transactions, to avoid a
529 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
530 // large transaction with a missing parent then we assume
531 // it will rebroadcast it later, after the parent transaction(s)
532 // have been mined or received.
533 // 10,000 orphans, each of which is at most 5,000 bytes big is
534 // at most 500 megabytes of orphans:
535 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
538 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
542 mapOrphanTransactions[hash].tx = tx;
543 mapOrphanTransactions[hash].fromPeer = peer;
544 BOOST_FOREACH(const CTxIn& txin, tx.vin)
545 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
547 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
548 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
552 void static EraseOrphanTx(uint256 hash)
554 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
555 if (it == mapOrphanTransactions.end())
557 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
559 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
560 if (itPrev == mapOrphanTransactionsByPrev.end())
562 itPrev->second.erase(hash);
563 if (itPrev->second.empty())
564 mapOrphanTransactionsByPrev.erase(itPrev);
566 mapOrphanTransactions.erase(it);
569 void EraseOrphansFor(NodeId peer)
572 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
573 while (iter != mapOrphanTransactions.end())
575 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
576 if (maybeErase->second.fromPeer == peer)
578 EraseOrphanTx(maybeErase->second.tx.GetHash());
582 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
586 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
588 unsigned int nEvicted = 0;
589 while (mapOrphanTransactions.size() > nMaxOrphans)
591 // Evict a random orphan:
592 uint256 randomhash = GetRandHash();
593 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
594 if (it == mapOrphanTransactions.end())
595 it = mapOrphanTransactions.begin();
596 EraseOrphanTx(it->first);
608 bool IsStandardTx(const CTransaction& tx, string& reason)
610 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
615 // Extremely large transactions with lots of inputs can cost the network
616 // almost as much to process as they cost the sender in fees, because
617 // computing signature hashes is O(ninputs*txsize). Limiting transactions
618 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
619 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
620 if (sz >= MAX_STANDARD_TX_SIZE) {
625 BOOST_FOREACH(const CTxIn& txin, tx.vin)
627 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
628 // keys. (remember the 520 byte limit on redeemScript size) That works
629 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
630 // bytes of scriptSig, which we round off to 1650 bytes for some minor
631 // future-proofing. That's also enough to spend a 20-of-20
632 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
633 // considered standard)
634 if (txin.scriptSig.size() > 1650) {
635 reason = "scriptsig-size";
638 if (!txin.scriptSig.IsPushOnly()) {
639 reason = "scriptsig-not-pushonly";
644 unsigned int nDataOut = 0;
645 txnouttype whichType;
646 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
647 if (!::IsStandard(txout.scriptPubKey, whichType)) {
648 reason = "scriptpubkey";
652 if (whichType == TX_NULL_DATA)
654 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
655 reason = "bare-multisig";
657 } else if (txout.IsDust(::minRelayTxFee)) {
663 // only one OP_RETURN txout is permitted
665 reason = "multi-op-return";
672 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
674 AssertLockHeld(cs_main);
675 // Time based nLockTime implemented in 0.1.6
676 if (tx.nLockTime == 0)
678 if (nBlockHeight == 0)
679 nBlockHeight = chainActive.Height();
681 nBlockTime = GetAdjustedTime();
682 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
684 BOOST_FOREACH(const CTxIn& txin, tx.vin)
691 * Check transaction inputs to mitigate two
692 * potential denial-of-service attacks:
694 * 1. scriptSigs with extra data stuffed into them,
695 * not consumed by scriptPubKey (or P2SH script)
696 * 2. P2SH scripts with a crazy number of expensive
697 * CHECKSIG/CHECKMULTISIG operations
699 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
702 return true; // Coinbases don't use vin normally
704 for (unsigned int i = 0; i < tx.vin.size(); i++)
706 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
708 vector<vector<unsigned char> > vSolutions;
709 txnouttype whichType;
710 // get the scriptPubKey corresponding to this input:
711 const CScript& prevScript = prev.scriptPubKey;
712 if (!Solver(prevScript, whichType, vSolutions))
714 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
715 if (nArgsExpected < 0)
718 // Transactions with extra stuff in their scriptSigs are
719 // non-standard. Note that this EvalScript() call will
720 // be quick, because if there are any operations
721 // beside "push data" in the scriptSig
722 // IsStandardTx() will have already returned false
723 // and this method isn't called.
724 vector<vector<unsigned char> > stack;
725 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
728 if (whichType == TX_SCRIPTHASH)
732 CScript subscript(stack.back().begin(), stack.back().end());
733 vector<vector<unsigned char> > vSolutions2;
734 txnouttype whichType2;
735 if (Solver(subscript, whichType2, vSolutions2))
737 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
740 nArgsExpected += tmpExpected;
744 // Any other Script with less than 15 sigops OK:
745 unsigned int sigops = subscript.GetSigOpCount(true);
746 // ... extra data left on the stack after execution is OK, too:
747 return (sigops <= MAX_P2SH_SIGOPS);
751 if (stack.size() != (unsigned int)nArgsExpected)
758 unsigned int GetLegacySigOpCount(const CTransaction& tx)
760 unsigned int nSigOps = 0;
761 BOOST_FOREACH(const CTxIn& txin, tx.vin)
763 nSigOps += txin.scriptSig.GetSigOpCount(false);
765 BOOST_FOREACH(const CTxOut& txout, tx.vout)
767 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
772 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
777 unsigned int nSigOps = 0;
778 for (unsigned int i = 0; i < tx.vin.size(); i++)
780 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
781 if (prevout.scriptPubKey.IsPayToScriptHash())
782 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
794 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
796 // Basic checks that don't depend on any context
798 return state.DoS(10, error("CheckTransaction(): vin empty"),
799 REJECT_INVALID, "bad-txns-vin-empty");
801 return state.DoS(10, error("CheckTransaction(): vout empty"),
802 REJECT_INVALID, "bad-txns-vout-empty");
804 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
805 return state.DoS(100, error("CheckTransaction(): size limits failed"),
806 REJECT_INVALID, "bad-txns-oversize");
808 // Check for negative or overflow output values
809 CAmount nValueOut = 0;
810 BOOST_FOREACH(const CTxOut& txout, tx.vout)
812 if (txout.nValue < 0)
813 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
814 REJECT_INVALID, "bad-txns-vout-negative");
815 if (txout.nValue > MAX_MONEY)
816 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
817 REJECT_INVALID, "bad-txns-vout-toolarge");
818 nValueOut += txout.nValue;
819 if (!MoneyRange(nValueOut))
820 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
821 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
824 // Check for duplicate inputs
825 set<COutPoint> vInOutPoints;
826 BOOST_FOREACH(const CTxIn& txin, tx.vin)
828 if (vInOutPoints.count(txin.prevout))
829 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
830 REJECT_INVALID, "bad-txns-inputs-duplicate");
831 vInOutPoints.insert(txin.prevout);
836 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
837 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
838 REJECT_INVALID, "bad-cb-length");
842 BOOST_FOREACH(const CTxIn& txin, tx.vin)
843 if (txin.prevout.IsNull())
844 return state.DoS(10, error("CheckTransaction(): prevout is null"),
845 REJECT_INVALID, "bad-txns-prevout-null");
851 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
855 uint256 hash = tx.GetHash();
856 double dPriorityDelta = 0;
857 CAmount nFeeDelta = 0;
858 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
859 if (dPriorityDelta > 0 || nFeeDelta > 0)
863 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
867 // There is a free transaction area in blocks created by most miners,
868 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
869 // to be considered to fall into this category. We don't want to encourage sending
870 // multiple transactions instead of one big transaction to avoid fees.
871 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
875 if (!MoneyRange(nMinFee))
881 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
882 bool* pfMissingInputs, bool fRejectAbsurdFee)
884 AssertLockHeld(cs_main);
886 *pfMissingInputs = false;
888 if (!CheckTransaction(tx, state))
889 return error("AcceptToMemoryPool: CheckTransaction failed");
891 // Coinbase is only valid in a block, not as a loose transaction
893 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
894 REJECT_INVALID, "coinbase");
896 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
898 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
900 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
901 REJECT_NONSTANDARD, reason);
903 // Only accept nLockTime-using transactions that can be mined in the next
904 // block; we don't want our mempool filled up with transactions that can't
907 // However, IsFinalTx() is confusing... Without arguments, it uses
908 // chainActive.Height() to evaluate nLockTime; when a block is accepted,
909 // chainActive.Height() is set to the value of nHeight in the block.
910 // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the
911 // height of the block *being* evaluated is what is used. Thus if we want
912 // to know if a transaction can be part of the *next* block, we need to
913 // call IsFinalTx() with one more than chainActive.Height().
915 // Timestamps on the other hand don't get any special treatment, because we
916 // can't know what timestamp the next block will have, and there aren't
917 // timestamp applications where it matters.
918 if (!IsFinalTx(tx, chainActive.Height() + 1))
920 error("AcceptToMemoryPool: non-final"),
921 REJECT_NONSTANDARD, "non-final");
923 // is it already in the memory pool?
924 uint256 hash = tx.GetHash();
925 if (pool.exists(hash))
928 // Check for conflicts with in-memory transactions
930 LOCK(pool.cs); // protect pool.mapNextTx
931 for (unsigned int i = 0; i < tx.vin.size(); i++)
933 COutPoint outpoint = tx.vin[i].prevout;
934 if (pool.mapNextTx.count(outpoint))
936 // Disable replacement feature for now
944 CCoinsViewCache view(&dummy);
946 CAmount nValueIn = 0;
949 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
950 view.SetBackend(viewMemPool);
952 // do we already have it?
953 if (view.HaveCoins(hash))
956 // do all inputs exist?
957 // Note that this does not check for the presence of actual outputs (see the next check for that),
958 // and only helps with filling in pfMissingInputs (to determine missing vs spent).
959 BOOST_FOREACH(const CTxIn txin, tx.vin) {
960 if (!view.HaveCoins(txin.prevout.hash)) {
962 *pfMissingInputs = true;
967 // are the actual inputs available?
968 if (!view.HaveInputs(tx))
969 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
970 REJECT_DUPLICATE, "bad-txns-inputs-spent");
972 // Bring the best block into scope
975 nValueIn = view.GetValueIn(tx);
977 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
978 view.SetBackend(dummy);
981 // Check for non-standard pay-to-script-hash in inputs
982 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
983 return error("AcceptToMemoryPool: nonstandard transaction input");
985 // Check that the transaction doesn't have an excessive number of
986 // sigops, making it impossible to mine. Since the coinbase transaction
987 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
988 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
989 // merely non-standard transaction.
990 unsigned int nSigOps = GetLegacySigOpCount(tx);
991 nSigOps += GetP2SHSigOpCount(tx, view);
992 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
994 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
995 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
996 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
998 CAmount nValueOut = tx.GetValueOut();
999 CAmount nFees = nValueIn-nValueOut;
1000 double dPriority = view.GetPriority(tx, chainActive.Height());
1002 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1003 unsigned int nSize = entry.GetTxSize();
1005 // Don't accept it if it can't get into a block
1006 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1007 if (fLimitFree && nFees < txMinFee)
1008 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1009 hash.ToString(), nFees, txMinFee),
1010 REJECT_INSUFFICIENTFEE, "insufficient fee");
1012 // Require that free transactions have sufficient priority to be mined in the next block.
1013 if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1014 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1017 // Continuously rate-limit free (really, very-low-fee) transactions
1018 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1019 // be annoying or make others' transactions take longer to confirm.
1020 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1022 static CCriticalSection csFreeLimiter;
1023 static double dFreeCount;
1024 static int64_t nLastTime;
1025 int64_t nNow = GetTime();
1027 LOCK(csFreeLimiter);
1029 // Use an exponentially decaying ~10-minute window:
1030 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1032 // -limitfreerelay unit is thousand-bytes-per-minute
1033 // At default rate it would take over a month to fill 1GB
1034 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1035 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1036 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1037 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1038 dFreeCount += nSize;
1041 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1042 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1044 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1046 // Check against previous transactions
1047 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1048 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1050 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1053 // Check again against just the consensus-critical mandatory script
1054 // verification flags, in case of bugs in the standard flags that cause
1055 // transactions to pass as valid when they're actually invalid. For
1056 // instance the STRICTENC flag was incorrectly allowing certain
1057 // CHECKSIG NOT scripts to pass, even though they were invalid.
1059 // There is a similar check in CreateNewBlock() to prevent creating
1060 // invalid blocks, however allowing such transactions into the mempool
1061 // can be exploited as a DoS attack.
1062 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1064 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1067 // Store transaction in memory
1068 pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1071 SyncWithWallets(tx, NULL);
1076 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1077 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1079 CBlockIndex *pindexSlow = NULL;
1083 if (mempool.lookup(hash, txOut))
1091 if (pblocktree->ReadTxIndex(hash, postx)) {
1092 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1094 return error("%s: OpenBlockFile failed", __func__);
1095 CBlockHeader header;
1098 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1100 } catch (const std::exception& e) {
1101 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1103 hashBlock = header.GetHash();
1104 if (txOut.GetHash() != hash)
1105 return error("%s: txid mismatch", __func__);
1110 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1113 CCoinsViewCache &view = *pcoinsTip;
1114 const CCoins* coins = view.AccessCoins(hash);
1116 nHeight = coins->nHeight;
1119 pindexSlow = chainActive[nHeight];
1125 if (ReadBlockFromDisk(block, pindexSlow)) {
1126 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1127 if (tx.GetHash() == hash) {
1129 hashBlock = pindexSlow->GetBlockHash();
1144 //////////////////////////////////////////////////////////////////////////////
1146 // CBlock and CBlockIndex
1149 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1151 // Open history file to append
1152 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1153 if (fileout.IsNull())
1154 return error("WriteBlockToDisk: OpenBlockFile failed");
1156 // Write index header
1157 unsigned int nSize = fileout.GetSerializeSize(block);
1158 fileout << FLATDATA(messageStart) << nSize;
1161 long fileOutPos = ftell(fileout.Get());
1163 return error("WriteBlockToDisk: ftell failed");
1164 pos.nPos = (unsigned int)fileOutPos;
1170 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1174 // Open history file to read
1175 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1176 if (filein.IsNull())
1177 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1183 catch (const std::exception& e) {
1184 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1188 if (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
1189 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1194 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1196 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1198 if (block.GetHash() != pindex->GetBlockHash())
1199 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1200 pindex->ToString(), pindex->GetBlockPos().ToString());
1204 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1206 int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1207 // Force block reward to zero when right shift is undefined.
1211 CAmount nSubsidy = 50 * COIN;
1212 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1213 nSubsidy >>= halvings;
1217 bool IsInitialBlockDownload()
1219 const CChainParams& chainParams = Params();
1221 if (fImporting || fReindex)
1223 if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1225 static bool lockIBDState = false;
1228 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1229 pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1231 lockIBDState = true;
1235 bool fLargeWorkForkFound = false;
1236 bool fLargeWorkInvalidChainFound = false;
1237 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1239 void CheckForkWarningConditions()
1241 AssertLockHeld(cs_main);
1242 // Before we get past initial download, we cannot reliably alert about forks
1243 // (we assume we don't get stuck on a fork before the last checkpoint)
1244 if (IsInitialBlockDownload())
1247 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1248 // of our head, drop it
1249 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1250 pindexBestForkTip = NULL;
1252 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1254 if (!fLargeWorkForkFound && pindexBestForkBase)
1256 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1257 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1258 CAlert::Notify(warning, true);
1260 if (pindexBestForkTip && pindexBestForkBase)
1262 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__,
1263 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1264 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1265 fLargeWorkForkFound = true;
1269 LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1270 fLargeWorkInvalidChainFound = true;
1275 fLargeWorkForkFound = false;
1276 fLargeWorkInvalidChainFound = false;
1280 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1282 AssertLockHeld(cs_main);
1283 // If we are on a fork that is sufficiently large, set a warning flag
1284 CBlockIndex* pfork = pindexNewForkTip;
1285 CBlockIndex* plonger = chainActive.Tip();
1286 while (pfork && pfork != plonger)
1288 while (plonger && plonger->nHeight > pfork->nHeight)
1289 plonger = plonger->pprev;
1290 if (pfork == plonger)
1292 pfork = pfork->pprev;
1295 // We define a condition where we should warn the user about as a fork of at least 7 blocks
1296 // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1297 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1298 // hash rate operating on the fork.
1299 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1300 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1301 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1302 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1303 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1304 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1306 pindexBestForkTip = pindexNewForkTip;
1307 pindexBestForkBase = pfork;
1310 CheckForkWarningConditions();
1313 // Requires cs_main.
1314 void Misbehaving(NodeId pnode, int howmuch)
1319 CNodeState *state = State(pnode);
1323 state->nMisbehavior += howmuch;
1324 int banscore = GetArg("-banscore", 100);
1325 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1327 LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1328 state->fShouldBan = true;
1330 LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1333 void static InvalidChainFound(CBlockIndex* pindexNew)
1335 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1336 pindexBestInvalid = pindexNew;
1338 LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
1339 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1340 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1341 pindexNew->GetBlockTime()));
1342 LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
1343 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1344 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1345 CheckForkWarningConditions();
1348 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1350 if (state.IsInvalid(nDoS)) {
1351 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1352 if (it != mapBlockSource.end() && State(it->second)) {
1353 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1354 State(it->second)->rejects.push_back(reject);
1356 Misbehaving(it->second, nDoS);
1359 if (!state.CorruptionPossible()) {
1360 pindex->nStatus |= BLOCK_FAILED_VALID;
1361 setDirtyBlockIndex.insert(pindex);
1362 setBlockIndexCandidates.erase(pindex);
1363 InvalidChainFound(pindex);
1367 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1369 // mark inputs spent
1370 if (!tx.IsCoinBase()) {
1371 txundo.vprevout.reserve(tx.vin.size());
1372 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1373 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1374 unsigned nPos = txin.prevout.n;
1376 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1378 // mark an outpoint spent, and construct undo information
1379 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1381 if (coins->vout.size() == 0) {
1382 CTxInUndo& undo = txundo.vprevout.back();
1383 undo.nHeight = coins->nHeight;
1384 undo.fCoinBase = coins->fCoinBase;
1385 undo.nVersion = coins->nVersion;
1391 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1394 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1397 UpdateCoins(tx, state, inputs, txundo, nHeight);
1400 bool CScriptCheck::operator()() {
1401 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1402 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1403 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1408 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1410 if (!tx.IsCoinBase())
1413 pvChecks->reserve(tx.vin.size());
1415 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1416 // for an attacker to attempt to split the network.
1417 if (!inputs.HaveInputs(tx))
1418 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1420 // While checking, GetBestBlock() refers to the parent block.
1421 // This is also true for mempool checks.
1422 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1423 int nSpendHeight = pindexPrev->nHeight + 1;
1424 CAmount nValueIn = 0;
1426 for (unsigned int i = 0; i < tx.vin.size(); i++)
1428 const COutPoint &prevout = tx.vin[i].prevout;
1429 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1432 // If prev is coinbase, check that it's matured
1433 if (coins->IsCoinBase()) {
1434 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1435 return state.Invalid(
1436 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1437 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1440 // Check for negative or overflow input values
1441 nValueIn += coins->vout[prevout.n].nValue;
1442 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1443 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1444 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1448 if (nValueIn < tx.GetValueOut())
1449 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1450 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1451 REJECT_INVALID, "bad-txns-in-belowout");
1453 // Tally transaction fees
1454 CAmount nTxFee = nValueIn - tx.GetValueOut();
1456 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1457 REJECT_INVALID, "bad-txns-fee-negative");
1459 if (!MoneyRange(nFees))
1460 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1461 REJECT_INVALID, "bad-txns-fee-outofrange");
1463 // The first loop above does all the inexpensive checks.
1464 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1465 // Helps prevent CPU exhaustion attacks.
1467 // Skip ECDSA signature verification when connecting blocks
1468 // before the last block chain checkpoint. This is safe because block merkle hashes are
1469 // still computed and checked, and any change will be caught at the next checkpoint.
1470 if (fScriptChecks) {
1471 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1472 const COutPoint &prevout = tx.vin[i].prevout;
1473 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1477 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1479 pvChecks->push_back(CScriptCheck());
1480 check.swap(pvChecks->back());
1481 } else if (!check()) {
1482 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1483 // Check whether the failure was caused by a
1484 // non-mandatory script verification check, such as
1485 // non-standard DER encodings or non-null dummy
1486 // arguments; if so, don't trigger DoS protection to
1487 // avoid splitting the network between upgraded and
1488 // non-upgraded nodes.
1489 CScriptCheck check(*coins, tx, i,
1490 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1492 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1494 // Failures of other flags indicate a transaction that is
1495 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1496 // such nodes as they are not following the protocol. That
1497 // said during an upgrade careful thought should be taken
1498 // as to the correct behavior - we may want to continue
1499 // peering with non-upgraded nodes even after a soft-fork
1500 // super-majority vote has passed.
1501 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1512 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1514 // Open history file to append
1515 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1516 if (fileout.IsNull())
1517 return error("%s: OpenUndoFile failed", __func__);
1519 // Write index header
1520 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1521 fileout << FLATDATA(messageStart) << nSize;
1524 long fileOutPos = ftell(fileout.Get());
1526 return error("%s: ftell failed", __func__);
1527 pos.nPos = (unsigned int)fileOutPos;
1528 fileout << blockundo;
1530 // calculate & write checksum
1531 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1532 hasher << hashBlock;
1533 hasher << blockundo;
1534 fileout << hasher.GetHash();
1539 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1541 // Open history file to read
1542 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1543 if (filein.IsNull())
1544 return error("%s: OpenBlockFile failed", __func__);
1547 uint256 hashChecksum;
1549 filein >> blockundo;
1550 filein >> hashChecksum;
1552 catch (const std::exception& e) {
1553 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1557 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1558 hasher << hashBlock;
1559 hasher << blockundo;
1560 if (hashChecksum != hasher.GetHash())
1561 return error("%s: Checksum mismatch", __func__);
1566 /** Abort with a message */
1567 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1569 strMiscWarning = strMessage;
1570 LogPrintf("*** %s\n", strMessage);
1571 uiInterface.ThreadSafeMessageBox(
1572 userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
1573 "", CClientUIInterface::MSG_ERROR);
1578 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1580 AbortNode(strMessage, userMessage);
1581 return state.Error(strMessage);
1587 * Apply the undo operation of a CTxInUndo to the given chain state.
1588 * @param undo The undo object.
1589 * @param view The coins view to which to apply the changes.
1590 * @param out The out point that corresponds to the tx input.
1591 * @return True on success.
1593 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1597 CCoinsModifier coins = view.ModifyCoins(out.hash);
1598 if (undo.nHeight != 0) {
1599 // undo data contains height: this is the last output of the prevout tx being spent
1600 if (!coins->IsPruned())
1601 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1603 coins->fCoinBase = undo.fCoinBase;
1604 coins->nHeight = undo.nHeight;
1605 coins->nVersion = undo.nVersion;
1607 if (coins->IsPruned())
1608 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1610 if (coins->IsAvailable(out.n))
1611 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1612 if (coins->vout.size() < out.n+1)
1613 coins->vout.resize(out.n+1);
1614 coins->vout[out.n] = undo.txout;
1619 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1621 assert(pindex->GetBlockHash() == view.GetBestBlock());
1628 CBlockUndo blockUndo;
1629 CDiskBlockPos pos = pindex->GetUndoPos();
1631 return error("DisconnectBlock(): no undo data available");
1632 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1633 return error("DisconnectBlock(): failure reading undo data");
1635 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1636 return error("DisconnectBlock(): block and undo data inconsistent");
1638 // undo transactions in reverse order
1639 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1640 const CTransaction &tx = block.vtx[i];
1641 uint256 hash = tx.GetHash();
1643 // Check that all outputs are available and match the outputs in the block itself
1646 CCoinsModifier outs = view.ModifyCoins(hash);
1647 outs->ClearUnspendable();
1649 CCoins outsBlock(tx, pindex->nHeight);
1650 // The CCoins serialization does not serialize negative numbers.
1651 // No network rules currently depend on the version here, so an inconsistency is harmless
1652 // but it must be corrected before txout nversion ever influences a network rule.
1653 if (outsBlock.nVersion < 0)
1654 outs->nVersion = outsBlock.nVersion;
1655 if (*outs != outsBlock)
1656 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1663 if (i > 0) { // not coinbases
1664 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1665 if (txundo.vprevout.size() != tx.vin.size())
1666 return error("DisconnectBlock(): transaction and undo data inconsistent");
1667 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1668 const COutPoint &out = tx.vin[j].prevout;
1669 const CTxInUndo &undo = txundo.vprevout[j];
1670 if (!ApplyTxInUndo(undo, view, out))
1676 // move best block pointer to prevout block
1677 view.SetBestBlock(pindex->pprev->GetBlockHash());
1687 void static FlushBlockFile(bool fFinalize = false)
1689 LOCK(cs_LastBlockFile);
1691 CDiskBlockPos posOld(nLastBlockFile, 0);
1693 FILE *fileOld = OpenBlockFile(posOld);
1696 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1697 FileCommit(fileOld);
1701 fileOld = OpenUndoFile(posOld);
1704 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1705 FileCommit(fileOld);
1710 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1712 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1714 void ThreadScriptCheck() {
1715 RenameThread("bitcoin-scriptch");
1716 scriptcheckqueue.Thread();
1720 // Called periodically asynchronously; alerts if it smells like
1721 // we're being fed a bad chain (blocks being generated much
1722 // too slowly or too quickly).
1724 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CChain& chain, int64_t nPowTargetSpacing)
1726 if (initialDownloadCheck()) return;
1728 static int64_t lastAlertTime = 0;
1729 int64_t now = GetAdjustedTime();
1730 if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1732 const int SPAN_HOURS=4;
1733 const int SPAN_SECONDS=SPAN_HOURS*60*60;
1734 int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1736 boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1738 std::string strWarning;
1739 int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1742 int h = chain.Height();
1743 while (h > 0 && chain[h]->GetBlockTime() >= startTime)
1745 int nBlocks = chain.Height()-h;
1747 // How likely is it to find that many by chance?
1748 double p = boost::math::pdf(poisson, nBlocks);
1750 LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1751 LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
1753 // Aim for one false-positive about every fifty years of normal running:
1754 const int FIFTY_YEARS = 50*365*24*60*60;
1755 double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
1757 if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
1759 // Many fewer blocks than expected: alert!
1760 strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
1761 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1763 else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
1765 // Many more blocks than expected: alert!
1766 strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
1767 nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1769 if (!strWarning.empty())
1771 strMiscWarning = strWarning;
1772 CAlert::Notify(strWarning, true);
1773 lastAlertTime = now;
1777 static int64_t nTimeVerify = 0;
1778 static int64_t nTimeConnect = 0;
1779 static int64_t nTimeIndex = 0;
1780 static int64_t nTimeCallbacks = 0;
1781 static int64_t nTimeTotal = 0;
1783 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1785 const CChainParams& chainparams = Params();
1786 AssertLockHeld(cs_main);
1787 // Check it again in case a previous version let a bad block in
1788 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1791 // verify that the view's current state corresponds to the previous block
1792 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1793 assert(hashPrevBlock == view.GetBestBlock());
1795 // Special case for the genesis block, skipping connection of its transactions
1796 // (its coinbase is unspendable)
1797 if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1799 view.SetBestBlock(pindex->GetBlockHash());
1803 bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
1805 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1806 // unless those are already completely spent.
1807 // If such overwrites are allowed, coinbases and transactions depending upon those
1808 // can be duplicated to remove the ability to spend the first instance -- even after
1809 // being sent to another address.
1810 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1811 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1812 // already refuses previously-known transaction ids entirely.
1813 // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1814 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1815 // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1816 // initial block download.
1817 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1818 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1819 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1820 if (fEnforceBIP30) {
1821 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1822 const CCoins* coins = view.AccessCoins(tx.GetHash());
1823 if (coins && !coins->IsPruned())
1824 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1825 REJECT_INVALID, "bad-txns-BIP30");
1829 // BIP16 didn't become active until Apr 1 2012
1830 int64_t nBIP16SwitchTime = 1333238400;
1831 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1833 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1835 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1836 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1837 flags |= SCRIPT_VERIFY_DERSIG;
1840 CBlockUndo blockundo;
1842 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1844 int64_t nTimeStart = GetTimeMicros();
1847 unsigned int nSigOps = 0;
1848 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1849 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1850 vPos.reserve(block.vtx.size());
1851 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1852 for (unsigned int i = 0; i < block.vtx.size(); i++)
1854 const CTransaction &tx = block.vtx[i];
1856 nInputs += tx.vin.size();
1857 nSigOps += GetLegacySigOpCount(tx);
1858 if (nSigOps > MAX_BLOCK_SIGOPS)
1859 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1860 REJECT_INVALID, "bad-blk-sigops");
1862 if (!tx.IsCoinBase())
1864 if (!view.HaveInputs(tx))
1865 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1866 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1868 if (fStrictPayToScriptHash)
1870 // Add in sigops done by pay-to-script-hash inputs;
1871 // this is to prevent a "rogue miner" from creating
1872 // an incredibly-expensive-to-validate block.
1873 nSigOps += GetP2SHSigOpCount(tx, view);
1874 if (nSigOps > MAX_BLOCK_SIGOPS)
1875 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1876 REJECT_INVALID, "bad-blk-sigops");
1879 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1881 std::vector<CScriptCheck> vChecks;
1882 if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1884 control.Add(vChecks);
1889 blockundo.vtxundo.push_back(CTxUndo());
1891 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1893 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1894 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1896 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1897 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);
1899 CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1900 if (block.vtx[0].GetValueOut() > blockReward)
1901 return state.DoS(100,
1902 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1903 block.vtx[0].GetValueOut(), blockReward),
1904 REJECT_INVALID, "bad-cb-amount");
1906 if (!control.Wait())
1907 return state.DoS(100, false);
1908 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1909 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);
1914 // Write undo information to disk
1915 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1917 if (pindex->GetUndoPos().IsNull()) {
1919 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1920 return error("ConnectBlock(): FindUndoPos failed");
1921 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1922 return AbortNode(state, "Failed to write undo data");
1924 // update nUndoPos in block index
1925 pindex->nUndoPos = pos.nPos;
1926 pindex->nStatus |= BLOCK_HAVE_UNDO;
1929 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1930 setDirtyBlockIndex.insert(pindex);
1934 if (!pblocktree->WriteTxIndex(vPos))
1935 return AbortNode(state, "Failed to write transaction index");
1937 // add this block to the view's block chain
1938 view.SetBestBlock(pindex->GetBlockHash());
1940 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1941 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1943 // Watch for changes to the previous coinbase transaction.
1944 static uint256 hashPrevBestCoinBase;
1945 GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1946 hashPrevBestCoinBase = block.vtx[0].GetHash();
1948 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1949 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1954 enum FlushStateMode {
1956 FLUSH_STATE_IF_NEEDED,
1957 FLUSH_STATE_PERIODIC,
1962 * Update the on-disk chain state.
1963 * The caches and indexes are flushed depending on the mode we're called with
1964 * if they're too large, if it's been a while since the last write,
1965 * or always and in all cases if we're in prune mode and are deleting files.
1967 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1968 LOCK2(cs_main, cs_LastBlockFile);
1969 static int64_t nLastWrite = 0;
1970 static int64_t nLastFlush = 0;
1971 static int64_t nLastSetChain = 0;
1972 std::set<int> setFilesToPrune;
1973 bool fFlushForPrune = false;
1975 if (fPruneMode && fCheckForPruning) {
1976 FindFilesToPrune(setFilesToPrune);
1977 fCheckForPruning = false;
1978 if (!setFilesToPrune.empty()) {
1979 fFlushForPrune = true;
1981 pblocktree->WriteFlag("prunedblockfiles", true);
1986 int64_t nNow = GetTimeMicros();
1987 // Avoid writing/flushing immediately after startup.
1988 if (nLastWrite == 0) {
1991 if (nLastFlush == 0) {
1994 if (nLastSetChain == 0) {
1995 nLastSetChain = nNow;
1997 size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1998 // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1999 bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2000 // The cache is over the limit, we have to write now.
2001 bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2002 // 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.
2003 bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2004 // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2005 bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2006 // Combine all conditions that result in a full cache flush.
2007 bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2008 // Write blocks and block index to disk.
2009 if (fDoFullFlush || fPeriodicWrite) {
2010 // Depend on nMinDiskSpace to ensure we can write block index
2011 if (!CheckDiskSpace(0))
2012 return state.Error("out of disk space");
2013 // First make sure all block and undo data is flushed to disk.
2015 // Then update all block file information (which may refer to block and undo files).
2017 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2018 vFiles.reserve(setDirtyFileInfo.size());
2019 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2020 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2021 setDirtyFileInfo.erase(it++);
2023 std::vector<const CBlockIndex*> vBlocks;
2024 vBlocks.reserve(setDirtyBlockIndex.size());
2025 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2026 vBlocks.push_back(*it);
2027 setDirtyBlockIndex.erase(it++);
2029 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2030 return AbortNode(state, "Files to write to block index database");
2033 // Finally remove any pruned files
2035 UnlinkPrunedFiles(setFilesToPrune);
2038 // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2040 // Typical CCoins structures on disk are around 128 bytes in size.
2041 // Pushing a new one to the database can cause it to be written
2042 // twice (once in the log, and once in the tables). This is already
2043 // an overestimation, as most will delete an existing entry or
2044 // overwrite one. Still, use a conservative safety factor of 2.
2045 if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2046 return state.Error("out of disk space");
2047 // Flush the chainstate (which may refer to block index entries).
2048 if (!pcoinsTip->Flush())
2049 return AbortNode(state, "Failed to write to coin database");
2052 if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2053 // Update best block in wallet (so we can detect restored wallets).
2054 GetMainSignals().SetBestChain(chainActive.GetLocator());
2055 nLastSetChain = nNow;
2057 } catch (const std::runtime_error& e) {
2058 return AbortNode(state, std::string("System error while flushing: ") + e.what());
2063 void FlushStateToDisk() {
2064 CValidationState state;
2065 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2068 void PruneAndFlush() {
2069 CValidationState state;
2070 fCheckForPruning = true;
2071 FlushStateToDisk(state, FLUSH_STATE_NONE);
2074 /** Update chainActive and related internal data structures. */
2075 void static UpdateTip(CBlockIndex *pindexNew) {
2076 const CChainParams& chainParams = Params();
2077 chainActive.SetTip(pindexNew);
2080 nTimeBestReceived = GetTime();
2081 mempool.AddTransactionsUpdated(1);
2083 LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__,
2084 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2085 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2086 Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2088 cvBlockChange.notify_all();
2090 // Check the version of the last 100 blocks to see if we need to upgrade:
2091 static bool fWarned = false;
2092 if (!IsInitialBlockDownload() && !fWarned)
2095 const CBlockIndex* pindex = chainActive.Tip();
2096 for (int i = 0; i < 100 && pindex != NULL; i++)
2098 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2100 pindex = pindex->pprev;
2103 LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2104 if (nUpgraded > 100/2)
2106 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2107 strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2108 CAlert::Notify(strMiscWarning, true);
2114 /** Disconnect chainActive's tip. */
2115 bool static DisconnectTip(CValidationState &state) {
2116 CBlockIndex *pindexDelete = chainActive.Tip();
2117 assert(pindexDelete);
2118 mempool.check(pcoinsTip);
2119 // Read block from disk.
2121 if (!ReadBlockFromDisk(block, pindexDelete))
2122 return AbortNode(state, "Failed to read block");
2123 // Apply the block atomically to the chain state.
2124 int64_t nStart = GetTimeMicros();
2126 CCoinsViewCache view(pcoinsTip);
2127 if (!DisconnectBlock(block, state, pindexDelete, view))
2128 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2129 assert(view.Flush());
2131 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2132 // Write the chain state to disk, if necessary.
2133 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2135 // Resurrect mempool transactions from the disconnected block.
2136 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2137 // ignore validation errors in resurrected transactions
2138 list<CTransaction> removed;
2139 CValidationState stateDummy;
2140 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2141 mempool.remove(tx, removed, true);
2143 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2144 mempool.check(pcoinsTip);
2145 // Update chainActive and related variables.
2146 UpdateTip(pindexDelete->pprev);
2147 // Let wallets know transactions went from 1-confirmed to
2148 // 0-confirmed or conflicted:
2149 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2150 SyncWithWallets(tx, NULL);
2155 static int64_t nTimeReadFromDisk = 0;
2156 static int64_t nTimeConnectTotal = 0;
2157 static int64_t nTimeFlush = 0;
2158 static int64_t nTimeChainState = 0;
2159 static int64_t nTimePostConnect = 0;
2162 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2163 * corresponding to pindexNew, to bypass loading it again from disk.
2165 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2166 assert(pindexNew->pprev == chainActive.Tip());
2167 mempool.check(pcoinsTip);
2168 // Read block from disk.
2169 int64_t nTime1 = GetTimeMicros();
2172 if (!ReadBlockFromDisk(block, pindexNew))
2173 return AbortNode(state, "Failed to read block");
2176 // Apply the block atomically to the chain state.
2177 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2179 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2181 CCoinsViewCache view(pcoinsTip);
2182 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2183 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2184 GetMainSignals().BlockChecked(*pblock, state);
2186 if (state.IsInvalid())
2187 InvalidBlockFound(pindexNew, state);
2188 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2190 mapBlockSource.erase(inv.hash);
2191 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2192 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2193 assert(view.Flush());
2195 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2196 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2197 // Write the chain state to disk, if necessary.
2198 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2200 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2201 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2202 // Remove conflicting transactions from the mempool.
2203 list<CTransaction> txConflicted;
2204 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2205 mempool.check(pcoinsTip);
2206 // Update chainActive & related variables.
2207 UpdateTip(pindexNew);
2208 // Tell wallet about transactions that went from mempool
2210 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2211 SyncWithWallets(tx, NULL);
2213 // ... and about transactions that got confirmed:
2214 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2215 SyncWithWallets(tx, pblock);
2218 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2219 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2220 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2225 * Return the tip of the chain with the most work in it, that isn't
2226 * known to be invalid (it's however far from certain to be valid).
2228 static CBlockIndex* FindMostWorkChain() {
2230 CBlockIndex *pindexNew = NULL;
2232 // Find the best candidate header.
2234 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2235 if (it == setBlockIndexCandidates.rend())
2240 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2241 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2242 CBlockIndex *pindexTest = pindexNew;
2243 bool fInvalidAncestor = false;
2244 while (pindexTest && !chainActive.Contains(pindexTest)) {
2245 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2247 // Pruned nodes may have entries in setBlockIndexCandidates for
2248 // which block files have been deleted. Remove those as candidates
2249 // for the most work chain if we come across them; we can't switch
2250 // to a chain unless we have all the non-active-chain parent blocks.
2251 bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2252 bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2253 if (fFailedChain || fMissingData) {
2254 // Candidate chain is not usable (either invalid or missing data)
2255 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2256 pindexBestInvalid = pindexNew;
2257 CBlockIndex *pindexFailed = pindexNew;
2258 // Remove the entire chain from the set.
2259 while (pindexTest != pindexFailed) {
2261 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2262 } else if (fMissingData) {
2263 // If we're missing data, then add back to mapBlocksUnlinked,
2264 // so that if the block arrives in the future we can try adding
2265 // to setBlockIndexCandidates again.
2266 mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2268 setBlockIndexCandidates.erase(pindexFailed);
2269 pindexFailed = pindexFailed->pprev;
2271 setBlockIndexCandidates.erase(pindexTest);
2272 fInvalidAncestor = true;
2275 pindexTest = pindexTest->pprev;
2277 if (!fInvalidAncestor)
2282 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2283 static void PruneBlockIndexCandidates() {
2284 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2285 // reorganization to a better block fails.
2286 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2287 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2288 setBlockIndexCandidates.erase(it++);
2290 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2291 assert(!setBlockIndexCandidates.empty());
2295 * Try to make some progress towards making pindexMostWork the active block.
2296 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2298 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2299 AssertLockHeld(cs_main);
2300 bool fInvalidFound = false;
2301 const CBlockIndex *pindexOldTip = chainActive.Tip();
2302 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2304 // Disconnect active blocks which are no longer in the best chain.
2305 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2306 if (!DisconnectTip(state))
2310 // Build list of new blocks to connect.
2311 std::vector<CBlockIndex*> vpindexToConnect;
2312 bool fContinue = true;
2313 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2314 while (fContinue && nHeight != pindexMostWork->nHeight) {
2315 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2316 // a few blocks along the way.
2317 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2318 vpindexToConnect.clear();
2319 vpindexToConnect.reserve(nTargetHeight - nHeight);
2320 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2321 while (pindexIter && pindexIter->nHeight != nHeight) {
2322 vpindexToConnect.push_back(pindexIter);
2323 pindexIter = pindexIter->pprev;
2325 nHeight = nTargetHeight;
2327 // Connect new blocks.
2328 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2329 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2330 if (state.IsInvalid()) {
2331 // The block violates a consensus rule.
2332 if (!state.CorruptionPossible())
2333 InvalidChainFound(vpindexToConnect.back());
2334 state = CValidationState();
2335 fInvalidFound = true;
2339 // A system error occurred (disk space, database error, ...).
2343 PruneBlockIndexCandidates();
2344 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2345 // We're in a better position than we were. Return temporarily to release the lock.
2353 // Callbacks/notifications for a new best chain.
2355 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2357 CheckForkWarningConditions();
2363 * Make the best chain active, in multiple steps. The result is either failure
2364 * or an activated best chain. pblock is either NULL or a pointer to a block
2365 * that is already loaded (to avoid loading it again from disk).
2367 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2368 CBlockIndex *pindexNewTip = NULL;
2369 CBlockIndex *pindexMostWork = NULL;
2370 const CChainParams& chainParams = Params();
2372 boost::this_thread::interruption_point();
2374 bool fInitialDownload;
2377 pindexMostWork = FindMostWorkChain();
2379 // Whether we have anything to do at all.
2380 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2383 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2386 pindexNewTip = chainActive.Tip();
2387 fInitialDownload = IsInitialBlockDownload();
2389 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2391 // Notifications/callbacks that can run without cs_main
2392 if (!fInitialDownload) {
2393 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2394 // Relay inventory, but don't relay old inventory during initial block download.
2395 int nBlockEstimate = 0;
2396 if (fCheckpointsEnabled)
2397 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2398 // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2399 // in a stalled download if the block file is pruned before the request.
2400 if (nLocalServices & NODE_NETWORK) {
2402 BOOST_FOREACH(CNode* pnode, vNodes)
2403 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2404 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2406 // Notify external listeners about the new tip.
2407 uiInterface.NotifyBlockTip(hashNewTip);
2409 } while(pindexMostWork != chainActive.Tip());
2412 // Write changes periodically to disk, after relay.
2413 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2420 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2421 AssertLockHeld(cs_main);
2423 // Mark the block itself as invalid.
2424 pindex->nStatus |= BLOCK_FAILED_VALID;
2425 setDirtyBlockIndex.insert(pindex);
2426 setBlockIndexCandidates.erase(pindex);
2428 while (chainActive.Contains(pindex)) {
2429 CBlockIndex *pindexWalk = chainActive.Tip();
2430 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2431 setDirtyBlockIndex.insert(pindexWalk);
2432 setBlockIndexCandidates.erase(pindexWalk);
2433 // ActivateBestChain considers blocks already in chainActive
2434 // unconditionally valid already, so force disconnect away from it.
2435 if (!DisconnectTip(state)) {
2440 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2442 BlockMap::iterator it = mapBlockIndex.begin();
2443 while (it != mapBlockIndex.end()) {
2444 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2445 setBlockIndexCandidates.insert(it->second);
2450 InvalidChainFound(pindex);
2454 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2455 AssertLockHeld(cs_main);
2457 int nHeight = pindex->nHeight;
2459 // Remove the invalidity flag from this block and all its descendants.
2460 BlockMap::iterator it = mapBlockIndex.begin();
2461 while (it != mapBlockIndex.end()) {
2462 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2463 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2464 setDirtyBlockIndex.insert(it->second);
2465 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2466 setBlockIndexCandidates.insert(it->second);
2468 if (it->second == pindexBestInvalid) {
2469 // Reset invalid block marker if it was pointing to one of those.
2470 pindexBestInvalid = NULL;
2476 // Remove the invalidity flag from all ancestors too.
2477 while (pindex != NULL) {
2478 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2479 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2480 setDirtyBlockIndex.insert(pindex);
2482 pindex = pindex->pprev;
2487 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2489 // Check for duplicate
2490 uint256 hash = block.GetHash();
2491 BlockMap::iterator it = mapBlockIndex.find(hash);
2492 if (it != mapBlockIndex.end())
2495 // Construct new block index object
2496 CBlockIndex* pindexNew = new CBlockIndex(block);
2498 // We assign the sequence id to blocks only when the full data is available,
2499 // to avoid miners withholding blocks but broadcasting headers, to get a
2500 // competitive advantage.
2501 pindexNew->nSequenceId = 0;
2502 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2503 pindexNew->phashBlock = &((*mi).first);
2504 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2505 if (miPrev != mapBlockIndex.end())
2507 pindexNew->pprev = (*miPrev).second;
2508 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2509 pindexNew->BuildSkip();
2511 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2512 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2513 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2514 pindexBestHeader = pindexNew;
2516 setDirtyBlockIndex.insert(pindexNew);
2521 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2522 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2524 pindexNew->nTx = block.vtx.size();
2525 pindexNew->nChainTx = 0;
2526 pindexNew->nFile = pos.nFile;
2527 pindexNew->nDataPos = pos.nPos;
2528 pindexNew->nUndoPos = 0;
2529 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2530 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2531 setDirtyBlockIndex.insert(pindexNew);
2533 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2534 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2535 deque<CBlockIndex*> queue;
2536 queue.push_back(pindexNew);
2538 // Recursively process any descendant blocks that now may be eligible to be connected.
2539 while (!queue.empty()) {
2540 CBlockIndex *pindex = queue.front();
2542 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2544 LOCK(cs_nBlockSequenceId);
2545 pindex->nSequenceId = nBlockSequenceId++;
2547 if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2548 setBlockIndexCandidates.insert(pindex);
2550 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2551 while (range.first != range.second) {
2552 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2553 queue.push_back(it->second);
2555 mapBlocksUnlinked.erase(it);
2559 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2560 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2567 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2569 LOCK(cs_LastBlockFile);
2571 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2572 if (vinfoBlockFile.size() <= nFile) {
2573 vinfoBlockFile.resize(nFile + 1);
2577 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2578 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2579 FlushBlockFile(true);
2581 if (vinfoBlockFile.size() <= nFile) {
2582 vinfoBlockFile.resize(nFile + 1);
2586 pos.nPos = vinfoBlockFile[nFile].nSize;
2589 nLastBlockFile = nFile;
2590 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2592 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2594 vinfoBlockFile[nFile].nSize += nAddSize;
2597 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2598 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2599 if (nNewChunks > nOldChunks) {
2601 fCheckForPruning = true;
2602 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2603 FILE *file = OpenBlockFile(pos);
2605 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2606 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2611 return state.Error("out of disk space");
2615 setDirtyFileInfo.insert(nFile);
2619 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2623 LOCK(cs_LastBlockFile);
2625 unsigned int nNewSize;
2626 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2627 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2628 setDirtyFileInfo.insert(nFile);
2630 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2631 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2632 if (nNewChunks > nOldChunks) {
2634 fCheckForPruning = true;
2635 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2636 FILE *file = OpenUndoFile(pos);
2638 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2639 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2644 return state.Error("out of disk space");
2650 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2652 // Check proof of work matches claimed amount
2653 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2654 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2655 REJECT_INVALID, "high-hash");
2658 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2659 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2660 REJECT_INVALID, "time-too-new");
2665 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2667 // These are checks that are independent of context.
2669 // Check that the header is valid (particularly PoW). This is mostly
2670 // redundant with the call in AcceptBlockHeader.
2671 if (!CheckBlockHeader(block, state, fCheckPOW))
2674 // Check the merkle root.
2675 if (fCheckMerkleRoot) {
2677 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2678 if (block.hashMerkleRoot != hashMerkleRoot2)
2679 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2680 REJECT_INVALID, "bad-txnmrklroot", true);
2682 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2683 // of transactions in a block without affecting the merkle root of a block,
2684 // while still invalidating it.
2686 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2687 REJECT_INVALID, "bad-txns-duplicate", true);
2690 // All potential-corruption validation must be done before we do any
2691 // transaction validation, as otherwise we may mark the header as invalid
2692 // because we receive the wrong transactions for it.
2695 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2696 return state.DoS(100, error("CheckBlock(): size limits failed"),
2697 REJECT_INVALID, "bad-blk-length");
2699 // First transaction must be coinbase, the rest must not be
2700 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2701 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2702 REJECT_INVALID, "bad-cb-missing");
2703 for (unsigned int i = 1; i < block.vtx.size(); i++)
2704 if (block.vtx[i].IsCoinBase())
2705 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2706 REJECT_INVALID, "bad-cb-multiple");
2708 // Check transactions
2709 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2710 if (!CheckTransaction(tx, state))
2711 return error("CheckBlock(): CheckTransaction failed");
2713 unsigned int nSigOps = 0;
2714 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2716 nSigOps += GetLegacySigOpCount(tx);
2718 if (nSigOps > MAX_BLOCK_SIGOPS)
2719 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2720 REJECT_INVALID, "bad-blk-sigops", true);
2725 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2727 const CChainParams& chainParams = Params();
2728 const Consensus::Params& consensusParams = chainParams.GetConsensus();
2729 uint256 hash = block.GetHash();
2730 if (hash == consensusParams.hashGenesisBlock)
2735 int nHeight = pindexPrev->nHeight+1;
2737 // Check proof of work
2738 if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2739 return state.DoS(100, error("%s: incorrect proof of work", __func__),
2740 REJECT_INVALID, "bad-diffbits");
2742 // Check timestamp against prev
2743 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2744 return state.Invalid(error("%s: block's timestamp is too early", __func__),
2745 REJECT_INVALID, "time-too-old");
2747 if(fCheckpointsEnabled)
2749 // Check that the block chain matches the known block chain up to a checkpoint
2750 if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
2751 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
2752 REJECT_CHECKPOINT, "checkpoint mismatch");
2754 // Don't accept any forks from the main chain prior to last checkpoint
2755 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
2756 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2757 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2760 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2761 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2762 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2763 REJECT_OBSOLETE, "bad-version");
2765 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2766 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2767 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2768 REJECT_OBSOLETE, "bad-version");
2773 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2775 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2776 const Consensus::Params& consensusParams = Params().GetConsensus();
2778 // Check that all transactions are finalized
2779 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2780 if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2781 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2784 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2785 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2786 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
2788 CScript expect = CScript() << nHeight;
2789 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2790 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2791 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2798 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2800 const CChainParams& chainparams = Params();
2801 AssertLockHeld(cs_main);
2802 // Check for duplicate
2803 uint256 hash = block.GetHash();
2804 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2805 CBlockIndex *pindex = NULL;
2806 if (miSelf != mapBlockIndex.end()) {
2807 // Block header is already known.
2808 pindex = miSelf->second;
2811 if (pindex->nStatus & BLOCK_FAILED_MASK)
2812 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2816 if (!CheckBlockHeader(block, state))
2819 // Get prev block index
2820 CBlockIndex* pindexPrev = NULL;
2821 if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2822 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2823 if (mi == mapBlockIndex.end())
2824 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2825 pindexPrev = (*mi).second;
2826 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2827 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2830 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2834 pindex = AddToBlockIndex(block);
2842 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2844 const CChainParams& chainparams = Params();
2845 AssertLockHeld(cs_main);
2847 CBlockIndex *&pindex = *ppindex;
2849 if (!AcceptBlockHeader(block, state, &pindex))
2852 // If we're pruning, ensure that we don't allow a peer to dump a copy
2853 // of old blocks. But we might need blocks that are not on the main chain
2854 // to handle a reorg, even if we've processed once.
2855 if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
2856 // TODO: deal better with duplicate blocks.
2857 // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2861 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2862 if (state.IsInvalid() && !state.CorruptionPossible()) {
2863 pindex->nStatus |= BLOCK_FAILED_VALID;
2864 setDirtyBlockIndex.insert(pindex);
2869 int nHeight = pindex->nHeight;
2871 // Write block to history file
2873 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2874 CDiskBlockPos blockPos;
2877 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2878 return error("AcceptBlock(): FindBlockPos failed");
2880 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2881 AbortNode(state, "Failed to write block");
2882 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2883 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2884 } catch (const std::runtime_error& e) {
2885 return AbortNode(state, std::string("System error: ") + e.what());
2888 if (fCheckForPruning)
2889 FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2894 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
2896 unsigned int nFound = 0;
2897 for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
2899 if (pstart->nVersion >= minVersion)
2901 pstart = pstart->pprev;
2903 return (nFound >= nRequired);
2907 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2909 // Preliminary checks
2910 bool checked = CheckBlock(*pblock, state);
2914 MarkBlockAsReceived(pblock->GetHash());
2916 return error("%s: CheckBlock FAILED", __func__);
2920 CBlockIndex *pindex = NULL;
2921 bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2922 if (pindex && pfrom) {
2923 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2927 return error("%s: AcceptBlock FAILED", __func__);
2930 if (!ActivateBestChain(state, pblock))
2931 return error("%s: ActivateBestChain failed", __func__);
2936 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2938 AssertLockHeld(cs_main);
2939 assert(pindexPrev == chainActive.Tip());
2941 CCoinsViewCache viewNew(pcoinsTip);
2942 CBlockIndex indexDummy(block);
2943 indexDummy.pprev = pindexPrev;
2944 indexDummy.nHeight = pindexPrev->nHeight + 1;
2946 // NOTE: CheckBlockHeader is called by CheckBlock
2947 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2949 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2951 if (!ContextualCheckBlock(block, state, pindexPrev))
2953 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2955 assert(state.IsValid());
2961 * BLOCK PRUNING CODE
2964 /* Calculate the amount of disk space the block & undo files currently use */
2965 uint64_t CalculateCurrentUsage()
2967 uint64_t retval = 0;
2968 BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
2969 retval += file.nSize + file.nUndoSize;
2974 /* Prune a block file (modify associated database entries)*/
2975 void PruneOneBlockFile(const int fileNumber)
2977 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
2978 CBlockIndex* pindex = it->second;
2979 if (pindex->nFile == fileNumber) {
2980 pindex->nStatus &= ~BLOCK_HAVE_DATA;
2981 pindex->nStatus &= ~BLOCK_HAVE_UNDO;
2983 pindex->nDataPos = 0;
2984 pindex->nUndoPos = 0;
2985 setDirtyBlockIndex.insert(pindex);
2987 // Prune from mapBlocksUnlinked -- any block we prune would have
2988 // to be downloaded again in order to consider its chain, at which
2989 // point it would be considered as a candidate for
2990 // mapBlocksUnlinked or setBlockIndexCandidates.
2991 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
2992 while (range.first != range.second) {
2993 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
2995 if (it->second == pindex) {
2996 mapBlocksUnlinked.erase(it);
3002 vinfoBlockFile[fileNumber].SetNull();
3003 setDirtyFileInfo.insert(fileNumber);
3007 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3009 for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3010 CDiskBlockPos pos(*it, 0);
3011 boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3012 boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3013 LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3017 /* Calculate the block/rev files that should be deleted to remain under target*/
3018 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3020 LOCK2(cs_main, cs_LastBlockFile);
3021 if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3024 if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3028 unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3029 uint64_t nCurrentUsage = CalculateCurrentUsage();
3030 // We don't check to prune until after we've allocated new space for files
3031 // So we should leave a buffer under our target to account for another allocation
3032 // before the next pruning.
3033 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3034 uint64_t nBytesToPrune;
3037 if (nCurrentUsage + nBuffer >= nPruneTarget) {
3038 for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3039 nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3041 if (vinfoBlockFile[fileNumber].nSize == 0)
3044 if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
3047 // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip
3048 if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3051 PruneOneBlockFile(fileNumber);
3052 // Queue up the files for removal
3053 setFilesToPrune.insert(fileNumber);
3054 nCurrentUsage -= nBytesToPrune;
3059 LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3060 nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3061 ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3062 nLastBlockWeCanPrune, count);
3065 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3067 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3069 // Check for nMinDiskSpace bytes (currently 50MB)
3070 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3071 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3076 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3080 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3081 boost::filesystem::create_directories(path.parent_path());
3082 FILE* file = fopen(path.string().c_str(), "rb+");
3083 if (!file && !fReadOnly)
3084 file = fopen(path.string().c_str(), "wb+");
3086 LogPrintf("Unable to open file %s\n", path.string());
3090 if (fseek(file, pos.nPos, SEEK_SET)) {
3091 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3099 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3100 return OpenDiskFile(pos, "blk", fReadOnly);
3103 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3104 return OpenDiskFile(pos, "rev", fReadOnly);
3107 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3109 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3112 CBlockIndex * InsertBlockIndex(uint256 hash)
3118 BlockMap::iterator mi = mapBlockIndex.find(hash);
3119 if (mi != mapBlockIndex.end())
3120 return (*mi).second;
3123 CBlockIndex* pindexNew = new CBlockIndex();
3125 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3126 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3127 pindexNew->phashBlock = &((*mi).first);
3132 bool static LoadBlockIndexDB()
3134 const CChainParams& chainparams = Params();
3135 if (!pblocktree->LoadBlockIndexGuts())
3138 boost::this_thread::interruption_point();
3140 // Calculate nChainWork
3141 vector<pair<int, CBlockIndex*> > vSortedByHeight;
3142 vSortedByHeight.reserve(mapBlockIndex.size());
3143 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3145 CBlockIndex* pindex = item.second;
3146 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3148 sort(vSortedByHeight.begin(), vSortedByHeight.end());
3149 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3151 CBlockIndex* pindex = item.second;
3152 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3153 // We can link the chain of blocks for which we've received transactions at some point.
3154 // Pruned nodes may have deleted the block.
3155 if (pindex->nTx > 0) {
3156 if (pindex->pprev) {
3157 if (pindex->pprev->nChainTx) {
3158 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3160 pindex->nChainTx = 0;
3161 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3164 pindex->nChainTx = pindex->nTx;
3167 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3168 setBlockIndexCandidates.insert(pindex);
3169 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3170 pindexBestInvalid = pindex;
3172 pindex->BuildSkip();
3173 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3174 pindexBestHeader = pindex;
3177 // Load block file info
3178 pblocktree->ReadLastBlockFile(nLastBlockFile);
3179 vinfoBlockFile.resize(nLastBlockFile + 1);
3180 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3181 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3182 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3184 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3185 for (int nFile = nLastBlockFile + 1; true; nFile++) {
3186 CBlockFileInfo info;
3187 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3188 vinfoBlockFile.push_back(info);
3194 // Check presence of blk files
3195 LogPrintf("Checking all blk files are present...\n");
3196 set<int> setBlkDataFiles;
3197 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3199 CBlockIndex* pindex = item.second;
3200 if (pindex->nStatus & BLOCK_HAVE_DATA) {
3201 setBlkDataFiles.insert(pindex->nFile);
3204 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3206 CDiskBlockPos pos(*it, 0);
3207 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3212 // Check whether we have ever pruned block & undo files
3213 pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3215 LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3217 // Check whether we need to continue reindexing
3218 bool fReindexing = false;
3219 pblocktree->ReadReindexing(fReindexing);
3220 fReindex |= fReindexing;
3222 // Check whether we have a transaction index
3223 pblocktree->ReadFlag("txindex", fTxIndex);
3224 LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3226 // Load pointer to end of best chain
3227 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3228 if (it == mapBlockIndex.end())
3230 chainActive.SetTip(it->second);
3232 PruneBlockIndexCandidates();
3234 LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3235 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3236 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3237 Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3242 CVerifyDB::CVerifyDB()
3244 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3247 CVerifyDB::~CVerifyDB()
3249 uiInterface.ShowProgress("", 100);
3252 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3255 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3258 // Verify blocks in the best chain
3259 if (nCheckDepth <= 0)
3260 nCheckDepth = 1000000000; // suffices until the year 19000
3261 if (nCheckDepth > chainActive.Height())
3262 nCheckDepth = chainActive.Height();
3263 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3264 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3265 CCoinsViewCache coins(coinsview);
3266 CBlockIndex* pindexState = chainActive.Tip();
3267 CBlockIndex* pindexFailure = NULL;
3268 int nGoodTransactions = 0;
3269 CValidationState state;
3270 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3272 boost::this_thread::interruption_point();
3273 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3274 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3277 // check level 0: read from disk
3278 if (!ReadBlockFromDisk(block, pindex))
3279 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3280 // check level 1: verify block validity
3281 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3282 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3283 // check level 2: verify undo validity
3284 if (nCheckLevel >= 2 && pindex) {
3286 CDiskBlockPos pos = pindex->GetUndoPos();
3287 if (!pos.IsNull()) {
3288 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3289 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3292 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3293 if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3295 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3296 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3297 pindexState = pindex->pprev;
3299 nGoodTransactions = 0;
3300 pindexFailure = pindex;
3302 nGoodTransactions += block.vtx.size();
3304 if (ShutdownRequested())
3308 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3310 // check level 4: try reconnecting blocks
3311 if (nCheckLevel >= 4) {
3312 CBlockIndex *pindex = pindexState;
3313 while (pindex != chainActive.Tip()) {
3314 boost::this_thread::interruption_point();
3315 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3316 pindex = chainActive.Next(pindex);
3318 if (!ReadBlockFromDisk(block, pindex))
3319 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3320 if (!ConnectBlock(block, state, pindex, coins))
3321 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3325 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3330 void UnloadBlockIndex()
3333 setBlockIndexCandidates.clear();
3334 chainActive.SetTip(NULL);
3335 pindexBestInvalid = NULL;
3336 pindexBestHeader = NULL;
3338 mapOrphanTransactions.clear();
3339 mapOrphanTransactionsByPrev.clear();
3341 mapBlocksUnlinked.clear();
3342 vinfoBlockFile.clear();
3344 nBlockSequenceId = 1;
3345 mapBlockSource.clear();
3346 mapBlocksInFlight.clear();
3347 nQueuedValidatedHeaders = 0;
3348 nPreferredDownload = 0;
3349 setDirtyBlockIndex.clear();
3350 setDirtyFileInfo.clear();
3351 mapNodeState.clear();
3353 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3354 delete entry.second;
3356 mapBlockIndex.clear();
3357 fHavePruned = false;
3360 bool LoadBlockIndex()
3362 // Load block index from databases
3363 if (!fReindex && !LoadBlockIndexDB())
3369 bool InitBlockIndex() {
3370 const CChainParams& chainparams = Params();
3372 // Check whether we're already initialized
3373 if (chainActive.Genesis() != NULL)
3376 // Use the provided setting for -txindex in the new database
3377 fTxIndex = GetBoolArg("-txindex", false);
3378 pblocktree->WriteFlag("txindex", fTxIndex);
3379 LogPrintf("Initializing databases...\n");
3381 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3384 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3385 // Start new block file
3386 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3387 CDiskBlockPos blockPos;
3388 CValidationState state;
3389 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3390 return error("LoadBlockIndex(): FindBlockPos failed");
3391 if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3392 return error("LoadBlockIndex(): writing genesis block to disk failed");
3393 CBlockIndex *pindex = AddToBlockIndex(block);
3394 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3395 return error("LoadBlockIndex(): genesis block not accepted");
3396 if (!ActivateBestChain(state, &block))
3397 return error("LoadBlockIndex(): genesis block cannot be activated");
3398 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3399 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3400 } catch (const std::runtime_error& e) {
3401 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3410 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3412 const CChainParams& chainparams = Params();
3413 // Map of disk positions for blocks with unknown parent (only used for reindex)
3414 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3415 int64_t nStart = GetTimeMillis();
3419 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3420 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3421 uint64_t nRewind = blkdat.GetPos();
3422 while (!blkdat.eof()) {
3423 boost::this_thread::interruption_point();
3425 blkdat.SetPos(nRewind);
3426 nRewind++; // start one byte further next time, in case of failure
3427 blkdat.SetLimit(); // remove former limit
3428 unsigned int nSize = 0;
3431 unsigned char buf[MESSAGE_START_SIZE];
3432 blkdat.FindByte(Params().MessageStart()[0]);
3433 nRewind = blkdat.GetPos()+1;
3434 blkdat >> FLATDATA(buf);
3435 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3439 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3441 } catch (const std::exception&) {
3442 // no valid block header found; don't complain
3447 uint64_t nBlockPos = blkdat.GetPos();
3449 dbp->nPos = nBlockPos;
3450 blkdat.SetLimit(nBlockPos + nSize);
3451 blkdat.SetPos(nBlockPos);
3454 nRewind = blkdat.GetPos();
3456 // detect out of order blocks, and store them for later
3457 uint256 hash = block.GetHash();
3458 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3459 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3460 block.hashPrevBlock.ToString());
3462 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3466 // process in case the block isn't known yet
3467 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3468 CValidationState state;
3469 if (ProcessNewBlock(state, NULL, &block, dbp))
3471 if (state.IsError())
3473 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3474 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3477 // Recursively process earlier encountered successors of this block
3478 deque<uint256> queue;
3479 queue.push_back(hash);
3480 while (!queue.empty()) {
3481 uint256 head = queue.front();
3483 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3484 while (range.first != range.second) {
3485 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3486 if (ReadBlockFromDisk(block, it->second))
3488 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3490 CValidationState dummy;
3491 if (ProcessNewBlock(dummy, NULL, &block, &it->second))
3494 queue.push_back(block.GetHash());
3498 mapBlocksUnknownParent.erase(it);
3501 } catch (const std::exception& e) {
3502 LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
3505 } catch (const std::runtime_error& e) {
3506 AbortNode(std::string("System error: ") + e.what());
3509 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3513 void static CheckBlockIndex()
3515 const Consensus::Params& consensusParams = Params().GetConsensus();
3516 if (!fCheckBlockIndex) {
3522 // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3523 // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
3524 // iterating the block tree require that chainActive has been initialized.)
3525 if (chainActive.Height() < 0) {
3526 assert(mapBlockIndex.size() <= 1);
3530 // Build forward-pointing map of the entire block tree.
3531 std::multimap<CBlockIndex*,CBlockIndex*> forward;
3532 for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3533 forward.insert(std::make_pair(it->second->pprev, it->second));
3536 assert(forward.size() == mapBlockIndex.size());
3538 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3539 CBlockIndex *pindex = rangeGenesis.first->second;
3540 rangeGenesis.first++;
3541 assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3543 // Iterate over the entire block tree, using depth-first search.
3544 // Along the way, remember whether there are blocks on the path from genesis
3545 // block being explored which are the first to have certain properties.
3548 CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3549 CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3550 CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3551 CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3552 CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3553 CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3554 CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3555 while (pindex != NULL) {
3557 if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3558 if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3559 if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3560 if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3561 if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3562 if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3563 if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3565 // Begin: actual consistency checks.
3566 if (pindex->pprev == NULL) {
3567 // Genesis block checks.
3568 assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3569 assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3571 if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
3572 // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3573 // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3575 // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3576 assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3577 assert(pindexFirstMissing == pindexFirstNeverProcessed);
3579 // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3580 if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3582 if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3583 assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3584 // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3585 assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3586 assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3587 assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3588 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.
3589 assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3590 assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3591 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3592 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3593 if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3594 if (pindexFirstInvalid == NULL) {
3595 // Checks for not-invalid blocks.
3596 assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3598 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3599 if (pindexFirstInvalid == NULL) {
3600 // If this block sorts at least as good as the current tip and
3601 // is valid and we have all data for its parents, it must be in
3602 // setBlockIndexCandidates. chainActive.Tip() must also be there
3603 // even if some data has been pruned.
3604 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3605 assert(setBlockIndexCandidates.count(pindex));
3607 // If some parent is missing, then it could be that this block was in
3608 // setBlockIndexCandidates but had to be removed because of the missing data.
3609 // In this case it must be in mapBlocksUnlinked -- see test below.
3611 } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3612 assert(setBlockIndexCandidates.count(pindex) == 0);
3614 // Check whether this block is in mapBlocksUnlinked.
3615 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3616 bool foundInUnlinked = false;
3617 while (rangeUnlinked.first != rangeUnlinked.second) {
3618 assert(rangeUnlinked.first->first == pindex->pprev);
3619 if (rangeUnlinked.first->second == pindex) {
3620 foundInUnlinked = true;
3623 rangeUnlinked.first++;
3625 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3626 // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3627 assert(foundInUnlinked);
3629 if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3630 if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3631 if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3632 // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3633 assert(fHavePruned); // We must have pruned.
3634 // This block may have entered mapBlocksUnlinked if:
3635 // - it has a descendant that at some point had more work than the
3637 // - we tried switching to that descendant but were missing
3638 // data for some intermediate block between chainActive and the
3640 // So if this block is itself better than chainActive.Tip() and it wasn't in
3641 // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3642 if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3643 if (pindexFirstInvalid == NULL) {
3644 assert(foundInUnlinked);
3648 // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3649 // End: actual consistency checks.
3651 // Try descending into the first subnode.
3652 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3653 if (range.first != range.second) {
3654 // A subnode was found.
3655 pindex = range.first->second;
3659 // This is a leaf node.
3660 // Move upwards until we reach a node of which we have not yet visited the last child.
3662 // We are going to either move to a parent or a sibling of pindex.
3663 // If pindex was the first with a certain property, unset the corresponding variable.
3664 if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3665 if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3666 if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3667 if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3668 if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3669 if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3670 if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3672 CBlockIndex* pindexPar = pindex->pprev;
3673 // Find which child we just visited.
3674 std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3675 while (rangePar.first->second != pindex) {
3676 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3679 // Proceed to the next one.
3681 if (rangePar.first != rangePar.second) {
3682 // Move to the sibling.
3683 pindex = rangePar.first->second;
3694 // Check that we actually traversed the entire map.
3695 assert(nNodes == forward.size());
3698 //////////////////////////////////////////////////////////////////////////////
3703 string GetWarnings(string strFor)
3706 string strStatusBar;
3709 if (!CLIENT_VERSION_IS_RELEASE)
3710 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3712 if (GetBoolArg("-testsafemode", false))
3713 strStatusBar = strRPC = "testsafemode enabled";
3715 // Misc warnings like out of disk space and clock is wrong
3716 if (strMiscWarning != "")
3719 strStatusBar = strMiscWarning;
3722 if (fLargeWorkForkFound)
3725 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3727 else if (fLargeWorkInvalidChainFound)
3730 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.");
3736 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3738 const CAlert& alert = item.second;
3739 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3741 nPriority = alert.nPriority;
3742 strStatusBar = alert.strStatusBar;
3747 if (strFor == "statusbar")
3748 return strStatusBar;
3749 else if (strFor == "rpc")
3751 assert(!"GetWarnings(): invalid parameter");
3762 //////////////////////////////////////////////////////////////////////////////
3768 bool static AlreadyHave(const CInv& inv)
3774 bool txInMap = false;
3775 txInMap = mempool.exists(inv.hash);
3776 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3777 pcoinsTip->HaveCoins(inv.hash);
3780 return mapBlockIndex.count(inv.hash);
3782 // Don't know what it is, just say we already got one
3786 void static ProcessGetData(CNode* pfrom)
3788 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3790 vector<CInv> vNotFound;
3794 while (it != pfrom->vRecvGetData.end()) {
3795 // Don't bother if send buffer is too full to respond anyway
3796 if (pfrom->nSendSize >= SendBufferSize())
3799 const CInv &inv = *it;
3801 boost::this_thread::interruption_point();
3804 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3807 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3808 if (mi != mapBlockIndex.end())
3810 if (chainActive.Contains(mi->second)) {
3813 static const int nOneMonth = 30 * 24 * 60 * 60;
3814 // To prevent fingerprinting attacks, only send blocks outside of the active
3815 // chain if they are valid, and no more than a month older (both in time, and in
3816 // best equivalent proof of work) than the best header chain we know about.
3817 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3818 (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
3819 (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
3821 LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
3825 // Pruned nodes may have deleted the block, so check whether
3826 // it's available before trying to send.
3827 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
3829 // Send block from disk
3831 if (!ReadBlockFromDisk(block, (*mi).second))
3832 assert(!"cannot load block from disk");
3833 if (inv.type == MSG_BLOCK)
3834 pfrom->PushMessage("block", block);
3835 else // MSG_FILTERED_BLOCK)
3837 LOCK(pfrom->cs_filter);
3840 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3841 pfrom->PushMessage("merkleblock", merkleBlock);
3842 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3843 // This avoids hurting performance by pointlessly requiring a round-trip
3844 // Note that there is currently no way for a node to request any single transactions we didn't send here -
3845 // they must either disconnect and retry or request the full block.
3846 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3847 // however we MUST always provide at least what the remote peer needs
3848 typedef std::pair<unsigned int, uint256> PairType;
3849 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3850 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3851 pfrom->PushMessage("tx", block.vtx[pair.first]);
3857 // Trigger the peer node to send a getblocks request for the next batch of inventory
3858 if (inv.hash == pfrom->hashContinue)
3860 // Bypass PushInventory, this must send even if redundant,
3861 // and we want it right after the last block so they don't
3862 // wait for other stuff first.
3864 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3865 pfrom->PushMessage("inv", vInv);
3866 pfrom->hashContinue.SetNull();
3870 else if (inv.IsKnownType())
3872 // Send stream from relay memory
3873 bool pushed = false;
3876 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3877 if (mi != mapRelay.end()) {
3878 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3882 if (!pushed && inv.type == MSG_TX) {
3884 if (mempool.lookup(inv.hash, tx)) {
3885 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3888 pfrom->PushMessage("tx", ss);
3893 vNotFound.push_back(inv);
3897 // Track requests for our stuff.
3898 GetMainSignals().Inventory(inv.hash);
3900 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3905 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3907 if (!vNotFound.empty()) {
3908 // Let the peer know that we didn't find what it asked for, so it doesn't
3909 // have to wait around forever. Currently only SPV clients actually care
3910 // about this message: it's needed when they are recursively walking the
3911 // dependencies of relevant unconfirmed transactions. SPV clients want to
3912 // do that because they want to know about (and store and rebroadcast and
3913 // risk analyze) the dependencies of transactions relevant to them, without
3914 // having to download the entire memory pool.
3915 pfrom->PushMessage("notfound", vNotFound);
3919 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3921 const CChainParams& chainparams = Params();
3922 RandAddSeedPerfmon();
3923 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3924 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3926 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3933 if (strCommand == "version")
3935 // Each connection can only send one version message
3936 if (pfrom->nVersion != 0)
3938 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3939 Misbehaving(pfrom->GetId(), 1);
3946 uint64_t nNonce = 1;
3947 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3948 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3950 // disconnect from peers older than this proto version
3951 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3952 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3953 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3954 pfrom->fDisconnect = true;
3958 if (pfrom->nVersion == 10300)
3959 pfrom->nVersion = 300;
3961 vRecv >> addrFrom >> nNonce;
3962 if (!vRecv.empty()) {
3963 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3964 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3967 vRecv >> pfrom->nStartingHeight;
3969 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3971 pfrom->fRelayTxes = true;
3973 // Disconnect if we connected to ourself
3974 if (nNonce == nLocalHostNonce && nNonce > 1)
3976 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3977 pfrom->fDisconnect = true;
3981 pfrom->addrLocal = addrMe;
3982 if (pfrom->fInbound && addrMe.IsRoutable())
3987 // Be shy and don't send version until we hear
3988 if (pfrom->fInbound)
3989 pfrom->PushVersion();
3991 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3993 // Potentially mark this peer as a preferred download peer.
3994 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3997 pfrom->PushMessage("verack");
3998 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4000 if (!pfrom->fInbound)
4002 // Advertise our address
4003 if (fListen && !IsInitialBlockDownload())
4005 CAddress addr = GetLocalAddress(&pfrom->addr);
4006 if (addr.IsRoutable())
4008 pfrom->PushAddress(addr);
4009 } else if (IsPeerAddrLocalGood(pfrom)) {
4010 addr.SetIP(pfrom->addrLocal);
4011 pfrom->PushAddress(addr);
4015 // Get recent addresses
4016 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4018 pfrom->PushMessage("getaddr");
4019 pfrom->fGetAddr = true;
4021 addrman.Good(pfrom->addr);
4023 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4025 addrman.Add(addrFrom, addrFrom);
4026 addrman.Good(addrFrom);
4033 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4034 item.second.RelayTo(pfrom);
4037 pfrom->fSuccessfullyConnected = true;
4041 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4043 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4044 pfrom->cleanSubVer, pfrom->nVersion,
4045 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4048 int64_t nTimeOffset = nTime - GetTime();
4049 pfrom->nTimeOffset = nTimeOffset;
4050 AddTimeData(pfrom->addr, nTimeOffset);
4054 else if (pfrom->nVersion == 0)
4056 // Must have a version message before anything else
4057 Misbehaving(pfrom->GetId(), 1);
4062 else if (strCommand == "verack")
4064 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4066 // Mark this node as currently connected, so we update its timestamp later.
4067 if (pfrom->fNetworkNode) {
4069 State(pfrom->GetId())->fCurrentlyConnected = true;
4074 else if (strCommand == "addr")
4076 vector<CAddress> vAddr;
4079 // Don't want addr from older versions unless seeding
4080 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4082 if (vAddr.size() > 1000)
4084 Misbehaving(pfrom->GetId(), 20);
4085 return error("message addr size() = %u", vAddr.size());
4088 // Store the new addresses
4089 vector<CAddress> vAddrOk;
4090 int64_t nNow = GetAdjustedTime();
4091 int64_t nSince = nNow - 10 * 60;
4092 BOOST_FOREACH(CAddress& addr, vAddr)
4094 boost::this_thread::interruption_point();
4096 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4097 addr.nTime = nNow - 5 * 24 * 60 * 60;
4098 pfrom->AddAddressKnown(addr);
4099 bool fReachable = IsReachable(addr);
4100 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4102 // Relay to a limited number of other nodes
4105 // Use deterministic randomness to send to the same nodes for 24 hours
4106 // at a time so the addrKnowns of the chosen nodes prevent repeats
4107 static uint256 hashSalt;
4108 if (hashSalt.IsNull())
4109 hashSalt = GetRandHash();
4110 uint64_t hashAddr = addr.GetHash();
4111 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4112 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4113 multimap<uint256, CNode*> mapMix;
4114 BOOST_FOREACH(CNode* pnode, vNodes)
4116 if (pnode->nVersion < CADDR_TIME_VERSION)
4118 unsigned int nPointer;
4119 memcpy(&nPointer, &pnode, sizeof(nPointer));
4120 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4121 hashKey = Hash(BEGIN(hashKey), END(hashKey));
4122 mapMix.insert(make_pair(hashKey, pnode));
4124 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4125 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4126 ((*mi).second)->PushAddress(addr);
4129 // Do not store addresses outside our network
4131 vAddrOk.push_back(addr);
4133 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4134 if (vAddr.size() < 1000)
4135 pfrom->fGetAddr = false;
4136 if (pfrom->fOneShot)
4137 pfrom->fDisconnect = true;
4141 else if (strCommand == "inv")
4145 if (vInv.size() > MAX_INV_SZ)
4147 Misbehaving(pfrom->GetId(), 20);
4148 return error("message inv size() = %u", vInv.size());
4153 std::vector<CInv> vToFetch;
4155 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4157 const CInv &inv = vInv[nInv];
4159 boost::this_thread::interruption_point();
4160 pfrom->AddInventoryKnown(inv);
4162 bool fAlreadyHave = AlreadyHave(inv);
4163 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4165 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4168 if (inv.type == MSG_BLOCK) {
4169 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4170 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4171 // First request the headers preceding the announced block. In the normal fully-synced
4172 // case where a new block is announced that succeeds the current tip (no reorganization),
4173 // there are no such headers.
4174 // Secondly, and only when we are close to being synced, we request the announced block directly,
4175 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4176 // time the block arrives, the header chain leading up to it is already validated. Not
4177 // doing this will result in the received block being rejected as an orphan in case it is
4178 // not a direct successor.
4179 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4180 CNodeState *nodestate = State(pfrom->GetId());
4181 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4182 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4183 vToFetch.push_back(inv);
4184 // Mark block as in flight already, even though the actual "getdata" message only goes out
4185 // later (within the same cs_main lock, though).
4186 MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
4188 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4192 // Track requests for our stuff
4193 GetMainSignals().Inventory(inv.hash);
4195 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4196 Misbehaving(pfrom->GetId(), 50);
4197 return error("send buffer size() = %u", pfrom->nSendSize);
4201 if (!vToFetch.empty())
4202 pfrom->PushMessage("getdata", vToFetch);
4206 else if (strCommand == "getdata")
4210 if (vInv.size() > MAX_INV_SZ)
4212 Misbehaving(pfrom->GetId(), 20);
4213 return error("message getdata size() = %u", vInv.size());
4216 if (fDebug || (vInv.size() != 1))
4217 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4219 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4220 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4222 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4223 ProcessGetData(pfrom);
4227 else if (strCommand == "getblocks")
4229 CBlockLocator locator;
4231 vRecv >> locator >> hashStop;
4235 // Find the last block the caller has in the main chain
4236 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4238 // Send the rest of the chain
4240 pindex = chainActive.Next(pindex);
4242 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4243 for (; pindex; pindex = chainActive.Next(pindex))
4245 if (pindex->GetBlockHash() == hashStop)
4247 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4250 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4253 // When this block is requested, we'll send an inv that'll
4254 // trigger the peer to getblocks the next batch of inventory.
4255 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4256 pfrom->hashContinue = pindex->GetBlockHash();
4263 else if (strCommand == "getheaders")
4265 CBlockLocator locator;
4267 vRecv >> locator >> hashStop;
4271 CBlockIndex* pindex = NULL;
4272 if (locator.IsNull())
4274 // If locator is null, return the hashStop block
4275 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4276 if (mi == mapBlockIndex.end())
4278 pindex = (*mi).second;
4282 // Find the last block the caller has in the main chain
4283 pindex = FindForkInGlobalIndex(chainActive, locator);
4285 pindex = chainActive.Next(pindex);
4288 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4289 vector<CBlock> vHeaders;
4290 int nLimit = MAX_HEADERS_RESULTS;
4291 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4292 for (; pindex; pindex = chainActive.Next(pindex))
4294 vHeaders.push_back(pindex->GetBlockHeader());
4295 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4298 pfrom->PushMessage("headers", vHeaders);
4302 else if (strCommand == "tx")
4304 vector<uint256> vWorkQueue;
4305 vector<uint256> vEraseQueue;
4309 CInv inv(MSG_TX, tx.GetHash());
4310 pfrom->AddInventoryKnown(inv);
4314 bool fMissingInputs = false;
4315 CValidationState state;
4317 mapAlreadyAskedFor.erase(inv);
4319 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4321 mempool.check(pcoinsTip);
4322 RelayTransaction(tx);
4323 vWorkQueue.push_back(inv.hash);
4324 vEraseQueue.push_back(inv.hash);
4326 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4327 pfrom->id, pfrom->cleanSubVer,
4328 tx.GetHash().ToString(),
4329 mempool.mapTx.size());
4331 // Recursively process any orphan transactions that depended on this one
4332 set<NodeId> setMisbehaving;
4333 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4335 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4336 if (itByPrev == mapOrphanTransactionsByPrev.end())
4338 for (set<uint256>::iterator mi = itByPrev->second.begin();
4339 mi != itByPrev->second.end();
4342 const uint256& orphanHash = *mi;
4343 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4344 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4345 bool fMissingInputs2 = false;
4346 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4347 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4348 // anyone relaying LegitTxX banned)
4349 CValidationState stateDummy;
4351 vEraseQueue.push_back(orphanHash);
4353 if (setMisbehaving.count(fromPeer))
4355 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4357 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
4358 RelayTransaction(orphanTx);
4359 vWorkQueue.push_back(orphanHash);
4361 else if (!fMissingInputs2)
4364 if (stateDummy.IsInvalid(nDos) && nDos > 0)
4366 // Punish peer that gave us an invalid orphan tx
4367 Misbehaving(fromPeer, nDos);
4368 setMisbehaving.insert(fromPeer);
4369 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
4371 // too-little-fee orphan
4372 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
4374 mempool.check(pcoinsTip);
4378 BOOST_FOREACH(uint256 hash, vEraseQueue)
4379 EraseOrphanTx(hash);
4381 else if (fMissingInputs)
4383 AddOrphanTx(tx, pfrom->GetId());
4385 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4386 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4387 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4389 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4390 } else if (pfrom->fWhitelisted) {
4391 // Always relay transactions received from whitelisted peers, even
4392 // if they are already in the mempool (allowing the node to function
4393 // as a gateway for nodes hidden behind it).
4394 RelayTransaction(tx);
4397 if (state.IsInvalid(nDoS))
4399 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4400 pfrom->id, pfrom->cleanSubVer,
4401 state.GetRejectReason());
4402 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4403 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4405 Misbehaving(pfrom->GetId(), nDoS);
4410 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4412 std::vector<CBlockHeader> headers;
4414 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4415 unsigned int nCount = ReadCompactSize(vRecv);
4416 if (nCount > MAX_HEADERS_RESULTS) {
4417 Misbehaving(pfrom->GetId(), 20);
4418 return error("headers message size = %u", nCount);
4420 headers.resize(nCount);
4421 for (unsigned int n = 0; n < nCount; n++) {
4422 vRecv >> headers[n];
4423 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4429 // Nothing interesting. Stop asking this peers for more headers.
4433 CBlockIndex *pindexLast = NULL;
4434 BOOST_FOREACH(const CBlockHeader& header, headers) {
4435 CValidationState state;
4436 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4437 Misbehaving(pfrom->GetId(), 20);
4438 return error("non-continuous headers sequence");
4440 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4442 if (state.IsInvalid(nDoS)) {
4444 Misbehaving(pfrom->GetId(), nDoS);
4445 return error("invalid header received");
4451 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4453 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4454 // Headers message had its maximum size; the peer may have more headers.
4455 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4456 // from there instead.
4457 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4458 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4464 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4469 CInv inv(MSG_BLOCK, block.GetHash());
4470 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4472 pfrom->AddInventoryKnown(inv);
4474 CValidationState state;
4475 ProcessNewBlock(state, pfrom, &block);
4477 if (state.IsInvalid(nDoS)) {
4478 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4479 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4482 Misbehaving(pfrom->GetId(), nDoS);
4489 // This asymmetric behavior for inbound and outbound connections was introduced
4490 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4491 // to users' AddrMan and later request them by sending getaddr messages.
4492 // Making nodes which are behind NAT and can only make outgoing connections ignore
4493 // the getaddr message mitigates the attack.
4494 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4496 pfrom->vAddrToSend.clear();
4497 vector<CAddress> vAddr = addrman.GetAddr();
4498 BOOST_FOREACH(const CAddress &addr, vAddr)
4499 pfrom->PushAddress(addr);
4503 else if (strCommand == "mempool")
4505 LOCK2(cs_main, pfrom->cs_filter);
4507 std::vector<uint256> vtxid;
4508 mempool.queryHashes(vtxid);
4510 BOOST_FOREACH(uint256& hash, vtxid) {
4511 CInv inv(MSG_TX, hash);
4513 bool fInMemPool = mempool.lookup(hash, tx);
4514 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4515 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4517 vInv.push_back(inv);
4518 if (vInv.size() == MAX_INV_SZ) {
4519 pfrom->PushMessage("inv", vInv);
4523 if (vInv.size() > 0)
4524 pfrom->PushMessage("inv", vInv);
4528 else if (strCommand == "ping")
4530 if (pfrom->nVersion > BIP0031_VERSION)
4534 // Echo the message back with the nonce. This allows for two useful features:
4536 // 1) A remote node can quickly check if the connection is operational
4537 // 2) Remote nodes can measure the latency of the network thread. If this node
4538 // is overloaded it won't respond to pings quickly and the remote node can
4539 // avoid sending us more work, like chain download requests.
4541 // The nonce stops the remote getting confused between different pings: without
4542 // it, if the remote node sends a ping once per second and this node takes 5
4543 // seconds to respond to each, the 5th ping the remote sends would appear to
4544 // return very quickly.
4545 pfrom->PushMessage("pong", nonce);
4550 else if (strCommand == "pong")
4552 int64_t pingUsecEnd = nTimeReceived;
4554 size_t nAvail = vRecv.in_avail();
4555 bool bPingFinished = false;
4556 std::string sProblem;
4558 if (nAvail >= sizeof(nonce)) {
4561 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4562 if (pfrom->nPingNonceSent != 0) {
4563 if (nonce == pfrom->nPingNonceSent) {
4564 // Matching pong received, this ping is no longer outstanding
4565 bPingFinished = true;
4566 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4567 if (pingUsecTime > 0) {
4568 // Successful ping time measurement, replace previous
4569 pfrom->nPingUsecTime = pingUsecTime;
4571 // This should never happen
4572 sProblem = "Timing mishap";
4575 // Nonce mismatches are normal when pings are overlapping
4576 sProblem = "Nonce mismatch";
4578 // This is most likely a bug in another implementation somewhere; cancel this ping
4579 bPingFinished = true;
4580 sProblem = "Nonce zero";
4584 sProblem = "Unsolicited pong without ping";
4587 // This is most likely a bug in another implementation somewhere; cancel this ping
4588 bPingFinished = true;
4589 sProblem = "Short payload";
4592 if (!(sProblem.empty())) {
4593 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4597 pfrom->nPingNonceSent,
4601 if (bPingFinished) {
4602 pfrom->nPingNonceSent = 0;
4607 else if (strCommand == "alert")
4612 uint256 alertHash = alert.GetHash();
4613 if (pfrom->setKnown.count(alertHash) == 0)
4615 if (alert.ProcessAlert(Params().AlertKey()))
4618 pfrom->setKnown.insert(alertHash);
4621 BOOST_FOREACH(CNode* pnode, vNodes)
4622 alert.RelayTo(pnode);
4626 // Small DoS penalty so peers that send us lots of
4627 // duplicate/expired/invalid-signature/whatever alerts
4628 // eventually get banned.
4629 // This isn't a Misbehaving(100) (immediate ban) because the
4630 // peer might be an older or different implementation with
4631 // a different signature key, etc.
4632 Misbehaving(pfrom->GetId(), 10);
4638 else if (strCommand == "filterload")
4640 CBloomFilter filter;
4643 if (!filter.IsWithinSizeConstraints())
4644 // There is no excuse for sending a too-large filter
4645 Misbehaving(pfrom->GetId(), 100);
4648 LOCK(pfrom->cs_filter);
4649 delete pfrom->pfilter;
4650 pfrom->pfilter = new CBloomFilter(filter);
4651 pfrom->pfilter->UpdateEmptyFull();
4653 pfrom->fRelayTxes = true;
4657 else if (strCommand == "filteradd")
4659 vector<unsigned char> vData;
4662 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4663 // and thus, the maximum size any matched object can have) in a filteradd message
4664 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4666 Misbehaving(pfrom->GetId(), 100);
4668 LOCK(pfrom->cs_filter);
4670 pfrom->pfilter->insert(vData);
4672 Misbehaving(pfrom->GetId(), 100);
4677 else if (strCommand == "filterclear")
4679 LOCK(pfrom->cs_filter);
4680 delete pfrom->pfilter;
4681 pfrom->pfilter = new CBloomFilter();
4682 pfrom->fRelayTxes = true;
4686 else if (strCommand == "reject")
4690 string strMsg; unsigned char ccode; string strReason;
4691 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4694 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4696 if (strMsg == "block" || strMsg == "tx")
4700 ss << ": hash " << hash.ToString();
4702 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4703 } catch (const std::ios_base::failure&) {
4704 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4705 LogPrint("net", "Unparseable reject message received\n");
4712 // Ignore unknown commands for extensibility
4713 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4721 // requires LOCK(cs_vRecvMsg)
4722 bool ProcessMessages(CNode* pfrom)
4725 // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
4729 // (4) message start
4737 if (!pfrom->vRecvGetData.empty())
4738 ProcessGetData(pfrom);
4740 // this maintains the order of responses
4741 if (!pfrom->vRecvGetData.empty()) return fOk;
4743 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4744 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4745 // Don't bother if send buffer is too full to respond anyway
4746 if (pfrom->nSendSize >= SendBufferSize())
4750 CNetMessage& msg = *it;
4753 // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
4754 // msg.hdr.nMessageSize, msg.vRecv.size(),
4755 // msg.complete() ? "Y" : "N");
4757 // end, if an incomplete message is found
4758 if (!msg.complete())
4761 // at this point, any failure means we can delete the current message
4764 // Scan for message start
4765 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4766 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4772 CMessageHeader& hdr = msg.hdr;
4773 if (!hdr.IsValid(Params().MessageStart()))
4775 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4778 string strCommand = hdr.GetCommand();
4781 unsigned int nMessageSize = hdr.nMessageSize;
4784 CDataStream& vRecv = msg.vRecv;
4785 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4786 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4787 if (nChecksum != hdr.nChecksum)
4789 LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
4790 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4798 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4799 boost::this_thread::interruption_point();
4801 catch (const std::ios_base::failure& e)
4803 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4804 if (strstr(e.what(), "end of data"))
4806 // Allow exceptions from under-length message on vRecv
4807 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());
4809 else if (strstr(e.what(), "size too large"))
4811 // Allow exceptions from over-long size
4812 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4816 PrintExceptionContinue(&e, "ProcessMessages()");
4819 catch (const boost::thread_interrupted&) {
4822 catch (const std::exception& e) {
4823 PrintExceptionContinue(&e, "ProcessMessages()");
4825 PrintExceptionContinue(NULL, "ProcessMessages()");
4829 LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
4834 // In case the connection got shut down, its receive buffer was wiped
4835 if (!pfrom->fDisconnect)
4836 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4842 bool SendMessages(CNode* pto, bool fSendTrickle)
4844 const Consensus::Params& consensusParams = Params().GetConsensus();
4846 // Don't send anything until we get its version message
4847 if (pto->nVersion == 0)
4853 bool pingSend = false;
4854 if (pto->fPingQueued) {
4855 // RPC ping request by user
4858 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4859 // Ping automatically sent as a latency probe & keepalive.
4864 while (nonce == 0) {
4865 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4867 pto->fPingQueued = false;
4868 pto->nPingUsecStart = GetTimeMicros();
4869 if (pto->nVersion > BIP0031_VERSION) {
4870 pto->nPingNonceSent = nonce;
4871 pto->PushMessage("ping", nonce);
4873 // Peer is too old to support ping command with nonce, pong will never arrive.
4874 pto->nPingNonceSent = 0;
4875 pto->PushMessage("ping");
4879 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4883 // Address refresh broadcast
4884 static int64_t nLastRebroadcast;
4885 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4888 BOOST_FOREACH(CNode* pnode, vNodes)
4890 // Periodically clear addrKnown to allow refresh broadcasts
4891 if (nLastRebroadcast)
4892 pnode->addrKnown.clear();
4894 // Rebroadcast our address
4895 AdvertizeLocal(pnode);
4897 if (!vNodes.empty())
4898 nLastRebroadcast = GetTime();
4906 vector<CAddress> vAddr;
4907 vAddr.reserve(pto->vAddrToSend.size());
4908 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4910 if (!pto->addrKnown.contains(addr.GetKey()))
4912 pto->addrKnown.insert(addr.GetKey());
4913 vAddr.push_back(addr);
4914 // receiver rejects addr messages larger than 1000
4915 if (vAddr.size() >= 1000)
4917 pto->PushMessage("addr", vAddr);
4922 pto->vAddrToSend.clear();
4924 pto->PushMessage("addr", vAddr);
4927 CNodeState &state = *State(pto->GetId());
4928 if (state.fShouldBan) {
4929 if (pto->fWhitelisted)
4930 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4932 pto->fDisconnect = true;
4933 if (pto->addr.IsLocal())
4934 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4937 CNode::Ban(pto->addr);
4940 state.fShouldBan = false;
4943 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4944 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4945 state.rejects.clear();
4948 if (pindexBestHeader == NULL)
4949 pindexBestHeader = chainActive.Tip();
4950 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.
4951 if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
4952 // Only actively request headers from a single peer, unless we're close to today.
4953 if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4954 state.fSyncStarted = true;
4956 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4957 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4958 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
4962 // Resend wallet transactions that haven't gotten in a block yet
4963 // Except during reindex, importing and IBD, when old wallet
4964 // transactions become unconfirmed and spams other nodes.
4965 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4967 GetMainSignals().Broadcast(nTimeBestReceived);
4971 // Message: inventory
4974 vector<CInv> vInvWait;
4976 LOCK(pto->cs_inventory);
4977 vInv.reserve(pto->vInventoryToSend.size());
4978 vInvWait.reserve(pto->vInventoryToSend.size());
4979 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4981 if (pto->setInventoryKnown.count(inv))
4984 // trickle out tx inv to protect privacy
4985 if (inv.type == MSG_TX && !fSendTrickle)
4987 // 1/4 of tx invs blast to all immediately
4988 static uint256 hashSalt;
4989 if (hashSalt.IsNull())
4990 hashSalt = GetRandHash();
4991 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
4992 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4993 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
4997 vInvWait.push_back(inv);
5002 // returns true if wasn't already contained in the set
5003 if (pto->setInventoryKnown.insert(inv).second)
5005 vInv.push_back(inv);
5006 if (vInv.size() >= 1000)
5008 pto->PushMessage("inv", vInv);
5013 pto->vInventoryToSend = vInvWait;
5016 pto->PushMessage("inv", vInv);
5018 // Detect whether we're stalling
5019 int64_t nNow = GetTimeMicros();
5020 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5021 // Stalling only triggers when the block download window cannot move. During normal steady state,
5022 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5023 // should only happen during initial block download.
5024 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5025 pto->fDisconnect = true;
5027 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5028 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5029 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5030 // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5031 // to unreasonably increase our timeout.
5032 // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5033 // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5034 // only looking at this peer's oldest request). This way a large queue in the past doesn't result in a
5035 // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5036 // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5037 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5038 QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5039 int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders);
5040 if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5041 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5042 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5044 if (queuedBlock.nTimeDisconnect < nNow) {
5045 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5046 pto->fDisconnect = true;
5051 // Message: getdata (blocks)
5053 vector<CInv> vGetData;
5054 if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5055 vector<CBlockIndex*> vToDownload;
5056 NodeId staller = -1;
5057 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5058 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5059 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5060 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
5061 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5062 pindex->nHeight, pto->id);
5064 if (state.nBlocksInFlight == 0 && staller != -1) {
5065 if (State(staller)->nStallingSince == 0) {
5066 State(staller)->nStallingSince = nNow;
5067 LogPrint("net", "Stall started peer=%d\n", staller);
5073 // Message: getdata (non-blocks)
5075 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5077 const CInv& inv = (*pto->mapAskFor.begin()).second;
5078 if (!AlreadyHave(inv))
5081 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5082 vGetData.push_back(inv);
5083 if (vGetData.size() >= 1000)
5085 pto->PushMessage("getdata", vGetData);
5089 pto->mapAskFor.erase(pto->mapAskFor.begin());
5091 if (!vGetData.empty())
5092 pto->PushMessage("getdata", vGetData);
5098 std::string CBlockFileInfo::ToString() const {
5099 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));
5110 BlockMap::iterator it1 = mapBlockIndex.begin();
5111 for (; it1 != mapBlockIndex.end(); it1++)
5112 delete (*it1).second;
5113 mapBlockIndex.clear();
5115 // orphan transactions
5116 mapOrphanTransactions.clear();
5117 mapOrphanTransactionsByPrev.clear();
5119 } instance_of_cmaincleanup;