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.
8 #include "arith_uint256.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
15 #include "merkleblock.h"
19 #include "txmempool.h"
20 #include "ui_interface.h"
23 #include "utilmoneystr.h"
27 #include <boost/algorithm/string/replace.hpp>
28 #include <boost/filesystem.hpp>
29 #include <boost/filesystem/fstream.hpp>
30 #include <boost/thread.hpp>
35 # error "Bitcoin cannot be compiled without assertions."
42 CCriticalSection cs_main;
44 BlockMap mapBlockIndex;
46 CBlockIndex *pindexBestHeader = NULL;
47 int64_t nTimeBestReceived = 0;
48 CWaitableCriticalSection csBestBlock;
49 CConditionVariable cvBlockChange;
50 int nScriptCheckThreads = 0;
51 bool fImporting = false;
52 bool fReindex = false;
53 bool fTxIndex = false;
54 bool fIsBareMultisigStd = true;
55 unsigned int nCoinCacheSize = 5000;
57 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
58 CFeeRate minRelayTxFee = CFeeRate(1000);
60 CTxMemPool mempool(::minRelayTxFee);
66 map<uint256, COrphanTx> mapOrphanTransactions;
67 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
68 void EraseOrphansFor(NodeId peer);
71 * Returns true if there are nRequired or more blocks of minVersion or above
72 * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
73 * and going backwards.
75 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
77 /** Constant stuff for coinbase transactions we create: */
78 CScript COINBASE_FLAGS;
80 const string strMessageMagic = "Bitcoin Signed Message:\n";
85 struct CBlockIndexWorkComparator
87 bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
88 // First sort by most total work, ...
89 if (pa->nChainWork > pb->nChainWork) return false;
90 if (pa->nChainWork < pb->nChainWork) return true;
92 // ... then by earliest time received, ...
93 if (pa->nSequenceId < pb->nSequenceId) return false;
94 if (pa->nSequenceId > pb->nSequenceId) return true;
96 // Use pointer address as tie breaker (should only happen with blocks
97 // loaded from disk, as those all have id 0).
98 if (pa < pb) return false;
99 if (pa > pb) return true;
106 CBlockIndex *pindexBestInvalid;
109 * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS or better that are at least
110 * as good as our current tip. Entries may be failed, though.
112 set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
113 /** Number of nodes with fSyncStarted. */
114 int nSyncStarted = 0;
115 /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
116 multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
118 CCriticalSection cs_LastBlockFile;
119 std::vector<CBlockFileInfo> vinfoBlockFile;
120 int nLastBlockFile = 0;
123 * Every received block is assigned a unique and increasing identifier, so we
124 * know which one to give priority in case of a fork.
126 CCriticalSection cs_nBlockSequenceId;
127 /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
128 uint32_t nBlockSequenceId = 1;
131 * Sources of received blocks, to be able to send them reject messages or ban
132 * them, if processing happens afterwards. Protected by cs_main.
134 map<uint256, NodeId> mapBlockSource;
136 /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
139 CBlockIndex *pindex; //! Optional.
140 int64_t nTime; //! Time of "getdata" request in microseconds.
141 int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested.
142 bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
144 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
146 /** Number of blocks in flight with validated headers. */
147 int nQueuedValidatedHeaders = 0;
149 /** Number of preferable block download peers. */
150 int nPreferredDownload = 0;
152 /** Dirty block index entries. */
153 set<CBlockIndex*> setDirtyBlockIndex;
155 /** Dirty block file entries. */
156 set<int> setDirtyFileInfo;
159 //////////////////////////////////////////////////////////////////////////////
161 // dispatching functions
164 // These functions dispatch to one or all registered wallets
168 struct CMainSignals {
169 /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
170 boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
171 /** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
172 boost::signals2::signal<void (const uint256 &)> EraseTransaction;
173 /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
174 boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
175 /** Notifies listeners of a new active block chain. */
176 boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
177 /** Notifies listeners about an inventory item being seen on the network. */
178 boost::signals2::signal<void (const uint256 &)> Inventory;
179 /** Tells listeners to broadcast their data. */
180 boost::signals2::signal<void ()> Broadcast;
181 /** Notifies listeners of a block validation result */
182 boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
187 void RegisterValidationInterface(CValidationInterface* pwalletIn) {
188 g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
189 g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
190 g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
191 g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
192 g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
193 g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
194 g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
197 void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
198 g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
199 g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
200 g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
201 g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
202 g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
203 g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
204 g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
207 void UnregisterAllValidationInterfaces() {
208 g_signals.BlockChecked.disconnect_all_slots();
209 g_signals.Broadcast.disconnect_all_slots();
210 g_signals.Inventory.disconnect_all_slots();
211 g_signals.SetBestChain.disconnect_all_slots();
212 g_signals.UpdatedTransaction.disconnect_all_slots();
213 g_signals.EraseTransaction.disconnect_all_slots();
214 g_signals.SyncTransaction.disconnect_all_slots();
217 void SyncWithWallets(const CTransaction &tx, const CBlock *pblock) {
218 g_signals.SyncTransaction(tx, pblock);
221 //////////////////////////////////////////////////////////////////////////////
223 // Registration of network node signals.
228 struct CBlockReject {
229 unsigned char chRejectCode;
230 string strRejectReason;
235 * Maintain validation-specific state about nodes, protected by cs_main, instead
236 * by CNode's own locks. This simplifies asynchronous operation, where
237 * processing of incoming data is done after the ProcessMessage call returns,
238 * and we're no longer holding the node's locks.
241 //! The peer's address
243 //! Whether we have a fully established connection.
244 bool fCurrentlyConnected;
245 //! Accumulated misbehaviour score for this peer.
247 //! Whether this peer should be disconnected and banned (unless whitelisted).
249 //! String name of this peer (debugging/logging purposes).
251 //! List of asynchronously-determined block rejections to notify this peer about.
252 std::vector<CBlockReject> rejects;
253 //! The best known block we know this peer has announced.
254 CBlockIndex *pindexBestKnownBlock;
255 //! The hash of the last unknown block this peer has announced.
256 uint256 hashLastUnknownBlock;
257 //! The last full block we both have.
258 CBlockIndex *pindexLastCommonBlock;
259 //! Whether we've started headers synchronization with this peer.
261 //! Since when we're stalling block download progress (in microseconds), or 0.
262 int64_t nStallingSince;
263 list<QueuedBlock> vBlocksInFlight;
265 //! Whether we consider this a preferred download peer.
266 bool fPreferredDownload;
269 fCurrentlyConnected = false;
272 pindexBestKnownBlock = NULL;
273 hashLastUnknownBlock.SetNull();
274 pindexLastCommonBlock = NULL;
275 fSyncStarted = false;
278 fPreferredDownload = false;
282 /** Map maintaining per-node state. Requires cs_main. */
283 map<NodeId, CNodeState> mapNodeState;
286 CNodeState *State(NodeId pnode) {
287 map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
288 if (it == mapNodeState.end())
296 return chainActive.Height();
299 void UpdatePreferredDownload(CNode* node, CNodeState* state)
301 nPreferredDownload -= state->fPreferredDownload;
303 // Whether this node should be marked as a preferred download node.
304 state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
306 nPreferredDownload += state->fPreferredDownload;
309 void InitializeNode(NodeId nodeid, const CNode *pnode) {
311 CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
312 state.name = pnode->addrName;
313 state.address = pnode->addr;
316 void FinalizeNode(NodeId nodeid) {
318 CNodeState *state = State(nodeid);
320 if (state->fSyncStarted)
323 if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
324 AddressCurrentlyConnected(state->address);
327 BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
328 mapBlocksInFlight.erase(entry.hash);
329 EraseOrphansFor(nodeid);
330 nPreferredDownload -= state->fPreferredDownload;
332 mapNodeState.erase(nodeid);
336 void MarkBlockAsReceived(const uint256& hash) {
337 map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
338 if (itInFlight != mapBlocksInFlight.end()) {
339 CNodeState *state = State(itInFlight->second.first);
340 nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
341 state->vBlocksInFlight.erase(itInFlight->second.second);
342 state->nBlocksInFlight--;
343 state->nStallingSince = 0;
344 mapBlocksInFlight.erase(itInFlight);
349 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
350 CNodeState *state = State(nodeid);
351 assert(state != NULL);
353 // Make sure it's not listed somewhere already.
354 MarkBlockAsReceived(hash);
356 QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
357 nQueuedValidatedHeaders += newentry.fValidatedHeaders;
358 list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
359 state->nBlocksInFlight++;
360 mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
363 /** Check whether the last unknown block a peer advertized is not yet known. */
364 void ProcessBlockAvailability(NodeId nodeid) {
365 CNodeState *state = State(nodeid);
366 assert(state != NULL);
368 if (!state->hashLastUnknownBlock.IsNull()) {
369 BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
370 if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
371 if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
372 state->pindexBestKnownBlock = itOld->second;
373 state->hashLastUnknownBlock.SetNull();
378 /** Update tracking information about which blocks a peer is assumed to have. */
379 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
380 CNodeState *state = State(nodeid);
381 assert(state != NULL);
383 ProcessBlockAvailability(nodeid);
385 BlockMap::iterator it = mapBlockIndex.find(hash);
386 if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
387 // An actually better block was announced.
388 if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
389 state->pindexBestKnownBlock = it->second;
391 // An unknown block was announced; just assume that the latest one is the best one.
392 state->hashLastUnknownBlock = hash;
396 /** Find the last common ancestor two blocks have.
397 * Both pa and pb must be non-NULL. */
398 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
399 if (pa->nHeight > pb->nHeight) {
400 pa = pa->GetAncestor(pb->nHeight);
401 } else if (pb->nHeight > pa->nHeight) {
402 pb = pb->GetAncestor(pa->nHeight);
405 while (pa != pb && pa && pb) {
410 // Eventually all chain branches meet at the genesis block.
415 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
416 * at most count entries. */
417 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
421 vBlocks.reserve(vBlocks.size() + count);
422 CNodeState *state = State(nodeid);
423 assert(state != NULL);
425 // Make sure pindexBestKnownBlock is up to date, we'll need it.
426 ProcessBlockAvailability(nodeid);
428 if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
429 // This peer has nothing interesting.
433 if (state->pindexLastCommonBlock == NULL) {
434 // Bootstrap quickly by guessing a parent of our best tip is the forking point.
435 // Guessing wrong in either direction is not a problem.
436 state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
439 // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
440 // of their current tip anymore. Go back enough to fix that.
441 state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
442 if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
445 std::vector<CBlockIndex*> vToFetch;
446 CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
447 // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
448 // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
449 // download that next block if the window were 1 larger.
450 int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
451 int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
452 NodeId waitingfor = -1;
453 while (pindexWalk->nHeight < nMaxHeight) {
454 // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
455 // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
456 // as iterating over ~100 CBlockIndex* entries anyway.
457 int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
458 vToFetch.resize(nToFetch);
459 pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
460 vToFetch[nToFetch - 1] = pindexWalk;
461 for (unsigned int i = nToFetch - 1; i > 0; i--) {
462 vToFetch[i - 1] = vToFetch[i]->pprev;
465 // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
466 // are not yet downloaded and not in flight to vBlocks. In the mean time, update
467 // pindexLastCommonBlock as long as all ancestors are already downloaded.
468 BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
469 if (!pindex->IsValid(BLOCK_VALID_TREE)) {
470 // We consider the chain that this peer is on invalid.
473 if (pindex->nStatus & BLOCK_HAVE_DATA) {
474 if (pindex->nChainTx)
475 state->pindexLastCommonBlock = pindex;
476 } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
477 // The block is not already downloaded, and not yet in flight.
478 if (pindex->nHeight > nWindowEnd) {
479 // We reached the end of the window.
480 if (vBlocks.size() == 0 && waitingfor != nodeid) {
481 // We aren't able to fetch anything, but we would be if the download window was one larger.
482 nodeStaller = waitingfor;
486 vBlocks.push_back(pindex);
487 if (vBlocks.size() == count) {
490 } else if (waitingfor == -1) {
491 // This is the first already-in-flight block.
492 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
500 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
502 CNodeState *state = State(nodeid);
505 stats.nMisbehavior = state->nMisbehavior;
506 stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
507 stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
508 BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
510 stats.vHeightInFlight.push_back(queue.pindex->nHeight);
515 void RegisterNodeSignals(CNodeSignals& nodeSignals)
517 nodeSignals.GetHeight.connect(&GetHeight);
518 nodeSignals.ProcessMessages.connect(&ProcessMessages);
519 nodeSignals.SendMessages.connect(&SendMessages);
520 nodeSignals.InitializeNode.connect(&InitializeNode);
521 nodeSignals.FinalizeNode.connect(&FinalizeNode);
524 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
526 nodeSignals.GetHeight.disconnect(&GetHeight);
527 nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
528 nodeSignals.SendMessages.disconnect(&SendMessages);
529 nodeSignals.InitializeNode.disconnect(&InitializeNode);
530 nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
533 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
535 // Find the first block the caller has in the main chain
536 BOOST_FOREACH(const uint256& hash, locator.vHave) {
537 BlockMap::iterator mi = mapBlockIndex.find(hash);
538 if (mi != mapBlockIndex.end())
540 CBlockIndex* pindex = (*mi).second;
541 if (chain.Contains(pindex))
545 return chain.Genesis();
548 CCoinsViewCache *pcoinsTip = NULL;
549 CBlockTreeDB *pblocktree = NULL;
551 //////////////////////////////////////////////////////////////////////////////
553 // mapOrphanTransactions
556 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
558 uint256 hash = tx.GetHash();
559 if (mapOrphanTransactions.count(hash))
562 // Ignore big transactions, to avoid a
563 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
564 // large transaction with a missing parent then we assume
565 // it will rebroadcast it later, after the parent transaction(s)
566 // have been mined or received.
567 // 10,000 orphans, each of which is at most 5,000 bytes big is
568 // at most 500 megabytes of orphans:
569 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
572 LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
576 mapOrphanTransactions[hash].tx = tx;
577 mapOrphanTransactions[hash].fromPeer = peer;
578 BOOST_FOREACH(const CTxIn& txin, tx.vin)
579 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
581 LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
582 mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
586 void static EraseOrphanTx(uint256 hash)
588 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
589 if (it == mapOrphanTransactions.end())
591 BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
593 map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
594 if (itPrev == mapOrphanTransactionsByPrev.end())
596 itPrev->second.erase(hash);
597 if (itPrev->second.empty())
598 mapOrphanTransactionsByPrev.erase(itPrev);
600 mapOrphanTransactions.erase(it);
603 void EraseOrphansFor(NodeId peer)
606 map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
607 while (iter != mapOrphanTransactions.end())
609 map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
610 if (maybeErase->second.fromPeer == peer)
612 EraseOrphanTx(maybeErase->second.tx.GetHash());
616 if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
620 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
622 unsigned int nEvicted = 0;
623 while (mapOrphanTransactions.size() > nMaxOrphans)
625 // Evict a random orphan:
626 uint256 randomhash = GetRandHash();
627 map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
628 if (it == mapOrphanTransactions.end())
629 it = mapOrphanTransactions.begin();
630 EraseOrphanTx(it->first);
642 bool IsStandardTx(const CTransaction& tx, string& reason)
644 if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
649 // Extremely large transactions with lots of inputs can cost the network
650 // almost as much to process as they cost the sender in fees, because
651 // computing signature hashes is O(ninputs*txsize). Limiting transactions
652 // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
653 unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
654 if (sz >= MAX_STANDARD_TX_SIZE) {
659 BOOST_FOREACH(const CTxIn& txin, tx.vin)
661 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
662 // keys. (remember the 520 byte limit on redeemScript size) That works
663 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
664 // bytes of scriptSig, which we round off to 1650 bytes for some minor
665 // future-proofing. That's also enough to spend a 20-of-20
666 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
667 // considered standard)
668 if (txin.scriptSig.size() > 1650) {
669 reason = "scriptsig-size";
672 if (!txin.scriptSig.IsPushOnly()) {
673 reason = "scriptsig-not-pushonly";
678 unsigned int nDataOut = 0;
679 txnouttype whichType;
680 BOOST_FOREACH(const CTxOut& txout, tx.vout) {
681 if (!::IsStandard(txout.scriptPubKey, whichType)) {
682 reason = "scriptpubkey";
686 if (whichType == TX_NULL_DATA)
688 else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
689 reason = "bare-multisig";
691 } else if (txout.IsDust(::minRelayTxFee)) {
697 // only one OP_RETURN txout is permitted
699 reason = "multi-op-return";
706 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
708 AssertLockHeld(cs_main);
709 // Time based nLockTime implemented in 0.1.6
710 if (tx.nLockTime == 0)
712 if (nBlockHeight == 0)
713 nBlockHeight = chainActive.Height();
715 nBlockTime = GetAdjustedTime();
716 if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
718 BOOST_FOREACH(const CTxIn& txin, tx.vin)
725 * Check transaction inputs to mitigate two
726 * potential denial-of-service attacks:
728 * 1. scriptSigs with extra data stuffed into them,
729 * not consumed by scriptPubKey (or P2SH script)
730 * 2. P2SH scripts with a crazy number of expensive
731 * CHECKSIG/CHECKMULTISIG operations
733 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
736 return true; // Coinbases don't use vin normally
738 for (unsigned int i = 0; i < tx.vin.size(); i++)
740 const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
742 vector<vector<unsigned char> > vSolutions;
743 txnouttype whichType;
744 // get the scriptPubKey corresponding to this input:
745 const CScript& prevScript = prev.scriptPubKey;
746 if (!Solver(prevScript, whichType, vSolutions))
748 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
749 if (nArgsExpected < 0)
752 // Transactions with extra stuff in their scriptSigs are
753 // non-standard. Note that this EvalScript() call will
754 // be quick, because if there are any operations
755 // beside "push data" in the scriptSig
756 // IsStandardTx() will have already returned false
757 // and this method isn't called.
758 vector<vector<unsigned char> > stack;
759 if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
762 if (whichType == TX_SCRIPTHASH)
766 CScript subscript(stack.back().begin(), stack.back().end());
767 vector<vector<unsigned char> > vSolutions2;
768 txnouttype whichType2;
769 if (Solver(subscript, whichType2, vSolutions2))
771 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
774 nArgsExpected += tmpExpected;
778 // Any other Script with less than 15 sigops OK:
779 unsigned int sigops = subscript.GetSigOpCount(true);
780 // ... extra data left on the stack after execution is OK, too:
781 return (sigops <= MAX_P2SH_SIGOPS);
785 if (stack.size() != (unsigned int)nArgsExpected)
792 unsigned int GetLegacySigOpCount(const CTransaction& tx)
794 unsigned int nSigOps = 0;
795 BOOST_FOREACH(const CTxIn& txin, tx.vin)
797 nSigOps += txin.scriptSig.GetSigOpCount(false);
799 BOOST_FOREACH(const CTxOut& txout, tx.vout)
801 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
806 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
811 unsigned int nSigOps = 0;
812 for (unsigned int i = 0; i < tx.vin.size(); i++)
814 const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
815 if (prevout.scriptPubKey.IsPayToScriptHash())
816 nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
828 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
830 // Basic checks that don't depend on any context
832 return state.DoS(10, error("CheckTransaction(): vin empty"),
833 REJECT_INVALID, "bad-txns-vin-empty");
835 return state.DoS(10, error("CheckTransaction(): vout empty"),
836 REJECT_INVALID, "bad-txns-vout-empty");
838 if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
839 return state.DoS(100, error("CheckTransaction(): size limits failed"),
840 REJECT_INVALID, "bad-txns-oversize");
842 // Check for negative or overflow output values
843 CAmount nValueOut = 0;
844 BOOST_FOREACH(const CTxOut& txout, tx.vout)
846 if (txout.nValue < 0)
847 return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
848 REJECT_INVALID, "bad-txns-vout-negative");
849 if (txout.nValue > MAX_MONEY)
850 return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
851 REJECT_INVALID, "bad-txns-vout-toolarge");
852 nValueOut += txout.nValue;
853 if (!MoneyRange(nValueOut))
854 return state.DoS(100, error("CheckTransaction(): txout total out of range"),
855 REJECT_INVALID, "bad-txns-txouttotal-toolarge");
858 // Check for duplicate inputs
859 set<COutPoint> vInOutPoints;
860 BOOST_FOREACH(const CTxIn& txin, tx.vin)
862 if (vInOutPoints.count(txin.prevout))
863 return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
864 REJECT_INVALID, "bad-txns-inputs-duplicate");
865 vInOutPoints.insert(txin.prevout);
870 if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
871 return state.DoS(100, error("CheckTransaction(): coinbase script size"),
872 REJECT_INVALID, "bad-cb-length");
876 BOOST_FOREACH(const CTxIn& txin, tx.vin)
877 if (txin.prevout.IsNull())
878 return state.DoS(10, error("CheckTransaction(): prevout is null"),
879 REJECT_INVALID, "bad-txns-prevout-null");
885 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
889 uint256 hash = tx.GetHash();
890 double dPriorityDelta = 0;
891 CAmount nFeeDelta = 0;
892 mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
893 if (dPriorityDelta > 0 || nFeeDelta > 0)
897 CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
901 // There is a free transaction area in blocks created by most miners,
902 // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
903 // to be considered to fall into this category. We don't want to encourage sending
904 // multiple transactions instead of one big transaction to avoid fees.
905 if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
909 if (!MoneyRange(nMinFee))
915 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
916 bool* pfMissingInputs, bool fRejectAbsurdFee)
918 AssertLockHeld(cs_main);
920 *pfMissingInputs = false;
922 if (!CheckTransaction(tx, state))
923 return error("AcceptToMemoryPool: CheckTransaction failed");
925 // Coinbase is only valid in a block, not as a loose transaction
927 return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
928 REJECT_INVALID, "coinbase");
930 // Rather not work on nonstandard transactions (unless -testnet/-regtest)
932 if (Params().RequireStandard() && !IsStandardTx(tx, reason))
934 error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
935 REJECT_NONSTANDARD, reason);
937 // Only accept nLockTime-using transactions that can be mined in the next
938 // block; we don't want our mempool filled up with transactions that can't
941 // However, IsFinalTx() is confusing... Without arguments, it uses
942 // chainActive.Height() to evaluate nLockTime; when a block is accepted,
943 // chainActive.Height() is set to the value of nHeight in the block.
944 // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the
945 // height of the block *being* evaluated is what is used. Thus if we want
946 // to know if a transaction can be part of the *next* block, we need to
947 // call IsFinalTx() with one more than chainActive.Height().
949 // Timestamps on the other hand don't get any special treatment, because we
950 // can't know what timestamp the next block will have, and there aren't
951 // timestamp applications where it matters.
952 if (!IsFinalTx(tx, chainActive.Height() + 1))
954 error("AcceptToMemoryPool: non-final"),
955 REJECT_NONSTANDARD, "non-final");
957 // is it already in the memory pool?
958 uint256 hash = tx.GetHash();
959 if (pool.exists(hash))
962 // Check for conflicts with in-memory transactions
964 LOCK(pool.cs); // protect pool.mapNextTx
965 for (unsigned int i = 0; i < tx.vin.size(); i++)
967 COutPoint outpoint = tx.vin[i].prevout;
968 if (pool.mapNextTx.count(outpoint))
970 // Disable replacement feature for now
978 CCoinsViewCache view(&dummy);
980 CAmount nValueIn = 0;
983 CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
984 view.SetBackend(viewMemPool);
986 // do we already have it?
987 if (view.HaveCoins(hash))
990 // do all inputs exist?
991 // Note that this does not check for the presence of actual outputs (see the next check for that),
992 // only helps filling in pfMissingInputs (to determine missing vs spent).
993 BOOST_FOREACH(const CTxIn txin, tx.vin) {
994 if (!view.HaveCoins(txin.prevout.hash)) {
996 *pfMissingInputs = true;
1001 // are the actual inputs available?
1002 if (!view.HaveInputs(tx))
1003 return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
1004 REJECT_DUPLICATE, "bad-txns-inputs-spent");
1006 // Bring the best block into scope
1007 view.GetBestBlock();
1009 nValueIn = view.GetValueIn(tx);
1011 // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
1012 view.SetBackend(dummy);
1015 // Check for non-standard pay-to-script-hash in inputs
1016 if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1017 return error("AcceptToMemoryPool: nonstandard transaction input");
1019 // Check that the transaction doesn't have an excessive number of
1020 // sigops, making it impossible to mine. Since the coinbase transaction
1021 // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
1022 // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1023 // merely non-standard transaction.
1024 unsigned int nSigOps = GetLegacySigOpCount(tx);
1025 nSigOps += GetP2SHSigOpCount(tx, view);
1026 if (nSigOps > MAX_STANDARD_TX_SIGOPS)
1028 error("AcceptToMemoryPool: too many sigops %s, %d > %d",
1029 hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
1030 REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1032 CAmount nValueOut = tx.GetValueOut();
1033 CAmount nFees = nValueIn-nValueOut;
1034 double dPriority = view.GetPriority(tx, chainActive.Height());
1036 CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
1037 unsigned int nSize = entry.GetTxSize();
1039 // Don't accept it if it can't get into a block
1040 CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1041 if (fLimitFree && nFees < txMinFee)
1042 return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1043 hash.ToString(), nFees, txMinFee),
1044 REJECT_INSUFFICIENTFEE, "insufficient fee");
1046 // Require that free transactions have sufficient priority to be mined in the next block.
1047 if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1048 return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1051 // Continuously rate-limit free (really, very-low-fee) transactions
1052 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1053 // be annoying or make others' transactions take longer to confirm.
1054 if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1056 static CCriticalSection csFreeLimiter;
1057 static double dFreeCount;
1058 static int64_t nLastTime;
1059 int64_t nNow = GetTime();
1061 LOCK(csFreeLimiter);
1063 // Use an exponentially decaying ~10-minute window:
1064 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1066 // -limitfreerelay unit is thousand-bytes-per-minute
1067 // At default rate it would take over a month to fill 1GB
1068 if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1069 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1070 REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1071 LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1072 dFreeCount += nSize;
1075 if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1076 return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1078 nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1080 // Check against previous transactions
1081 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1082 if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1084 return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1087 // Check again against just the consensus-critical mandatory script
1088 // verification flags, in case of bugs in the standard flags that cause
1089 // transactions to pass as valid when they're actually invalid. For
1090 // instance the STRICTENC flag was incorrectly allowing certain
1091 // CHECKSIG NOT scripts to pass, even though they were invalid.
1093 // There is a similar check in CreateNewBlock() to prevent creating
1094 // invalid blocks, however allowing such transactions into the mempool
1095 // can be exploited as a DoS attack.
1096 if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1098 return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1101 // Store transaction in memory
1102 pool.addUnchecked(hash, entry);
1105 SyncWithWallets(tx, NULL);
1110 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1111 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1113 CBlockIndex *pindexSlow = NULL;
1117 if (mempool.lookup(hash, txOut))
1125 if (pblocktree->ReadTxIndex(hash, postx)) {
1126 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1128 return error("%s: OpenBlockFile failed", __func__);
1129 CBlockHeader header;
1132 fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1134 } catch (const std::exception& e) {
1135 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1137 hashBlock = header.GetHash();
1138 if (txOut.GetHash() != hash)
1139 return error("%s: txid mismatch", __func__);
1144 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1147 CCoinsViewCache &view = *pcoinsTip;
1148 const CCoins* coins = view.AccessCoins(hash);
1150 nHeight = coins->nHeight;
1153 pindexSlow = chainActive[nHeight];
1159 if (ReadBlockFromDisk(block, pindexSlow)) {
1160 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1161 if (tx.GetHash() == hash) {
1163 hashBlock = pindexSlow->GetBlockHash();
1178 //////////////////////////////////////////////////////////////////////////////
1180 // CBlock and CBlockIndex
1183 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1185 // Open history file to append
1186 CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1187 if (fileout.IsNull())
1188 return error("WriteBlockToDisk: OpenBlockFile failed");
1190 // Write index header
1191 unsigned int nSize = fileout.GetSerializeSize(block);
1192 fileout << FLATDATA(Params().MessageStart()) << nSize;
1195 long fileOutPos = ftell(fileout.Get());
1197 return error("WriteBlockToDisk: ftell failed");
1198 pos.nPos = (unsigned int)fileOutPos;
1204 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1208 // Open history file to read
1209 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1210 if (filein.IsNull())
1211 return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1217 catch (const std::exception& e) {
1218 return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1222 if (!CheckProofOfWork(block.GetHash(), block.nBits))
1223 return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1228 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1230 if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1232 if (block.GetHash() != pindex->GetBlockHash())
1233 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1234 pindex->ToString(), pindex->GetBlockPos().ToString());
1238 CAmount GetBlockValue(int nHeight, const CAmount& nFees)
1240 CAmount nSubsidy = 50 * COIN;
1241 int halvings = nHeight / Params().SubsidyHalvingInterval();
1243 // Force block reward to zero when right shift is undefined.
1247 // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1248 nSubsidy >>= halvings;
1250 return nSubsidy + nFees;
1253 bool IsInitialBlockDownload()
1256 if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1258 static bool lockIBDState = false;
1261 bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1262 pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1264 lockIBDState = true;
1268 bool fLargeWorkForkFound = false;
1269 bool fLargeWorkInvalidChainFound = false;
1270 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1272 void CheckForkWarningConditions()
1274 AssertLockHeld(cs_main);
1275 // Before we get past initial download, we cannot reliably alert about forks
1276 // (we assume we don't get stuck on a fork before the last checkpoint)
1277 if (IsInitialBlockDownload())
1280 // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1281 // of our head, drop it
1282 if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1283 pindexBestForkTip = NULL;
1285 if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1287 if (!fLargeWorkForkFound && pindexBestForkBase)
1289 std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1290 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1291 CAlert::Notify(warning, true);
1293 if (pindexBestForkTip && pindexBestForkBase)
1295 LogPrintf("CheckForkWarningConditions: 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",
1296 pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1297 pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1298 fLargeWorkForkFound = true;
1302 LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1303 fLargeWorkInvalidChainFound = true;
1308 fLargeWorkForkFound = false;
1309 fLargeWorkInvalidChainFound = false;
1313 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1315 AssertLockHeld(cs_main);
1316 // If we are on a fork that is sufficiently large, set a warning flag
1317 CBlockIndex* pfork = pindexNewForkTip;
1318 CBlockIndex* plonger = chainActive.Tip();
1319 while (pfork && pfork != plonger)
1321 while (plonger && plonger->nHeight > pfork->nHeight)
1322 plonger = plonger->pprev;
1323 if (pfork == plonger)
1325 pfork = pfork->pprev;
1328 // We define a condition which we should warn the user about as a fork of at least 7 blocks
1329 // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1330 // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1331 // hash rate operating on the fork.
1332 // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1333 // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1334 // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1335 if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1336 pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1337 chainActive.Height() - pindexNewForkTip->nHeight < 72)
1339 pindexBestForkTip = pindexNewForkTip;
1340 pindexBestForkBase = pfork;
1343 CheckForkWarningConditions();
1346 // Requires cs_main.
1347 void Misbehaving(NodeId pnode, int howmuch)
1352 CNodeState *state = State(pnode);
1356 state->nMisbehavior += howmuch;
1357 int banscore = GetArg("-banscore", 100);
1358 if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1360 LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1361 state->fShouldBan = true;
1363 LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1366 void static InvalidChainFound(CBlockIndex* pindexNew)
1368 if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1369 pindexBestInvalid = pindexNew;
1371 LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
1372 pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1373 log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1374 pindexNew->GetBlockTime()));
1375 LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
1376 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1377 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1378 CheckForkWarningConditions();
1381 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1383 if (state.IsInvalid(nDoS)) {
1384 std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1385 if (it != mapBlockSource.end() && State(it->second)) {
1386 CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1387 State(it->second)->rejects.push_back(reject);
1389 Misbehaving(it->second, nDoS);
1392 if (!state.CorruptionPossible()) {
1393 pindex->nStatus |= BLOCK_FAILED_VALID;
1394 setDirtyBlockIndex.insert(pindex);
1395 setBlockIndexCandidates.erase(pindex);
1396 InvalidChainFound(pindex);
1400 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1402 // mark inputs spent
1403 if (!tx.IsCoinBase()) {
1404 txundo.vprevout.reserve(tx.vin.size());
1405 BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1406 CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1407 unsigned nPos = txin.prevout.n;
1409 if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1411 // mark an outpoint spent, and construct undo information
1412 txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1414 if (coins->vout.size() == 0) {
1415 CTxInUndo& undo = txundo.vprevout.back();
1416 undo.nHeight = coins->nHeight;
1417 undo.fCoinBase = coins->fCoinBase;
1418 undo.nVersion = coins->nVersion;
1424 inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1427 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1430 UpdateCoins(tx, state, inputs, txundo, nHeight);
1433 bool CScriptCheck::operator()() {
1434 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1435 if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1436 return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1441 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1443 if (!tx.IsCoinBase())
1446 pvChecks->reserve(tx.vin.size());
1448 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1449 // for an attacker to attempt to split the network.
1450 if (!inputs.HaveInputs(tx))
1451 return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1453 // While checking, GetBestBlock() refers to the parent block.
1454 // This is also true for mempool checks.
1455 CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1456 int nSpendHeight = pindexPrev->nHeight + 1;
1457 CAmount nValueIn = 0;
1459 for (unsigned int i = 0; i < tx.vin.size(); i++)
1461 const COutPoint &prevout = tx.vin[i].prevout;
1462 const CCoins *coins = inputs.AccessCoins(prevout.hash);
1465 // If prev is coinbase, check that it's matured
1466 if (coins->IsCoinBase()) {
1467 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1468 return state.Invalid(
1469 error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1470 REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1473 // Check for negative or overflow input values
1474 nValueIn += coins->vout[prevout.n].nValue;
1475 if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1476 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1477 REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1481 if (nValueIn < tx.GetValueOut())
1482 return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1483 tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1484 REJECT_INVALID, "bad-txns-in-belowout");
1486 // Tally transaction fees
1487 CAmount nTxFee = nValueIn - tx.GetValueOut();
1489 return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1490 REJECT_INVALID, "bad-txns-fee-negative");
1492 if (!MoneyRange(nFees))
1493 return state.DoS(100, error("CheckInputs(): nFees out of range"),
1494 REJECT_INVALID, "bad-txns-fee-outofrange");
1496 // The first loop above does all the inexpensive checks.
1497 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1498 // Helps prevent CPU exhaustion attacks.
1500 // Skip ECDSA signature verification when connecting blocks
1501 // before the last block chain checkpoint. This is safe because block merkle hashes are
1502 // still computed and checked, and any change will be caught at the next checkpoint.
1503 if (fScriptChecks) {
1504 for (unsigned int i = 0; i < tx.vin.size(); i++) {
1505 const COutPoint &prevout = tx.vin[i].prevout;
1506 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1510 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1512 pvChecks->push_back(CScriptCheck());
1513 check.swap(pvChecks->back());
1514 } else if (!check()) {
1515 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1516 // Check whether the failure was caused by a
1517 // non-mandatory script verification check, such as
1518 // non-standard DER encodings or non-null dummy
1519 // arguments; if so, don't trigger DoS protection to
1520 // avoid splitting the network between upgraded and
1521 // non-upgraded nodes.
1522 CScriptCheck check(*coins, tx, i,
1523 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1525 return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1527 // Failures of other flags indicate a transaction that is
1528 // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1529 // such nodes as they are not following the protocol. That
1530 // said during an upgrade careful thought should be taken
1531 // as to the correct behavior - we may want to continue
1532 // peering with non-upgraded nodes even after a soft-fork
1533 // super-majority vote has passed.
1534 return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1545 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock)
1547 // Open history file to append
1548 CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1549 if (fileout.IsNull())
1550 return error("%s: OpenUndoFile failed", __func__);
1552 // Write index header
1553 unsigned int nSize = fileout.GetSerializeSize(blockundo);
1554 fileout << FLATDATA(Params().MessageStart()) << nSize;
1557 long fileOutPos = ftell(fileout.Get());
1559 return error("%s: ftell failed", __func__);
1560 pos.nPos = (unsigned int)fileOutPos;
1561 fileout << blockundo;
1563 // calculate & write checksum
1564 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1565 hasher << hashBlock;
1566 hasher << blockundo;
1567 fileout << hasher.GetHash();
1572 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1574 // Open history file to read
1575 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1576 if (filein.IsNull())
1577 return error("%s: OpenBlockFile failed", __func__);
1580 uint256 hashChecksum;
1582 filein >> blockundo;
1583 filein >> hashChecksum;
1585 catch (const std::exception& e) {
1586 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1590 CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1591 hasher << hashBlock;
1592 hasher << blockundo;
1593 if (hashChecksum != hasher.GetHash())
1594 return error("%s: Checksum mismatch", __func__);
1602 * Apply the undo operation of a CTxInUndo to the given chain state.
1603 * @param undo The undo object.
1604 * @param view The coins view to which to apply the changes.
1605 * @param out The out point that corresponds to the tx input.
1606 * @return True on success.
1608 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1612 CCoinsModifier coins = view.ModifyCoins(out.hash);
1613 if (undo.nHeight != 0) {
1614 // undo data contains height: this is the last output of the prevout tx being spent
1615 if (!coins->IsPruned())
1616 fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1618 coins->fCoinBase = undo.fCoinBase;
1619 coins->nHeight = undo.nHeight;
1620 coins->nVersion = undo.nVersion;
1622 if (coins->IsPruned())
1623 fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1625 if (coins->IsAvailable(out.n))
1626 fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1627 if (coins->vout.size() < out.n+1)
1628 coins->vout.resize(out.n+1);
1629 coins->vout[out.n] = undo.txout;
1634 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1636 assert(pindex->GetBlockHash() == view.GetBestBlock());
1643 CBlockUndo blockUndo;
1644 CDiskBlockPos pos = pindex->GetUndoPos();
1646 return error("DisconnectBlock(): no undo data available");
1647 if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1648 return error("DisconnectBlock(): failure reading undo data");
1650 if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1651 return error("DisconnectBlock(): block and undo data inconsistent");
1653 // undo transactions in reverse order
1654 for (int i = block.vtx.size() - 1; i >= 0; i--) {
1655 const CTransaction &tx = block.vtx[i];
1656 uint256 hash = tx.GetHash();
1658 // Check that all outputs are available and match the outputs in the block itself
1661 CCoinsModifier outs = view.ModifyCoins(hash);
1662 outs->ClearUnspendable();
1664 CCoins outsBlock(tx, pindex->nHeight);
1665 // The CCoins serialization does not serialize negative numbers.
1666 // No network rules currently depend on the version here, so an inconsistency is harmless
1667 // but it must be corrected before txout nversion ever influences a network rule.
1668 if (outsBlock.nVersion < 0)
1669 outs->nVersion = outsBlock.nVersion;
1670 if (*outs != outsBlock)
1671 fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1678 if (i > 0) { // not coinbases
1679 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1680 if (txundo.vprevout.size() != tx.vin.size())
1681 return error("DisconnectBlock(): transaction and undo data inconsistent");
1682 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1683 const COutPoint &out = tx.vin[j].prevout;
1684 const CTxInUndo &undo = txundo.vprevout[j];
1685 if (!ApplyTxInUndo(undo, view, out))
1691 // move best block pointer to prevout block
1692 view.SetBestBlock(pindex->pprev->GetBlockHash());
1702 void static FlushBlockFile(bool fFinalize = false)
1704 LOCK(cs_LastBlockFile);
1706 CDiskBlockPos posOld(nLastBlockFile, 0);
1708 FILE *fileOld = OpenBlockFile(posOld);
1711 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1712 FileCommit(fileOld);
1716 fileOld = OpenUndoFile(posOld);
1719 TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1720 FileCommit(fileOld);
1725 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1727 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1729 void ThreadScriptCheck() {
1730 RenameThread("bitcoin-scriptch");
1731 scriptcheckqueue.Thread();
1734 static int64_t nTimeVerify = 0;
1735 static int64_t nTimeConnect = 0;
1736 static int64_t nTimeIndex = 0;
1737 static int64_t nTimeCallbacks = 0;
1738 static int64_t nTimeTotal = 0;
1740 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1742 AssertLockHeld(cs_main);
1743 // Check it again in case a previous version let a bad block in
1744 if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1747 // verify that the view's current state corresponds to the previous block
1748 uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1749 assert(hashPrevBlock == view.GetBestBlock());
1751 // Special case for the genesis block, skipping connection of its transactions
1752 // (its coinbase is unspendable)
1753 if (block.GetHash() == Params().HashGenesisBlock()) {
1755 view.SetBestBlock(pindex->GetBlockHash());
1759 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1761 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1762 // unless those are already completely spent.
1763 // If such overwrites are allowed, coinbases and transactions depending upon those
1764 // can be duplicated to remove the ability to spend the first instance -- even after
1765 // being sent to another address.
1766 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1767 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1768 // already refuses previously-known transaction ids entirely.
1769 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1770 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1771 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1772 // initial block download.
1773 bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1774 !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1775 (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1776 if (fEnforceBIP30) {
1777 BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1778 const CCoins* coins = view.AccessCoins(tx.GetHash());
1779 if (coins && !coins->IsPruned())
1780 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1781 REJECT_INVALID, "bad-txns-BIP30");
1785 // BIP16 didn't become active until Apr 1 2012
1786 int64_t nBIP16SwitchTime = 1333238400;
1787 bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1789 unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1791 // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1792 if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
1793 flags |= SCRIPT_VERIFY_DERSIG;
1796 CBlockUndo blockundo;
1798 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1800 int64_t nTimeStart = GetTimeMicros();
1803 unsigned int nSigOps = 0;
1804 CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1805 std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1806 vPos.reserve(block.vtx.size());
1807 blockundo.vtxundo.reserve(block.vtx.size() - 1);
1808 for (unsigned int i = 0; i < block.vtx.size(); i++)
1810 const CTransaction &tx = block.vtx[i];
1812 nInputs += tx.vin.size();
1813 nSigOps += GetLegacySigOpCount(tx);
1814 if (nSigOps > MAX_BLOCK_SIGOPS)
1815 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1816 REJECT_INVALID, "bad-blk-sigops");
1818 if (!tx.IsCoinBase())
1820 if (!view.HaveInputs(tx))
1821 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1822 REJECT_INVALID, "bad-txns-inputs-missingorspent");
1824 if (fStrictPayToScriptHash)
1826 // Add in sigops done by pay-to-script-hash inputs;
1827 // this is to prevent a "rogue miner" from creating
1828 // an incredibly-expensive-to-validate block.
1829 nSigOps += GetP2SHSigOpCount(tx, view);
1830 if (nSigOps > MAX_BLOCK_SIGOPS)
1831 return state.DoS(100, error("ConnectBlock(): too many sigops"),
1832 REJECT_INVALID, "bad-blk-sigops");
1835 nFees += view.GetValueIn(tx)-tx.GetValueOut();
1837 std::vector<CScriptCheck> vChecks;
1838 if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1840 control.Add(vChecks);
1845 blockundo.vtxundo.push_back(CTxUndo());
1847 UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1849 vPos.push_back(std::make_pair(tx.GetHash(), pos));
1850 pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1852 int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1853 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);
1855 if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1856 return state.DoS(100,
1857 error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1858 block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
1859 REJECT_INVALID, "bad-cb-amount");
1861 if (!control.Wait())
1862 return state.DoS(100, false);
1863 int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1864 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);
1869 // Write undo information to disk
1870 if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1872 if (pindex->GetUndoPos().IsNull()) {
1874 if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1875 return error("ConnectBlock(): FindUndoPos failed");
1876 if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash()))
1877 return state.Abort("Failed to write undo data");
1879 // update nUndoPos in block index
1880 pindex->nUndoPos = pos.nPos;
1881 pindex->nStatus |= BLOCK_HAVE_UNDO;
1884 pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1885 setDirtyBlockIndex.insert(pindex);
1889 if (!pblocktree->WriteTxIndex(vPos))
1890 return state.Abort("Failed to write transaction index");
1892 // add this block to the view's block chain
1893 view.SetBestBlock(pindex->GetBlockHash());
1895 int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1896 LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1898 // Watch for changes to the previous coinbase transaction.
1899 static uint256 hashPrevBestCoinBase;
1900 g_signals.UpdatedTransaction(hashPrevBestCoinBase);
1901 hashPrevBestCoinBase = block.vtx[0].GetHash();
1903 int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1904 LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1909 enum FlushStateMode {
1910 FLUSH_STATE_IF_NEEDED,
1911 FLUSH_STATE_PERIODIC,
1916 * Update the on-disk chain state.
1917 * The caches and indexes are flushed if either they're too large, forceWrite is set, or
1918 * fast is not set and it's been a while since the last write.
1920 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1922 static int64_t nLastWrite = 0;
1924 if ((mode == FLUSH_STATE_ALWAYS) ||
1925 ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
1926 (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
1927 // Typical CCoins structures on disk are around 100 bytes in size.
1928 // Pushing a new one to the database can cause it to be written
1929 // twice (once in the log, and once in the tables). This is already
1930 // an overestimation, as most will delete an existing entry or
1931 // overwrite one. Still, use a conservative safety factor of 2.
1932 if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1933 return state.Error("out of disk space");
1934 // First make sure all block and undo data is flushed to disk.
1936 // Then update all block file information (which may refer to block and undo files).
1938 std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
1939 vFiles.reserve(setDirtyFileInfo.size());
1940 for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1941 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
1942 setDirtyFileInfo.erase(it++);
1944 std::vector<const CBlockIndex*> vBlocks;
1945 vBlocks.reserve(setDirtyBlockIndex.size());
1946 for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1947 vBlocks.push_back(*it);
1948 setDirtyBlockIndex.erase(it++);
1950 if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
1951 return state.Abort("Files to write to block index database");
1954 // Finally flush the chainstate (which may refer to block index entries).
1955 if (!pcoinsTip->Flush())
1956 return state.Abort("Failed to write to coin database");
1957 // Update best block in wallet (so we can detect restored wallets).
1958 if (mode != FLUSH_STATE_IF_NEEDED) {
1959 g_signals.SetBestChain(chainActive.GetLocator());
1961 nLastWrite = GetTimeMicros();
1963 } catch (const std::runtime_error& e) {
1964 return state.Abort(std::string("System error while flushing: ") + e.what());
1969 void FlushStateToDisk() {
1970 CValidationState state;
1971 FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1974 /** Update chainActive and related internal data structures. */
1975 void static UpdateTip(CBlockIndex *pindexNew) {
1976 chainActive.SetTip(pindexNew);
1979 nTimeBestReceived = GetTime();
1980 mempool.AddTransactionsUpdated(1);
1982 LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n",
1983 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1984 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1985 Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
1987 cvBlockChange.notify_all();
1989 // Check the version of the last 100 blocks to see if we need to upgrade:
1990 static bool fWarned = false;
1991 if (!IsInitialBlockDownload() && !fWarned)
1994 const CBlockIndex* pindex = chainActive.Tip();
1995 for (int i = 0; i < 100 && pindex != NULL; i++)
1997 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1999 pindex = pindex->pprev;
2002 LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
2003 if (nUpgraded > 100/2)
2005 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2006 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2007 CAlert::Notify(strMiscWarning, true);
2013 /** Disconnect chainActive's tip. */
2014 bool static DisconnectTip(CValidationState &state) {
2015 CBlockIndex *pindexDelete = chainActive.Tip();
2016 assert(pindexDelete);
2017 mempool.check(pcoinsTip);
2018 // Read block from disk.
2020 if (!ReadBlockFromDisk(block, pindexDelete))
2021 return state.Abort("Failed to read block");
2022 // Apply the block atomically to the chain state.
2023 int64_t nStart = GetTimeMicros();
2025 CCoinsViewCache view(pcoinsTip);
2026 if (!DisconnectBlock(block, state, pindexDelete, view))
2027 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2028 assert(view.Flush());
2030 LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2031 // Write the chain state to disk, if necessary.
2032 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2034 // Resurrect mempool transactions from the disconnected block.
2035 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2036 // ignore validation errors in resurrected transactions
2037 list<CTransaction> removed;
2038 CValidationState stateDummy;
2039 if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2040 mempool.remove(tx, removed, true);
2042 mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2043 mempool.check(pcoinsTip);
2044 // Update chainActive and related variables.
2045 UpdateTip(pindexDelete->pprev);
2046 // Let wallets know transactions went from 1-confirmed to
2047 // 0-confirmed or conflicted:
2048 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2049 SyncWithWallets(tx, NULL);
2054 static int64_t nTimeReadFromDisk = 0;
2055 static int64_t nTimeConnectTotal = 0;
2056 static int64_t nTimeFlush = 0;
2057 static int64_t nTimeChainState = 0;
2058 static int64_t nTimePostConnect = 0;
2061 * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2062 * corresponding to pindexNew, to bypass loading it again from disk.
2064 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2065 assert(pindexNew->pprev == chainActive.Tip());
2066 mempool.check(pcoinsTip);
2067 // Read block from disk.
2068 int64_t nTime1 = GetTimeMicros();
2071 if (!ReadBlockFromDisk(block, pindexNew))
2072 return state.Abort("Failed to read block");
2075 // Apply the block atomically to the chain state.
2076 int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2078 LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2080 CCoinsViewCache view(pcoinsTip);
2081 CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2082 bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2083 g_signals.BlockChecked(*pblock, state);
2085 if (state.IsInvalid())
2086 InvalidBlockFound(pindexNew, state);
2087 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2089 mapBlockSource.erase(inv.hash);
2090 nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2091 LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2092 assert(view.Flush());
2094 int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2095 LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2096 // Write the chain state to disk, if necessary.
2097 if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2099 int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2100 LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2101 // Remove conflicting transactions from the mempool.
2102 list<CTransaction> txConflicted;
2103 mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
2104 mempool.check(pcoinsTip);
2105 // Update chainActive & related variables.
2106 UpdateTip(pindexNew);
2107 // Tell wallet about transactions that went from mempool
2109 BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2110 SyncWithWallets(tx, NULL);
2112 // ... and about transactions that got confirmed:
2113 BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2114 SyncWithWallets(tx, pblock);
2117 int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2118 LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2119 LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2124 * Return the tip of the chain with the most work in it, that isn't
2125 * known to be invalid (it's however far from certain to be valid).
2127 static CBlockIndex* FindMostWorkChain() {
2129 CBlockIndex *pindexNew = NULL;
2131 // Find the best candidate header.
2133 std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2134 if (it == setBlockIndexCandidates.rend())
2139 // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2140 // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2141 CBlockIndex *pindexTest = pindexNew;
2142 bool fInvalidAncestor = false;
2143 while (pindexTest && !chainActive.Contains(pindexTest)) {
2144 assert(pindexTest->nStatus & BLOCK_HAVE_DATA);
2145 assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2146 if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
2147 // Candidate has an invalid ancestor, remove entire chain from the set.
2148 if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
2149 pindexBestInvalid = pindexNew;
2150 CBlockIndex *pindexFailed = pindexNew;
2151 while (pindexTest != pindexFailed) {
2152 pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2153 setBlockIndexCandidates.erase(pindexFailed);
2154 pindexFailed = pindexFailed->pprev;
2156 setBlockIndexCandidates.erase(pindexTest);
2157 fInvalidAncestor = true;
2160 pindexTest = pindexTest->pprev;
2162 if (!fInvalidAncestor)
2167 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2168 static void PruneBlockIndexCandidates() {
2169 // Note that we can't delete the current block itself, as we may need to return to it later in case a
2170 // reorganization to a better block fails.
2171 std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2172 while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2173 setBlockIndexCandidates.erase(it++);
2175 // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2176 assert(!setBlockIndexCandidates.empty());
2180 * Try to make some progress towards making pindexMostWork the active block.
2181 * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2183 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2184 AssertLockHeld(cs_main);
2185 bool fInvalidFound = false;
2186 const CBlockIndex *pindexOldTip = chainActive.Tip();
2187 const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2189 // Disconnect active blocks which are no longer in the best chain.
2190 while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2191 if (!DisconnectTip(state))
2195 // Build list of new blocks to connect.
2196 std::vector<CBlockIndex*> vpindexToConnect;
2197 bool fContinue = true;
2198 int nHeight = pindexFork ? pindexFork->nHeight : -1;
2199 while (fContinue && nHeight != pindexMostWork->nHeight) {
2200 // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2201 // a few blocks along the way.
2202 int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2203 vpindexToConnect.clear();
2204 vpindexToConnect.reserve(nTargetHeight - nHeight);
2205 CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2206 while (pindexIter && pindexIter->nHeight != nHeight) {
2207 vpindexToConnect.push_back(pindexIter);
2208 pindexIter = pindexIter->pprev;
2210 nHeight = nTargetHeight;
2212 // Connect new blocks.
2213 BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2214 if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2215 if (state.IsInvalid()) {
2216 // The block violates a consensus rule.
2217 if (!state.CorruptionPossible())
2218 InvalidChainFound(vpindexToConnect.back());
2219 state = CValidationState();
2220 fInvalidFound = true;
2224 // A system error occurred (disk space, database error, ...).
2228 PruneBlockIndexCandidates();
2229 if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2230 // We're in a better position than we were. Return temporarily to release the lock.
2238 // Callbacks/notifications for a new best chain.
2240 CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2242 CheckForkWarningConditions();
2248 * Make the best chain active, in multiple steps. The result is either failure
2249 * or an activated best chain. pblock is either NULL or a pointer to a block
2250 * that is already loaded (to avoid loading it again from disk).
2252 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2253 CBlockIndex *pindexNewTip = NULL;
2254 CBlockIndex *pindexMostWork = NULL;
2256 boost::this_thread::interruption_point();
2258 bool fInitialDownload;
2261 pindexMostWork = FindMostWorkChain();
2263 // Whether we have anything to do at all.
2264 if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2267 if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2270 pindexNewTip = chainActive.Tip();
2271 fInitialDownload = IsInitialBlockDownload();
2273 // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2275 // Notifications/callbacks that can run without cs_main
2276 if (!fInitialDownload) {
2277 uint256 hashNewTip = pindexNewTip->GetBlockHash();
2278 // Relay inventory, but don't relay old inventory during initial block download.
2279 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2282 BOOST_FOREACH(CNode* pnode, vNodes)
2283 if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2284 pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2286 // Notify external listeners about the new tip.
2287 uiInterface.NotifyBlockTip(hashNewTip);
2289 } while(pindexMostWork != chainActive.Tip());
2291 // Write changes periodically to disk, after relay.
2292 if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2299 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2300 AssertLockHeld(cs_main);
2302 // Mark the block itself as invalid.
2303 pindex->nStatus |= BLOCK_FAILED_VALID;
2304 setDirtyBlockIndex.insert(pindex);
2305 setBlockIndexCandidates.erase(pindex);
2307 while (chainActive.Contains(pindex)) {
2308 CBlockIndex *pindexWalk = chainActive.Tip();
2309 pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2310 setDirtyBlockIndex.insert(pindexWalk);
2311 setBlockIndexCandidates.erase(pindexWalk);
2312 // ActivateBestChain considers blocks already in chainActive
2313 // unconditionally valid already, so force disconnect away from it.
2314 if (!DisconnectTip(state)) {
2319 // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2321 BlockMap::iterator it = mapBlockIndex.begin();
2322 while (it != mapBlockIndex.end()) {
2323 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2324 setBlockIndexCandidates.insert(it->second);
2329 InvalidChainFound(pindex);
2333 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2334 AssertLockHeld(cs_main);
2336 int nHeight = pindex->nHeight;
2338 // Remove the invalidity flag from this block and all its descendants.
2339 BlockMap::iterator it = mapBlockIndex.begin();
2340 while (it != mapBlockIndex.end()) {
2341 if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2342 it->second->nStatus &= ~BLOCK_FAILED_MASK;
2343 setDirtyBlockIndex.insert(it->second);
2344 if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2345 setBlockIndexCandidates.insert(it->second);
2347 if (it->second == pindexBestInvalid) {
2348 // Reset invalid block marker if it was pointing to one of those.
2349 pindexBestInvalid = NULL;
2355 // Remove the invalidity flag from all ancestors too.
2356 while (pindex != NULL) {
2357 if (pindex->nStatus & BLOCK_FAILED_MASK) {
2358 pindex->nStatus &= ~BLOCK_FAILED_MASK;
2359 setDirtyBlockIndex.insert(pindex);
2361 pindex = pindex->pprev;
2366 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2368 // Check for duplicate
2369 uint256 hash = block.GetHash();
2370 BlockMap::iterator it = mapBlockIndex.find(hash);
2371 if (it != mapBlockIndex.end())
2374 // Construct new block index object
2375 CBlockIndex* pindexNew = new CBlockIndex(block);
2377 // We assign the sequence id to blocks only when the full data is available,
2378 // to avoid miners withholding blocks but broadcasting headers, to get a
2379 // competitive advantage.
2380 pindexNew->nSequenceId = 0;
2381 BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2382 pindexNew->phashBlock = &((*mi).first);
2383 BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2384 if (miPrev != mapBlockIndex.end())
2386 pindexNew->pprev = (*miPrev).second;
2387 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2388 pindexNew->BuildSkip();
2390 pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2391 pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2392 if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2393 pindexBestHeader = pindexNew;
2395 setDirtyBlockIndex.insert(pindexNew);
2400 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2401 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2403 pindexNew->nTx = block.vtx.size();
2404 pindexNew->nChainTx = 0;
2405 pindexNew->nFile = pos.nFile;
2406 pindexNew->nDataPos = pos.nPos;
2407 pindexNew->nUndoPos = 0;
2408 pindexNew->nStatus |= BLOCK_HAVE_DATA;
2409 pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2411 LOCK(cs_nBlockSequenceId);
2412 pindexNew->nSequenceId = nBlockSequenceId++;
2414 setDirtyBlockIndex.insert(pindexNew);
2416 if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2417 // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2418 deque<CBlockIndex*> queue;
2419 queue.push_back(pindexNew);
2421 // Recursively process any descendant blocks that now may be eligible to be connected.
2422 while (!queue.empty()) {
2423 CBlockIndex *pindex = queue.front();
2425 pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2426 setBlockIndexCandidates.insert(pindex);
2427 std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2428 while (range.first != range.second) {
2429 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2430 queue.push_back(it->second);
2432 mapBlocksUnlinked.erase(it);
2436 if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2437 mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2444 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2446 LOCK(cs_LastBlockFile);
2448 unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2449 if (vinfoBlockFile.size() <= nFile) {
2450 vinfoBlockFile.resize(nFile + 1);
2454 while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2455 LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2456 FlushBlockFile(true);
2458 if (vinfoBlockFile.size() <= nFile) {
2459 vinfoBlockFile.resize(nFile + 1);
2463 pos.nPos = vinfoBlockFile[nFile].nSize;
2466 nLastBlockFile = nFile;
2467 vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2469 vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2471 vinfoBlockFile[nFile].nSize += nAddSize;
2474 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2475 unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2476 if (nNewChunks > nOldChunks) {
2477 if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2478 FILE *file = OpenBlockFile(pos);
2480 LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2481 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2486 return state.Error("out of disk space");
2490 setDirtyFileInfo.insert(nFile);
2494 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2498 LOCK(cs_LastBlockFile);
2500 unsigned int nNewSize;
2501 pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2502 nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2503 setDirtyFileInfo.insert(nFile);
2505 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2506 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2507 if (nNewChunks > nOldChunks) {
2508 if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2509 FILE *file = OpenUndoFile(pos);
2511 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2512 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2517 return state.Error("out of disk space");
2523 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2525 // Check proof of work matches claimed amount
2526 if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2527 return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2528 REJECT_INVALID, "high-hash");
2531 if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2532 return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2533 REJECT_INVALID, "time-too-new");
2538 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2540 // These are checks that are independent of context.
2542 // Check that the header is valid (particularly PoW). This is mostly
2543 // redundant with the call in AcceptBlockHeader.
2544 if (!CheckBlockHeader(block, state, fCheckPOW))
2547 // Check the merkle root.
2548 if (fCheckMerkleRoot) {
2550 uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2551 if (block.hashMerkleRoot != hashMerkleRoot2)
2552 return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2553 REJECT_INVALID, "bad-txnmrklroot", true);
2555 // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2556 // of transactions in a block without affecting the merkle root of a block,
2557 // while still invalidating it.
2559 return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2560 REJECT_INVALID, "bad-txns-duplicate", true);
2563 // All potential-corruption validation must be done before we do any
2564 // transaction validation, as otherwise we may mark the header as invalid
2565 // because we receive the wrong transactions for it.
2568 if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2569 return state.DoS(100, error("CheckBlock(): size limits failed"),
2570 REJECT_INVALID, "bad-blk-length");
2572 // First transaction must be coinbase, the rest must not be
2573 if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2574 return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2575 REJECT_INVALID, "bad-cb-missing");
2576 for (unsigned int i = 1; i < block.vtx.size(); i++)
2577 if (block.vtx[i].IsCoinBase())
2578 return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2579 REJECT_INVALID, "bad-cb-multiple");
2581 // Check transactions
2582 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2583 if (!CheckTransaction(tx, state))
2584 return error("CheckBlock(): CheckTransaction failed");
2586 unsigned int nSigOps = 0;
2587 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2589 nSigOps += GetLegacySigOpCount(tx);
2591 if (nSigOps > MAX_BLOCK_SIGOPS)
2592 return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2593 REJECT_INVALID, "bad-blk-sigops", true);
2598 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2600 uint256 hash = block.GetHash();
2601 if (hash == Params().HashGenesisBlock())
2606 int nHeight = pindexPrev->nHeight+1;
2608 // Check proof of work
2609 if ((block.nBits != GetNextWorkRequired(pindexPrev, &block)))
2610 return state.DoS(100, error("%s: incorrect proof of work", __func__),
2611 REJECT_INVALID, "bad-diffbits");
2613 // Check timestamp against prev
2614 if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2615 return state.Invalid(error("%s: block's timestamp is too early", __func__),
2616 REJECT_INVALID, "time-too-old");
2618 // Check that the block chain matches the known block chain up to a checkpoint
2619 if (!Checkpoints::CheckBlock(nHeight, hash))
2620 return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
2621 REJECT_CHECKPOINT, "checkpoint mismatch");
2623 // Don't accept any forks from the main chain prior to last checkpoint
2624 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
2625 if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2626 return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2628 // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2629 if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
2631 return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2632 REJECT_OBSOLETE, "bad-version");
2635 // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2636 if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority()))
2638 return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2639 REJECT_OBSOLETE, "bad-version");
2645 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2647 const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2649 // Check that all transactions are finalized
2650 BOOST_FOREACH(const CTransaction& tx, block.vtx)
2651 if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2652 return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2655 // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2656 // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2657 if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority()))
2659 CScript expect = CScript() << nHeight;
2660 if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2661 !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2662 return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2669 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2671 AssertLockHeld(cs_main);
2672 // Check for duplicate
2673 uint256 hash = block.GetHash();
2674 BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2675 CBlockIndex *pindex = NULL;
2676 if (miSelf != mapBlockIndex.end()) {
2677 // Block header is already known.
2678 pindex = miSelf->second;
2681 if (pindex->nStatus & BLOCK_FAILED_MASK)
2682 return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2686 if (!CheckBlockHeader(block, state))
2689 // Get prev block index
2690 CBlockIndex* pindexPrev = NULL;
2691 if (hash != Params().HashGenesisBlock()) {
2692 BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2693 if (mi == mapBlockIndex.end())
2694 return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2695 pindexPrev = (*mi).second;
2696 if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2697 return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2700 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2704 pindex = AddToBlockIndex(block);
2712 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2714 AssertLockHeld(cs_main);
2716 CBlockIndex *&pindex = *ppindex;
2718 if (!AcceptBlockHeader(block, state, &pindex))
2721 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2722 // TODO: deal better with duplicate blocks.
2723 // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2727 if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2728 if (state.IsInvalid() && !state.CorruptionPossible()) {
2729 pindex->nStatus |= BLOCK_FAILED_VALID;
2730 setDirtyBlockIndex.insert(pindex);
2735 int nHeight = pindex->nHeight;
2737 // Write block to history file
2739 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2740 CDiskBlockPos blockPos;
2743 if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2744 return error("AcceptBlock(): FindBlockPos failed");
2746 if (!WriteBlockToDisk(block, blockPos))
2747 return state.Abort("Failed to write block");
2748 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2749 return error("AcceptBlock(): ReceivedBlockTransactions failed");
2750 } catch (const std::runtime_error& e) {
2751 return state.Abort(std::string("System error: ") + e.what());
2757 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
2759 unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
2760 unsigned int nFound = 0;
2761 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2763 if (pstart->nVersion >= minVersion)
2765 pstart = pstart->pprev;
2767 return (nFound >= nRequired);
2771 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2773 // Preliminary checks
2774 bool checked = CheckBlock(*pblock, state);
2778 MarkBlockAsReceived(pblock->GetHash());
2780 return error("%s: CheckBlock FAILED", __func__);
2784 CBlockIndex *pindex = NULL;
2785 bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2786 if (pindex && pfrom) {
2787 mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2790 return error("%s: AcceptBlock FAILED", __func__);
2793 if (!ActivateBestChain(state, pblock))
2794 return error("%s: ActivateBestChain failed", __func__);
2799 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2801 AssertLockHeld(cs_main);
2802 assert(pindexPrev == chainActive.Tip());
2804 CCoinsViewCache viewNew(pcoinsTip);
2805 CBlockIndex indexDummy(block);
2806 indexDummy.pprev = pindexPrev;
2807 indexDummy.nHeight = pindexPrev->nHeight + 1;
2809 // NOTE: CheckBlockHeader is called by CheckBlock
2810 if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2812 if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2814 if (!ContextualCheckBlock(block, state, pindexPrev))
2816 if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2818 assert(state.IsValid());
2830 bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
2831 strMiscWarning = strMessage;
2832 LogPrintf("*** %s\n", strMessage);
2833 uiInterface.ThreadSafeMessageBox(
2834 userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
2835 "", CClientUIInterface::MSG_ERROR);
2840 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2842 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2844 // Check for nMinDiskSpace bytes (currently 50MB)
2845 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2846 return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
2851 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2855 boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
2856 boost::filesystem::create_directories(path.parent_path());
2857 FILE* file = fopen(path.string().c_str(), "rb+");
2858 if (!file && !fReadOnly)
2859 file = fopen(path.string().c_str(), "wb+");
2861 LogPrintf("Unable to open file %s\n", path.string());
2865 if (fseek(file, pos.nPos, SEEK_SET)) {
2866 LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
2874 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2875 return OpenDiskFile(pos, "blk", fReadOnly);
2878 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2879 return OpenDiskFile(pos, "rev", fReadOnly);
2882 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
2884 return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2887 CBlockIndex * InsertBlockIndex(uint256 hash)
2893 BlockMap::iterator mi = mapBlockIndex.find(hash);
2894 if (mi != mapBlockIndex.end())
2895 return (*mi).second;
2898 CBlockIndex* pindexNew = new CBlockIndex();
2900 throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
2901 mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2902 pindexNew->phashBlock = &((*mi).first);
2907 bool static LoadBlockIndexDB()
2909 if (!pblocktree->LoadBlockIndexGuts())
2912 boost::this_thread::interruption_point();
2914 // Calculate nChainWork
2915 vector<pair<int, CBlockIndex*> > vSortedByHeight;
2916 vSortedByHeight.reserve(mapBlockIndex.size());
2917 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2919 CBlockIndex* pindex = item.second;
2920 vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2922 sort(vSortedByHeight.begin(), vSortedByHeight.end());
2923 BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2925 CBlockIndex* pindex = item.second;
2926 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
2927 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2928 if (pindex->pprev) {
2929 if (pindex->pprev->nChainTx) {
2930 pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
2932 pindex->nChainTx = 0;
2933 mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
2936 pindex->nChainTx = pindex->nTx;
2939 if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
2940 setBlockIndexCandidates.insert(pindex);
2941 if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
2942 pindexBestInvalid = pindex;
2944 pindex->BuildSkip();
2945 if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
2946 pindexBestHeader = pindex;
2949 // Load block file info
2950 pblocktree->ReadLastBlockFile(nLastBlockFile);
2951 vinfoBlockFile.resize(nLastBlockFile + 1);
2952 LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
2953 for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
2954 pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
2956 LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
2957 for (int nFile = nLastBlockFile + 1; true; nFile++) {
2958 CBlockFileInfo info;
2959 if (pblocktree->ReadBlockFileInfo(nFile, info)) {
2960 vinfoBlockFile.push_back(info);
2966 // Check presence of blk files
2967 LogPrintf("Checking all blk files are present...\n");
2968 set<int> setBlkDataFiles;
2969 BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2971 CBlockIndex* pindex = item.second;
2972 if (pindex->nStatus & BLOCK_HAVE_DATA) {
2973 setBlkDataFiles.insert(pindex->nFile);
2976 for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
2978 CDiskBlockPos pos(*it, 0);
2979 if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
2984 // Check whether we need to continue reindexing
2985 bool fReindexing = false;
2986 pblocktree->ReadReindexing(fReindexing);
2987 fReindex |= fReindexing;
2989 // Check whether we have a transaction index
2990 pblocktree->ReadFlag("txindex", fTxIndex);
2991 LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2993 // Load pointer to end of best chain
2994 BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
2995 if (it == mapBlockIndex.end())
2997 chainActive.SetTip(it->second);
2999 PruneBlockIndexCandidates();
3001 LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
3002 chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3003 DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3004 Checkpoints::GuessVerificationProgress(chainActive.Tip()));
3009 CVerifyDB::CVerifyDB()
3011 uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3014 CVerifyDB::~CVerifyDB()
3016 uiInterface.ShowProgress("", 100);
3019 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3022 if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3025 // Verify blocks in the best chain
3026 if (nCheckDepth <= 0)
3027 nCheckDepth = 1000000000; // suffices until the year 19000
3028 if (nCheckDepth > chainActive.Height())
3029 nCheckDepth = chainActive.Height();
3030 nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3031 LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3032 CCoinsViewCache coins(coinsview);
3033 CBlockIndex* pindexState = chainActive.Tip();
3034 CBlockIndex* pindexFailure = NULL;
3035 int nGoodTransactions = 0;
3036 CValidationState state;
3037 for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3039 boost::this_thread::interruption_point();
3040 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3041 if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3044 // check level 0: read from disk
3045 if (!ReadBlockFromDisk(block, pindex))
3046 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3047 // check level 1: verify block validity
3048 if (nCheckLevel >= 1 && !CheckBlock(block, state))
3049 return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3050 // check level 2: verify undo validity
3051 if (nCheckLevel >= 2 && pindex) {
3053 CDiskBlockPos pos = pindex->GetUndoPos();
3054 if (!pos.IsNull()) {
3055 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3056 return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3059 // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3060 if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
3062 if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3063 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3064 pindexState = pindex->pprev;
3066 nGoodTransactions = 0;
3067 pindexFailure = pindex;
3069 nGoodTransactions += block.vtx.size();
3071 if (ShutdownRequested())
3075 return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3077 // check level 4: try reconnecting blocks
3078 if (nCheckLevel >= 4) {
3079 CBlockIndex *pindex = pindexState;
3080 while (pindex != chainActive.Tip()) {
3081 boost::this_thread::interruption_point();
3082 uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3083 pindex = chainActive.Next(pindex);
3085 if (!ReadBlockFromDisk(block, pindex))
3086 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3087 if (!ConnectBlock(block, state, pindex, coins))
3088 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3092 LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3097 void UnloadBlockIndex()
3100 setBlockIndexCandidates.clear();
3101 chainActive.SetTip(NULL);
3102 pindexBestInvalid = NULL;
3103 pindexBestHeader = NULL;
3105 mapOrphanTransactions.clear();
3106 mapOrphanTransactionsByPrev.clear();
3108 mapBlocksUnlinked.clear();
3109 vinfoBlockFile.clear();
3111 nBlockSequenceId = 1;
3112 mapBlockSource.clear();
3113 mapBlocksInFlight.clear();
3114 nQueuedValidatedHeaders = 0;
3115 nPreferredDownload = 0;
3116 setDirtyBlockIndex.clear();
3117 setDirtyFileInfo.clear();
3118 mapNodeState.clear();
3120 BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3121 delete entry.second;
3123 mapBlockIndex.clear();
3126 bool LoadBlockIndex()
3128 // Load block index from databases
3129 if (!fReindex && !LoadBlockIndexDB())
3135 bool InitBlockIndex() {
3137 // Check whether we're already initialized
3138 if (chainActive.Genesis() != NULL)
3141 // Use the provided setting for -txindex in the new database
3142 fTxIndex = GetBoolArg("-txindex", false);
3143 pblocktree->WriteFlag("txindex", fTxIndex);
3144 LogPrintf("Initializing databases...\n");
3146 // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3149 CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3150 // Start new block file
3151 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3152 CDiskBlockPos blockPos;
3153 CValidationState state;
3154 if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3155 return error("LoadBlockIndex(): FindBlockPos failed");
3156 if (!WriteBlockToDisk(block, blockPos))
3157 return error("LoadBlockIndex(): writing genesis block to disk failed");
3158 CBlockIndex *pindex = AddToBlockIndex(block);
3159 if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3160 return error("LoadBlockIndex(): genesis block not accepted");
3161 if (!ActivateBestChain(state, &block))
3162 return error("LoadBlockIndex(): genesis block cannot be activated");
3163 // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3164 return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3165 } catch (const std::runtime_error& e) {
3166 return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3175 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3177 // Map of disk positions for blocks with unknown parent (only used for reindex)
3178 static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3179 int64_t nStart = GetTimeMillis();
3183 // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3184 CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3185 uint64_t nRewind = blkdat.GetPos();
3186 while (!blkdat.eof()) {
3187 boost::this_thread::interruption_point();
3189 blkdat.SetPos(nRewind);
3190 nRewind++; // start one byte further next time, in case of failure
3191 blkdat.SetLimit(); // remove former limit
3192 unsigned int nSize = 0;
3195 unsigned char buf[MESSAGE_START_SIZE];
3196 blkdat.FindByte(Params().MessageStart()[0]);
3197 nRewind = blkdat.GetPos()+1;
3198 blkdat >> FLATDATA(buf);
3199 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3203 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3205 } catch (const std::exception&) {
3206 // no valid block header found; don't complain
3211 uint64_t nBlockPos = blkdat.GetPos();
3213 dbp->nPos = nBlockPos;
3214 blkdat.SetLimit(nBlockPos + nSize);
3215 blkdat.SetPos(nBlockPos);
3218 nRewind = blkdat.GetPos();
3220 // detect out of order blocks, and store them for later
3221 uint256 hash = block.GetHash();
3222 if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3223 LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3224 block.hashPrevBlock.ToString());
3226 mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3230 // process in case the block isn't known yet
3231 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3232 CValidationState state;
3233 if (ProcessNewBlock(state, NULL, &block, dbp))
3235 if (state.IsError())
3237 } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3238 LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3241 // Recursively process earlier encountered successors of this block
3242 deque<uint256> queue;
3243 queue.push_back(hash);
3244 while (!queue.empty()) {
3245 uint256 head = queue.front();
3247 std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3248 while (range.first != range.second) {
3249 std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3250 if (ReadBlockFromDisk(block, it->second))
3252 LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3254 CValidationState dummy;
3255 if (ProcessNewBlock(dummy, NULL, &block, &it->second))
3258 queue.push_back(block.GetHash());
3262 mapBlocksUnknownParent.erase(it);
3265 } catch (const std::exception& e) {
3266 LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
3269 } catch (const std::runtime_error& e) {
3270 AbortNode(std::string("System error: ") + e.what());
3273 LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3277 //////////////////////////////////////////////////////////////////////////////
3282 string GetWarnings(string strFor)
3285 string strStatusBar;
3288 if (!CLIENT_VERSION_IS_RELEASE)
3289 strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3291 if (GetBoolArg("-testsafemode", false))
3292 strStatusBar = strRPC = "testsafemode enabled";
3294 // Misc warnings like out of disk space and clock is wrong
3295 if (strMiscWarning != "")
3298 strStatusBar = strMiscWarning;
3301 if (fLargeWorkForkFound)
3304 strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3306 else if (fLargeWorkInvalidChainFound)
3309 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.");
3315 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3317 const CAlert& alert = item.second;
3318 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3320 nPriority = alert.nPriority;
3321 strStatusBar = alert.strStatusBar;
3326 if (strFor == "statusbar")
3327 return strStatusBar;
3328 else if (strFor == "rpc")
3330 assert(!"GetWarnings(): invalid parameter");
3341 //////////////////////////////////////////////////////////////////////////////
3347 bool static AlreadyHave(const CInv& inv)
3353 bool txInMap = false;
3354 txInMap = mempool.exists(inv.hash);
3355 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3356 pcoinsTip->HaveCoins(inv.hash);
3359 return mapBlockIndex.count(inv.hash);
3361 // Don't know what it is, just say we already got one
3366 void static ProcessGetData(CNode* pfrom)
3368 std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3370 vector<CInv> vNotFound;
3374 while (it != pfrom->vRecvGetData.end()) {
3375 // Don't bother if send buffer is too full to respond anyway
3376 if (pfrom->nSendSize >= SendBufferSize())
3379 const CInv &inv = *it;
3381 boost::this_thread::interruption_point();
3384 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3387 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3388 if (mi != mapBlockIndex.end())
3390 if (chainActive.Contains(mi->second)) {
3393 // To prevent fingerprinting attacks, only send blocks outside of the active
3394 // chain if they are valid, and no more than a month older than the best header
3395 // chain we know about.
3396 send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3397 (mi->second->GetBlockTime() > pindexBestHeader->GetBlockTime() - 30 * 24 * 60 * 60);
3399 LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
3405 // Send block from disk
3407 if (!ReadBlockFromDisk(block, (*mi).second))
3408 assert(!"cannot load block from disk");
3409 if (inv.type == MSG_BLOCK)
3410 pfrom->PushMessage("block", block);
3411 else // MSG_FILTERED_BLOCK)
3413 LOCK(pfrom->cs_filter);
3416 CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3417 pfrom->PushMessage("merkleblock", merkleBlock);
3418 // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3419 // This avoids hurting performance by pointlessly requiring a round-trip
3420 // Note that there is currently no way for a node to request any single transactions we didnt send here -
3421 // they must either disconnect and retry or request the full block.
3422 // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3423 // however we MUST always provide at least what the remote peer needs
3424 typedef std::pair<unsigned int, uint256> PairType;
3425 BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3426 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3427 pfrom->PushMessage("tx", block.vtx[pair.first]);
3433 // Trigger them to send a getblocks request for the next batch of inventory
3434 if (inv.hash == pfrom->hashContinue)
3436 // Bypass PushInventory, this must send even if redundant,
3437 // and we want it right after the last block so they don't
3438 // wait for other stuff first.
3440 vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3441 pfrom->PushMessage("inv", vInv);
3442 pfrom->hashContinue.SetNull();
3446 else if (inv.IsKnownType())
3448 // Send stream from relay memory
3449 bool pushed = false;
3452 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3453 if (mi != mapRelay.end()) {
3454 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3458 if (!pushed && inv.type == MSG_TX) {
3460 if (mempool.lookup(inv.hash, tx)) {
3461 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3464 pfrom->PushMessage("tx", ss);
3469 vNotFound.push_back(inv);
3473 // Track requests for our stuff.
3474 g_signals.Inventory(inv.hash);
3476 if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3481 pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3483 if (!vNotFound.empty()) {
3484 // Let the peer know that we didn't find what it asked for, so it doesn't
3485 // have to wait around forever. Currently only SPV clients actually care
3486 // about this message: it's needed when they are recursively walking the
3487 // dependencies of relevant unconfirmed transactions. SPV clients want to
3488 // do that because they want to know about (and store and rebroadcast and
3489 // risk analyze) the dependencies of transactions relevant to them, without
3490 // having to download the entire memory pool.
3491 pfrom->PushMessage("notfound", vNotFound);
3495 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3497 RandAddSeedPerfmon();
3498 LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3499 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3501 LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3508 if (strCommand == "version")
3510 // Each connection can only send one version message
3511 if (pfrom->nVersion != 0)
3513 pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3514 Misbehaving(pfrom->GetId(), 1);
3521 uint64_t nNonce = 1;
3522 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3523 if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3525 // disconnect from peers older than this proto version
3526 LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3527 pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3528 strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3529 pfrom->fDisconnect = true;
3533 if (pfrom->nVersion == 10300)
3534 pfrom->nVersion = 300;
3536 vRecv >> addrFrom >> nNonce;
3537 if (!vRecv.empty()) {
3538 vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3539 pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3542 vRecv >> pfrom->nStartingHeight;
3544 vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3546 pfrom->fRelayTxes = true;
3548 // Disconnect if we connected to ourself
3549 if (nNonce == nLocalHostNonce && nNonce > 1)
3551 LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3552 pfrom->fDisconnect = true;
3556 pfrom->addrLocal = addrMe;
3557 if (pfrom->fInbound && addrMe.IsRoutable())
3562 // Be shy and don't send version until we hear
3563 if (pfrom->fInbound)
3564 pfrom->PushVersion();
3566 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3568 // Potentially mark this peer as a preferred download peer.
3569 UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3572 pfrom->PushMessage("verack");
3573 pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3575 if (!pfrom->fInbound)
3577 // Advertise our address
3578 if (fListen && !IsInitialBlockDownload())
3580 CAddress addr = GetLocalAddress(&pfrom->addr);
3581 if (addr.IsRoutable())
3583 pfrom->PushAddress(addr);
3584 } else if (IsPeerAddrLocalGood(pfrom)) {
3585 addr.SetIP(pfrom->addrLocal);
3586 pfrom->PushAddress(addr);
3590 // Get recent addresses
3591 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3593 pfrom->PushMessage("getaddr");
3594 pfrom->fGetAddr = true;
3596 addrman.Good(pfrom->addr);
3598 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3600 addrman.Add(addrFrom, addrFrom);
3601 addrman.Good(addrFrom);
3608 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3609 item.second.RelayTo(pfrom);
3612 pfrom->fSuccessfullyConnected = true;
3616 remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
3618 LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
3619 pfrom->cleanSubVer, pfrom->nVersion,
3620 pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
3623 int64_t nTimeOffset = nTime - GetTime();
3624 pfrom->nTimeOffset = nTimeOffset;
3625 AddTimeData(pfrom->addr, nTimeOffset);
3629 else if (pfrom->nVersion == 0)
3631 // Must have a version message before anything else
3632 Misbehaving(pfrom->GetId(), 1);
3637 else if (strCommand == "verack")
3639 pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3641 // Mark this node as currently connected, so we update its timestamp later.
3642 if (pfrom->fNetworkNode) {
3644 State(pfrom->GetId())->fCurrentlyConnected = true;
3649 else if (strCommand == "addr")
3651 vector<CAddress> vAddr;
3654 // Don't want addr from older versions unless seeding
3655 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3657 if (vAddr.size() > 1000)
3659 Misbehaving(pfrom->GetId(), 20);
3660 return error("message addr size() = %u", vAddr.size());
3663 // Store the new addresses
3664 vector<CAddress> vAddrOk;
3665 int64_t nNow = GetAdjustedTime();
3666 int64_t nSince = nNow - 10 * 60;
3667 BOOST_FOREACH(CAddress& addr, vAddr)
3669 boost::this_thread::interruption_point();
3671 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3672 addr.nTime = nNow - 5 * 24 * 60 * 60;
3673 pfrom->AddAddressKnown(addr);
3674 bool fReachable = IsReachable(addr);
3675 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3677 // Relay to a limited number of other nodes
3680 // Use deterministic randomness to send to the same nodes for 24 hours
3681 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3682 static uint256 hashSalt;
3683 if (hashSalt.IsNull())
3684 hashSalt = GetRandHash();
3685 uint64_t hashAddr = addr.GetHash();
3686 uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
3687 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3688 multimap<uint256, CNode*> mapMix;
3689 BOOST_FOREACH(CNode* pnode, vNodes)
3691 if (pnode->nVersion < CADDR_TIME_VERSION)
3693 unsigned int nPointer;
3694 memcpy(&nPointer, &pnode, sizeof(nPointer));
3695 uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
3696 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3697 mapMix.insert(make_pair(hashKey, pnode));
3699 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3700 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3701 ((*mi).second)->PushAddress(addr);
3704 // Do not store addresses outside our network
3706 vAddrOk.push_back(addr);
3708 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3709 if (vAddr.size() < 1000)
3710 pfrom->fGetAddr = false;
3711 if (pfrom->fOneShot)
3712 pfrom->fDisconnect = true;
3716 else if (strCommand == "inv")
3720 if (vInv.size() > MAX_INV_SZ)
3722 Misbehaving(pfrom->GetId(), 20);
3723 return error("message inv size() = %u", vInv.size());
3728 std::vector<CInv> vToFetch;
3730 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3732 const CInv &inv = vInv[nInv];
3734 boost::this_thread::interruption_point();
3735 pfrom->AddInventoryKnown(inv);
3737 bool fAlreadyHave = AlreadyHave(inv);
3738 LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
3740 if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
3743 if (inv.type == MSG_BLOCK) {
3744 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
3745 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
3746 // First request the headers preceeding the announced block. In the normal fully-synced
3747 // case where a new block is announced that succeeds the current tip (no reorganization),
3748 // there are no such headers.
3749 // Secondly, and only when we are close to being synced, we request the announced block directly,
3750 // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
3751 // time the block arrives, the header chain leading up to it is already validated. Not
3752 // doing this will result in the received block being rejected as an orphan in case it is
3753 // not a direct successor.
3754 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
3755 CNodeState *nodestate = State(pfrom->GetId());
3756 if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - Params().TargetSpacing() * 20 &&
3757 nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3758 vToFetch.push_back(inv);
3759 // Mark block as in flight already, even though the actual "getdata" message only goes out
3760 // later (within the same cs_main lock, though).
3761 MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
3763 LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
3767 // Track requests for our stuff
3768 g_signals.Inventory(inv.hash);
3770 if (pfrom->nSendSize > (SendBufferSize() * 2)) {
3771 Misbehaving(pfrom->GetId(), 50);
3772 return error("send buffer size() = %u", pfrom->nSendSize);
3776 if (!vToFetch.empty())
3777 pfrom->PushMessage("getdata", vToFetch);
3781 else if (strCommand == "getdata")
3785 if (vInv.size() > MAX_INV_SZ)
3787 Misbehaving(pfrom->GetId(), 20);
3788 return error("message getdata size() = %u", vInv.size());
3791 if (fDebug || (vInv.size() != 1))
3792 LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
3794 if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
3795 LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
3797 pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3798 ProcessGetData(pfrom);
3802 else if (strCommand == "getblocks")
3804 CBlockLocator locator;
3806 vRecv >> locator >> hashStop;
3810 // Find the last block the caller has in the main chain
3811 CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
3813 // Send the rest of the chain
3815 pindex = chainActive.Next(pindex);
3817 LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
3818 for (; pindex; pindex = chainActive.Next(pindex))
3820 if (pindex->GetBlockHash() == hashStop)
3822 LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3825 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3828 // When this block is requested, we'll send an inv that'll make them
3829 // getblocks the next batch of inventory.
3830 LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3831 pfrom->hashContinue = pindex->GetBlockHash();
3838 else if (strCommand == "getheaders")
3840 CBlockLocator locator;
3842 vRecv >> locator >> hashStop;
3846 CBlockIndex* pindex = NULL;
3847 if (locator.IsNull())
3849 // If locator is null, return the hashStop block
3850 BlockMap::iterator mi = mapBlockIndex.find(hashStop);
3851 if (mi == mapBlockIndex.end())
3853 pindex = (*mi).second;
3857 // Find the last block the caller has in the main chain
3858 pindex = FindForkInGlobalIndex(chainActive, locator);
3860 pindex = chainActive.Next(pindex);
3863 // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3864 vector<CBlock> vHeaders;
3865 int nLimit = MAX_HEADERS_RESULTS;
3866 LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
3867 for (; pindex; pindex = chainActive.Next(pindex))
3869 vHeaders.push_back(pindex->GetBlockHeader());
3870 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3873 pfrom->PushMessage("headers", vHeaders);
3877 else if (strCommand == "tx")
3879 vector<uint256> vWorkQueue;
3880 vector<uint256> vEraseQueue;
3884 CInv inv(MSG_TX, tx.GetHash());
3885 pfrom->AddInventoryKnown(inv);
3889 bool fMissingInputs = false;
3890 CValidationState state;
3892 mapAlreadyAskedFor.erase(inv);
3894 if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
3896 mempool.check(pcoinsTip);
3897 RelayTransaction(tx);
3898 vWorkQueue.push_back(inv.hash);
3899 vEraseQueue.push_back(inv.hash);
3901 LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
3902 pfrom->id, pfrom->cleanSubVer,
3903 tx.GetHash().ToString(),
3904 mempool.mapTx.size());
3906 // Recursively process any orphan transactions that depended on this one
3907 set<NodeId> setMisbehaving;
3908 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3910 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3911 if (itByPrev == mapOrphanTransactionsByPrev.end())
3913 for (set<uint256>::iterator mi = itByPrev->second.begin();
3914 mi != itByPrev->second.end();
3917 const uint256& orphanHash = *mi;
3918 const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3919 NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3920 bool fMissingInputs2 = false;
3921 // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3922 // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3923 // anyone relaying LegitTxX banned)
3924 CValidationState stateDummy;
3926 vEraseQueue.push_back(orphanHash);
3928 if (setMisbehaving.count(fromPeer))
3930 if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
3932 LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
3933 RelayTransaction(orphanTx);
3934 vWorkQueue.push_back(orphanHash);
3936 else if (!fMissingInputs2)
3939 if (stateDummy.IsInvalid(nDos) && nDos > 0)
3941 // Punish peer that gave us an invalid orphan tx
3942 Misbehaving(fromPeer, nDos);
3943 setMisbehaving.insert(fromPeer);
3944 LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
3946 // too-little-fee orphan
3947 LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
3949 mempool.check(pcoinsTip);
3953 BOOST_FOREACH(uint256 hash, vEraseQueue)
3954 EraseOrphanTx(hash);
3956 else if (fMissingInputs)
3958 AddOrphanTx(tx, pfrom->GetId());
3960 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3961 unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3962 unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
3964 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3965 } else if (pfrom->fWhitelisted) {
3966 // Always relay transactions received from whitelisted peers, even
3967 // if they are already in the mempool (allowing the node to function
3968 // as a gateway for nodes hidden behind it).
3969 RelayTransaction(tx);
3972 if (state.IsInvalid(nDoS))
3974 LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3975 pfrom->id, pfrom->cleanSubVer,
3976 state.GetRejectReason());
3977 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3978 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
3980 Misbehaving(pfrom->GetId(), nDoS);
3985 else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
3987 std::vector<CBlockHeader> headers;
3989 // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3990 unsigned int nCount = ReadCompactSize(vRecv);
3991 if (nCount > MAX_HEADERS_RESULTS) {
3992 Misbehaving(pfrom->GetId(), 20);
3993 return error("headers message size = %u", nCount);
3995 headers.resize(nCount);
3996 for (unsigned int n = 0; n < nCount; n++) {
3997 vRecv >> headers[n];
3998 ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4004 // Nothing interesting. Stop asking this peers for more headers.
4008 CBlockIndex *pindexLast = NULL;
4009 BOOST_FOREACH(const CBlockHeader& header, headers) {
4010 CValidationState state;
4011 if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4012 Misbehaving(pfrom->GetId(), 20);
4013 return error("non-continuous headers sequence");
4015 if (!AcceptBlockHeader(header, state, &pindexLast)) {
4017 if (state.IsInvalid(nDoS)) {
4019 Misbehaving(pfrom->GetId(), nDoS);
4020 return error("invalid header received");
4026 UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4028 if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4029 // Headers message had its maximum size; the peer may have more headers.
4030 // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4031 // from there instead.
4032 LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4033 pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4037 else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4042 CInv inv(MSG_BLOCK, block.GetHash());
4043 LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4045 pfrom->AddInventoryKnown(inv);
4047 CValidationState state;
4048 ProcessNewBlock(state, pfrom, &block);
4050 if (state.IsInvalid(nDoS)) {
4051 pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4052 state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4055 Misbehaving(pfrom->GetId(), nDoS);
4062 // This asymmetric behavior for inbound and outbound connections was introduced
4063 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4064 // to users' AddrMan and later request them by sending getaddr messages.
4065 // Making users (which are behind NAT and can only make outgoing connections) ignore
4066 // getaddr message mitigates the attack.
4067 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4069 pfrom->vAddrToSend.clear();
4070 vector<CAddress> vAddr = addrman.GetAddr();
4071 BOOST_FOREACH(const CAddress &addr, vAddr)
4072 pfrom->PushAddress(addr);
4076 else if (strCommand == "mempool")
4078 LOCK2(cs_main, pfrom->cs_filter);
4080 std::vector<uint256> vtxid;
4081 mempool.queryHashes(vtxid);
4083 BOOST_FOREACH(uint256& hash, vtxid) {
4084 CInv inv(MSG_TX, hash);
4086 bool fInMemPool = mempool.lookup(hash, tx);
4087 if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4088 if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4090 vInv.push_back(inv);
4091 if (vInv.size() == MAX_INV_SZ) {
4092 pfrom->PushMessage("inv", vInv);
4096 if (vInv.size() > 0)
4097 pfrom->PushMessage("inv", vInv);
4101 else if (strCommand == "ping")
4103 if (pfrom->nVersion > BIP0031_VERSION)
4107 // Echo the message back with the nonce. This allows for two useful features:
4109 // 1) A remote node can quickly check if the connection is operational
4110 // 2) Remote nodes can measure the latency of the network thread. If this node
4111 // is overloaded it won't respond to pings quickly and the remote node can
4112 // avoid sending us more work, like chain download requests.
4114 // The nonce stops the remote getting confused between different pings: without
4115 // it, if the remote node sends a ping once per second and this node takes 5
4116 // seconds to respond to each, the 5th ping the remote sends would appear to
4117 // return very quickly.
4118 pfrom->PushMessage("pong", nonce);
4123 else if (strCommand == "pong")
4125 int64_t pingUsecEnd = nTimeReceived;
4127 size_t nAvail = vRecv.in_avail();
4128 bool bPingFinished = false;
4129 std::string sProblem;
4131 if (nAvail >= sizeof(nonce)) {
4134 // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4135 if (pfrom->nPingNonceSent != 0) {
4136 if (nonce == pfrom->nPingNonceSent) {
4137 // Matching pong received, this ping is no longer outstanding
4138 bPingFinished = true;
4139 int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4140 if (pingUsecTime > 0) {
4141 // Successful ping time measurement, replace previous
4142 pfrom->nPingUsecTime = pingUsecTime;
4144 // This should never happen
4145 sProblem = "Timing mishap";
4148 // Nonce mismatches are normal when pings are overlapping
4149 sProblem = "Nonce mismatch";
4151 // This is most likely a bug in another implementation somewhere, cancel this ping
4152 bPingFinished = true;
4153 sProblem = "Nonce zero";
4157 sProblem = "Unsolicited pong without ping";
4160 // This is most likely a bug in another implementation somewhere, cancel this ping
4161 bPingFinished = true;
4162 sProblem = "Short payload";
4165 if (!(sProblem.empty())) {
4166 LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4170 pfrom->nPingNonceSent,
4174 if (bPingFinished) {
4175 pfrom->nPingNonceSent = 0;
4180 else if (strCommand == "alert")
4185 uint256 alertHash = alert.GetHash();
4186 if (pfrom->setKnown.count(alertHash) == 0)
4188 if (alert.ProcessAlert())
4191 pfrom->setKnown.insert(alertHash);
4194 BOOST_FOREACH(CNode* pnode, vNodes)
4195 alert.RelayTo(pnode);
4199 // Small DoS penalty so peers that send us lots of
4200 // duplicate/expired/invalid-signature/whatever alerts
4201 // eventually get banned.
4202 // This isn't a Misbehaving(100) (immediate ban) because the
4203 // peer might be an older or different implementation with
4204 // a different signature key, etc.
4205 Misbehaving(pfrom->GetId(), 10);
4211 else if (strCommand == "filterload")
4213 CBloomFilter filter;
4216 if (!filter.IsWithinSizeConstraints())
4217 // There is no excuse for sending a too-large filter
4218 Misbehaving(pfrom->GetId(), 100);
4221 LOCK(pfrom->cs_filter);
4222 delete pfrom->pfilter;
4223 pfrom->pfilter = new CBloomFilter(filter);
4224 pfrom->pfilter->UpdateEmptyFull();
4226 pfrom->fRelayTxes = true;
4230 else if (strCommand == "filteradd")
4232 vector<unsigned char> vData;
4235 // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4236 // and thus, the maximum size any matched object can have) in a filteradd message
4237 if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4239 Misbehaving(pfrom->GetId(), 100);
4241 LOCK(pfrom->cs_filter);
4243 pfrom->pfilter->insert(vData);
4245 Misbehaving(pfrom->GetId(), 100);
4250 else if (strCommand == "filterclear")
4252 LOCK(pfrom->cs_filter);
4253 delete pfrom->pfilter;
4254 pfrom->pfilter = new CBloomFilter();
4255 pfrom->fRelayTxes = true;
4259 else if (strCommand == "reject")
4263 string strMsg; unsigned char ccode; string strReason;
4264 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4267 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4269 if (strMsg == "block" || strMsg == "tx")
4273 ss << ": hash " << hash.ToString();
4275 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4276 } catch (const std::ios_base::failure&) {
4277 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4278 LogPrint("net", "Unparseable reject message received\n");
4285 // Ignore unknown commands for extensibility
4286 LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4294 // requires LOCK(cs_vRecvMsg)
4295 bool ProcessMessages(CNode* pfrom)
4298 // LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
4302 // (4) message start
4310 if (!pfrom->vRecvGetData.empty())
4311 ProcessGetData(pfrom);
4313 // this maintains the order of responses
4314 if (!pfrom->vRecvGetData.empty()) return fOk;
4316 std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4317 while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4318 // Don't bother if send buffer is too full to respond anyway
4319 if (pfrom->nSendSize >= SendBufferSize())
4323 CNetMessage& msg = *it;
4326 // LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
4327 // msg.hdr.nMessageSize, msg.vRecv.size(),
4328 // msg.complete() ? "Y" : "N");
4330 // end, if an incomplete message is found
4331 if (!msg.complete())
4334 // at this point, any failure means we can delete the current message
4337 // Scan for message start
4338 if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4339 LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4345 CMessageHeader& hdr = msg.hdr;
4346 if (!hdr.IsValid(Params().MessageStart()))
4348 LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4351 string strCommand = hdr.GetCommand();
4354 unsigned int nMessageSize = hdr.nMessageSize;
4357 CDataStream& vRecv = msg.vRecv;
4358 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4359 unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4360 if (nChecksum != hdr.nChecksum)
4362 LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4363 SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4371 fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4372 boost::this_thread::interruption_point();
4374 catch (const std::ios_base::failure& e)
4376 pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4377 if (strstr(e.what(), "end of data"))
4379 // Allow exceptions from under-length message on vRecv
4380 LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
4382 else if (strstr(e.what(), "size too large"))
4384 // Allow exceptions from over-long size
4385 LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
4389 PrintExceptionContinue(&e, "ProcessMessages()");
4392 catch (const boost::thread_interrupted&) {
4395 catch (const std::exception& e) {
4396 PrintExceptionContinue(&e, "ProcessMessages()");
4398 PrintExceptionContinue(NULL, "ProcessMessages()");
4402 LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
4407 // In case the connection got shut down, its receive buffer was wiped
4408 if (!pfrom->fDisconnect)
4409 pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4415 bool SendMessages(CNode* pto, bool fSendTrickle)
4418 // Don't send anything until we get their version message
4419 if (pto->nVersion == 0)
4425 bool pingSend = false;
4426 if (pto->fPingQueued) {
4427 // RPC ping request by user
4430 if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4431 // Ping automatically sent as a latency probe & keepalive.
4436 while (nonce == 0) {
4437 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4439 pto->fPingQueued = false;
4440 pto->nPingUsecStart = GetTimeMicros();
4441 if (pto->nVersion > BIP0031_VERSION) {
4442 pto->nPingNonceSent = nonce;
4443 pto->PushMessage("ping", nonce);
4445 // Peer is too old to support ping command with nonce, pong will never arrive.
4446 pto->nPingNonceSent = 0;
4447 pto->PushMessage("ping");
4451 TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4455 // Address refresh broadcast
4456 static int64_t nLastRebroadcast;
4457 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4460 BOOST_FOREACH(CNode* pnode, vNodes)
4462 // Periodically clear setAddrKnown to allow refresh broadcasts
4463 if (nLastRebroadcast)
4464 pnode->setAddrKnown.clear();
4466 // Rebroadcast our address
4467 AdvertizeLocal(pnode);
4469 if (!vNodes.empty())
4470 nLastRebroadcast = GetTime();
4478 vector<CAddress> vAddr;
4479 vAddr.reserve(pto->vAddrToSend.size());
4480 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4482 // returns true if wasn't already contained in the set
4483 if (pto->setAddrKnown.insert(addr).second)
4485 vAddr.push_back(addr);
4486 // receiver rejects addr messages larger than 1000
4487 if (vAddr.size() >= 1000)
4489 pto->PushMessage("addr", vAddr);
4494 pto->vAddrToSend.clear();
4496 pto->PushMessage("addr", vAddr);
4499 CNodeState &state = *State(pto->GetId());
4500 if (state.fShouldBan) {
4501 if (pto->fWhitelisted)
4502 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4504 pto->fDisconnect = true;
4505 if (pto->addr.IsLocal())
4506 LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4509 CNode::Ban(pto->addr);
4512 state.fShouldBan = false;
4515 BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4516 pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4517 state.rejects.clear();
4520 if (pindexBestHeader == NULL)
4521 pindexBestHeader = chainActive.Tip();
4522 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.
4523 if (!state.fSyncStarted && !pto->fClient && fFetch && !fImporting && !fReindex) {
4524 // Only actively request headers from a single peer, unless we're close to today.
4525 if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4526 state.fSyncStarted = true;
4528 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4529 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4530 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
4534 // Resend wallet transactions that haven't gotten in a block yet
4535 // Except during reindex, importing and IBD, when old wallet
4536 // transactions become unconfirmed and spams other nodes.
4537 if (!fReindex && !fImporting && !IsInitialBlockDownload())
4539 g_signals.Broadcast();
4543 // Message: inventory
4546 vector<CInv> vInvWait;
4548 LOCK(pto->cs_inventory);
4549 vInv.reserve(pto->vInventoryToSend.size());
4550 vInvWait.reserve(pto->vInventoryToSend.size());
4551 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4553 if (pto->setInventoryKnown.count(inv))
4556 // trickle out tx inv to protect privacy
4557 if (inv.type == MSG_TX && !fSendTrickle)
4559 // 1/4 of tx invs blast to all immediately
4560 static uint256 hashSalt;
4561 if (hashSalt.IsNull())
4562 hashSalt = GetRandHash();
4563 uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
4564 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4565 bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
4569 vInvWait.push_back(inv);
4574 // returns true if wasn't already contained in the set
4575 if (pto->setInventoryKnown.insert(inv).second)
4577 vInv.push_back(inv);
4578 if (vInv.size() >= 1000)
4580 pto->PushMessage("inv", vInv);
4585 pto->vInventoryToSend = vInvWait;
4588 pto->PushMessage("inv", vInv);
4590 // Detect whether we're stalling
4591 int64_t nNow = GetTimeMicros();
4592 if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4593 // Stalling only triggers when the block download window cannot move. During normal steady state,
4594 // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4595 // should only happen during initial block download.
4596 LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
4597 pto->fDisconnect = true;
4599 // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
4600 // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
4601 // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
4602 // being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
4603 // to unreasonably increase our timeout.
4604 if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
4605 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
4606 pto->fDisconnect = true;
4610 // Message: getdata (blocks)
4612 vector<CInv> vGetData;
4613 if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4614 vector<CBlockIndex*> vToDownload;
4615 NodeId staller = -1;
4616 FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4617 BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
4618 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4619 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
4620 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4621 pindex->nHeight, pto->id);
4623 if (state.nBlocksInFlight == 0 && staller != -1) {
4624 if (State(staller)->nStallingSince == 0) {
4625 State(staller)->nStallingSince = nNow;
4626 LogPrint("net", "Stall started peer=%d\n", staller);
4632 // Message: getdata (non-blocks)
4634 while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4636 const CInv& inv = (*pto->mapAskFor.begin()).second;
4637 if (!AlreadyHave(inv))
4640 LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
4641 vGetData.push_back(inv);
4642 if (vGetData.size() >= 1000)
4644 pto->PushMessage("getdata", vGetData);
4648 pto->mapAskFor.erase(pto->mapAskFor.begin());
4650 if (!vGetData.empty())
4651 pto->PushMessage("getdata", vGetData);
4657 std::string CBlockFileInfo::ToString() const {
4658 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));
4669 BlockMap::iterator it1 = mapBlockIndex.begin();
4670 for (; it1 != mapBlockIndex.end(); it1++)
4671 delete (*it1).second;
4672 mapBlockIndex.clear();
4674 // orphan transactions
4675 mapOrphanTransactions.clear();
4676 mapOrphanTransactionsByPrev.clear();
4678 } instance_of_cmaincleanup;