Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2014 The Bitcoin developers
0003 // Distributed under the MIT software license, see the accompanying
0004 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
0005 
0006 #include "main.h"
0007 
0008 #include "addrman.h"
0009 #include "alert.h"
0010 #include "chainparams.h"
0011 #include "checkpoints.h"
0012 #include "checkqueue.h"
0013 #include "init.h"
0014 #include "merkleblock.h"
0015 #include "net.h"
0016 #include "pow.h"
0017 #include "txdb.h"
0018 #include "txmempool.h"
0019 #include "ui_interface.h"
0020 #include "util.h"
0021 #include "utilmoneystr.h"
0022 
0023 #include <sstream>
0024 
0025 #include <boost/algorithm/string/replace.hpp>
0026 #include <boost/filesystem.hpp>
0027 #include <boost/filesystem/fstream.hpp>
0028 #include <boost/thread.hpp>
0029 
0030 using namespace boost;
0031 using namespace std;
0032 
0033 #if defined(NDEBUG)
0034 # error "Bitcoin cannot be compiled without assertions."
0035 #endif
0036 
0037 /**
0038  * Global state
0039  */
0040 
0041 CCriticalSection cs_main;
0042 
0043 BlockMap mapBlockIndex;
0044 CChain chainActive;
0045 CBlockIndex *pindexBestHeader = NULL;
0046 int64_t nTimeBestReceived = 0;
0047 CWaitableCriticalSection csBestBlock;
0048 CConditionVariable cvBlockChange;
0049 int nScriptCheckThreads = 0;
0050 bool fImporting = false;
0051 bool fReindex = false;
0052 bool fTxIndex = false;
0053 bool fIsBareMultisigStd = true;
0054 unsigned int nCoinCacheSize = 5000;
0055 
0056 
0057 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
0058 CFeeRate minRelayTxFee = CFeeRate(1000);
0059 
0060 CTxMemPool mempool(::minRelayTxFee);
0061 
0062 struct COrphanTx {
0063     CTransaction tx;
0064     NodeId fromPeer;
0065 };
0066 map<uint256, COrphanTx> mapOrphanTransactions;
0067 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
0068 void EraseOrphansFor(NodeId peer);
0069 
0070 /** Constant stuff for coinbase transactions we create: */
0071 CScript COINBASE_FLAGS;
0072 
0073 const string strMessageMagic = "Bitcoin Signed Message:\n";
0074 
0075 // Internal stuff
0076 namespace {
0077 
0078     struct CBlockIndexWorkComparator
0079     {
0080         bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
0081             // First sort by most total work, ...
0082             if (pa->nChainWork > pb->nChainWork) return false;
0083             if (pa->nChainWork < pb->nChainWork) return true;
0084 
0085             // ... then by earliest time received, ...
0086             if (pa->nSequenceId < pb->nSequenceId) return false;
0087             if (pa->nSequenceId > pb->nSequenceId) return true;
0088 
0089             // Use pointer address as tie breaker (should only happen with blocks
0090             // loaded from disk, as those all have id 0).
0091             if (pa < pb) return false;
0092             if (pa > pb) return true;
0093 
0094             // Identical blocks.
0095             return false;
0096         }
0097     };
0098 
0099     CBlockIndex *pindexBestInvalid;
0100 
0101     /**
0102      * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS or better that are at least
0103      * as good as our current tip. Entries may be failed, though.
0104      */
0105     set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
0106     /** Number of nodes with fSyncStarted. */
0107     int nSyncStarted = 0;
0108     /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
0109     multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
0110 
0111     CCriticalSection cs_LastBlockFile;
0112     std::vector<CBlockFileInfo> vinfoBlockFile;
0113     int nLastBlockFile = 0;
0114 
0115     /**
0116      * Every received block is assigned a unique and increasing identifier, so we
0117      * know which one to give priority in case of a fork.
0118      */
0119     CCriticalSection cs_nBlockSequenceId;
0120     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
0121     uint32_t nBlockSequenceId = 1;
0122 
0123     /**
0124      * Sources of received blocks, to be able to send them reject messages or ban
0125      * them, if processing happens afterwards. Protected by cs_main.
0126      */
0127     map<uint256, NodeId> mapBlockSource;
0128 
0129     /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
0130     struct QueuedBlock {
0131         uint256 hash;
0132         CBlockIndex *pindex;  //! Optional.
0133         int64_t nTime;  //! Time of "getdata" request in microseconds.
0134         int nValidatedQueuedBefore;  //! Number of blocks queued with validated headers (globally) at the time this one is requested.
0135         bool fValidatedHeaders;  //! Whether this block has validated headers at the time of request.
0136     };
0137     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
0138 
0139     /** Number of blocks in flight with validated headers. */
0140     int nQueuedValidatedHeaders = 0;
0141 
0142     /** Number of preferable block download peers. */
0143     int nPreferredDownload = 0;
0144 
0145     /** Dirty block index entries. */
0146     set<CBlockIndex*> setDirtyBlockIndex;
0147 
0148     /** Dirty block file entries. */
0149     set<int> setDirtyFileInfo;
0150 } // anon namespace
0151 
0152 //////////////////////////////////////////////////////////////////////////////
0153 //
0154 // dispatching functions
0155 //
0156 
0157 // These functions dispatch to one or all registered wallets
0158 
0159 namespace {
0160 
0161 struct CMainSignals {
0162     /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
0163     boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
0164     /** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
0165     boost::signals2::signal<void (const uint256 &)> EraseTransaction;
0166     /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
0167     boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
0168     /** Notifies listeners of a new active block chain. */
0169     boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
0170     /** Notifies listeners about an inventory item being seen on the network. */
0171     boost::signals2::signal<void (const uint256 &)> Inventory;
0172     /** Tells listeners to broadcast their data. */
0173     boost::signals2::signal<void ()> Broadcast;
0174     /** Notifies listeners of a block validation result */
0175     boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
0176 } g_signals;
0177 
0178 } // anon namespace
0179 
0180 void RegisterValidationInterface(CValidationInterface* pwalletIn) {
0181     g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
0182     g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
0183     g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
0184     g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
0185     g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
0186     g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
0187     g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
0188 }
0189 
0190 void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
0191     g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
0192     g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
0193     g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
0194     g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
0195     g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
0196     g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
0197     g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
0198 }
0199 
0200 void UnregisterAllValidationInterfaces() {
0201     g_signals.BlockChecked.disconnect_all_slots();
0202     g_signals.Broadcast.disconnect_all_slots();
0203     g_signals.Inventory.disconnect_all_slots();
0204     g_signals.SetBestChain.disconnect_all_slots();
0205     g_signals.UpdatedTransaction.disconnect_all_slots();
0206     g_signals.EraseTransaction.disconnect_all_slots();
0207     g_signals.SyncTransaction.disconnect_all_slots();
0208 }
0209 
0210 void SyncWithWallets(const CTransaction &tx, const CBlock *pblock) {
0211     g_signals.SyncTransaction(tx, pblock);
0212 }
0213 
0214 //////////////////////////////////////////////////////////////////////////////
0215 //
0216 // Registration of network node signals.
0217 //
0218 
0219 namespace {
0220 
0221 struct CBlockReject {
0222     unsigned char chRejectCode;
0223     string strRejectReason;
0224     uint256 hashBlock;
0225 };
0226 
0227 /**
0228  * Maintain validation-specific state about nodes, protected by cs_main, instead
0229  * by CNode's own locks. This simplifies asynchronous operation, where
0230  * processing of incoming data is done after the ProcessMessage call returns,
0231  * and we're no longer holding the node's locks.
0232  */
0233 struct CNodeState {
0234     //! Accumulated misbehaviour score for this peer.
0235     int nMisbehavior;
0236     //! Whether this peer should be disconnected and banned (unless whitelisted).
0237     bool fShouldBan;
0238     //! String name of this peer (debugging/logging purposes).
0239     std::string name;
0240     //! List of asynchronously-determined block rejections to notify this peer about.
0241     std::vector<CBlockReject> rejects;
0242     //! The best known block we know this peer has announced.
0243     CBlockIndex *pindexBestKnownBlock;
0244     //! The hash of the last unknown block this peer has announced.
0245     uint256 hashLastUnknownBlock;
0246     //! The last full block we both have.
0247     CBlockIndex *pindexLastCommonBlock;
0248     //! Whether we've started headers synchronization with this peer.
0249     bool fSyncStarted;
0250     //! Since when we're stalling block download progress (in microseconds), or 0.
0251     int64_t nStallingSince;
0252     list<QueuedBlock> vBlocksInFlight;
0253     int nBlocksInFlight;
0254     //! Whether we consider this a preferred download peer.
0255     bool fPreferredDownload;
0256 
0257     CNodeState() {
0258         nMisbehavior = 0;
0259         fShouldBan = false;
0260         pindexBestKnownBlock = NULL;
0261         hashLastUnknownBlock = uint256(0);
0262         pindexLastCommonBlock = NULL;
0263         fSyncStarted = false;
0264         nStallingSince = 0;
0265         nBlocksInFlight = 0;
0266         fPreferredDownload = false;
0267     }
0268 };
0269 
0270 /** Map maintaining per-node state. Requires cs_main. */
0271 map<NodeId, CNodeState> mapNodeState;
0272 
0273 // Requires cs_main.
0274 CNodeState *State(NodeId pnode) {
0275     map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
0276     if (it == mapNodeState.end())
0277         return NULL;
0278     return &it->second;
0279 }
0280 
0281 int GetHeight()
0282 {
0283     LOCK(cs_main);
0284     return chainActive.Height();
0285 }
0286 
0287 void UpdatePreferredDownload(CNode* node, CNodeState* state)
0288 {
0289     nPreferredDownload -= state->fPreferredDownload;
0290 
0291     // Whether this node should be marked as a preferred download node.
0292     state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
0293 
0294     nPreferredDownload += state->fPreferredDownload;
0295 }
0296 
0297 void InitializeNode(NodeId nodeid, const CNode *pnode) {
0298     LOCK(cs_main);
0299     CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
0300     state.name = pnode->addrName;
0301 }
0302 
0303 void FinalizeNode(NodeId nodeid) {
0304     LOCK(cs_main);
0305     CNodeState *state = State(nodeid);
0306 
0307     if (state->fSyncStarted)
0308         nSyncStarted--;
0309 
0310     BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
0311         mapBlocksInFlight.erase(entry.hash);
0312     EraseOrphansFor(nodeid);
0313     nPreferredDownload -= state->fPreferredDownload;
0314 
0315     mapNodeState.erase(nodeid);
0316 }
0317 
0318 // Requires cs_main.
0319 void MarkBlockAsReceived(const uint256& hash) {
0320     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
0321     if (itInFlight != mapBlocksInFlight.end()) {
0322         CNodeState *state = State(itInFlight->second.first);
0323         nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
0324         state->vBlocksInFlight.erase(itInFlight->second.second);
0325         state->nBlocksInFlight--;
0326         state->nStallingSince = 0;
0327         mapBlocksInFlight.erase(itInFlight);
0328     }
0329 }
0330 
0331 // Requires cs_main.
0332 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
0333     CNodeState *state = State(nodeid);
0334     assert(state != NULL);
0335 
0336     // Make sure it's not listed somewhere already.
0337     MarkBlockAsReceived(hash);
0338 
0339     QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
0340     nQueuedValidatedHeaders += newentry.fValidatedHeaders;
0341     list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
0342     state->nBlocksInFlight++;
0343     mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
0344 }
0345 
0346 /** Check whether the last unknown block a peer advertized is not yet known. */
0347 void ProcessBlockAvailability(NodeId nodeid) {
0348     CNodeState *state = State(nodeid);
0349     assert(state != NULL);
0350 
0351     if (state->hashLastUnknownBlock != 0) {
0352         BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
0353         if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
0354             if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
0355                 state->pindexBestKnownBlock = itOld->second;
0356             state->hashLastUnknownBlock = uint256(0);
0357         }
0358     }
0359 }
0360 
0361 /** Update tracking information about which blocks a peer is assumed to have. */
0362 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
0363     CNodeState *state = State(nodeid);
0364     assert(state != NULL);
0365 
0366     ProcessBlockAvailability(nodeid);
0367 
0368     BlockMap::iterator it = mapBlockIndex.find(hash);
0369     if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
0370         // An actually better block was announced.
0371         if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
0372             state->pindexBestKnownBlock = it->second;
0373     } else {
0374         // An unknown block was announced; just assume that the latest one is the best one.
0375         state->hashLastUnknownBlock = hash;
0376     }
0377 }
0378 
0379 /** Find the last common ancestor two blocks have.
0380  *  Both pa and pb must be non-NULL. */
0381 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
0382     if (pa->nHeight > pb->nHeight) {
0383         pa = pa->GetAncestor(pb->nHeight);
0384     } else if (pb->nHeight > pa->nHeight) {
0385         pb = pb->GetAncestor(pa->nHeight);
0386     }
0387 
0388     while (pa != pb && pa && pb) {
0389         pa = pa->pprev;
0390         pb = pb->pprev;
0391     }
0392 
0393     // Eventually all chain branches meet at the genesis block.
0394     assert(pa == pb);
0395     return pa;
0396 }
0397 
0398 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
0399  *  at most count entries. */
0400 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
0401     if (count == 0)
0402         return;
0403 
0404     vBlocks.reserve(vBlocks.size() + count);
0405     CNodeState *state = State(nodeid);
0406     assert(state != NULL);
0407 
0408     // Make sure pindexBestKnownBlock is up to date, we'll need it.
0409     ProcessBlockAvailability(nodeid);
0410 
0411     if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
0412         // This peer has nothing interesting.
0413         return;
0414     }
0415 
0416     if (state->pindexLastCommonBlock == NULL) {
0417         // Bootstrap quickly by guessing a parent of our best tip is the forking point.
0418         // Guessing wrong in either direction is not a problem.
0419         state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
0420     }
0421 
0422     // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
0423     // of their current tip anymore. Go back enough to fix that.
0424     state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
0425     if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
0426         return;
0427 
0428     std::vector<CBlockIndex*> vToFetch;
0429     CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
0430     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
0431     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
0432     // download that next block if the window were 1 larger.
0433     int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
0434     int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
0435     NodeId waitingfor = -1;
0436     while (pindexWalk->nHeight < nMaxHeight) {
0437         // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
0438         // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
0439         // as iterating over ~100 CBlockIndex* entries anyway.
0440         int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
0441         vToFetch.resize(nToFetch);
0442         pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
0443         vToFetch[nToFetch - 1] = pindexWalk;
0444         for (unsigned int i = nToFetch - 1; i > 0; i--) {
0445             vToFetch[i - 1] = vToFetch[i]->pprev;
0446         }
0447 
0448         // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
0449         // are not yet downloaded and not in flight to vBlocks. In the mean time, update
0450         // pindexLastCommonBlock as long as all ancestors are already downloaded.
0451         BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
0452             if (!pindex->IsValid(BLOCK_VALID_TREE)) {
0453                 // We consider the chain that this peer is on invalid.
0454                 return;
0455             }
0456             if (pindex->nStatus & BLOCK_HAVE_DATA) {
0457                 if (pindex->nChainTx)
0458                     state->pindexLastCommonBlock = pindex;
0459             } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
0460                 // The block is not already downloaded, and not yet in flight.
0461                 if (pindex->nHeight > nWindowEnd) {
0462                     // We reached the end of the window.
0463                     if (vBlocks.size() == 0 && waitingfor != nodeid) {
0464                         // We aren't able to fetch anything, but we would be if the download window was one larger.
0465                         nodeStaller = waitingfor;
0466                     }
0467                     return;
0468                 }
0469                 vBlocks.push_back(pindex);
0470                 if (vBlocks.size() == count) {
0471                     return;
0472                 }
0473             } else if (waitingfor == -1) {
0474                 // This is the first already-in-flight block.
0475                 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
0476             }
0477         }
0478     }
0479 }
0480 
0481 } // anon namespace
0482 
0483 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
0484     LOCK(cs_main);
0485     CNodeState *state = State(nodeid);
0486     if (state == NULL)
0487         return false;
0488     stats.nMisbehavior = state->nMisbehavior;
0489     stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
0490     stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
0491     BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
0492         if (queue.pindex)
0493             stats.vHeightInFlight.push_back(queue.pindex->nHeight);
0494     }
0495     return true;
0496 }
0497 
0498 void RegisterNodeSignals(CNodeSignals& nodeSignals)
0499 {
0500     nodeSignals.GetHeight.connect(&GetHeight);
0501     nodeSignals.ProcessMessages.connect(&ProcessMessages);
0502     nodeSignals.SendMessages.connect(&SendMessages);
0503     nodeSignals.InitializeNode.connect(&InitializeNode);
0504     nodeSignals.FinalizeNode.connect(&FinalizeNode);
0505 }
0506 
0507 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
0508 {
0509     nodeSignals.GetHeight.disconnect(&GetHeight);
0510     nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
0511     nodeSignals.SendMessages.disconnect(&SendMessages);
0512     nodeSignals.InitializeNode.disconnect(&InitializeNode);
0513     nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
0514 }
0515 
0516 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
0517 {
0518     // Find the first block the caller has in the main chain
0519     BOOST_FOREACH(const uint256& hash, locator.vHave) {
0520         BlockMap::iterator mi = mapBlockIndex.find(hash);
0521         if (mi != mapBlockIndex.end())
0522         {
0523             CBlockIndex* pindex = (*mi).second;
0524             if (chain.Contains(pindex))
0525                 return pindex;
0526         }
0527     }
0528     return chain.Genesis();
0529 }
0530 
0531 CCoinsViewCache *pcoinsTip = NULL;
0532 CBlockTreeDB *pblocktree = NULL;
0533 
0534 //////////////////////////////////////////////////////////////////////////////
0535 //
0536 // mapOrphanTransactions
0537 //
0538 
0539 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
0540 {
0541     uint256 hash = tx.GetHash();
0542     if (mapOrphanTransactions.count(hash))
0543         return false;
0544 
0545     // Ignore big transactions, to avoid a
0546     // send-big-orphans memory exhaustion attack. If a peer has a legitimate
0547     // large transaction with a missing parent then we assume
0548     // it will rebroadcast it later, after the parent transaction(s)
0549     // have been mined or received.
0550     // 10,000 orphans, each of which is at most 5,000 bytes big is
0551     // at most 500 megabytes of orphans:
0552     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
0553     if (sz > 5000)
0554     {
0555         LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
0556         return false;
0557     }
0558 
0559     mapOrphanTransactions[hash].tx = tx;
0560     mapOrphanTransactions[hash].fromPeer = peer;
0561     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0562         mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
0563 
0564     LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
0565              mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
0566     return true;
0567 }
0568 
0569 void static EraseOrphanTx(uint256 hash)
0570 {
0571     map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
0572     if (it == mapOrphanTransactions.end())
0573         return;
0574     BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
0575     {
0576         map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
0577         if (itPrev == mapOrphanTransactionsByPrev.end())
0578             continue;
0579         itPrev->second.erase(hash);
0580         if (itPrev->second.empty())
0581             mapOrphanTransactionsByPrev.erase(itPrev);
0582     }
0583     mapOrphanTransactions.erase(it);
0584 }
0585 
0586 void EraseOrphansFor(NodeId peer)
0587 {
0588     int nErased = 0;
0589     map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
0590     while (iter != mapOrphanTransactions.end())
0591     {
0592         map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
0593         if (maybeErase->second.fromPeer == peer)
0594         {
0595             EraseOrphanTx(maybeErase->second.tx.GetHash());
0596             ++nErased;
0597         }
0598     }
0599     if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
0600 }
0601 
0602 
0603 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
0604 {
0605     unsigned int nEvicted = 0;
0606     while (mapOrphanTransactions.size() > nMaxOrphans)
0607     {
0608         // Evict a random orphan:
0609         uint256 randomhash = GetRandHash();
0610         map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
0611         if (it == mapOrphanTransactions.end())
0612             it = mapOrphanTransactions.begin();
0613         EraseOrphanTx(it->first);
0614         ++nEvicted;
0615     }
0616     return nEvicted;
0617 }
0618 
0619 
0620 
0621 
0622 
0623 
0624 
0625 bool IsStandardTx(const CTransaction& tx, string& reason)
0626 {
0627     AssertLockHeld(cs_main);
0628     if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
0629         reason = "version";
0630         return false;
0631     }
0632 
0633     // Treat non-final transactions as non-standard to prevent a specific type
0634     // of double-spend attack, as well as DoS attacks. (if the transaction
0635     // can't be mined, the attacker isn't expending resources broadcasting it)
0636     // Basically we don't want to propagate transactions that can't be included in
0637     // the next block.
0638     //
0639     // However, IsFinalTx() is confusing... Without arguments, it uses
0640     // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
0641     // is set to the value of nHeight in the block. However, when IsFinalTx()
0642     // is called within CBlock::AcceptBlock(), the height of the block *being*
0643     // evaluated is what is used. Thus if we want to know if a transaction can
0644     // be part of the *next* block, we need to call IsFinalTx() with one more
0645     // than chainActive.Height().
0646     //
0647     // Timestamps on the other hand don't get any special treatment, because we
0648     // can't know what timestamp the next block will have, and there aren't
0649     // timestamp applications where it matters.
0650     if (!IsFinalTx(tx, chainActive.Height() + 1)) {
0651         reason = "non-final";
0652         return false;
0653     }
0654 
0655     // Extremely large transactions with lots of inputs can cost the network
0656     // almost as much to process as they cost the sender in fees, because
0657     // computing signature hashes is O(ninputs*txsize). Limiting transactions
0658     // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
0659     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
0660     if (sz >= MAX_STANDARD_TX_SIZE) {
0661         reason = "tx-size";
0662         return false;
0663     }
0664 
0665     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0666     {
0667         // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
0668         // keys. (remember the 520 byte limit on redeemScript size) That works
0669         // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
0670         // bytes of scriptSig, which we round off to 1650 bytes for some minor
0671         // future-proofing. That's also enough to spend a 20-of-20
0672         // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
0673         // considered standard)
0674         if (txin.scriptSig.size() > 1650) {
0675             reason = "scriptsig-size";
0676             return false;
0677         }
0678         if (!txin.scriptSig.IsPushOnly()) {
0679             reason = "scriptsig-not-pushonly";
0680             return false;
0681         }
0682     }
0683 
0684     unsigned int nDataOut = 0;
0685     txnouttype whichType;
0686     BOOST_FOREACH(const CTxOut& txout, tx.vout) {
0687         if (!::IsStandard(txout.scriptPubKey, whichType)) {
0688             reason = "scriptpubkey";
0689             return false;
0690         }
0691 
0692         if (whichType == TX_NULL_DATA)
0693             nDataOut++;
0694         else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
0695             reason = "bare-multisig";
0696             return false;
0697         } else if (txout.IsDust(::minRelayTxFee)) {
0698             reason = "dust";
0699             return false;
0700         }
0701     }
0702 
0703     // only one OP_RETURN txout is permitted
0704     if (nDataOut > 1) {
0705         reason = "multi-op-return";
0706         return false;
0707     }
0708 
0709     return true;
0710 }
0711 
0712 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
0713 {
0714     AssertLockHeld(cs_main);
0715     // Time based nLockTime implemented in 0.1.6
0716     if (tx.nLockTime == 0)
0717         return true;
0718     if (nBlockHeight == 0)
0719         nBlockHeight = chainActive.Height();
0720     if (nBlockTime == 0)
0721         nBlockTime = GetAdjustedTime();
0722     if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
0723         return true;
0724     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0725         if (!txin.IsFinal())
0726             return false;
0727     return true;
0728 }
0729 
0730 /**
0731  * Check transaction inputs to mitigate two
0732  * potential denial-of-service attacks:
0733  * 
0734  * 1. scriptSigs with extra data stuffed into them,
0735  *    not consumed by scriptPubKey (or P2SH script)
0736  * 2. P2SH scripts with a crazy number of expensive
0737  *    CHECKSIG/CHECKMULTISIG operations
0738  */
0739 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
0740 {
0741     if (tx.IsCoinBase())
0742         return true; // Coinbases don't use vin normally
0743 
0744     for (unsigned int i = 0; i < tx.vin.size(); i++)
0745     {
0746         const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
0747 
0748         vector<vector<unsigned char> > vSolutions;
0749         txnouttype whichType;
0750         // get the scriptPubKey corresponding to this input:
0751         const CScript& prevScript = prev.scriptPubKey;
0752         if (!Solver(prevScript, whichType, vSolutions))
0753             return false;
0754         int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
0755         if (nArgsExpected < 0)
0756             return false;
0757 
0758         // Transactions with extra stuff in their scriptSigs are
0759         // non-standard. Note that this EvalScript() call will
0760         // be quick, because if there are any operations
0761         // beside "push data" in the scriptSig
0762         // IsStandard() will have already returned false
0763         // and this method isn't called.
0764         vector<vector<unsigned char> > stack;
0765         if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker()))
0766             return false;
0767 
0768         if (whichType == TX_SCRIPTHASH)
0769         {
0770             if (stack.empty())
0771                 return false;
0772             CScript subscript(stack.back().begin(), stack.back().end());
0773             vector<vector<unsigned char> > vSolutions2;
0774             txnouttype whichType2;
0775             if (Solver(subscript, whichType2, vSolutions2))
0776             {
0777                 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
0778                 if (tmpExpected < 0)
0779                     return false;
0780                 nArgsExpected += tmpExpected;
0781             }
0782             else
0783             {
0784                 // Any other Script with less than 15 sigops OK:
0785                 unsigned int sigops = subscript.GetSigOpCount(true);
0786                 // ... extra data left on the stack after execution is OK, too:
0787                 return (sigops <= MAX_P2SH_SIGOPS);
0788             }
0789         }
0790 
0791         if (stack.size() != (unsigned int)nArgsExpected)
0792             return false;
0793     }
0794 
0795     return true;
0796 }
0797 
0798 unsigned int GetLegacySigOpCount(const CTransaction& tx)
0799 {
0800     unsigned int nSigOps = 0;
0801     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0802     {
0803         nSigOps += txin.scriptSig.GetSigOpCount(false);
0804     }
0805     BOOST_FOREACH(const CTxOut& txout, tx.vout)
0806     {
0807         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
0808     }
0809     return nSigOps;
0810 }
0811 
0812 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
0813 {
0814     if (tx.IsCoinBase())
0815         return 0;
0816 
0817     unsigned int nSigOps = 0;
0818     for (unsigned int i = 0; i < tx.vin.size(); i++)
0819     {
0820         const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
0821         if (prevout.scriptPubKey.IsPayToScriptHash())
0822             nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
0823     }
0824     return nSigOps;
0825 }
0826 
0827 
0828 
0829 
0830 
0831 
0832 
0833 
0834 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
0835 {
0836     // Basic checks that don't depend on any context
0837     if (tx.vin.empty())
0838         return state.DoS(10, error("CheckTransaction() : vin empty"),
0839                          REJECT_INVALID, "bad-txns-vin-empty");
0840     if (tx.vout.empty())
0841         return state.DoS(10, error("CheckTransaction() : vout empty"),
0842                          REJECT_INVALID, "bad-txns-vout-empty");
0843     // Size limits
0844     if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
0845         return state.DoS(100, error("CheckTransaction() : size limits failed"),
0846                          REJECT_INVALID, "bad-txns-oversize");
0847 
0848     // Check for negative or overflow output values
0849     CAmount nValueOut = 0;
0850     BOOST_FOREACH(const CTxOut& txout, tx.vout)
0851     {
0852         if (txout.nValue < 0)
0853             return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
0854                              REJECT_INVALID, "bad-txns-vout-negative");
0855         if (txout.nValue > MAX_MONEY)
0856             return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
0857                              REJECT_INVALID, "bad-txns-vout-toolarge");
0858         nValueOut += txout.nValue;
0859         if (!MoneyRange(nValueOut))
0860             return state.DoS(100, error("CheckTransaction() : txout total out of range"),
0861                              REJECT_INVALID, "bad-txns-txouttotal-toolarge");
0862     }
0863 
0864     // Check for duplicate inputs
0865     set<COutPoint> vInOutPoints;
0866     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0867     {
0868         if (vInOutPoints.count(txin.prevout))
0869             return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
0870                              REJECT_INVALID, "bad-txns-inputs-duplicate");
0871         vInOutPoints.insert(txin.prevout);
0872     }
0873 
0874     if (tx.IsCoinBase())
0875     {
0876         if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
0877             return state.DoS(100, error("CheckTransaction() : coinbase script size"),
0878                              REJECT_INVALID, "bad-cb-length");
0879     }
0880     else
0881     {
0882         BOOST_FOREACH(const CTxIn& txin, tx.vin)
0883             if (txin.prevout.IsNull())
0884                 return state.DoS(10, error("CheckTransaction() : prevout is null"),
0885                                  REJECT_INVALID, "bad-txns-prevout-null");
0886     }
0887 
0888     return true;
0889 }
0890 
0891 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
0892 {
0893     {
0894         LOCK(mempool.cs);
0895         uint256 hash = tx.GetHash();
0896         double dPriorityDelta = 0;
0897         CAmount nFeeDelta = 0;
0898         mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
0899         if (dPriorityDelta > 0 || nFeeDelta > 0)
0900             return 0;
0901     }
0902 
0903     CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
0904 
0905     if (fAllowFree)
0906     {
0907         // There is a free transaction area in blocks created by most miners,
0908         // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
0909         //   to be considered to fall into this category. We don't want to encourage sending
0910         //   multiple transactions instead of one big transaction to avoid fees.
0911         if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
0912             nMinFee = 0;
0913     }
0914 
0915     if (!MoneyRange(nMinFee))
0916         nMinFee = MAX_MONEY;
0917     return nMinFee;
0918 }
0919 
0920 
0921 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
0922                         bool* pfMissingInputs, bool fRejectInsaneFee)
0923 {
0924     AssertLockHeld(cs_main);
0925     if (pfMissingInputs)
0926         *pfMissingInputs = false;
0927 
0928     if (!CheckTransaction(tx, state))
0929         return error("AcceptToMemoryPool: : CheckTransaction failed");
0930 
0931     // Coinbase is only valid in a block, not as a loose transaction
0932     if (tx.IsCoinBase())
0933         return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
0934                          REJECT_INVALID, "coinbase");
0935 
0936     // Rather not work on nonstandard transactions (unless -testnet/-regtest)
0937     string reason;
0938     if (Params().RequireStandard() && !IsStandardTx(tx, reason))
0939         return state.DoS(0,
0940                          error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
0941                          REJECT_NONSTANDARD, reason);
0942 
0943     // is it already in the memory pool?
0944     uint256 hash = tx.GetHash();
0945     if (pool.exists(hash))
0946         return false;
0947 
0948     // Check for conflicts with in-memory transactions
0949     {
0950     LOCK(pool.cs); // protect pool.mapNextTx
0951     for (unsigned int i = 0; i < tx.vin.size(); i++)
0952     {
0953         COutPoint outpoint = tx.vin[i].prevout;
0954         if (pool.mapNextTx.count(outpoint))
0955         {
0956             // Disable replacement feature for now
0957             return false;
0958         }
0959     }
0960     }
0961 
0962     {
0963         CCoinsView dummy;
0964         CCoinsViewCache view(&dummy);
0965 
0966         CAmount nValueIn = 0;
0967         {
0968         LOCK(pool.cs);
0969         CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
0970         view.SetBackend(viewMemPool);
0971 
0972         // do we already have it?
0973         if (view.HaveCoins(hash))
0974             return false;
0975 
0976         // do all inputs exist?
0977         // Note that this does not check for the presence of actual outputs (see the next check for that),
0978         // only helps filling in pfMissingInputs (to determine missing vs spent).
0979         BOOST_FOREACH(const CTxIn txin, tx.vin) {
0980             if (!view.HaveCoins(txin.prevout.hash)) {
0981                 if (pfMissingInputs)
0982                     *pfMissingInputs = true;
0983                 return false;
0984             }
0985         }
0986 
0987         // are the actual inputs available?
0988         if (!view.HaveInputs(tx))
0989             return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
0990                                  REJECT_DUPLICATE, "bad-txns-inputs-spent");
0991 
0992         // Bring the best block into scope
0993         view.GetBestBlock();
0994 
0995         nValueIn = view.GetValueIn(tx);
0996 
0997         // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
0998         view.SetBackend(dummy);
0999         }
1000 
1001         // Check for non-standard pay-to-script-hash in inputs
1002         if (Params().RequireStandard() && !AreInputsStandard(tx, view))
1003             return error("AcceptToMemoryPool: : nonstandard transaction input");
1004 
1005         // Check that the transaction doesn't have an excessive number of
1006         // sigops, making it impossible to mine. Since the coinbase transaction
1007         // itself can contain sigops MAX_TX_SIGOPS is less than
1008         // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
1009         // merely non-standard transaction.
1010         unsigned int nSigOps = GetLegacySigOpCount(tx);
1011         nSigOps += GetP2SHSigOpCount(tx, view);
1012         if (nSigOps > MAX_TX_SIGOPS)
1013             return state.DoS(0,
1014                              error("AcceptToMemoryPool : too many sigops %s, %d > %d",
1015                                    hash.ToString(), nSigOps, MAX_TX_SIGOPS),
1016                              REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
1017 
1018         CAmount nValueOut = tx.GetValueOut();
1019         CAmount nFees = nValueIn-nValueOut;
1020         double dPriority = view.GetPriority(tx, chainActive.Height());
1021 
1022         CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
1023         unsigned int nSize = entry.GetTxSize();
1024 
1025         // Don't accept it if it can't get into a block
1026         CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1027         if (fLimitFree && nFees < txMinFee)
1028             return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d",
1029                                       hash.ToString(), nFees, txMinFee),
1030                              REJECT_INSUFFICIENTFEE, "insufficient fee");
1031 
1032         // Require that free transactions have sufficient priority to be mined in the next block.
1033         if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1034             return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1035         }
1036 
1037         // Continuously rate-limit free (really, very-low-fee) transactions
1038         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1039         // be annoying or make others' transactions take longer to confirm.
1040         if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1041         {
1042             static CCriticalSection csFreeLimiter;
1043             static double dFreeCount;
1044             static int64_t nLastTime;
1045             int64_t nNow = GetTime();
1046 
1047             LOCK(csFreeLimiter);
1048 
1049             // Use an exponentially decaying ~10-minute window:
1050             dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1051             nLastTime = nNow;
1052             // -limitfreerelay unit is thousand-bytes-per-minute
1053             // At default rate it would take over a month to fill 1GB
1054             if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1055                 return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
1056                                  REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1057             LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1058             dFreeCount += nSize;
1059         }
1060 
1061         if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1062             return error("AcceptToMemoryPool: : insane fees %s, %d > %d",
1063                          hash.ToString(),
1064                          nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1065 
1066         // Check against previous transactions
1067         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1068         if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1069         {
1070             return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
1071         }
1072 
1073         // Check again against just the consensus-critical mandatory script
1074         // verification flags, in case of bugs in the standard flags that cause
1075         // transactions to pass as valid when they're actually invalid. For
1076         // instance the STRICTENC flag was incorrectly allowing certain
1077         // CHECKSIG NOT scripts to pass, even though they were invalid.
1078         //
1079         // There is a similar check in CreateNewBlock() to prevent creating
1080         // invalid blocks, however allowing such transactions into the mempool
1081         // can be exploited as a DoS attack.
1082         if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1083         {
1084             return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1085         }
1086 
1087         // Store transaction in memory
1088         pool.addUnchecked(hash, entry);
1089     }
1090 
1091     SyncWithWallets(tx, NULL);
1092 
1093     return true;
1094 }
1095 
1096 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1097 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1098 {
1099     CBlockIndex *pindexSlow = NULL;
1100     {
1101         LOCK(cs_main);
1102         {
1103             if (mempool.lookup(hash, txOut))
1104             {
1105                 return true;
1106             }
1107         }
1108 
1109         if (fTxIndex) {
1110             CDiskTxPos postx;
1111             if (pblocktree->ReadTxIndex(hash, postx)) {
1112                 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1113                 if (file.IsNull())
1114                     return error("%s: OpenBlockFile failed", __func__);
1115                 CBlockHeader header;
1116                 try {
1117                     file >> header;
1118                     fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1119                     file >> txOut;
1120                 } catch (std::exception &e) {
1121                     return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1122                 }
1123                 hashBlock = header.GetHash();
1124                 if (txOut.GetHash() != hash)
1125                     return error("%s : txid mismatch", __func__);
1126                 return true;
1127             }
1128         }
1129 
1130         if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1131             int nHeight = -1;
1132             {
1133                 CCoinsViewCache &view = *pcoinsTip;
1134                 const CCoins* coins = view.AccessCoins(hash);
1135                 if (coins)
1136                     nHeight = coins->nHeight;
1137             }
1138             if (nHeight > 0)
1139                 pindexSlow = chainActive[nHeight];
1140         }
1141     }
1142 
1143     if (pindexSlow) {
1144         CBlock block;
1145         if (ReadBlockFromDisk(block, pindexSlow)) {
1146             BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1147                 if (tx.GetHash() == hash) {
1148                     txOut = tx;
1149                     hashBlock = pindexSlow->GetBlockHash();
1150                     return true;
1151                 }
1152             }
1153         }
1154     }
1155 
1156     return false;
1157 }
1158 
1159 
1160 
1161 
1162 
1163 
1164 //////////////////////////////////////////////////////////////////////////////
1165 //
1166 // CBlock and CBlockIndex
1167 //
1168 
1169 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
1170 {
1171     // Open history file to append
1172     CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1173     if (fileout.IsNull())
1174         return error("WriteBlockToDisk : OpenBlockFile failed");
1175 
1176     // Write index header
1177     unsigned int nSize = fileout.GetSerializeSize(block);
1178     fileout << FLATDATA(Params().MessageStart()) << nSize;
1179 
1180     // Write block
1181     long fileOutPos = ftell(fileout.Get());
1182     if (fileOutPos < 0)
1183         return error("WriteBlockToDisk : ftell failed");
1184     pos.nPos = (unsigned int)fileOutPos;
1185     fileout << block;
1186 
1187     return true;
1188 }
1189 
1190 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1191 {
1192     block.SetNull();
1193 
1194     // Open history file to read
1195     CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1196     if (filein.IsNull())
1197         return error("ReadBlockFromDisk : OpenBlockFile failed");
1198 
1199     // Read block
1200     try {
1201         filein >> block;
1202     }
1203     catch (std::exception &e) {
1204         return error("%s : Deserialize or I/O error - %s", __func__, e.what());
1205     }
1206 
1207     // Check the header
1208     if (!CheckProofOfWork(block.GetHash(), block.nBits))
1209         return error("ReadBlockFromDisk : Errors in block header");
1210 
1211     return true;
1212 }
1213 
1214 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1215 {
1216     if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1217         return false;
1218     if (block.GetHash() != pindex->GetBlockHash())
1219         return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
1220     return true;
1221 }
1222 
1223 CAmount GetBlockValue(int nHeight, const CAmount& nFees)
1224 {
1225     CAmount nSubsidy = 50 * COIN;
1226     int halvings = nHeight / Params().SubsidyHalvingInterval();
1227 
1228     // Force block reward to zero when right shift is undefined.
1229     if (halvings >= 64)
1230         return nFees;
1231 
1232     // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1233     nSubsidy >>= halvings;
1234 
1235     return nSubsidy + nFees;
1236 }
1237 
1238 bool IsInitialBlockDownload()
1239 {
1240     LOCK(cs_main);
1241     if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
1242         return true;
1243     static bool lockIBDState = false;
1244     if (lockIBDState)
1245         return false;
1246     bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1247             pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1248     if (!state)
1249         lockIBDState = true;
1250     return state;
1251 }
1252 
1253 bool fLargeWorkForkFound = false;
1254 bool fLargeWorkInvalidChainFound = false;
1255 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1256 
1257 void CheckForkWarningConditions()
1258 {
1259     AssertLockHeld(cs_main);
1260     // Before we get past initial download, we cannot reliably alert about forks
1261     // (we assume we don't get stuck on a fork before the last checkpoint)
1262     if (IsInitialBlockDownload())
1263         return;
1264 
1265     // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1266     // of our head, drop it
1267     if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1268         pindexBestForkTip = NULL;
1269 
1270     if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1271     {
1272         if (!fLargeWorkForkFound && pindexBestForkBase)
1273         {
1274             std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1275                 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1276             CAlert::Notify(warning, true);
1277         }
1278         if (pindexBestForkTip && pindexBestForkBase)
1279         {
1280             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",
1281                    pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1282                    pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1283             fLargeWorkForkFound = true;
1284         }
1285         else
1286         {
1287             LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
1288             fLargeWorkInvalidChainFound = true;
1289         }
1290     }
1291     else
1292     {
1293         fLargeWorkForkFound = false;
1294         fLargeWorkInvalidChainFound = false;
1295     }
1296 }
1297 
1298 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1299 {
1300     AssertLockHeld(cs_main);
1301     // If we are on a fork that is sufficiently large, set a warning flag
1302     CBlockIndex* pfork = pindexNewForkTip;
1303     CBlockIndex* plonger = chainActive.Tip();
1304     while (pfork && pfork != plonger)
1305     {
1306         while (plonger && plonger->nHeight > pfork->nHeight)
1307             plonger = plonger->pprev;
1308         if (pfork == plonger)
1309             break;
1310         pfork = pfork->pprev;
1311     }
1312 
1313     // We define a condition which we should warn the user about as a fork of at least 7 blocks
1314     // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
1315     // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1316     // hash rate operating on the fork.
1317     // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1318     // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1319     // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1320     if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1321             pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1322             chainActive.Height() - pindexNewForkTip->nHeight < 72)
1323     {
1324         pindexBestForkTip = pindexNewForkTip;
1325         pindexBestForkBase = pfork;
1326     }
1327 
1328     CheckForkWarningConditions();
1329 }
1330 
1331 // Requires cs_main.
1332 void Misbehaving(NodeId pnode, int howmuch)
1333 {
1334     if (howmuch == 0)
1335         return;
1336 
1337     CNodeState *state = State(pnode);
1338     if (state == NULL)
1339         return;
1340 
1341     state->nMisbehavior += howmuch;
1342     int banscore = GetArg("-banscore", 100);
1343     if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1344     {
1345         LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1346         state->fShouldBan = true;
1347     } else
1348         LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1349 }
1350 
1351 void static InvalidChainFound(CBlockIndex* pindexNew)
1352 {
1353     if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1354         pindexBestInvalid = pindexNew;
1355 
1356     LogPrintf("InvalidChainFound: invalid block=%s  height=%d  log2_work=%.8g  date=%s\n",
1357       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1358       log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1359       pindexNew->GetBlockTime()));
1360     LogPrintf("InvalidChainFound:  current best=%s  height=%d  log2_work=%.8g  date=%s\n",
1361       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1362       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1363     CheckForkWarningConditions();
1364 }
1365 
1366 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1367     int nDoS = 0;
1368     if (state.IsInvalid(nDoS)) {
1369         std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1370         if (it != mapBlockSource.end() && State(it->second)) {
1371             CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1372             State(it->second)->rejects.push_back(reject);
1373             if (nDoS > 0)
1374                 Misbehaving(it->second, nDoS);
1375         }
1376     }
1377     if (!state.CorruptionPossible()) {
1378         pindex->nStatus |= BLOCK_FAILED_VALID;
1379         setDirtyBlockIndex.insert(pindex);
1380         setBlockIndexCandidates.erase(pindex);
1381         InvalidChainFound(pindex);
1382     }
1383 }
1384 
1385 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1386 {
1387     // mark inputs spent
1388     if (!tx.IsCoinBase()) {
1389         txundo.vprevout.reserve(tx.vin.size());
1390         BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1391             txundo.vprevout.push_back(CTxInUndo());
1392             bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back());
1393             assert(ret);
1394         }
1395     }
1396 
1397     // add outputs
1398     inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1399 }
1400 
1401 bool CScriptCheck::operator()() {
1402     const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1403     if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1404         return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1405     }
1406     return true;
1407 }
1408 
1409 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1410 {
1411     if (!tx.IsCoinBase())
1412     {
1413         if (pvChecks)
1414             pvChecks->reserve(tx.vin.size());
1415 
1416         // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1417         // for an attacker to attempt to split the network.
1418         if (!inputs.HaveInputs(tx))
1419             return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
1420 
1421         // While checking, GetBestBlock() refers to the parent block.
1422         // This is also true for mempool checks.
1423         CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1424         int nSpendHeight = pindexPrev->nHeight + 1;
1425         CAmount nValueIn = 0;
1426         CAmount nFees = 0;
1427         for (unsigned int i = 0; i < tx.vin.size(); i++)
1428         {
1429             const COutPoint &prevout = tx.vin[i].prevout;
1430             const CCoins *coins = inputs.AccessCoins(prevout.hash);
1431             assert(coins);
1432 
1433             // If prev is coinbase, check that it's matured
1434             if (coins->IsCoinBase()) {
1435                 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1436                     return state.Invalid(
1437                         error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1438                         REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1439             }
1440 
1441             // Check for negative or overflow input values
1442             nValueIn += coins->vout[prevout.n].nValue;
1443             if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1444                 return state.DoS(100, error("CheckInputs() : txin values out of range"),
1445                                  REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1446 
1447         }
1448 
1449         if (nValueIn < tx.GetValueOut())
1450             return state.DoS(100, error("CheckInputs() : %s value in (%s) < value out (%s)",
1451                                         tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1452                              REJECT_INVALID, "bad-txns-in-belowout");
1453 
1454         // Tally transaction fees
1455         CAmount nTxFee = nValueIn - tx.GetValueOut();
1456         if (nTxFee < 0)
1457             return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
1458                              REJECT_INVALID, "bad-txns-fee-negative");
1459         nFees += nTxFee;
1460         if (!MoneyRange(nFees))
1461             return state.DoS(100, error("CheckInputs() : nFees out of range"),
1462                              REJECT_INVALID, "bad-txns-fee-outofrange");
1463 
1464         // The first loop above does all the inexpensive checks.
1465         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1466         // Helps prevent CPU exhaustion attacks.
1467 
1468         // Skip ECDSA signature verification when connecting blocks
1469         // before the last block chain checkpoint. This is safe because block merkle hashes are
1470         // still computed and checked, and any change will be caught at the next checkpoint.
1471         if (fScriptChecks) {
1472             for (unsigned int i = 0; i < tx.vin.size(); i++) {
1473                 const COutPoint &prevout = tx.vin[i].prevout;
1474                 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1475                 assert(coins);
1476 
1477                 // Verify signature
1478                 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1479                 if (pvChecks) {
1480                     pvChecks->push_back(CScriptCheck());
1481                     check.swap(pvChecks->back());
1482                 } else if (!check()) {
1483                     if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1484                         // Check whether the failure was caused by a
1485                         // non-mandatory script verification check, such as
1486                         // non-standard DER encodings or non-null dummy
1487                         // arguments; if so, don't trigger DoS protection to
1488                         // avoid splitting the network between upgraded and
1489                         // non-upgraded nodes.
1490                         CScriptCheck check(*coins, tx, i,
1491                                 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1492                         if (check())
1493                             return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1494                     }
1495                     // Failures of other flags indicate a transaction that is
1496                     // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1497                     // such nodes as they are not following the protocol. That
1498                     // said during an upgrade careful thought should be taken
1499                     // as to the correct behavior - we may want to continue
1500                     // peering with non-upgraded nodes even after a soft-fork
1501                     // super-majority vote has passed.
1502                     return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1503                 }
1504             }
1505         }
1506     }
1507 
1508     return true;
1509 }
1510 
1511 
1512 
1513 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1514 {
1515     assert(pindex->GetBlockHash() == view.GetBestBlock());
1516 
1517     if (pfClean)
1518         *pfClean = false;
1519 
1520     bool fClean = true;
1521 
1522     CBlockUndo blockUndo;
1523     CDiskBlockPos pos = pindex->GetUndoPos();
1524     if (pos.IsNull())
1525         return error("DisconnectBlock() : no undo data available");
1526     if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
1527         return error("DisconnectBlock() : failure reading undo data");
1528 
1529     if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1530         return error("DisconnectBlock() : block and undo data inconsistent");
1531 
1532     // undo transactions in reverse order
1533     for (int i = block.vtx.size() - 1; i >= 0; i--) {
1534         const CTransaction &tx = block.vtx[i];
1535         uint256 hash = tx.GetHash();
1536 
1537         // Check that all outputs are available and match the outputs in the block itself
1538         // exactly. Note that transactions with only provably unspendable outputs won't
1539         // have outputs available even in the block itself, so we handle that case
1540         // specially with outsEmpty.
1541         {
1542         CCoins outsEmpty;
1543         CCoinsModifier outs = view.ModifyCoins(hash);
1544         outs->ClearUnspendable();
1545 
1546         CCoins outsBlock(tx, pindex->nHeight);
1547         // The CCoins serialization does not serialize negative numbers.
1548         // No network rules currently depend on the version here, so an inconsistency is harmless
1549         // but it must be corrected before txout nversion ever influences a network rule.
1550         if (outsBlock.nVersion < 0)
1551             outs->nVersion = outsBlock.nVersion;
1552         if (*outs != outsBlock)
1553             fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
1554 
1555         // remove outputs
1556         outs->Clear();
1557         }
1558 
1559         // restore inputs
1560         if (i > 0) { // not coinbases
1561             const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1562             if (txundo.vprevout.size() != tx.vin.size())
1563                 return error("DisconnectBlock() : transaction and undo data inconsistent");
1564             for (unsigned int j = tx.vin.size(); j-- > 0;) {
1565                 const COutPoint &out = tx.vin[j].prevout;
1566                 const CTxInUndo &undo = txundo.vprevout[j];
1567                 CCoinsModifier coins = view.ModifyCoins(out.hash);
1568                 if (undo.nHeight != 0) {
1569                     // undo data contains height: this is the last output of the prevout tx being spent
1570                     if (!coins->IsPruned())
1571                         fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
1572                     coins->Clear();
1573                     coins->fCoinBase = undo.fCoinBase;
1574                     coins->nHeight = undo.nHeight;
1575                     coins->nVersion = undo.nVersion;
1576                 } else {
1577                     if (coins->IsPruned())
1578                         fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
1579                 }
1580                 if (coins->IsAvailable(out.n))
1581                     fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
1582                 if (coins->vout.size() < out.n+1)
1583                     coins->vout.resize(out.n+1);
1584                 coins->vout[out.n] = undo.txout;
1585             }
1586         }
1587     }
1588 
1589     // move best block pointer to prevout block
1590     view.SetBestBlock(pindex->pprev->GetBlockHash());
1591 
1592     if (pfClean) {
1593         *pfClean = fClean;
1594         return true;
1595     } else {
1596         return fClean;
1597     }
1598 }
1599 
1600 void static FlushBlockFile(bool fFinalize = false)
1601 {
1602     LOCK(cs_LastBlockFile);
1603 
1604     CDiskBlockPos posOld(nLastBlockFile, 0);
1605 
1606     FILE *fileOld = OpenBlockFile(posOld);
1607     if (fileOld) {
1608         if (fFinalize)
1609             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1610         FileCommit(fileOld);
1611         fclose(fileOld);
1612     }
1613 
1614     fileOld = OpenUndoFile(posOld);
1615     if (fileOld) {
1616         if (fFinalize)
1617             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1618         FileCommit(fileOld);
1619         fclose(fileOld);
1620     }
1621 }
1622 
1623 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1624 
1625 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1626 
1627 void ThreadScriptCheck() {
1628     RenameThread("bitcoin-scriptch");
1629     scriptcheckqueue.Thread();
1630 }
1631 
1632 static int64_t nTimeVerify = 0;
1633 static int64_t nTimeConnect = 0;
1634 static int64_t nTimeIndex = 0;
1635 static int64_t nTimeCallbacks = 0;
1636 static int64_t nTimeTotal = 0;
1637 
1638 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1639 {
1640     AssertLockHeld(cs_main);
1641     // Check it again in case a previous version let a bad block in
1642     if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1643         return false;
1644 
1645     // verify that the view's current state corresponds to the previous block
1646     uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
1647     assert(hashPrevBlock == view.GetBestBlock());
1648 
1649     // Special case for the genesis block, skipping connection of its transactions
1650     // (its coinbase is unspendable)
1651     if (block.GetHash() == Params().HashGenesisBlock()) {
1652         view.SetBestBlock(pindex->GetBlockHash());
1653         return true;
1654     }
1655 
1656     bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1657 
1658     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1659     // unless those are already completely spent.
1660     // If such overwrites are allowed, coinbases and transactions depending upon those
1661     // can be duplicated to remove the ability to spend the first instance -- even after
1662     // being sent to another address.
1663     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1664     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1665     // already refuses previously-known transaction ids entirely.
1666     // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1667     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1668     // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1669     // initial block download.
1670     bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1671                           !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1672                            (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1673     if (fEnforceBIP30) {
1674         BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1675             const CCoins* coins = view.AccessCoins(tx.GetHash());
1676             if (coins && !coins->IsPruned())
1677                 return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
1678                                  REJECT_INVALID, "bad-txns-BIP30");
1679         }
1680     }
1681 
1682     // BIP16 didn't become active until Apr 1 2012
1683     int64_t nBIP16SwitchTime = 1333238400;
1684     bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1685 
1686     unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1687 
1688     // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1689     if (block.nVersion >= 3 && CBlockIndex::IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
1690         flags |= SCRIPT_VERIFY_DERSIG;
1691     }
1692 
1693     CBlockUndo blockundo;
1694 
1695     CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1696 
1697     int64_t nTimeStart = GetTimeMicros();
1698     CAmount nFees = 0;
1699     int nInputs = 0;
1700     unsigned int nSigOps = 0;
1701     CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1702     std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1703     vPos.reserve(block.vtx.size());
1704     blockundo.vtxundo.reserve(block.vtx.size() - 1);
1705     for (unsigned int i = 0; i < block.vtx.size(); i++)
1706     {
1707         const CTransaction &tx = block.vtx[i];
1708 
1709         nInputs += tx.vin.size();
1710         nSigOps += GetLegacySigOpCount(tx);
1711         if (nSigOps > MAX_BLOCK_SIGOPS)
1712             return state.DoS(100, error("ConnectBlock() : too many sigops"),
1713                              REJECT_INVALID, "bad-blk-sigops");
1714 
1715         if (!tx.IsCoinBase())
1716         {
1717             if (!view.HaveInputs(tx))
1718                 return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
1719                                  REJECT_INVALID, "bad-txns-inputs-missingorspent");
1720 
1721             if (fStrictPayToScriptHash)
1722             {
1723                 // Add in sigops done by pay-to-script-hash inputs;
1724                 // this is to prevent a "rogue miner" from creating
1725                 // an incredibly-expensive-to-validate block.
1726                 nSigOps += GetP2SHSigOpCount(tx, view);
1727                 if (nSigOps > MAX_BLOCK_SIGOPS)
1728                     return state.DoS(100, error("ConnectBlock() : too many sigops"),
1729                                      REJECT_INVALID, "bad-blk-sigops");
1730             }
1731 
1732             nFees += view.GetValueIn(tx)-tx.GetValueOut();
1733 
1734             std::vector<CScriptCheck> vChecks;
1735             if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1736                 return false;
1737             control.Add(vChecks);
1738         }
1739 
1740         CTxUndo undoDummy;
1741         if (i > 0) {
1742             blockundo.vtxundo.push_back(CTxUndo());
1743         }
1744         UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1745 
1746         vPos.push_back(std::make_pair(tx.GetHash(), pos));
1747         pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1748     }
1749     int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1750     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);
1751 
1752     if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1753         return state.DoS(100,
1754                          error("ConnectBlock() : coinbase pays too much (actual=%d vs limit=%d)",
1755                                block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
1756                                REJECT_INVALID, "bad-cb-amount");
1757 
1758     if (!control.Wait())
1759         return state.DoS(100, false);
1760     int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1761     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);
1762 
1763     if (fJustCheck)
1764         return true;
1765 
1766     // Write undo information to disk
1767     if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1768     {
1769         if (pindex->GetUndoPos().IsNull()) {
1770             CDiskBlockPos pos;
1771             if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1772                 return error("ConnectBlock() : FindUndoPos failed");
1773             if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
1774                 return state.Abort("Failed to write undo data");
1775 
1776             // update nUndoPos in block index
1777             pindex->nUndoPos = pos.nPos;
1778             pindex->nStatus |= BLOCK_HAVE_UNDO;
1779         }
1780 
1781         pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1782         setDirtyBlockIndex.insert(pindex);
1783     }
1784 
1785     if (fTxIndex)
1786         if (!pblocktree->WriteTxIndex(vPos))
1787             return state.Abort("Failed to write transaction index");
1788 
1789     // add this block to the view's block chain
1790     view.SetBestBlock(pindex->GetBlockHash());
1791 
1792     int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1793     LogPrint("bench", "    - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1794 
1795     // Watch for changes to the previous coinbase transaction.
1796     static uint256 hashPrevBestCoinBase;
1797     g_signals.UpdatedTransaction(hashPrevBestCoinBase);
1798     hashPrevBestCoinBase = block.vtx[0].GetHash();
1799 
1800     int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1801     LogPrint("bench", "    - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1802 
1803     return true;
1804 }
1805 
1806 enum FlushStateMode {
1807     FLUSH_STATE_IF_NEEDED,
1808     FLUSH_STATE_PERIODIC,
1809     FLUSH_STATE_ALWAYS
1810 };
1811 
1812 /**
1813  * Update the on-disk chain state.
1814  * The caches and indexes are flushed if either they're too large, forceWrite is set, or
1815  * fast is not set and it's been a while since the last write.
1816  */
1817 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1818     LOCK(cs_main);
1819     static int64_t nLastWrite = 0;
1820     try {
1821     if ((mode == FLUSH_STATE_ALWAYS) ||
1822         ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
1823         (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
1824         // Typical CCoins structures on disk are around 100 bytes in size.
1825         // Pushing a new one to the database can cause it to be written
1826         // twice (once in the log, and once in the tables). This is already
1827         // an overestimation, as most will delete an existing entry or
1828         // overwrite one. Still, use a conservative safety factor of 2.
1829         if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
1830             return state.Error("out of disk space");
1831         // First make sure all block and undo data is flushed to disk.
1832         FlushBlockFile();
1833         // Then update all block file information (which may refer to block and undo files).
1834         bool fileschanged = false;
1835         for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
1836             if (!pblocktree->WriteBlockFileInfo(*it, vinfoBlockFile[*it])) {
1837                 return state.Abort("Failed to write to block index");
1838             }
1839             fileschanged = true;
1840             setDirtyFileInfo.erase(it++);
1841         }
1842         if (fileschanged && !pblocktree->WriteLastBlockFile(nLastBlockFile)) {
1843             return state.Abort("Failed to write to block index");
1844         }
1845         for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
1846              if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(*it))) {
1847                  return state.Abort("Failed to write to block index");
1848              }
1849              setDirtyBlockIndex.erase(it++);
1850         }
1851         pblocktree->Sync();
1852         // Finally flush the chainstate (which may refer to block index entries).
1853         if (!pcoinsTip->Flush())
1854             return state.Abort("Failed to write to coin database");
1855         // Update best block in wallet (so we can detect restored wallets).
1856         if (mode != FLUSH_STATE_IF_NEEDED) {
1857             g_signals.SetBestChain(chainActive.GetLocator());
1858         }
1859         nLastWrite = GetTimeMicros();
1860     }
1861     } catch (const std::runtime_error& e) {
1862         return state.Abort(std::string("System error while flushing: ") + e.what());
1863     }
1864     return true;
1865 }
1866 
1867 void FlushStateToDisk() {
1868     CValidationState state;
1869     FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
1870 }
1871 
1872 /** Update chainActive and related internal data structures. */
1873 void static UpdateTip(CBlockIndex *pindexNew) {
1874     chainActive.SetTip(pindexNew);
1875 
1876     // New best block
1877     nTimeBestReceived = GetTime();
1878     mempool.AddTransactionsUpdated(1);
1879 
1880     LogPrintf("UpdateTip: new best=%s  height=%d  log2_work=%.8g  tx=%lu  date=%s progress=%f  cache=%u\n",
1881       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
1882       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
1883       Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
1884 
1885     cvBlockChange.notify_all();
1886 
1887     // Check the version of the last 100 blocks to see if we need to upgrade:
1888     static bool fWarned = false;
1889     if (!IsInitialBlockDownload() && !fWarned)
1890     {
1891         int nUpgraded = 0;
1892         const CBlockIndex* pindex = chainActive.Tip();
1893         for (int i = 0; i < 100 && pindex != NULL; i++)
1894         {
1895             if (pindex->nVersion > CBlock::CURRENT_VERSION)
1896                 ++nUpgraded;
1897             pindex = pindex->pprev;
1898         }
1899         if (nUpgraded > 0)
1900             LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
1901         if (nUpgraded > 100/2)
1902         {
1903             // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1904             strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1905             CAlert::Notify(strMiscWarning, true);
1906             fWarned = true;
1907         }
1908     }
1909 }
1910 
1911 /** Disconnect chainActive's tip. */
1912 bool static DisconnectTip(CValidationState &state) {
1913     CBlockIndex *pindexDelete = chainActive.Tip();
1914     assert(pindexDelete);
1915     mempool.check(pcoinsTip);
1916     // Read block from disk.
1917     CBlock block;
1918     if (!ReadBlockFromDisk(block, pindexDelete))
1919         return state.Abort("Failed to read block");
1920     // Apply the block atomically to the chain state.
1921     int64_t nStart = GetTimeMicros();
1922     {
1923         CCoinsViewCache view(pcoinsTip);
1924         if (!DisconnectBlock(block, state, pindexDelete, view))
1925             return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
1926         assert(view.Flush());
1927     }
1928     LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
1929     // Write the chain state to disk, if necessary.
1930     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
1931         return false;
1932     // Resurrect mempool transactions from the disconnected block.
1933     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1934         // ignore validation errors in resurrected transactions
1935         list<CTransaction> removed;
1936         CValidationState stateDummy;
1937         if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
1938             mempool.remove(tx, removed, true);
1939     }
1940     mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
1941     mempool.check(pcoinsTip);
1942     // Update chainActive and related variables.
1943     UpdateTip(pindexDelete->pprev);
1944     // Let wallets know transactions went from 1-confirmed to
1945     // 0-confirmed or conflicted:
1946     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1947         SyncWithWallets(tx, NULL);
1948     }
1949     return true;
1950 }
1951 
1952 static int64_t nTimeReadFromDisk = 0;
1953 static int64_t nTimeConnectTotal = 0;
1954 static int64_t nTimeFlush = 0;
1955 static int64_t nTimeChainState = 0;
1956 static int64_t nTimePostConnect = 0;
1957 
1958 /** 
1959  * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
1960  * corresponding to pindexNew, to bypass loading it again from disk.
1961  */
1962 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
1963     assert(pindexNew->pprev == chainActive.Tip());
1964     mempool.check(pcoinsTip);
1965     // Read block from disk.
1966     int64_t nTime1 = GetTimeMicros();
1967     CBlock block;
1968     if (!pblock) {
1969         if (!ReadBlockFromDisk(block, pindexNew))
1970             return state.Abort("Failed to read block");
1971         pblock = &block;
1972     }
1973     // Apply the block atomically to the chain state.
1974     int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
1975     int64_t nTime3;
1976     LogPrint("bench", "  - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
1977     {
1978         CCoinsViewCache view(pcoinsTip);
1979         CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
1980         bool rv = ConnectBlock(*pblock, state, pindexNew, view);
1981         g_signals.BlockChecked(*pblock, state);
1982         if (!rv) {
1983             if (state.IsInvalid())
1984                 InvalidBlockFound(pindexNew, state);
1985             return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
1986         }
1987         mapBlockSource.erase(inv.hash);
1988         nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
1989         LogPrint("bench", "  - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
1990         assert(view.Flush());
1991     }
1992     int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
1993     LogPrint("bench", "  - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
1994     // Write the chain state to disk, if necessary.
1995     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
1996         return false;
1997     int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
1998     LogPrint("bench", "  - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
1999     // Remove conflicting transactions from the mempool.
2000     list<CTransaction> txConflicted;
2001     mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
2002     mempool.check(pcoinsTip);
2003     // Update chainActive & related variables.
2004     UpdateTip(pindexNew);
2005     // Tell wallet about transactions that went from mempool
2006     // to conflicted:
2007     BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2008         SyncWithWallets(tx, NULL);
2009     }
2010     // ... and about transactions that got confirmed:
2011     BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2012         SyncWithWallets(tx, pblock);
2013     }
2014 
2015     int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2016     LogPrint("bench", "  - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2017     LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2018     return true;
2019 }
2020 
2021 /**
2022  * Return the tip of the chain with the most work in it, that isn't
2023  * known to be invalid (it's however far from certain to be valid).
2024  */
2025 static CBlockIndex* FindMostWorkChain() {
2026     do {
2027         CBlockIndex *pindexNew = NULL;
2028 
2029         // Find the best candidate header.
2030         {
2031             std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2032             if (it == setBlockIndexCandidates.rend())
2033                 return NULL;
2034             pindexNew = *it;
2035         }
2036 
2037         // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2038         // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2039         CBlockIndex *pindexTest = pindexNew;
2040         bool fInvalidAncestor = false;
2041         while (pindexTest && !chainActive.Contains(pindexTest)) {
2042             assert(pindexTest->nStatus & BLOCK_HAVE_DATA);
2043             assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2044             if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
2045                 // Candidate has an invalid ancestor, remove entire chain from the set.
2046                 if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
2047                     pindexBestInvalid = pindexNew;
2048                 CBlockIndex *pindexFailed = pindexNew;
2049                 while (pindexTest != pindexFailed) {
2050                     pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2051                     setBlockIndexCandidates.erase(pindexFailed);
2052                     pindexFailed = pindexFailed->pprev;
2053                 }
2054                 setBlockIndexCandidates.erase(pindexTest);
2055                 fInvalidAncestor = true;
2056                 break;
2057             }
2058             pindexTest = pindexTest->pprev;
2059         }
2060         if (!fInvalidAncestor)
2061             return pindexNew;
2062     } while(true);
2063 }
2064 
2065 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2066 static void PruneBlockIndexCandidates() {
2067     // Note that we can't delete the current block itself, as we may need to return to it later in case a
2068     // reorganization to a better block fails.
2069     std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2070     while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2071         setBlockIndexCandidates.erase(it++);
2072     }
2073     // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2074     assert(!setBlockIndexCandidates.empty());
2075 }
2076 
2077 /**
2078  * Try to make some progress towards making pindexMostWork the active block.
2079  * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2080  */
2081 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2082     AssertLockHeld(cs_main);
2083     bool fInvalidFound = false;
2084     const CBlockIndex *pindexOldTip = chainActive.Tip();
2085     const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2086 
2087     // Disconnect active blocks which are no longer in the best chain.
2088     while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2089         if (!DisconnectTip(state))
2090             return false;
2091     }
2092 
2093     // Build list of new blocks to connect.
2094     std::vector<CBlockIndex*> vpindexToConnect;
2095     bool fContinue = true;
2096     int nHeight = pindexFork ? pindexFork->nHeight : -1;
2097     while (fContinue && nHeight != pindexMostWork->nHeight) {
2098     // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2099     // a few blocks along the way.
2100     int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2101     vpindexToConnect.clear();
2102     vpindexToConnect.reserve(nTargetHeight - nHeight);
2103     CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2104     while (pindexIter && pindexIter->nHeight != nHeight) {
2105         vpindexToConnect.push_back(pindexIter);
2106         pindexIter = pindexIter->pprev;
2107     }
2108     nHeight = nTargetHeight;
2109 
2110     // Connect new blocks.
2111     BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2112         if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2113             if (state.IsInvalid()) {
2114                 // The block violates a consensus rule.
2115                 if (!state.CorruptionPossible())
2116                     InvalidChainFound(vpindexToConnect.back());
2117                 state = CValidationState();
2118                 fInvalidFound = true;
2119                 fContinue = false;
2120                 break;
2121             } else {
2122                 // A system error occurred (disk space, database error, ...).
2123                 return false;
2124             }
2125         } else {
2126             PruneBlockIndexCandidates();
2127             if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2128                 // We're in a better position than we were. Return temporarily to release the lock.
2129                 fContinue = false;
2130                 break;
2131             }
2132         }
2133     }
2134     }
2135 
2136     // Callbacks/notifications for a new best chain.
2137     if (fInvalidFound)
2138         CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2139     else
2140         CheckForkWarningConditions();
2141 
2142     return true;
2143 }
2144 
2145 /**
2146  * Make the best chain active, in multiple steps. The result is either failure
2147  * or an activated best chain. pblock is either NULL or a pointer to a block
2148  * that is already loaded (to avoid loading it again from disk).
2149  */
2150 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2151     CBlockIndex *pindexNewTip = NULL;
2152     CBlockIndex *pindexMostWork = NULL;
2153     do {
2154         boost::this_thread::interruption_point();
2155 
2156         bool fInitialDownload;
2157         {
2158             LOCK(cs_main);
2159             pindexMostWork = FindMostWorkChain();
2160 
2161             // Whether we have anything to do at all.
2162             if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2163                 return true;
2164 
2165             if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2166                 return false;
2167 
2168             pindexNewTip = chainActive.Tip();
2169             fInitialDownload = IsInitialBlockDownload();
2170         }
2171         // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2172 
2173         // Notifications/callbacks that can run without cs_main
2174         if (!fInitialDownload) {
2175             uint256 hashNewTip = pindexNewTip->GetBlockHash();
2176             // Relay inventory, but don't relay old inventory during initial block download.
2177             int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2178             {
2179                 LOCK(cs_vNodes);
2180                 BOOST_FOREACH(CNode* pnode, vNodes)
2181                     if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2182                         pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2183             }
2184             // Notify external listeners about the new tip.
2185             uiInterface.NotifyBlockTip(hashNewTip);
2186         }
2187     } while(pindexMostWork != chainActive.Tip());
2188 
2189     // Write changes periodically to disk, after relay.
2190     if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2191         return false;
2192     }
2193 
2194     return true;
2195 }
2196 
2197 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2198     AssertLockHeld(cs_main);
2199 
2200     // Mark the block itself as invalid.
2201     pindex->nStatus |= BLOCK_FAILED_VALID;
2202     setDirtyBlockIndex.insert(pindex);
2203     setBlockIndexCandidates.erase(pindex);
2204 
2205     while (chainActive.Contains(pindex)) {
2206         CBlockIndex *pindexWalk = chainActive.Tip();
2207         pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2208         setDirtyBlockIndex.insert(pindexWalk);
2209         setBlockIndexCandidates.erase(pindexWalk);
2210         // ActivateBestChain considers blocks already in chainActive
2211         // unconditionally valid already, so force disconnect away from it.
2212         if (!DisconnectTip(state)) {
2213             return false;
2214         }
2215     }
2216 
2217     // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2218     // add them again.
2219     BlockMap::iterator it = mapBlockIndex.begin();
2220     while (it != mapBlockIndex.end()) {
2221         if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2222             setBlockIndexCandidates.insert(pindex);
2223         }
2224         it++;
2225     }
2226 
2227     InvalidChainFound(pindex);
2228     return true;
2229 }
2230 
2231 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2232     AssertLockHeld(cs_main);
2233 
2234     int nHeight = pindex->nHeight;
2235 
2236     // Remove the invalidity flag from this block and all its descendants.
2237     BlockMap::iterator it = mapBlockIndex.begin();
2238     while (it != mapBlockIndex.end()) {
2239         if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2240             it->second->nStatus &= ~BLOCK_FAILED_MASK;
2241             setDirtyBlockIndex.insert(it->second);
2242             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2243                 setBlockIndexCandidates.insert(it->second);
2244             }
2245             if (it->second == pindexBestInvalid) {
2246                 // Reset invalid block marker if it was pointing to one of those.
2247                 pindexBestInvalid = NULL;
2248             }
2249         }
2250         it++;
2251     }
2252 
2253     // Remove the invalidity flag from all ancestors too.
2254     while (pindex != NULL) {
2255         if (pindex->nStatus & BLOCK_FAILED_MASK) {
2256             pindex->nStatus &= ~BLOCK_FAILED_MASK;
2257             setDirtyBlockIndex.insert(pindex);
2258         }
2259         pindex = pindex->pprev;
2260     }
2261     return true;
2262 }
2263 
2264 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2265 {
2266     // Check for duplicate
2267     uint256 hash = block.GetHash();
2268     BlockMap::iterator it = mapBlockIndex.find(hash);
2269     if (it != mapBlockIndex.end())
2270         return it->second;
2271 
2272     // Construct new block index object
2273     CBlockIndex* pindexNew = new CBlockIndex(block);
2274     assert(pindexNew);
2275     // We assign the sequence id to blocks only when the full data is available,
2276     // to avoid miners withholding blocks but broadcasting headers, to get a
2277     // competitive advantage.
2278     pindexNew->nSequenceId = 0;
2279     BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2280     pindexNew->phashBlock = &((*mi).first);
2281     BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2282     if (miPrev != mapBlockIndex.end())
2283     {
2284         pindexNew->pprev = (*miPrev).second;
2285         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2286         pindexNew->BuildSkip();
2287     }
2288     pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2289     pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2290     if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2291         pindexBestHeader = pindexNew;
2292 
2293     setDirtyBlockIndex.insert(pindexNew);
2294 
2295     return pindexNew;
2296 }
2297 
2298 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2299 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2300 {
2301     pindexNew->nTx = block.vtx.size();
2302     pindexNew->nChainTx = 0;
2303     pindexNew->nFile = pos.nFile;
2304     pindexNew->nDataPos = pos.nPos;
2305     pindexNew->nUndoPos = 0;
2306     pindexNew->nStatus |= BLOCK_HAVE_DATA;
2307     pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2308     {
2309          LOCK(cs_nBlockSequenceId);
2310          pindexNew->nSequenceId = nBlockSequenceId++;
2311     }
2312     setDirtyBlockIndex.insert(pindexNew);
2313 
2314     if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2315         // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2316         deque<CBlockIndex*> queue;
2317         queue.push_back(pindexNew);
2318 
2319         // Recursively process any descendant blocks that now may be eligible to be connected.
2320         while (!queue.empty()) {
2321             CBlockIndex *pindex = queue.front();
2322             queue.pop_front();
2323             pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2324             setBlockIndexCandidates.insert(pindex);
2325             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2326             while (range.first != range.second) {
2327                 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2328                 queue.push_back(it->second);
2329                 range.first++;
2330                 mapBlocksUnlinked.erase(it);
2331             }
2332         }
2333     } else {
2334         if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2335             mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2336         }
2337     }
2338 
2339     return true;
2340 }
2341 
2342 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2343 {
2344     LOCK(cs_LastBlockFile);
2345 
2346     unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2347     if (vinfoBlockFile.size() <= nFile) {
2348         vinfoBlockFile.resize(nFile + 1);
2349     }
2350 
2351     if (!fKnown) {
2352         while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2353             LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2354             FlushBlockFile(true);
2355             nFile++;
2356             if (vinfoBlockFile.size() <= nFile) {
2357                 vinfoBlockFile.resize(nFile + 1);
2358             }
2359         }
2360         pos.nFile = nFile;
2361         pos.nPos = vinfoBlockFile[nFile].nSize;
2362     }
2363 
2364     nLastBlockFile = nFile;
2365     vinfoBlockFile[nFile].nSize += nAddSize;
2366     vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2367 
2368     if (!fKnown) {
2369         unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2370         unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2371         if (nNewChunks > nOldChunks) {
2372             if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2373                 FILE *file = OpenBlockFile(pos);
2374                 if (file) {
2375                     LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2376                     AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2377                     fclose(file);
2378                 }
2379             }
2380             else
2381                 return state.Error("out of disk space");
2382         }
2383     }
2384 
2385     setDirtyFileInfo.insert(nFile);
2386     return true;
2387 }
2388 
2389 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2390 {
2391     pos.nFile = nFile;
2392 
2393     LOCK(cs_LastBlockFile);
2394 
2395     unsigned int nNewSize;
2396     pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2397     nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2398     setDirtyFileInfo.insert(nFile);
2399 
2400     unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2401     unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2402     if (nNewChunks > nOldChunks) {
2403         if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2404             FILE *file = OpenUndoFile(pos);
2405             if (file) {
2406                 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2407                 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2408                 fclose(file);
2409             }
2410         }
2411         else
2412             return state.Error("out of disk space");
2413     }
2414 
2415     return true;
2416 }
2417 
2418 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2419 {
2420     // Check proof of work matches claimed amount
2421     if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
2422         return state.DoS(50, error("CheckBlockHeader() : proof of work failed"),
2423                          REJECT_INVALID, "high-hash");
2424 
2425     // Check timestamp
2426     if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2427         return state.Invalid(error("CheckBlockHeader() : block timestamp too far in the future"),
2428                              REJECT_INVALID, "time-too-new");
2429 
2430     return true;
2431 }
2432 
2433 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2434 {
2435     // These are checks that are independent of context.
2436 
2437     // Check that the header is valid (particularly PoW).  This is mostly
2438     // redundant with the call in AcceptBlockHeader.
2439     if (!CheckBlockHeader(block, state, fCheckPOW))
2440         return false;
2441 
2442     // Check the merkle root.
2443     if (fCheckMerkleRoot) {
2444         bool mutated;
2445         uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2446         if (block.hashMerkleRoot != hashMerkleRoot2)
2447             return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
2448                              REJECT_INVALID, "bad-txnmrklroot", true);
2449 
2450         // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2451         // of transactions in a block without affecting the merkle root of a block,
2452         // while still invalidating it.
2453         if (mutated)
2454             return state.DoS(100, error("CheckBlock() : duplicate transaction"),
2455                              REJECT_INVALID, "bad-txns-duplicate", true);
2456     }
2457 
2458     // All potential-corruption validation must be done before we do any
2459     // transaction validation, as otherwise we may mark the header as invalid
2460     // because we receive the wrong transactions for it.
2461 
2462     // Size limits
2463     if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2464         return state.DoS(100, error("CheckBlock() : size limits failed"),
2465                          REJECT_INVALID, "bad-blk-length");
2466 
2467     // First transaction must be coinbase, the rest must not be
2468     if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2469         return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
2470                          REJECT_INVALID, "bad-cb-missing");
2471     for (unsigned int i = 1; i < block.vtx.size(); i++)
2472         if (block.vtx[i].IsCoinBase())
2473             return state.DoS(100, error("CheckBlock() : more than one coinbase"),
2474                              REJECT_INVALID, "bad-cb-multiple");
2475 
2476     // Check transactions
2477     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2478         if (!CheckTransaction(tx, state))
2479             return error("CheckBlock() : CheckTransaction failed");
2480 
2481     unsigned int nSigOps = 0;
2482     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2483     {
2484         nSigOps += GetLegacySigOpCount(tx);
2485     }
2486     if (nSigOps > MAX_BLOCK_SIGOPS)
2487         return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
2488                          REJECT_INVALID, "bad-blk-sigops", true);
2489 
2490     return true;
2491 }
2492 
2493 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2494 {
2495     uint256 hash = block.GetHash();
2496     if (hash == Params().HashGenesisBlock())
2497         return true;
2498 
2499     assert(pindexPrev);
2500 
2501     int nHeight = pindexPrev->nHeight+1;
2502 
2503     // Check proof of work
2504     if ((!Params().SkipProofOfWorkCheck()) &&
2505        (block.nBits != GetNextWorkRequired(pindexPrev, &block)))
2506         return state.DoS(100, error("%s : incorrect proof of work", __func__),
2507                          REJECT_INVALID, "bad-diffbits");
2508 
2509     // Check timestamp against prev
2510     if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2511         return state.Invalid(error("%s : block's timestamp is too early", __func__),
2512                              REJECT_INVALID, "time-too-old");
2513 
2514     // Check that the block chain matches the known block chain up to a checkpoint
2515     if (!Checkpoints::CheckBlock(nHeight, hash))
2516         return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
2517                          REJECT_CHECKPOINT, "checkpoint mismatch");
2518 
2519     // Don't accept any forks from the main chain prior to last checkpoint
2520     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
2521     if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2522         return state.DoS(100, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
2523 
2524     // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2525     if (block.nVersion < 2 && 
2526         CBlockIndex::IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
2527     {
2528         return state.Invalid(error("%s : rejected nVersion=1 block", __func__),
2529                              REJECT_OBSOLETE, "bad-version");
2530     }
2531 
2532     // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2533     if (block.nVersion < 3 && CBlockIndex::IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority()))
2534     {
2535         return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2536                              REJECT_OBSOLETE, "bad-version");
2537     }
2538 
2539     return true;
2540 }
2541 
2542 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2543 {
2544     const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2545 
2546     // Check that all transactions are finalized
2547     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2548         if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2549             return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2550         }
2551 
2552     // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2553     // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2554     if (block.nVersion >= 2 && 
2555         CBlockIndex::IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority()))
2556     {
2557         CScript expect = CScript() << nHeight;
2558         if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2559             !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2560             return state.DoS(100, error("%s : block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2561         }
2562     }
2563 
2564     return true;
2565 }
2566 
2567 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2568 {
2569     AssertLockHeld(cs_main);
2570     // Check for duplicate
2571     uint256 hash = block.GetHash();
2572     BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2573     CBlockIndex *pindex = NULL;
2574     if (miSelf != mapBlockIndex.end()) {
2575         // Block header is already known.
2576         pindex = miSelf->second;
2577         if (ppindex)
2578             *ppindex = pindex;
2579         if (pindex->nStatus & BLOCK_FAILED_MASK)
2580             return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate");
2581         return true;
2582     }
2583 
2584     if (!CheckBlockHeader(block, state))
2585         return false;
2586 
2587     // Get prev block index
2588     CBlockIndex* pindexPrev = NULL;
2589     if (hash != Params().HashGenesisBlock()) {
2590         BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2591         if (mi == mapBlockIndex.end())
2592             return state.DoS(10, error("%s : prev block not found", __func__), 0, "bad-prevblk");
2593         pindexPrev = (*mi).second;
2594         if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2595             return state.DoS(100, error("%s : prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2596     }
2597 
2598     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2599         return false;
2600 
2601     if (pindex == NULL)
2602         pindex = AddToBlockIndex(block);
2603 
2604     if (ppindex)
2605         *ppindex = pindex;
2606 
2607     return true;
2608 }
2609 
2610 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2611 {
2612     AssertLockHeld(cs_main);
2613 
2614     CBlockIndex *&pindex = *ppindex;
2615 
2616     if (!AcceptBlockHeader(block, state, &pindex))
2617         return false;
2618 
2619     if (pindex->nStatus & BLOCK_HAVE_DATA) {
2620         // TODO: deal better with duplicate blocks.
2621         // return state.DoS(20, error("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2622         return true;
2623     }
2624 
2625     if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2626         if (state.IsInvalid() && !state.CorruptionPossible()) {
2627             pindex->nStatus |= BLOCK_FAILED_VALID;
2628             setDirtyBlockIndex.insert(pindex);
2629         }
2630         return false;
2631     }
2632 
2633     int nHeight = pindex->nHeight;
2634 
2635     // Write block to history file
2636     try {
2637         unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2638         CDiskBlockPos blockPos;
2639         if (dbp != NULL)
2640             blockPos = *dbp;
2641         if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2642             return error("AcceptBlock() : FindBlockPos failed");
2643         if (dbp == NULL)
2644             if (!WriteBlockToDisk(block, blockPos))
2645                 return state.Abort("Failed to write block");
2646         if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2647             return error("AcceptBlock() : ReceivedBlockTransactions failed");
2648     } catch(std::runtime_error &e) {
2649         return state.Abort(std::string("System error: ") + e.what());
2650     }
2651 
2652     return true;
2653 }
2654 
2655 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
2656 {
2657     unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
2658     unsigned int nFound = 0;
2659     for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2660     {
2661         if (pstart->nVersion >= minVersion)
2662             ++nFound;
2663         pstart = pstart->pprev;
2664     }
2665     return (nFound >= nRequired);
2666 }
2667 
2668 /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
2669 int static inline InvertLowestOne(int n) { return n & (n - 1); }
2670 
2671 /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
2672 int static inline GetSkipHeight(int height) {
2673     if (height < 2)
2674         return 0;
2675 
2676     // Determine which height to jump back to. Any number strictly lower than height is acceptable,
2677     // but the following expression seems to perform well in simulations (max 110 steps to go back
2678     // up to 2**18 blocks).
2679     return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
2680 }
2681 
2682 CBlockIndex* CBlockIndex::GetAncestor(int height)
2683 {
2684     if (height > nHeight || height < 0)
2685         return NULL;
2686 
2687     CBlockIndex* pindexWalk = this;
2688     int heightWalk = nHeight;
2689     while (heightWalk > height) {
2690         int heightSkip = GetSkipHeight(heightWalk);
2691         int heightSkipPrev = GetSkipHeight(heightWalk - 1);
2692         if (heightSkip == height ||
2693             (heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
2694                                       heightSkipPrev >= height))) {
2695             // Only follow pskip if pprev->pskip isn't better than pskip->pprev.
2696             pindexWalk = pindexWalk->pskip;
2697             heightWalk = heightSkip;
2698         } else {
2699             pindexWalk = pindexWalk->pprev;
2700             heightWalk--;
2701         }
2702     }
2703     return pindexWalk;
2704 }
2705 
2706 const CBlockIndex* CBlockIndex::GetAncestor(int height) const
2707 {
2708     return const_cast<CBlockIndex*>(this)->GetAncestor(height);
2709 }
2710 
2711 void CBlockIndex::BuildSkip()
2712 {
2713     if (pprev)
2714         pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
2715 }
2716 
2717 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2718 {
2719     // Preliminary checks
2720     bool checked = CheckBlock(*pblock, state);
2721 
2722     {
2723         LOCK(cs_main);
2724         MarkBlockAsReceived(pblock->GetHash());
2725         if (!checked) {
2726             return error("%s : CheckBlock FAILED", __func__);
2727         }
2728 
2729         // Store to disk
2730         CBlockIndex *pindex = NULL;
2731         bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2732         if (pindex && pfrom) {
2733             mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2734         }
2735         if (!ret)
2736             return error("%s : AcceptBlock FAILED", __func__);
2737     }
2738 
2739     if (!ActivateBestChain(state, pblock))
2740         return error("%s : ActivateBestChain failed", __func__);
2741 
2742     return true;
2743 }
2744 
2745 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2746 {
2747     AssertLockHeld(cs_main);
2748     assert(pindexPrev == chainActive.Tip());
2749 
2750     CCoinsViewCache viewNew(pcoinsTip);
2751     CBlockIndex indexDummy(block);
2752     indexDummy.pprev = pindexPrev;
2753     indexDummy.nHeight = pindexPrev->nHeight + 1;
2754 
2755     // NOTE: CheckBlockHeader is called by CheckBlock
2756     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2757         return false;
2758     if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2759         return false;
2760     if (!ContextualCheckBlock(block, state, pindexPrev))
2761         return false;
2762     if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2763         return false;
2764     assert(state.IsValid());
2765 
2766     return true;
2767 }
2768 
2769 
2770 
2771 
2772 
2773 
2774 
2775 
2776 bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
2777     strMiscWarning = strMessage;
2778     LogPrintf("*** %s\n", strMessage);
2779     uiInterface.ThreadSafeMessageBox(
2780         userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
2781         "", CClientUIInterface::MSG_ERROR);
2782     StartShutdown();
2783     return false;
2784 }
2785 
2786 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2787 {
2788     uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2789 
2790     // Check for nMinDiskSpace bytes (currently 50MB)
2791     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2792         return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
2793 
2794     return true;
2795 }
2796 
2797 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2798 {
2799     if (pos.IsNull())
2800         return NULL;
2801     boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
2802     boost::filesystem::create_directories(path.parent_path());
2803     FILE* file = fopen(path.string().c_str(), "rb+");
2804     if (!file && !fReadOnly)
2805         file = fopen(path.string().c_str(), "wb+");
2806     if (!file) {
2807         LogPrintf("Unable to open file %s\n", path.string());
2808         return NULL;
2809     }
2810     if (pos.nPos) {
2811         if (fseek(file, pos.nPos, SEEK_SET)) {
2812             LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
2813             fclose(file);
2814             return NULL;
2815         }
2816     }
2817     return file;
2818 }
2819 
2820 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2821     return OpenDiskFile(pos, "blk", fReadOnly);
2822 }
2823 
2824 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2825     return OpenDiskFile(pos, "rev", fReadOnly);
2826 }
2827 
2828 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
2829 {
2830     return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2831 }
2832 
2833 CBlockIndex * InsertBlockIndex(uint256 hash)
2834 {
2835     if (hash == 0)
2836         return NULL;
2837 
2838     // Return existing
2839     BlockMap::iterator mi = mapBlockIndex.find(hash);
2840     if (mi != mapBlockIndex.end())
2841         return (*mi).second;
2842 
2843     // Create new
2844     CBlockIndex* pindexNew = new CBlockIndex();
2845     if (!pindexNew)
2846         throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
2847     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2848     pindexNew->phashBlock = &((*mi).first);
2849 
2850     return pindexNew;
2851 }
2852 
2853 bool static LoadBlockIndexDB()
2854 {
2855     if (!pblocktree->LoadBlockIndexGuts())
2856         return false;
2857 
2858     boost::this_thread::interruption_point();
2859 
2860     // Calculate nChainWork
2861     vector<pair<int, CBlockIndex*> > vSortedByHeight;
2862     vSortedByHeight.reserve(mapBlockIndex.size());
2863     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2864     {
2865         CBlockIndex* pindex = item.second;
2866         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
2867     }
2868     sort(vSortedByHeight.begin(), vSortedByHeight.end());
2869     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
2870     {
2871         CBlockIndex* pindex = item.second;
2872         pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
2873         if (pindex->nStatus & BLOCK_HAVE_DATA) {
2874             if (pindex->pprev) {
2875                 if (pindex->pprev->nChainTx) {
2876                     pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
2877                 } else {
2878                     pindex->nChainTx = 0;
2879                     mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
2880                 }
2881             } else {
2882                 pindex->nChainTx = pindex->nTx;
2883             }
2884         }
2885         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
2886             setBlockIndexCandidates.insert(pindex);
2887         if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
2888             pindexBestInvalid = pindex;
2889         if (pindex->pprev)
2890             pindex->BuildSkip();
2891         if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
2892             pindexBestHeader = pindex;
2893     }
2894 
2895     // Load block file info
2896     pblocktree->ReadLastBlockFile(nLastBlockFile);
2897     vinfoBlockFile.resize(nLastBlockFile + 1);
2898     LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
2899     for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
2900         pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
2901     }
2902     LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
2903     for (int nFile = nLastBlockFile + 1; true; nFile++) {
2904         CBlockFileInfo info;
2905         if (pblocktree->ReadBlockFileInfo(nFile, info)) {
2906             vinfoBlockFile.push_back(info);
2907         } else {
2908             break;
2909         }
2910     }
2911 
2912     // Check presence of blk files
2913     LogPrintf("Checking all blk files are present...\n");
2914     set<int> setBlkDataFiles;
2915     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
2916     {
2917         CBlockIndex* pindex = item.second;
2918         if (pindex->nStatus & BLOCK_HAVE_DATA) {
2919             setBlkDataFiles.insert(pindex->nFile);
2920         }
2921     }
2922     for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
2923     {
2924         CDiskBlockPos pos(*it, 0);
2925         if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
2926             return false;
2927         }
2928     }
2929 
2930     // Check whether we need to continue reindexing
2931     bool fReindexing = false;
2932     pblocktree->ReadReindexing(fReindexing);
2933     fReindex |= fReindexing;
2934 
2935     // Check whether we have a transaction index
2936     pblocktree->ReadFlag("txindex", fTxIndex);
2937     LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
2938 
2939     // Load pointer to end of best chain
2940     BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
2941     if (it == mapBlockIndex.end())
2942         return true;
2943     chainActive.SetTip(it->second);
2944 
2945     PruneBlockIndexCandidates();
2946 
2947     LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
2948         chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
2949         DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2950         Checkpoints::GuessVerificationProgress(chainActive.Tip()));
2951 
2952     return true;
2953 }
2954 
2955 CVerifyDB::CVerifyDB()
2956 {
2957     uiInterface.ShowProgress(_("Verifying blocks..."), 0);
2958 }
2959 
2960 CVerifyDB::~CVerifyDB()
2961 {
2962     uiInterface.ShowProgress("", 100);
2963 }
2964 
2965 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
2966 {
2967     LOCK(cs_main);
2968     if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
2969         return true;
2970 
2971     // Verify blocks in the best chain
2972     if (nCheckDepth <= 0)
2973         nCheckDepth = 1000000000; // suffices until the year 19000
2974     if (nCheckDepth > chainActive.Height())
2975         nCheckDepth = chainActive.Height();
2976     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
2977     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
2978     CCoinsViewCache coins(coinsview);
2979     CBlockIndex* pindexState = chainActive.Tip();
2980     CBlockIndex* pindexFailure = NULL;
2981     int nGoodTransactions = 0;
2982     CValidationState state;
2983     for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
2984     {
2985         boost::this_thread::interruption_point();
2986         uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
2987         if (pindex->nHeight < chainActive.Height()-nCheckDepth)
2988             break;
2989         CBlock block;
2990         // check level 0: read from disk
2991         if (!ReadBlockFromDisk(block, pindex))
2992             return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
2993         // check level 1: verify block validity
2994         if (nCheckLevel >= 1 && !CheckBlock(block, state))
2995             return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
2996         // check level 2: verify undo validity
2997         if (nCheckLevel >= 2 && pindex) {
2998             CBlockUndo undo;
2999             CDiskBlockPos pos = pindex->GetUndoPos();
3000             if (!pos.IsNull()) {
3001                 if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
3002                     return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3003             }
3004         }
3005         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3006         if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
3007             bool fClean = true;
3008             if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3009                 return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3010             pindexState = pindex->pprev;
3011             if (!fClean) {
3012                 nGoodTransactions = 0;
3013                 pindexFailure = pindex;
3014             } else
3015                 nGoodTransactions += block.vtx.size();
3016         }
3017         if (ShutdownRequested())
3018             return true;
3019     }
3020     if (pindexFailure)
3021         return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3022 
3023     // check level 4: try reconnecting blocks
3024     if (nCheckLevel >= 4) {
3025         CBlockIndex *pindex = pindexState;
3026         while (pindex != chainActive.Tip()) {
3027             boost::this_thread::interruption_point();
3028             uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3029             pindex = chainActive.Next(pindex);
3030             CBlock block;
3031             if (!ReadBlockFromDisk(block, pindex))
3032                 return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3033             if (!ConnectBlock(block, state, pindex, coins))
3034                 return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3035         }
3036     }
3037 
3038     LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3039 
3040     return true;
3041 }
3042 
3043 void UnloadBlockIndex()
3044 {
3045     mapBlockIndex.clear();
3046     setBlockIndexCandidates.clear();
3047     chainActive.SetTip(NULL);
3048     pindexBestInvalid = NULL;
3049 }
3050 
3051 bool LoadBlockIndex()
3052 {
3053     // Load block index from databases
3054     if (!fReindex && !LoadBlockIndexDB())
3055         return false;
3056     return true;
3057 }
3058 
3059 
3060 bool InitBlockIndex() {
3061     LOCK(cs_main);
3062     // Check whether we're already initialized
3063     if (chainActive.Genesis() != NULL)
3064         return true;
3065 
3066     // Use the provided setting for -txindex in the new database
3067     fTxIndex = GetBoolArg("-txindex", false);
3068     pblocktree->WriteFlag("txindex", fTxIndex);
3069     LogPrintf("Initializing databases...\n");
3070 
3071     // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3072     if (!fReindex) {
3073         try {
3074             CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3075             // Start new block file
3076             unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3077             CDiskBlockPos blockPos;
3078             CValidationState state;
3079             if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3080                 return error("LoadBlockIndex() : FindBlockPos failed");
3081             if (!WriteBlockToDisk(block, blockPos))
3082                 return error("LoadBlockIndex() : writing genesis block to disk failed");
3083             CBlockIndex *pindex = AddToBlockIndex(block);
3084             if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3085                 return error("LoadBlockIndex() : genesis block not accepted");
3086             if (!ActivateBestChain(state, &block))
3087                 return error("LoadBlockIndex() : genesis block cannot be activated");
3088             // Force a chainstate write so that when we VerifyDB in a moment, it doesnt check stale data
3089             return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3090         } catch(std::runtime_error &e) {
3091             return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
3092         }
3093     }
3094 
3095     return true;
3096 }
3097 
3098 
3099 
3100 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3101 {
3102     // Map of disk positions for blocks with unknown parent (only used for reindex)
3103     static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3104     int64_t nStart = GetTimeMillis();
3105 
3106     int nLoaded = 0;
3107     try {
3108         // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3109         CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3110         uint64_t nRewind = blkdat.GetPos();
3111         while (!blkdat.eof()) {
3112             boost::this_thread::interruption_point();
3113 
3114             blkdat.SetPos(nRewind);
3115             nRewind++; // start one byte further next time, in case of failure
3116             blkdat.SetLimit(); // remove former limit
3117             unsigned int nSize = 0;
3118             try {
3119                 // locate a header
3120                 unsigned char buf[MESSAGE_START_SIZE];
3121                 blkdat.FindByte(Params().MessageStart()[0]);
3122                 nRewind = blkdat.GetPos()+1;
3123                 blkdat >> FLATDATA(buf);
3124                 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3125                     continue;
3126                 // read size
3127                 blkdat >> nSize;
3128                 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3129                     continue;
3130             } catch (const std::exception &) {
3131                 // no valid block header found; don't complain
3132                 break;
3133             }
3134             try {
3135                 // read block
3136                 uint64_t nBlockPos = blkdat.GetPos();
3137                 if (dbp)
3138                     dbp->nPos = nBlockPos;
3139                 blkdat.SetLimit(nBlockPos + nSize);
3140                 blkdat.SetPos(nBlockPos);
3141                 CBlock block;
3142                 blkdat >> block;
3143                 nRewind = blkdat.GetPos();
3144 
3145                 // detect out of order blocks, and store them for later
3146                 uint256 hash = block.GetHash();
3147                 if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3148                     LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3149                             block.hashPrevBlock.ToString());
3150                     if (dbp)
3151                         mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3152                     continue;
3153                 }
3154 
3155                 // process in case the block isn't known yet
3156                 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3157                     CValidationState state;
3158                     if (ProcessNewBlock(state, NULL, &block, dbp))
3159                         nLoaded++;
3160                     if (state.IsError())
3161                         break;
3162                 } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3163                     LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3164                 }
3165 
3166                 // Recursively process earlier encountered successors of this block
3167                 deque<uint256> queue;
3168                 queue.push_back(hash);
3169                 while (!queue.empty()) {
3170                     uint256 head = queue.front();
3171                     queue.pop_front();
3172                     std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3173                     while (range.first != range.second) {
3174                         std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3175                         if (ReadBlockFromDisk(block, it->second))
3176                         {
3177                             LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3178                                     head.ToString());
3179                             CValidationState dummy;
3180                             if (ProcessNewBlock(dummy, NULL, &block, &it->second))
3181                             {
3182                                 nLoaded++;
3183                                 queue.push_back(block.GetHash());
3184                             }
3185                         }
3186                         range.first++;
3187                         mapBlocksUnknownParent.erase(it);
3188                     }
3189                 }
3190             } catch (std::exception &e) {
3191                 LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what());
3192             }
3193         }
3194     } catch(std::runtime_error &e) {
3195         AbortNode(std::string("System error: ") + e.what());
3196     }
3197     if (nLoaded > 0)
3198         LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3199     return nLoaded > 0;
3200 }
3201 
3202 //////////////////////////////////////////////////////////////////////////////
3203 //
3204 // CAlert
3205 //
3206 
3207 string GetWarnings(string strFor)
3208 {
3209     int nPriority = 0;
3210     string strStatusBar;
3211     string strRPC;
3212 
3213     if (!CLIENT_VERSION_IS_RELEASE)
3214         strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3215 
3216     if (GetBoolArg("-testsafemode", false))
3217         strStatusBar = strRPC = "testsafemode enabled";
3218 
3219     // Misc warnings like out of disk space and clock is wrong
3220     if (strMiscWarning != "")
3221     {
3222         nPriority = 1000;
3223         strStatusBar = strMiscWarning;
3224     }
3225 
3226     if (fLargeWorkForkFound)
3227     {
3228         nPriority = 2000;
3229         strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3230     }
3231     else if (fLargeWorkInvalidChainFound)
3232     {
3233         nPriority = 2000;
3234         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.");
3235     }
3236 
3237     // Alerts
3238     {
3239         LOCK(cs_mapAlerts);
3240         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3241         {
3242             const CAlert& alert = item.second;
3243             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3244             {
3245                 nPriority = alert.nPriority;
3246                 strStatusBar = alert.strStatusBar;
3247             }
3248         }
3249     }
3250 
3251     if (strFor == "statusbar")
3252         return strStatusBar;
3253     else if (strFor == "rpc")
3254         return strRPC;
3255     assert(!"GetWarnings() : invalid parameter");
3256     return "error";
3257 }
3258 
3259 
3260 
3261 
3262 
3263 
3264 
3265 
3266 //////////////////////////////////////////////////////////////////////////////
3267 //
3268 // Messages
3269 //
3270 
3271 
3272 bool static AlreadyHave(const CInv& inv)
3273 {
3274     switch (inv.type)
3275     {
3276     case MSG_TX:
3277         {
3278             bool txInMap = false;
3279             txInMap = mempool.exists(inv.hash);
3280             return txInMap || mapOrphanTransactions.count(inv.hash) ||
3281                 pcoinsTip->HaveCoins(inv.hash);
3282         }
3283     case MSG_BLOCK:
3284         return mapBlockIndex.count(inv.hash);
3285     }
3286     // Don't know what it is, just say we already got one
3287     return true;
3288 }
3289 
3290 
3291 void static ProcessGetData(CNode* pfrom)
3292 {
3293     std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3294 
3295     vector<CInv> vNotFound;
3296 
3297     LOCK(cs_main);
3298 
3299     while (it != pfrom->vRecvGetData.end()) {
3300         // Don't bother if send buffer is too full to respond anyway
3301         if (pfrom->nSendSize >= SendBufferSize())
3302             break;
3303 
3304         const CInv &inv = *it;
3305         {
3306             boost::this_thread::interruption_point();
3307             it++;
3308 
3309             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3310             {
3311                 bool send = false;
3312                 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3313                 if (mi != mapBlockIndex.end())
3314                 {
3315                     // If the requested block is at a height below our last
3316                     // checkpoint, only serve it if it's in the checkpointed chain
3317                     int nHeight = mi->second->nHeight;
3318                     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
3319                     if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
3320                         if (!chainActive.Contains(mi->second))
3321                         {
3322                             LogPrintf("ProcessGetData(): ignoring request for old block that isn't in the main chain\n");
3323                         } else {
3324                             send = true;
3325                         }
3326                     } else {
3327                         send = true;
3328                     }
3329                 }
3330                 if (send)
3331                 {
3332                     // Send block from disk
3333                     CBlock block;
3334                     if (!ReadBlockFromDisk(block, (*mi).second))
3335                         assert(!"cannot load block from disk");
3336                     if (inv.type == MSG_BLOCK)
3337                         pfrom->PushMessage("block", block);
3338                     else // MSG_FILTERED_BLOCK)
3339                     {
3340                         LOCK(pfrom->cs_filter);
3341                         if (pfrom->pfilter)
3342                         {
3343                             CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3344                             pfrom->PushMessage("merkleblock", merkleBlock);
3345                             // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3346                             // This avoids hurting performance by pointlessly requiring a round-trip
3347                             // Note that there is currently no way for a node to request any single transactions we didnt send here -
3348                             // they must either disconnect and retry or request the full block.
3349                             // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3350                             // however we MUST always provide at least what the remote peer needs
3351                             typedef std::pair<unsigned int, uint256> PairType;
3352                             BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3353                                 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3354                                     pfrom->PushMessage("tx", block.vtx[pair.first]);
3355                         }
3356                         // else
3357                             // no response
3358                     }
3359 
3360                     // Trigger them to send a getblocks request for the next batch of inventory
3361                     if (inv.hash == pfrom->hashContinue)
3362                     {
3363                         // Bypass PushInventory, this must send even if redundant,
3364                         // and we want it right after the last block so they don't
3365                         // wait for other stuff first.
3366                         vector<CInv> vInv;
3367                         vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3368                         pfrom->PushMessage("inv", vInv);
3369                         pfrom->hashContinue = 0;
3370                     }
3371                 }
3372             }
3373             else if (inv.IsKnownType())
3374             {
3375                 // Send stream from relay memory
3376                 bool pushed = false;
3377                 {
3378                     LOCK(cs_mapRelay);
3379                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3380                     if (mi != mapRelay.end()) {
3381                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3382                         pushed = true;
3383                     }
3384                 }
3385                 if (!pushed && inv.type == MSG_TX) {
3386                     CTransaction tx;
3387                     if (mempool.lookup(inv.hash, tx)) {
3388                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3389                         ss.reserve(1000);
3390                         ss << tx;
3391                         pfrom->PushMessage("tx", ss);
3392                         pushed = true;
3393                     }
3394                 }
3395                 if (!pushed) {
3396                     vNotFound.push_back(inv);
3397                 }
3398             }
3399 
3400             // Track requests for our stuff.
3401             g_signals.Inventory(inv.hash);
3402 
3403             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3404                 break;
3405         }
3406     }
3407 
3408     pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3409 
3410     if (!vNotFound.empty()) {
3411         // Let the peer know that we didn't find what it asked for, so it doesn't
3412         // have to wait around forever. Currently only SPV clients actually care
3413         // about this message: it's needed when they are recursively walking the
3414         // dependencies of relevant unconfirmed transactions. SPV clients want to
3415         // do that because they want to know about (and store and rebroadcast and
3416         // risk analyze) the dependencies of transactions relevant to them, without
3417         // having to download the entire memory pool.
3418         pfrom->PushMessage("notfound", vNotFound);
3419     }
3420 }
3421 
3422 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3423 {
3424     RandAddSeedPerfmon();
3425     LogPrint("net", "received: %s (%u bytes) peer=%d\n", strCommand, vRecv.size(), pfrom->id);
3426     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3427     {
3428         LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3429         return true;
3430     }
3431 
3432 
3433 
3434 
3435     if (strCommand == "version")
3436     {
3437         // Each connection can only send one version message
3438         if (pfrom->nVersion != 0)
3439         {
3440             pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3441             Misbehaving(pfrom->GetId(), 1);
3442             return false;
3443         }
3444 
3445         int64_t nTime;
3446         CAddress addrMe;
3447         CAddress addrFrom;
3448         uint64_t nNonce = 1;
3449         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3450         if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3451         {
3452             // disconnect from peers older than this proto version
3453             LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3454             pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3455                                strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3456             pfrom->fDisconnect = true;
3457             return false;
3458         }
3459 
3460         if (pfrom->nVersion == 10300)
3461             pfrom->nVersion = 300;
3462         if (!vRecv.empty())
3463             vRecv >> addrFrom >> nNonce;
3464         if (!vRecv.empty()) {
3465             vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3466             pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3467         }
3468         if (!vRecv.empty())
3469             vRecv >> pfrom->nStartingHeight;
3470         if (!vRecv.empty())
3471             vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3472         else
3473             pfrom->fRelayTxes = true;
3474 
3475         // Disconnect if we connected to ourself
3476         if (nNonce == nLocalHostNonce && nNonce > 1)
3477         {
3478             LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3479             pfrom->fDisconnect = true;
3480             return true;
3481         }
3482 
3483         pfrom->addrLocal = addrMe;
3484         if (pfrom->fInbound && addrMe.IsRoutable())
3485         {
3486             SeenLocal(addrMe);
3487         }
3488 
3489         // Be shy and don't send version until we hear
3490         if (pfrom->fInbound)
3491             pfrom->PushVersion();
3492 
3493         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3494 
3495         // Potentially mark this peer as a preferred download peer.
3496         UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3497 
3498         // Change version
3499         pfrom->PushMessage("verack");
3500         pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3501 
3502         if (!pfrom->fInbound)
3503         {
3504             // Advertise our address
3505             if (fListen && !IsInitialBlockDownload())
3506             {
3507                 CAddress addr = GetLocalAddress(&pfrom->addr);
3508                 if (addr.IsRoutable())
3509                 {
3510                     pfrom->PushAddress(addr);
3511                 } else if (IsPeerAddrLocalGood(pfrom)) {
3512                     addr.SetIP(pfrom->addrLocal);
3513                     pfrom->PushAddress(addr);
3514                 }
3515             }
3516 
3517             // Get recent addresses
3518             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3519             {
3520                 pfrom->PushMessage("getaddr");
3521                 pfrom->fGetAddr = true;
3522             }
3523             addrman.Good(pfrom->addr);
3524         } else {
3525             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3526             {
3527                 addrman.Add(addrFrom, addrFrom);
3528                 addrman.Good(addrFrom);
3529             }
3530         }
3531 
3532         // Relay alerts
3533         {
3534             LOCK(cs_mapAlerts);
3535             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3536                 item.second.RelayTo(pfrom);
3537         }
3538 
3539         pfrom->fSuccessfullyConnected = true;
3540 
3541         string remoteAddr;
3542         if (fLogIPs)
3543             remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
3544 
3545         LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
3546                   pfrom->cleanSubVer, pfrom->nVersion,
3547                   pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
3548                   remoteAddr);
3549 
3550         AddTimeData(pfrom->addr, nTime);
3551     }
3552 
3553 
3554     else if (pfrom->nVersion == 0)
3555     {
3556         // Must have a version message before anything else
3557         Misbehaving(pfrom->GetId(), 1);
3558         return false;
3559     }
3560 
3561 
3562     else if (strCommand == "verack")
3563     {
3564         pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3565     }
3566 
3567 
3568     else if (strCommand == "addr")
3569     {
3570         vector<CAddress> vAddr;
3571         vRecv >> vAddr;
3572 
3573         // Don't want addr from older versions unless seeding
3574         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3575             return true;
3576         if (vAddr.size() > 1000)
3577         {
3578             Misbehaving(pfrom->GetId(), 20);
3579             return error("message addr size() = %u", vAddr.size());
3580         }
3581 
3582         // Store the new addresses
3583         vector<CAddress> vAddrOk;
3584         int64_t nNow = GetAdjustedTime();
3585         int64_t nSince = nNow - 10 * 60;
3586         BOOST_FOREACH(CAddress& addr, vAddr)
3587         {
3588             boost::this_thread::interruption_point();
3589 
3590             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3591                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3592             pfrom->AddAddressKnown(addr);
3593             bool fReachable = IsReachable(addr);
3594             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3595             {
3596                 // Relay to a limited number of other nodes
3597                 {
3598                     LOCK(cs_vNodes);
3599                     // Use deterministic randomness to send to the same nodes for 24 hours
3600                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3601                     static uint256 hashSalt;
3602                     if (hashSalt == 0)
3603                         hashSalt = GetRandHash();
3604                     uint64_t hashAddr = addr.GetHash();
3605                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3606                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3607                     multimap<uint256, CNode*> mapMix;
3608                     BOOST_FOREACH(CNode* pnode, vNodes)
3609                     {
3610                         if (pnode->nVersion < CADDR_TIME_VERSION)
3611                             continue;
3612                         unsigned int nPointer;
3613                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3614                         uint256 hashKey = hashRand ^ nPointer;
3615                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3616                         mapMix.insert(make_pair(hashKey, pnode));
3617                     }
3618                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3619                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3620                         ((*mi).second)->PushAddress(addr);
3621                 }
3622             }
3623             // Do not store addresses outside our network
3624             if (fReachable)
3625                 vAddrOk.push_back(addr);
3626         }
3627         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3628         if (vAddr.size() < 1000)
3629             pfrom->fGetAddr = false;
3630         if (pfrom->fOneShot)
3631             pfrom->fDisconnect = true;
3632     }
3633 
3634 
3635     else if (strCommand == "inv")
3636     {
3637         vector<CInv> vInv;
3638         vRecv >> vInv;
3639         if (vInv.size() > MAX_INV_SZ)
3640         {
3641             Misbehaving(pfrom->GetId(), 20);
3642             return error("message inv size() = %u", vInv.size());
3643         }
3644 
3645         LOCK(cs_main);
3646 
3647         std::vector<CInv> vToFetch;
3648 
3649         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3650         {
3651             const CInv &inv = vInv[nInv];
3652 
3653             boost::this_thread::interruption_point();
3654             pfrom->AddInventoryKnown(inv);
3655 
3656             bool fAlreadyHave = AlreadyHave(inv);
3657             LogPrint("net", "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
3658 
3659             if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
3660                 pfrom->AskFor(inv);
3661 
3662             if (inv.type == MSG_BLOCK) {
3663                 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
3664                 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
3665                     // First request the headers preceeding the announced block. In the normal fully-synced
3666                     // case where a new block is announced that succeeds the current tip (no reorganization),
3667                     // there are no such headers.
3668                     // Secondly, and only when we are close to being synced, we request the announced block directly,
3669                     // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
3670                     // time the block arrives, the header chain leading up to it is already validated. Not
3671                     // doing this will result in the received block being rejected as an orphan in case it is
3672                     // not a direct successor.
3673                     pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
3674                     CNodeState *nodestate = State(pfrom->GetId());
3675                     if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - Params().TargetSpacing() * 20 &&
3676                         nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
3677                         vToFetch.push_back(inv);
3678                         // Mark block as in flight already, even though the actual "getdata" message only goes out
3679                         // later (within the same cs_main lock, though).
3680                         MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
3681                     }
3682                     LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
3683                 }
3684             }
3685 
3686             // Track requests for our stuff
3687             g_signals.Inventory(inv.hash);
3688 
3689             if (pfrom->nSendSize > (SendBufferSize() * 2)) {
3690                 Misbehaving(pfrom->GetId(), 50);
3691                 return error("send buffer size() = %u", pfrom->nSendSize);
3692             }
3693         }
3694 
3695         if (!vToFetch.empty())
3696             pfrom->PushMessage("getdata", vToFetch);
3697     }
3698 
3699 
3700     else if (strCommand == "getdata")
3701     {
3702         vector<CInv> vInv;
3703         vRecv >> vInv;
3704         if (vInv.size() > MAX_INV_SZ)
3705         {
3706             Misbehaving(pfrom->GetId(), 20);
3707             return error("message getdata size() = %u", vInv.size());
3708         }
3709 
3710         if (fDebug || (vInv.size() != 1))
3711             LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
3712 
3713         if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
3714             LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
3715 
3716         pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
3717         ProcessGetData(pfrom);
3718     }
3719 
3720 
3721     else if (strCommand == "getblocks")
3722     {
3723         CBlockLocator locator;
3724         uint256 hashStop;
3725         vRecv >> locator >> hashStop;
3726 
3727         LOCK(cs_main);
3728 
3729         // Find the last block the caller has in the main chain
3730         CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
3731 
3732         // Send the rest of the chain
3733         if (pindex)
3734             pindex = chainActive.Next(pindex);
3735         int nLimit = 500;
3736         LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop==uint256(0) ? "end" : hashStop.ToString(), nLimit, pfrom->id);
3737         for (; pindex; pindex = chainActive.Next(pindex))
3738         {
3739             if (pindex->GetBlockHash() == hashStop)
3740             {
3741                 LogPrint("net", "  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3742                 break;
3743             }
3744             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3745             if (--nLimit <= 0)
3746             {
3747                 // When this block is requested, we'll send an inv that'll make them
3748                 // getblocks the next batch of inventory.
3749                 LogPrint("net", "  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3750                 pfrom->hashContinue = pindex->GetBlockHash();
3751                 break;
3752             }
3753         }
3754     }
3755 
3756 
3757     else if (strCommand == "getheaders")
3758     {
3759         CBlockLocator locator;
3760         uint256 hashStop;
3761         vRecv >> locator >> hashStop;
3762 
3763         LOCK(cs_main);
3764 
3765         CBlockIndex* pindex = NULL;
3766         if (locator.IsNull())
3767         {
3768             // If locator is null, return the hashStop block
3769             BlockMap::iterator mi = mapBlockIndex.find(hashStop);
3770             if (mi == mapBlockIndex.end())
3771                 return true;
3772             pindex = (*mi).second;
3773         }
3774         else
3775         {
3776             // Find the last block the caller has in the main chain
3777             pindex = FindForkInGlobalIndex(chainActive, locator);
3778             if (pindex)
3779                 pindex = chainActive.Next(pindex);
3780         }
3781 
3782         // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
3783         vector<CBlock> vHeaders;
3784         int nLimit = MAX_HEADERS_RESULTS;
3785         LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
3786         for (; pindex; pindex = chainActive.Next(pindex))
3787         {
3788             vHeaders.push_back(pindex->GetBlockHeader());
3789             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3790                 break;
3791         }
3792         pfrom->PushMessage("headers", vHeaders);
3793     }
3794 
3795 
3796     else if (strCommand == "tx")
3797     {
3798         vector<uint256> vWorkQueue;
3799         vector<uint256> vEraseQueue;
3800         CTransaction tx;
3801         vRecv >> tx;
3802 
3803         CInv inv(MSG_TX, tx.GetHash());
3804         pfrom->AddInventoryKnown(inv);
3805 
3806         LOCK(cs_main);
3807 
3808         bool fMissingInputs = false;
3809         CValidationState state;
3810 
3811         mapAlreadyAskedFor.erase(inv);
3812 
3813         if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
3814         {
3815             mempool.check(pcoinsTip);
3816             RelayTransaction(tx);
3817             vWorkQueue.push_back(inv.hash);
3818             vEraseQueue.push_back(inv.hash);
3819 
3820             LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n",
3821                 pfrom->id, pfrom->cleanSubVer,
3822                 tx.GetHash().ToString(),
3823                 mempool.mapTx.size());
3824 
3825             // Recursively process any orphan transactions that depended on this one
3826             set<NodeId> setMisbehaving;
3827             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3828             {
3829                 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
3830                 if (itByPrev == mapOrphanTransactionsByPrev.end())
3831                     continue;
3832                 for (set<uint256>::iterator mi = itByPrev->second.begin();
3833                      mi != itByPrev->second.end();
3834                      ++mi)
3835                 {
3836                     const uint256& orphanHash = *mi;
3837                     const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
3838                     NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
3839                     bool fMissingInputs2 = false;
3840                     // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
3841                     // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
3842                     // anyone relaying LegitTxX banned)
3843                     CValidationState stateDummy;
3844 
3845                     vEraseQueue.push_back(orphanHash);
3846 
3847                     if (setMisbehaving.count(fromPeer))
3848                         continue;
3849                     if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
3850                     {
3851                         LogPrint("mempool", "   accepted orphan tx %s\n", orphanHash.ToString());
3852                         RelayTransaction(orphanTx);
3853                         vWorkQueue.push_back(orphanHash);
3854                     }
3855                     else if (!fMissingInputs2)
3856                     {
3857                         int nDos = 0;
3858                         if (stateDummy.IsInvalid(nDos) && nDos > 0)
3859                         {
3860                             // Punish peer that gave us an invalid orphan tx
3861                             Misbehaving(fromPeer, nDos);
3862                             setMisbehaving.insert(fromPeer);
3863                             LogPrint("mempool", "   invalid orphan tx %s\n", orphanHash.ToString());
3864                         }
3865                         // too-little-fee orphan
3866                         LogPrint("mempool", "   removed orphan tx %s\n", orphanHash.ToString());
3867                     }
3868                     mempool.check(pcoinsTip);
3869                 }
3870             }
3871 
3872             BOOST_FOREACH(uint256 hash, vEraseQueue)
3873                 EraseOrphanTx(hash);
3874         }
3875         else if (fMissingInputs)
3876         {
3877             AddOrphanTx(tx, pfrom->GetId());
3878 
3879             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3880             unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
3881             unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
3882             if (nEvicted > 0)
3883                 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
3884         } else if (pfrom->fWhitelisted) {
3885             // Always relay transactions received from whitelisted peers, even
3886             // if they are already in the mempool (allowing the node to function
3887             // as a gateway for nodes hidden behind it).
3888             RelayTransaction(tx);
3889         }
3890         int nDoS = 0;
3891         if (state.IsInvalid(nDoS))
3892         {
3893             LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
3894                 pfrom->id, pfrom->cleanSubVer,
3895                 state.GetRejectReason());
3896             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3897                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
3898             if (nDoS > 0)
3899                 Misbehaving(pfrom->GetId(), nDoS);
3900         }
3901     }
3902 
3903 
3904     else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
3905     {
3906         std::vector<CBlockHeader> headers;
3907 
3908         // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
3909         unsigned int nCount = ReadCompactSize(vRecv);
3910         if (nCount > MAX_HEADERS_RESULTS) {
3911             Misbehaving(pfrom->GetId(), 20);
3912             return error("headers message size = %u", nCount);
3913         }
3914         headers.resize(nCount);
3915         for (unsigned int n = 0; n < nCount; n++) {
3916             vRecv >> headers[n];
3917             ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
3918         }
3919 
3920         LOCK(cs_main);
3921 
3922         if (nCount == 0) {
3923             // Nothing interesting. Stop asking this peers for more headers.
3924             return true;
3925         }
3926 
3927         CBlockIndex *pindexLast = NULL;
3928         BOOST_FOREACH(const CBlockHeader& header, headers) {
3929             CValidationState state;
3930             if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
3931                 Misbehaving(pfrom->GetId(), 20);
3932                 return error("non-continuous headers sequence");
3933             }
3934             if (!AcceptBlockHeader(header, state, &pindexLast)) {
3935                 int nDoS;
3936                 if (state.IsInvalid(nDoS)) {
3937                     if (nDoS > 0)
3938                         Misbehaving(pfrom->GetId(), nDoS);
3939                     return error("invalid header received");
3940                 }
3941             }
3942         }
3943 
3944         if (pindexLast)
3945             UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
3946 
3947         if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
3948             // Headers message had its maximum size; the peer may have more headers.
3949             // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
3950             // from there instead.
3951             LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
3952             pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256(0));
3953         }
3954     }
3955 
3956     else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
3957     {
3958         CBlock block;
3959         vRecv >> block;
3960 
3961         CInv inv(MSG_BLOCK, block.GetHash());
3962         LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
3963 
3964         pfrom->AddInventoryKnown(inv);
3965 
3966         CValidationState state;
3967         ProcessNewBlock(state, pfrom, &block);
3968         int nDoS;
3969         if (state.IsInvalid(nDoS)) {
3970             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
3971                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
3972             if (nDoS > 0) {
3973                 LOCK(cs_main);
3974                 Misbehaving(pfrom->GetId(), nDoS);
3975             }
3976         }
3977 
3978     }
3979 
3980 
3981     else if (strCommand == "getaddr")
3982     {
3983         pfrom->vAddrToSend.clear();
3984         vector<CAddress> vAddr = addrman.GetAddr();
3985         BOOST_FOREACH(const CAddress &addr, vAddr)
3986             pfrom->PushAddress(addr);
3987     }
3988 
3989 
3990     else if (strCommand == "mempool")
3991     {
3992         LOCK2(cs_main, pfrom->cs_filter);
3993 
3994         std::vector<uint256> vtxid;
3995         mempool.queryHashes(vtxid);
3996         vector<CInv> vInv;
3997         BOOST_FOREACH(uint256& hash, vtxid) {
3998             CInv inv(MSG_TX, hash);
3999             CTransaction tx;
4000             bool fInMemPool = mempool.lookup(hash, tx);
4001             if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4002             if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4003                (!pfrom->pfilter))
4004                 vInv.push_back(inv);
4005             if (vInv.size() == MAX_INV_SZ) {
4006                 pfrom->PushMessage("inv", vInv);
4007                 vInv.clear();
4008             }
4009         }
4010         if (vInv.size() > 0)
4011             pfrom->PushMessage("inv", vInv);
4012     }
4013 
4014 
4015     else if (strCommand == "ping")
4016     {
4017         if (pfrom->nVersion > BIP0031_VERSION)
4018         {
4019             uint64_t nonce = 0;
4020             vRecv >> nonce;
4021             // Echo the message back with the nonce. This allows for two useful features:
4022             //
4023             // 1) A remote node can quickly check if the connection is operational
4024             // 2) Remote nodes can measure the latency of the network thread. If this node
4025             //    is overloaded it won't respond to pings quickly and the remote node can
4026             //    avoid sending us more work, like chain download requests.
4027             //
4028             // The nonce stops the remote getting confused between different pings: without
4029             // it, if the remote node sends a ping once per second and this node takes 5
4030             // seconds to respond to each, the 5th ping the remote sends would appear to
4031             // return very quickly.
4032             pfrom->PushMessage("pong", nonce);
4033         }
4034     }
4035 
4036 
4037     else if (strCommand == "pong")
4038     {
4039         int64_t pingUsecEnd = nTimeReceived;
4040         uint64_t nonce = 0;
4041         size_t nAvail = vRecv.in_avail();
4042         bool bPingFinished = false;
4043         std::string sProblem;
4044 
4045         if (nAvail >= sizeof(nonce)) {
4046             vRecv >> nonce;
4047 
4048             // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4049             if (pfrom->nPingNonceSent != 0) {
4050                 if (nonce == pfrom->nPingNonceSent) {
4051                     // Matching pong received, this ping is no longer outstanding
4052                     bPingFinished = true;
4053                     int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4054                     if (pingUsecTime > 0) {
4055                         // Successful ping time measurement, replace previous
4056                         pfrom->nPingUsecTime = pingUsecTime;
4057                     } else {
4058                         // This should never happen
4059                         sProblem = "Timing mishap";
4060                     }
4061                 } else {
4062                     // Nonce mismatches are normal when pings are overlapping
4063                     sProblem = "Nonce mismatch";
4064                     if (nonce == 0) {
4065                         // This is most likely a bug in another implementation somewhere, cancel this ping
4066                         bPingFinished = true;
4067                         sProblem = "Nonce zero";
4068                     }
4069                 }
4070             } else {
4071                 sProblem = "Unsolicited pong without ping";
4072             }
4073         } else {
4074             // This is most likely a bug in another implementation somewhere, cancel this ping
4075             bPingFinished = true;
4076             sProblem = "Short payload";
4077         }
4078 
4079         if (!(sProblem.empty())) {
4080             LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4081                 pfrom->id,
4082                 pfrom->cleanSubVer,
4083                 sProblem,
4084                 pfrom->nPingNonceSent,
4085                 nonce,
4086                 nAvail);
4087         }
4088         if (bPingFinished) {
4089             pfrom->nPingNonceSent = 0;
4090         }
4091     }
4092 
4093 
4094     else if (strCommand == "alert")
4095     {
4096         CAlert alert;
4097         vRecv >> alert;
4098 
4099         uint256 alertHash = alert.GetHash();
4100         if (pfrom->setKnown.count(alertHash) == 0)
4101         {
4102             if (alert.ProcessAlert())
4103             {
4104                 // Relay
4105                 pfrom->setKnown.insert(alertHash);
4106                 {
4107                     LOCK(cs_vNodes);
4108                     BOOST_FOREACH(CNode* pnode, vNodes)
4109                         alert.RelayTo(pnode);
4110                 }
4111             }
4112             else {
4113                 // Small DoS penalty so peers that send us lots of
4114                 // duplicate/expired/invalid-signature/whatever alerts
4115                 // eventually get banned.
4116                 // This isn't a Misbehaving(100) (immediate ban) because the
4117                 // peer might be an older or different implementation with
4118                 // a different signature key, etc.
4119                 Misbehaving(pfrom->GetId(), 10);
4120             }
4121         }
4122     }
4123 
4124 
4125     else if (strCommand == "filterload")
4126     {
4127         CBloomFilter filter;
4128         vRecv >> filter;
4129 
4130         if (!filter.IsWithinSizeConstraints())
4131             // There is no excuse for sending a too-large filter
4132             Misbehaving(pfrom->GetId(), 100);
4133         else
4134         {
4135             LOCK(pfrom->cs_filter);
4136             delete pfrom->pfilter;
4137             pfrom->pfilter = new CBloomFilter(filter);
4138             pfrom->pfilter->UpdateEmptyFull();
4139         }
4140         pfrom->fRelayTxes = true;
4141     }
4142 
4143 
4144     else if (strCommand == "filteradd")
4145     {
4146         vector<unsigned char> vData;
4147         vRecv >> vData;
4148 
4149         // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4150         // and thus, the maximum size any matched object can have) in a filteradd message
4151         if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4152         {
4153             Misbehaving(pfrom->GetId(), 100);
4154         } else {
4155             LOCK(pfrom->cs_filter);
4156             if (pfrom->pfilter)
4157                 pfrom->pfilter->insert(vData);
4158             else
4159                 Misbehaving(pfrom->GetId(), 100);
4160         }
4161     }
4162 
4163 
4164     else if (strCommand == "filterclear")
4165     {
4166         LOCK(pfrom->cs_filter);
4167         delete pfrom->pfilter;
4168         pfrom->pfilter = new CBloomFilter();
4169         pfrom->fRelayTxes = true;
4170     }
4171 
4172 
4173     else if (strCommand == "reject")
4174     {
4175         if (fDebug) {
4176             try {
4177                 string strMsg; unsigned char ccode; string strReason;
4178                 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4179 
4180                 ostringstream ss;
4181                 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4182 
4183                 if (strMsg == "block" || strMsg == "tx")
4184                 {
4185                     uint256 hash;
4186                     vRecv >> hash;
4187                     ss << ": hash " << hash.ToString();
4188                 }
4189                 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4190             } catch (std::ios_base::failure& e) {
4191                 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4192                 LogPrint("net", "Unparseable reject message received\n");
4193             }
4194         }
4195     }
4196 
4197     else
4198     {
4199         // Ignore unknown commands for extensibility
4200         LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4201     }
4202 
4203 
4204     // Update the last seen time for this node's address
4205     if (pfrom->fNetworkNode)
4206         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
4207             AddressCurrentlyConnected(pfrom->addr);
4208 
4209 
4210     return true;
4211 }
4212 
4213 // requires LOCK(cs_vRecvMsg)
4214 bool ProcessMessages(CNode* pfrom)
4215 {
4216     //if (fDebug)
4217     //    LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
4218 
4219     //
4220     // Message format
4221     //  (4) message start
4222     //  (12) command
4223     //  (4) size
4224     //  (4) checksum
4225     //  (x) data
4226     //
4227     bool fOk = true;
4228 
4229     if (!pfrom->vRecvGetData.empty())
4230         ProcessGetData(pfrom);
4231 
4232     // this maintains the order of responses
4233     if (!pfrom->vRecvGetData.empty()) return fOk;
4234 
4235     std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4236     while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4237         // Don't bother if send buffer is too full to respond anyway
4238         if (pfrom->nSendSize >= SendBufferSize())
4239             break;
4240 
4241         // get next message
4242         CNetMessage& msg = *it;
4243 
4244         //if (fDebug)
4245         //    LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
4246         //            msg.hdr.nMessageSize, msg.vRecv.size(),
4247         //            msg.complete() ? "Y" : "N");
4248 
4249         // end, if an incomplete message is found
4250         if (!msg.complete())
4251             break;
4252 
4253         // at this point, any failure means we can delete the current message
4254         it++;
4255 
4256         // Scan for message start
4257         if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4258             LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", msg.hdr.GetCommand(), pfrom->id);
4259             fOk = false;
4260             break;
4261         }
4262 
4263         // Read header
4264         CMessageHeader& hdr = msg.hdr;
4265         if (!hdr.IsValid())
4266         {
4267             LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", hdr.GetCommand(), pfrom->id);
4268             continue;
4269         }
4270         string strCommand = hdr.GetCommand();
4271 
4272         // Message size
4273         unsigned int nMessageSize = hdr.nMessageSize;
4274 
4275         // Checksum
4276         CDataStream& vRecv = msg.vRecv;
4277         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4278         unsigned int nChecksum = 0;
4279         memcpy(&nChecksum, &hash, sizeof(nChecksum));
4280         if (nChecksum != hdr.nChecksum)
4281         {
4282             LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4283                strCommand, nMessageSize, nChecksum, hdr.nChecksum);
4284             continue;
4285         }
4286 
4287         // Process message
4288         bool fRet = false;
4289         try
4290         {
4291             fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4292             boost::this_thread::interruption_point();
4293         }
4294         catch (std::ios_base::failure& e)
4295         {
4296             pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4297             if (strstr(e.what(), "end of data"))
4298             {
4299                 // Allow exceptions from under-length message on vRecv
4300                 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
4301             }
4302             else if (strstr(e.what(), "size too large"))
4303             {
4304                 // Allow exceptions from over-long size
4305                 LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
4306             }
4307             else
4308             {
4309                 PrintExceptionContinue(&e, "ProcessMessages()");
4310             }
4311         }
4312         catch (boost::thread_interrupted) {
4313             throw;
4314         }
4315         catch (std::exception& e) {
4316             PrintExceptionContinue(&e, "ProcessMessages()");
4317         } catch (...) {
4318             PrintExceptionContinue(NULL, "ProcessMessages()");
4319         }
4320 
4321         if (!fRet)
4322             LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", strCommand, nMessageSize, pfrom->id);
4323 
4324         break;
4325     }
4326 
4327     // In case the connection got shut down, its receive buffer was wiped
4328     if (!pfrom->fDisconnect)
4329         pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4330 
4331     return fOk;
4332 }
4333 
4334 
4335 bool SendMessages(CNode* pto, bool fSendTrickle)
4336 {
4337     {
4338         // Don't send anything until we get their version message
4339         if (pto->nVersion == 0)
4340             return true;
4341 
4342         //
4343         // Message: ping
4344         //
4345         bool pingSend = false;
4346         if (pto->fPingQueued) {
4347             // RPC ping request by user
4348             pingSend = true;
4349         }
4350         if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4351             // Ping automatically sent as a latency probe & keepalive.
4352             pingSend = true;
4353         }
4354         if (pingSend) {
4355             uint64_t nonce = 0;
4356             while (nonce == 0) {
4357                 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4358             }
4359             pto->fPingQueued = false;
4360             pto->nPingUsecStart = GetTimeMicros();
4361             if (pto->nVersion > BIP0031_VERSION) {
4362                 pto->nPingNonceSent = nonce;
4363                 pto->PushMessage("ping", nonce);
4364             } else {
4365                 // Peer is too old to support ping command with nonce, pong will never arrive.
4366                 pto->nPingNonceSent = 0;
4367                 pto->PushMessage("ping");
4368             }
4369         }
4370 
4371         TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4372         if (!lockMain)
4373             return true;
4374 
4375         // Address refresh broadcast
4376         static int64_t nLastRebroadcast;
4377         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4378         {
4379             LOCK(cs_vNodes);
4380             BOOST_FOREACH(CNode* pnode, vNodes)
4381             {
4382                 // Periodically clear setAddrKnown to allow refresh broadcasts
4383                 if (nLastRebroadcast)
4384                     pnode->setAddrKnown.clear();
4385 
4386                 // Rebroadcast our address
4387                 AdvertizeLocal(pnode);
4388             }
4389             if (!vNodes.empty())
4390                 nLastRebroadcast = GetTime();
4391         }
4392 
4393         //
4394         // Message: addr
4395         //
4396         if (fSendTrickle)
4397         {
4398             vector<CAddress> vAddr;
4399             vAddr.reserve(pto->vAddrToSend.size());
4400             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4401             {
4402                 // returns true if wasn't already contained in the set
4403                 if (pto->setAddrKnown.insert(addr).second)
4404                 {
4405                     vAddr.push_back(addr);
4406                     // receiver rejects addr messages larger than 1000
4407                     if (vAddr.size() >= 1000)
4408                     {
4409                         pto->PushMessage("addr", vAddr);
4410                         vAddr.clear();
4411                     }
4412                 }
4413             }
4414             pto->vAddrToSend.clear();
4415             if (!vAddr.empty())
4416                 pto->PushMessage("addr", vAddr);
4417         }
4418 
4419         CNodeState &state = *State(pto->GetId());
4420         if (state.fShouldBan) {
4421             if (pto->fWhitelisted)
4422                 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4423             else {
4424                 pto->fDisconnect = true;
4425                 if (pto->addr.IsLocal())
4426                     LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4427                 else
4428                 {
4429                     CNode::Ban(pto->addr);
4430                 }
4431             }
4432             state.fShouldBan = false;
4433         }
4434 
4435         BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4436             pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4437         state.rejects.clear();
4438 
4439         // Start block sync
4440         if (pindexBestHeader == NULL)
4441             pindexBestHeader = chainActive.Tip();
4442         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.
4443         if (!state.fSyncStarted && !pto->fClient && fFetch && !fImporting && !fReindex) {
4444             // Only actively request headers from a single peer, unless we're close to today.
4445             if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4446                 state.fSyncStarted = true;
4447                 nSyncStarted++;
4448                 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4449                 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4450                 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256(0));
4451             }
4452         }
4453 
4454         // Resend wallet transactions that haven't gotten in a block yet
4455         // Except during reindex, importing and IBD, when old wallet
4456         // transactions become unconfirmed and spams other nodes.
4457         if (!fReindex && !fImporting && !IsInitialBlockDownload())
4458         {
4459             g_signals.Broadcast();
4460         }
4461 
4462         //
4463         // Message: inventory
4464         //
4465         vector<CInv> vInv;
4466         vector<CInv> vInvWait;
4467         {
4468             LOCK(pto->cs_inventory);
4469             vInv.reserve(pto->vInventoryToSend.size());
4470             vInvWait.reserve(pto->vInventoryToSend.size());
4471             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4472             {
4473                 if (pto->setInventoryKnown.count(inv))
4474                     continue;
4475 
4476                 // trickle out tx inv to protect privacy
4477                 if (inv.type == MSG_TX && !fSendTrickle)
4478                 {
4479                     // 1/4 of tx invs blast to all immediately
4480                     static uint256 hashSalt;
4481                     if (hashSalt == 0)
4482                         hashSalt = GetRandHash();
4483                     uint256 hashRand = inv.hash ^ hashSalt;
4484                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4485                     bool fTrickleWait = ((hashRand & 3) != 0);
4486 
4487                     if (fTrickleWait)
4488                     {
4489                         vInvWait.push_back(inv);
4490                         continue;
4491                     }
4492                 }
4493 
4494                 // returns true if wasn't already contained in the set
4495                 if (pto->setInventoryKnown.insert(inv).second)
4496                 {
4497                     vInv.push_back(inv);
4498                     if (vInv.size() >= 1000)
4499                     {
4500                         pto->PushMessage("inv", vInv);
4501                         vInv.clear();
4502                     }
4503                 }
4504             }
4505             pto->vInventoryToSend = vInvWait;
4506         }
4507         if (!vInv.empty())
4508             pto->PushMessage("inv", vInv);
4509 
4510         // Detect whether we're stalling
4511         int64_t nNow = GetTimeMicros();
4512         if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
4513             // Stalling only triggers when the block download window cannot move. During normal steady state,
4514             // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
4515             // should only happen during initial block download.
4516             LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
4517             pto->fDisconnect = true;
4518         }
4519         // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
4520         // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
4521         // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
4522         // being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
4523         // to unreasonably increase our timeout.
4524         if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
4525             LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
4526             pto->fDisconnect = true;
4527         }
4528 
4529         //
4530         // Message: getdata (blocks)
4531         //
4532         vector<CInv> vGetData;
4533         if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4534             vector<CBlockIndex*> vToDownload;
4535             NodeId staller = -1;
4536             FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
4537             BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
4538                 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4539                 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
4540                 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
4541                     pindex->nHeight, pto->id);
4542             }
4543             if (state.nBlocksInFlight == 0 && staller != -1) {
4544                 if (State(staller)->nStallingSince == 0) {
4545                     State(staller)->nStallingSince = nNow;
4546                     LogPrint("net", "Stall started peer=%d\n", staller);
4547                 }
4548             }
4549         }
4550 
4551         //
4552         // Message: getdata (non-blocks)
4553         //
4554         while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4555         {
4556             const CInv& inv = (*pto->mapAskFor.begin()).second;
4557             if (!AlreadyHave(inv))
4558             {
4559                 if (fDebug)
4560                     LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
4561                 vGetData.push_back(inv);
4562                 if (vGetData.size() >= 1000)
4563                 {
4564                     pto->PushMessage("getdata", vGetData);
4565                     vGetData.clear();
4566                 }
4567             }
4568             pto->mapAskFor.erase(pto->mapAskFor.begin());
4569         }
4570         if (!vGetData.empty())
4571             pto->PushMessage("getdata", vGetData);
4572 
4573     }
4574     return true;
4575 }
4576 
4577 
4578 bool CBlockUndo::WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
4579 {
4580     // Open history file to append
4581     CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
4582     if (fileout.IsNull())
4583         return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
4584 
4585     // Write index header
4586     unsigned int nSize = fileout.GetSerializeSize(*this);
4587     fileout << FLATDATA(Params().MessageStart()) << nSize;
4588 
4589     // Write undo data
4590     long fileOutPos = ftell(fileout.Get());
4591     if (fileOutPos < 0)
4592         return error("CBlockUndo::WriteToDisk : ftell failed");
4593     pos.nPos = (unsigned int)fileOutPos;
4594     fileout << *this;
4595 
4596     // calculate & write checksum
4597     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
4598     hasher << hashBlock;
4599     hasher << *this;
4600     fileout << hasher.GetHash();
4601 
4602     return true;
4603 }
4604 
4605 bool CBlockUndo::ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
4606 {
4607     // Open history file to read
4608     CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
4609     if (filein.IsNull())
4610         return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
4611 
4612     // Read block
4613     uint256 hashChecksum;
4614     try {
4615         filein >> *this;
4616         filein >> hashChecksum;
4617     }
4618     catch (std::exception &e) {
4619         return error("%s : Deserialize or I/O error - %s", __func__, e.what());
4620     }
4621 
4622     // Verify checksum
4623     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
4624     hasher << hashBlock;
4625     hasher << *this;
4626     if (hashChecksum != hasher.GetHash())
4627         return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
4628 
4629     return true;
4630 }
4631 
4632  std::string CBlockFileInfo::ToString() const {
4633      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));
4634  }
4635 
4636 
4637 
4638 class CMainCleanup
4639 {
4640 public:
4641     CMainCleanup() {}
4642     ~CMainCleanup() {
4643         // block headers
4644         BlockMap::iterator it1 = mapBlockIndex.begin();
4645         for (; it1 != mapBlockIndex.end(); it1++)
4646             delete (*it1).second;
4647         mapBlockIndex.clear();
4648 
4649         // orphan transactions
4650         mapOrphanTransactions.clear();
4651         mapOrphanTransactionsByPrev.clear();
4652     }
4653 } instance_of_cmaincleanup;