]> Git Repo - VerusCoin.git/blob - src/main.cpp
Chainparams: Explicit CMessageHeader::MessageStartChars to functions in main:
[VerusCoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "main.h"
7
8 #include "addrman.h"
9 #include "alert.h"
10 #include "arith_uint256.h"
11 #include "chainparams.h"
12 #include "checkpoints.h"
13 #include "checkqueue.h"
14 #include "consensus/validation.h"
15 #include "init.h"
16 #include "merkleblock.h"
17 #include "net.h"
18 #include "pow.h"
19 #include "txdb.h"
20 #include "txmempool.h"
21 #include "ui_interface.h"
22 #include "undo.h"
23 #include "util.h"
24 #include "utilmoneystr.h"
25 #include "validationinterface.h"
26
27 #include <sstream>
28
29 #include <boost/algorithm/string/replace.hpp>
30 #include <boost/filesystem.hpp>
31 #include <boost/filesystem/fstream.hpp>
32 #include <boost/math/distributions/poisson.hpp>
33 #include <boost/thread.hpp>
34
35 using namespace std;
36
37 #if defined(NDEBUG)
38 # error "Bitcoin cannot be compiled without assertions."
39 #endif
40
41 /**
42  * Global state
43  */
44
45 CCriticalSection cs_main;
46
47 BlockMap mapBlockIndex;
48 CChain chainActive;
49 CBlockIndex *pindexBestHeader = NULL;
50 int64_t nTimeBestReceived = 0;
51 CWaitableCriticalSection csBestBlock;
52 CConditionVariable cvBlockChange;
53 int nScriptCheckThreads = 0;
54 bool fImporting = false;
55 bool fReindex = false;
56 bool fTxIndex = false;
57 bool fHavePruned = false;
58 bool fPruneMode = false;
59 bool fIsBareMultisigStd = true;
60 bool fCheckBlockIndex = false;
61 bool fCheckpointsEnabled = true;
62 size_t nCoinCacheUsage = 5000 * 300;
63 uint64_t nPruneTarget = 0;
64
65 /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
66 CFeeRate minRelayTxFee = CFeeRate(1000);
67
68 CTxMemPool mempool(::minRelayTxFee);
69
70 struct COrphanTx {
71     CTransaction tx;
72     NodeId fromPeer;
73 };
74 map<uint256, COrphanTx> mapOrphanTransactions;
75 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
76 void EraseOrphansFor(NodeId peer);
77
78 /**
79  * Returns true if there are nRequired or more blocks of minVersion or above
80  * in the last Consensus::Params::nMajorityWindow blocks, starting at pstart and going backwards.
81  */
82 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams);
83 static void CheckBlockIndex();
84
85 /** Constant stuff for coinbase transactions we create: */
86 CScript COINBASE_FLAGS;
87
88 const string strMessageMagic = "Bitcoin Signed Message:\n";
89
90 // Internal stuff
91 namespace {
92
93     struct CBlockIndexWorkComparator
94     {
95         bool operator()(CBlockIndex *pa, CBlockIndex *pb) const {
96             // First sort by most total work, ...
97             if (pa->nChainWork > pb->nChainWork) return false;
98             if (pa->nChainWork < pb->nChainWork) return true;
99
100             // ... then by earliest time received, ...
101             if (pa->nSequenceId < pb->nSequenceId) return false;
102             if (pa->nSequenceId > pb->nSequenceId) return true;
103
104             // Use pointer address as tie breaker (should only happen with blocks
105             // loaded from disk, as those all have id 0).
106             if (pa < pb) return false;
107             if (pa > pb) return true;
108
109             // Identical blocks.
110             return false;
111         }
112     };
113
114     CBlockIndex *pindexBestInvalid;
115
116     /**
117      * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
118      * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
119      * missing the data for the block.
120      */
121     set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
122     /** Number of nodes with fSyncStarted. */
123     int nSyncStarted = 0;
124     /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions.
125       * Pruned nodes may have entries where B is missing data.
126       */
127     multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
128
129     CCriticalSection cs_LastBlockFile;
130     std::vector<CBlockFileInfo> vinfoBlockFile;
131     int nLastBlockFile = 0;
132     /** Global flag to indicate we should check to see if there are
133      *  block/undo files that should be deleted.  Set on startup
134      *  or if we allocate more file space when we're in prune mode
135      */
136     bool fCheckForPruning = false;
137
138     /**
139      * Every received block is assigned a unique and increasing identifier, so we
140      * know which one to give priority in case of a fork.
141      */
142     CCriticalSection cs_nBlockSequenceId;
143     /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
144     uint32_t nBlockSequenceId = 1;
145
146     /**
147      * Sources of received blocks, saved to be able to send them reject
148      * messages or ban them when processing happens afterwards. Protected by
149      * cs_main.
150      */
151     map<uint256, NodeId> mapBlockSource;
152
153     /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
154     struct QueuedBlock {
155         uint256 hash;
156         CBlockIndex *pindex;  //! Optional.
157         int64_t nTime;  //! Time of "getdata" request in microseconds.
158         bool fValidatedHeaders;  //! Whether this block has validated headers at the time of request.
159         int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer)
160     };
161     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
162
163     /** Number of blocks in flight with validated headers. */
164     int nQueuedValidatedHeaders = 0;
165
166     /** Number of preferable block download peers. */
167     int nPreferredDownload = 0;
168
169     /** Dirty block index entries. */
170     set<CBlockIndex*> setDirtyBlockIndex;
171
172     /** Dirty block file entries. */
173     set<int> setDirtyFileInfo;
174 } // anon namespace
175
176 //////////////////////////////////////////////////////////////////////////////
177 //
178 // Registration of network node signals.
179 //
180
181 namespace {
182
183 struct CBlockReject {
184     unsigned char chRejectCode;
185     string strRejectReason;
186     uint256 hashBlock;
187 };
188
189 /**
190  * Maintain validation-specific state about nodes, protected by cs_main, instead
191  * by CNode's own locks. This simplifies asynchronous operation, where
192  * processing of incoming data is done after the ProcessMessage call returns,
193  * and we're no longer holding the node's locks.
194  */
195 struct CNodeState {
196     //! The peer's address
197     CService address;
198     //! Whether we have a fully established connection.
199     bool fCurrentlyConnected;
200     //! Accumulated misbehaviour score for this peer.
201     int nMisbehavior;
202     //! Whether this peer should be disconnected and banned (unless whitelisted).
203     bool fShouldBan;
204     //! String name of this peer (debugging/logging purposes).
205     std::string name;
206     //! List of asynchronously-determined block rejections to notify this peer about.
207     std::vector<CBlockReject> rejects;
208     //! The best known block we know this peer has announced.
209     CBlockIndex *pindexBestKnownBlock;
210     //! The hash of the last unknown block this peer has announced.
211     uint256 hashLastUnknownBlock;
212     //! The last full block we both have.
213     CBlockIndex *pindexLastCommonBlock;
214     //! Whether we've started headers synchronization with this peer.
215     bool fSyncStarted;
216     //! Since when we're stalling block download progress (in microseconds), or 0.
217     int64_t nStallingSince;
218     list<QueuedBlock> vBlocksInFlight;
219     int nBlocksInFlight;
220     int nBlocksInFlightValidHeaders;
221     //! Whether we consider this a preferred download peer.
222     bool fPreferredDownload;
223
224     CNodeState() {
225         fCurrentlyConnected = false;
226         nMisbehavior = 0;
227         fShouldBan = false;
228         pindexBestKnownBlock = NULL;
229         hashLastUnknownBlock.SetNull();
230         pindexLastCommonBlock = NULL;
231         fSyncStarted = false;
232         nStallingSince = 0;
233         nBlocksInFlight = 0;
234         nBlocksInFlightValidHeaders = 0;
235         fPreferredDownload = false;
236     }
237 };
238
239 /** Map maintaining per-node state. Requires cs_main. */
240 map<NodeId, CNodeState> mapNodeState;
241
242 // Requires cs_main.
243 CNodeState *State(NodeId pnode) {
244     map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
245     if (it == mapNodeState.end())
246         return NULL;
247     return &it->second;
248 }
249
250 int GetHeight()
251 {
252     LOCK(cs_main);
253     return chainActive.Height();
254 }
255
256 void UpdatePreferredDownload(CNode* node, CNodeState* state)
257 {
258     nPreferredDownload -= state->fPreferredDownload;
259
260     // Whether this node should be marked as a preferred download node.
261     state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
262
263     nPreferredDownload += state->fPreferredDownload;
264 }
265
266 // Returns time at which to timeout block request (nTime in microseconds)
267 int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore)
268 {
269     return nTime + 500000 * Params().GetConsensus().nPowTargetSpacing * (4 + nValidatedQueuedBefore);
270 }
271
272 void InitializeNode(NodeId nodeid, const CNode *pnode) {
273     LOCK(cs_main);
274     CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
275     state.name = pnode->addrName;
276     state.address = pnode->addr;
277 }
278
279 void FinalizeNode(NodeId nodeid) {
280     LOCK(cs_main);
281     CNodeState *state = State(nodeid);
282
283     if (state->fSyncStarted)
284         nSyncStarted--;
285
286     if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
287         AddressCurrentlyConnected(state->address);
288     }
289
290     BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
291         mapBlocksInFlight.erase(entry.hash);
292     EraseOrphansFor(nodeid);
293     nPreferredDownload -= state->fPreferredDownload;
294
295     mapNodeState.erase(nodeid);
296 }
297
298 // Requires cs_main.
299 void MarkBlockAsReceived(const uint256& hash) {
300     map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
301     if (itInFlight != mapBlocksInFlight.end()) {
302         CNodeState *state = State(itInFlight->second.first);
303         nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
304         state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
305         state->vBlocksInFlight.erase(itInFlight->second.second);
306         state->nBlocksInFlight--;
307         state->nStallingSince = 0;
308         mapBlocksInFlight.erase(itInFlight);
309     }
310 }
311
312 // Requires cs_main.
313 void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
314     CNodeState *state = State(nodeid);
315     assert(state != NULL);
316
317     // Make sure it's not listed somewhere already.
318     MarkBlockAsReceived(hash);
319
320     int64_t nNow = GetTimeMicros();
321     QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders)};
322     nQueuedValidatedHeaders += newentry.fValidatedHeaders;
323     list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
324     state->nBlocksInFlight++;
325     state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders;
326     mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
327 }
328
329 /** Check whether the last unknown block a peer advertized is not yet known. */
330 void ProcessBlockAvailability(NodeId nodeid) {
331     CNodeState *state = State(nodeid);
332     assert(state != NULL);
333
334     if (!state->hashLastUnknownBlock.IsNull()) {
335         BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
336         if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
337             if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
338                 state->pindexBestKnownBlock = itOld->second;
339             state->hashLastUnknownBlock.SetNull();
340         }
341     }
342 }
343
344 /** Update tracking information about which blocks a peer is assumed to have. */
345 void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
346     CNodeState *state = State(nodeid);
347     assert(state != NULL);
348
349     ProcessBlockAvailability(nodeid);
350
351     BlockMap::iterator it = mapBlockIndex.find(hash);
352     if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
353         // An actually better block was announced.
354         if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
355             state->pindexBestKnownBlock = it->second;
356     } else {
357         // An unknown block was announced; just assume that the latest one is the best one.
358         state->hashLastUnknownBlock = hash;
359     }
360 }
361
362 /** Find the last common ancestor two blocks have.
363  *  Both pa and pb must be non-NULL. */
364 CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
365     if (pa->nHeight > pb->nHeight) {
366         pa = pa->GetAncestor(pb->nHeight);
367     } else if (pb->nHeight > pa->nHeight) {
368         pb = pb->GetAncestor(pa->nHeight);
369     }
370
371     while (pa != pb && pa && pb) {
372         pa = pa->pprev;
373         pb = pb->pprev;
374     }
375
376     // Eventually all chain branches meet at the genesis block.
377     assert(pa == pb);
378     return pa;
379 }
380
381 /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
382  *  at most count entries. */
383 void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
384     if (count == 0)
385         return;
386
387     vBlocks.reserve(vBlocks.size() + count);
388     CNodeState *state = State(nodeid);
389     assert(state != NULL);
390
391     // Make sure pindexBestKnownBlock is up to date, we'll need it.
392     ProcessBlockAvailability(nodeid);
393
394     if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
395         // This peer has nothing interesting.
396         return;
397     }
398
399     if (state->pindexLastCommonBlock == NULL) {
400         // Bootstrap quickly by guessing a parent of our best tip is the forking point.
401         // Guessing wrong in either direction is not a problem.
402         state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
403     }
404
405     // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
406     // of its current tip anymore. Go back enough to fix that.
407     state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
408     if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
409         return;
410
411     std::vector<CBlockIndex*> vToFetch;
412     CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
413     // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
414     // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
415     // download that next block if the window were 1 larger.
416     int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
417     int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
418     NodeId waitingfor = -1;
419     while (pindexWalk->nHeight < nMaxHeight) {
420         // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
421         // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
422         // as iterating over ~100 CBlockIndex* entries anyway.
423         int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
424         vToFetch.resize(nToFetch);
425         pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
426         vToFetch[nToFetch - 1] = pindexWalk;
427         for (unsigned int i = nToFetch - 1; i > 0; i--) {
428             vToFetch[i - 1] = vToFetch[i]->pprev;
429         }
430
431         // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
432         // are not yet downloaded and not in flight to vBlocks. In the mean time, update
433         // pindexLastCommonBlock as long as all ancestors are already downloaded.
434         BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
435             if (!pindex->IsValid(BLOCK_VALID_TREE)) {
436                 // We consider the chain that this peer is on invalid.
437                 return;
438             }
439             if (pindex->nStatus & BLOCK_HAVE_DATA) {
440                 if (pindex->nChainTx)
441                     state->pindexLastCommonBlock = pindex;
442             } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
443                 // The block is not already downloaded, and not yet in flight.
444                 if (pindex->nHeight > nWindowEnd) {
445                     // We reached the end of the window.
446                     if (vBlocks.size() == 0 && waitingfor != nodeid) {
447                         // We aren't able to fetch anything, but we would be if the download window was one larger.
448                         nodeStaller = waitingfor;
449                     }
450                     return;
451                 }
452                 vBlocks.push_back(pindex);
453                 if (vBlocks.size() == count) {
454                     return;
455                 }
456             } else if (waitingfor == -1) {
457                 // This is the first already-in-flight block.
458                 waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
459             }
460         }
461     }
462 }
463
464 } // anon namespace
465
466 bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
467     LOCK(cs_main);
468     CNodeState *state = State(nodeid);
469     if (state == NULL)
470         return false;
471     stats.nMisbehavior = state->nMisbehavior;
472     stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
473     stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
474     BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
475         if (queue.pindex)
476             stats.vHeightInFlight.push_back(queue.pindex->nHeight);
477     }
478     return true;
479 }
480
481 void RegisterNodeSignals(CNodeSignals& nodeSignals)
482 {
483     nodeSignals.GetHeight.connect(&GetHeight);
484     nodeSignals.ProcessMessages.connect(&ProcessMessages);
485     nodeSignals.SendMessages.connect(&SendMessages);
486     nodeSignals.InitializeNode.connect(&InitializeNode);
487     nodeSignals.FinalizeNode.connect(&FinalizeNode);
488 }
489
490 void UnregisterNodeSignals(CNodeSignals& nodeSignals)
491 {
492     nodeSignals.GetHeight.disconnect(&GetHeight);
493     nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
494     nodeSignals.SendMessages.disconnect(&SendMessages);
495     nodeSignals.InitializeNode.disconnect(&InitializeNode);
496     nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
497 }
498
499 CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
500 {
501     // Find the first block the caller has in the main chain
502     BOOST_FOREACH(const uint256& hash, locator.vHave) {
503         BlockMap::iterator mi = mapBlockIndex.find(hash);
504         if (mi != mapBlockIndex.end())
505         {
506             CBlockIndex* pindex = (*mi).second;
507             if (chain.Contains(pindex))
508                 return pindex;
509         }
510     }
511     return chain.Genesis();
512 }
513
514 CCoinsViewCache *pcoinsTip = NULL;
515 CBlockTreeDB *pblocktree = NULL;
516
517 //////////////////////////////////////////////////////////////////////////////
518 //
519 // mapOrphanTransactions
520 //
521
522 bool AddOrphanTx(const CTransaction& tx, NodeId peer)
523 {
524     uint256 hash = tx.GetHash();
525     if (mapOrphanTransactions.count(hash))
526         return false;
527
528     // Ignore big transactions, to avoid a
529     // send-big-orphans memory exhaustion attack. If a peer has a legitimate
530     // large transaction with a missing parent then we assume
531     // it will rebroadcast it later, after the parent transaction(s)
532     // have been mined or received.
533     // 10,000 orphans, each of which is at most 5,000 bytes big is
534     // at most 500 megabytes of orphans:
535     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
536     if (sz > 5000)
537     {
538         LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
539         return false;
540     }
541
542     mapOrphanTransactions[hash].tx = tx;
543     mapOrphanTransactions[hash].fromPeer = peer;
544     BOOST_FOREACH(const CTxIn& txin, tx.vin)
545         mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
546
547     LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
548              mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
549     return true;
550 }
551
552 void static EraseOrphanTx(uint256 hash)
553 {
554     map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
555     if (it == mapOrphanTransactions.end())
556         return;
557     BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
558     {
559         map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
560         if (itPrev == mapOrphanTransactionsByPrev.end())
561             continue;
562         itPrev->second.erase(hash);
563         if (itPrev->second.empty())
564             mapOrphanTransactionsByPrev.erase(itPrev);
565     }
566     mapOrphanTransactions.erase(it);
567 }
568
569 void EraseOrphansFor(NodeId peer)
570 {
571     int nErased = 0;
572     map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
573     while (iter != mapOrphanTransactions.end())
574     {
575         map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
576         if (maybeErase->second.fromPeer == peer)
577         {
578             EraseOrphanTx(maybeErase->second.tx.GetHash());
579             ++nErased;
580         }
581     }
582     if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
583 }
584
585
586 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
587 {
588     unsigned int nEvicted = 0;
589     while (mapOrphanTransactions.size() > nMaxOrphans)
590     {
591         // Evict a random orphan:
592         uint256 randomhash = GetRandHash();
593         map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
594         if (it == mapOrphanTransactions.end())
595             it = mapOrphanTransactions.begin();
596         EraseOrphanTx(it->first);
597         ++nEvicted;
598     }
599     return nEvicted;
600 }
601
602
603
604
605
606
607
608 bool IsStandardTx(const CTransaction& tx, string& reason)
609 {
610     if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
611         reason = "version";
612         return false;
613     }
614
615     // Extremely large transactions with lots of inputs can cost the network
616     // almost as much to process as they cost the sender in fees, because
617     // computing signature hashes is O(ninputs*txsize). Limiting transactions
618     // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
619     unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
620     if (sz >= MAX_STANDARD_TX_SIZE) {
621         reason = "tx-size";
622         return false;
623     }
624
625     BOOST_FOREACH(const CTxIn& txin, tx.vin)
626     {
627         // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
628         // keys. (remember the 520 byte limit on redeemScript size) That works
629         // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
630         // bytes of scriptSig, which we round off to 1650 bytes for some minor
631         // future-proofing. That's also enough to spend a 20-of-20
632         // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
633         // considered standard)
634         if (txin.scriptSig.size() > 1650) {
635             reason = "scriptsig-size";
636             return false;
637         }
638         if (!txin.scriptSig.IsPushOnly()) {
639             reason = "scriptsig-not-pushonly";
640             return false;
641         }
642     }
643
644     unsigned int nDataOut = 0;
645     txnouttype whichType;
646     BOOST_FOREACH(const CTxOut& txout, tx.vout) {
647         if (!::IsStandard(txout.scriptPubKey, whichType)) {
648             reason = "scriptpubkey";
649             return false;
650         }
651
652         if (whichType == TX_NULL_DATA)
653             nDataOut++;
654         else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
655             reason = "bare-multisig";
656             return false;
657         } else if (txout.IsDust(::minRelayTxFee)) {
658             reason = "dust";
659             return false;
660         }
661     }
662
663     // only one OP_RETURN txout is permitted
664     if (nDataOut > 1) {
665         reason = "multi-op-return";
666         return false;
667     }
668
669     return true;
670 }
671
672 bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
673 {
674     AssertLockHeld(cs_main);
675     // Time based nLockTime implemented in 0.1.6
676     if (tx.nLockTime == 0)
677         return true;
678     if (nBlockHeight == 0)
679         nBlockHeight = chainActive.Height();
680     if (nBlockTime == 0)
681         nBlockTime = GetAdjustedTime();
682     if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
683         return true;
684     BOOST_FOREACH(const CTxIn& txin, tx.vin)
685         if (!txin.IsFinal())
686             return false;
687     return true;
688 }
689
690 /**
691  * Check transaction inputs to mitigate two
692  * potential denial-of-service attacks:
693  * 
694  * 1. scriptSigs with extra data stuffed into them,
695  *    not consumed by scriptPubKey (or P2SH script)
696  * 2. P2SH scripts with a crazy number of expensive
697  *    CHECKSIG/CHECKMULTISIG operations
698  */
699 bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
700 {
701     if (tx.IsCoinBase())
702         return true; // Coinbases don't use vin normally
703
704     for (unsigned int i = 0; i < tx.vin.size(); i++)
705     {
706         const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
707
708         vector<vector<unsigned char> > vSolutions;
709         txnouttype whichType;
710         // get the scriptPubKey corresponding to this input:
711         const CScript& prevScript = prev.scriptPubKey;
712         if (!Solver(prevScript, whichType, vSolutions))
713             return false;
714         int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
715         if (nArgsExpected < 0)
716             return false;
717
718         // Transactions with extra stuff in their scriptSigs are
719         // non-standard. Note that this EvalScript() call will
720         // be quick, because if there are any operations
721         // beside "push data" in the scriptSig
722         // IsStandardTx() will have already returned false
723         // and this method isn't called.
724         vector<vector<unsigned char> > stack;
725         if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
726             return false;
727
728         if (whichType == TX_SCRIPTHASH)
729         {
730             if (stack.empty())
731                 return false;
732             CScript subscript(stack.back().begin(), stack.back().end());
733             vector<vector<unsigned char> > vSolutions2;
734             txnouttype whichType2;
735             if (Solver(subscript, whichType2, vSolutions2))
736             {
737                 int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
738                 if (tmpExpected < 0)
739                     return false;
740                 nArgsExpected += tmpExpected;
741             }
742             else
743             {
744                 // Any other Script with less than 15 sigops OK:
745                 unsigned int sigops = subscript.GetSigOpCount(true);
746                 // ... extra data left on the stack after execution is OK, too:
747                 return (sigops <= MAX_P2SH_SIGOPS);
748             }
749         }
750
751         if (stack.size() != (unsigned int)nArgsExpected)
752             return false;
753     }
754
755     return true;
756 }
757
758 unsigned int GetLegacySigOpCount(const CTransaction& tx)
759 {
760     unsigned int nSigOps = 0;
761     BOOST_FOREACH(const CTxIn& txin, tx.vin)
762     {
763         nSigOps += txin.scriptSig.GetSigOpCount(false);
764     }
765     BOOST_FOREACH(const CTxOut& txout, tx.vout)
766     {
767         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
768     }
769     return nSigOps;
770 }
771
772 unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
773 {
774     if (tx.IsCoinBase())
775         return 0;
776
777     unsigned int nSigOps = 0;
778     for (unsigned int i = 0; i < tx.vin.size(); i++)
779     {
780         const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
781         if (prevout.scriptPubKey.IsPayToScriptHash())
782             nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
783     }
784     return nSigOps;
785 }
786
787
788
789
790
791
792
793
794 bool CheckTransaction(const CTransaction& tx, CValidationState &state)
795 {
796     // Basic checks that don't depend on any context
797     if (tx.vin.empty())
798         return state.DoS(10, error("CheckTransaction(): vin empty"),
799                          REJECT_INVALID, "bad-txns-vin-empty");
800     if (tx.vout.empty())
801         return state.DoS(10, error("CheckTransaction(): vout empty"),
802                          REJECT_INVALID, "bad-txns-vout-empty");
803     // Size limits
804     if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
805         return state.DoS(100, error("CheckTransaction(): size limits failed"),
806                          REJECT_INVALID, "bad-txns-oversize");
807
808     // Check for negative or overflow output values
809     CAmount nValueOut = 0;
810     BOOST_FOREACH(const CTxOut& txout, tx.vout)
811     {
812         if (txout.nValue < 0)
813             return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
814                              REJECT_INVALID, "bad-txns-vout-negative");
815         if (txout.nValue > MAX_MONEY)
816             return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
817                              REJECT_INVALID, "bad-txns-vout-toolarge");
818         nValueOut += txout.nValue;
819         if (!MoneyRange(nValueOut))
820             return state.DoS(100, error("CheckTransaction(): txout total out of range"),
821                              REJECT_INVALID, "bad-txns-txouttotal-toolarge");
822     }
823
824     // Check for duplicate inputs
825     set<COutPoint> vInOutPoints;
826     BOOST_FOREACH(const CTxIn& txin, tx.vin)
827     {
828         if (vInOutPoints.count(txin.prevout))
829             return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
830                              REJECT_INVALID, "bad-txns-inputs-duplicate");
831         vInOutPoints.insert(txin.prevout);
832     }
833
834     if (tx.IsCoinBase())
835     {
836         if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
837             return state.DoS(100, error("CheckTransaction(): coinbase script size"),
838                              REJECT_INVALID, "bad-cb-length");
839     }
840     else
841     {
842         BOOST_FOREACH(const CTxIn& txin, tx.vin)
843             if (txin.prevout.IsNull())
844                 return state.DoS(10, error("CheckTransaction(): prevout is null"),
845                                  REJECT_INVALID, "bad-txns-prevout-null");
846     }
847
848     return true;
849 }
850
851 CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
852 {
853     {
854         LOCK(mempool.cs);
855         uint256 hash = tx.GetHash();
856         double dPriorityDelta = 0;
857         CAmount nFeeDelta = 0;
858         mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
859         if (dPriorityDelta > 0 || nFeeDelta > 0)
860             return 0;
861     }
862
863     CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
864
865     if (fAllowFree)
866     {
867         // There is a free transaction area in blocks created by most miners,
868         // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
869         //   to be considered to fall into this category. We don't want to encourage sending
870         //   multiple transactions instead of one big transaction to avoid fees.
871         if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
872             nMinFee = 0;
873     }
874
875     if (!MoneyRange(nMinFee))
876         nMinFee = MAX_MONEY;
877     return nMinFee;
878 }
879
880
881 bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
882                         bool* pfMissingInputs, bool fRejectAbsurdFee)
883 {
884     AssertLockHeld(cs_main);
885     if (pfMissingInputs)
886         *pfMissingInputs = false;
887
888     if (!CheckTransaction(tx, state))
889         return error("AcceptToMemoryPool: CheckTransaction failed");
890
891     // Coinbase is only valid in a block, not as a loose transaction
892     if (tx.IsCoinBase())
893         return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
894                          REJECT_INVALID, "coinbase");
895
896     // Rather not work on nonstandard transactions (unless -testnet/-regtest)
897     string reason;
898     if (Params().RequireStandard() && !IsStandardTx(tx, reason))
899         return state.DoS(0,
900                          error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
901                          REJECT_NONSTANDARD, reason);
902
903     // Only accept nLockTime-using transactions that can be mined in the next
904     // block; we don't want our mempool filled up with transactions that can't
905     // be mined yet.
906     //
907     // However, IsFinalTx() is confusing... Without arguments, it uses
908     // chainActive.Height() to evaluate nLockTime; when a block is accepted,
909     // chainActive.Height() is set to the value of nHeight in the block.
910     // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the
911     // height of the block *being* evaluated is what is used. Thus if we want
912     // to know if a transaction can be part of the *next* block, we need to
913     // call IsFinalTx() with one more than chainActive.Height().
914     //
915     // Timestamps on the other hand don't get any special treatment, because we
916     // can't know what timestamp the next block will have, and there aren't
917     // timestamp applications where it matters.
918     if (!IsFinalTx(tx, chainActive.Height() + 1))
919         return state.DoS(0,
920                          error("AcceptToMemoryPool: non-final"),
921                          REJECT_NONSTANDARD, "non-final");
922
923     // is it already in the memory pool?
924     uint256 hash = tx.GetHash();
925     if (pool.exists(hash))
926         return false;
927
928     // Check for conflicts with in-memory transactions
929     {
930     LOCK(pool.cs); // protect pool.mapNextTx
931     for (unsigned int i = 0; i < tx.vin.size(); i++)
932     {
933         COutPoint outpoint = tx.vin[i].prevout;
934         if (pool.mapNextTx.count(outpoint))
935         {
936             // Disable replacement feature for now
937             return false;
938         }
939     }
940     }
941
942     {
943         CCoinsView dummy;
944         CCoinsViewCache view(&dummy);
945
946         CAmount nValueIn = 0;
947         {
948         LOCK(pool.cs);
949         CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
950         view.SetBackend(viewMemPool);
951
952         // do we already have it?
953         if (view.HaveCoins(hash))
954             return false;
955
956         // do all inputs exist?
957         // Note that this does not check for the presence of actual outputs (see the next check for that),
958         // and only helps with filling in pfMissingInputs (to determine missing vs spent).
959         BOOST_FOREACH(const CTxIn txin, tx.vin) {
960             if (!view.HaveCoins(txin.prevout.hash)) {
961                 if (pfMissingInputs)
962                     *pfMissingInputs = true;
963                 return false;
964             }
965         }
966
967         // are the actual inputs available?
968         if (!view.HaveInputs(tx))
969             return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
970                                  REJECT_DUPLICATE, "bad-txns-inputs-spent");
971
972         // Bring the best block into scope
973         view.GetBestBlock();
974
975         nValueIn = view.GetValueIn(tx);
976
977         // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
978         view.SetBackend(dummy);
979         }
980
981         // Check for non-standard pay-to-script-hash in inputs
982         if (Params().RequireStandard() && !AreInputsStandard(tx, view))
983             return error("AcceptToMemoryPool: nonstandard transaction input");
984
985         // Check that the transaction doesn't have an excessive number of
986         // sigops, making it impossible to mine. Since the coinbase transaction
987         // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
988         // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
989         // merely non-standard transaction.
990         unsigned int nSigOps = GetLegacySigOpCount(tx);
991         nSigOps += GetP2SHSigOpCount(tx, view);
992         if (nSigOps > MAX_STANDARD_TX_SIGOPS)
993             return state.DoS(0,
994                              error("AcceptToMemoryPool: too many sigops %s, %d > %d",
995                                    hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
996                              REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
997
998         CAmount nValueOut = tx.GetValueOut();
999         CAmount nFees = nValueIn-nValueOut;
1000         double dPriority = view.GetPriority(tx, chainActive.Height());
1001
1002         CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx));
1003         unsigned int nSize = entry.GetTxSize();
1004
1005         // Don't accept it if it can't get into a block
1006         CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
1007         if (fLimitFree && nFees < txMinFee)
1008             return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
1009                                       hash.ToString(), nFees, txMinFee),
1010                              REJECT_INSUFFICIENTFEE, "insufficient fee");
1011
1012         // Require that free transactions have sufficient priority to be mined in the next block.
1013         if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
1014             return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
1015         }
1016
1017         // Continuously rate-limit free (really, very-low-fee) transactions
1018         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
1019         // be annoying or make others' transactions take longer to confirm.
1020         if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
1021         {
1022             static CCriticalSection csFreeLimiter;
1023             static double dFreeCount;
1024             static int64_t nLastTime;
1025             int64_t nNow = GetTime();
1026
1027             LOCK(csFreeLimiter);
1028
1029             // Use an exponentially decaying ~10-minute window:
1030             dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
1031             nLastTime = nNow;
1032             // -limitfreerelay unit is thousand-bytes-per-minute
1033             // At default rate it would take over a month to fill 1GB
1034             if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
1035                 return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
1036                                  REJECT_INSUFFICIENTFEE, "rate limited free transaction");
1037             LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
1038             dFreeCount += nSize;
1039         }
1040
1041         if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
1042             return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
1043                          hash.ToString(),
1044                          nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
1045
1046         // Check against previous transactions
1047         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
1048         if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
1049         {
1050             return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
1051         }
1052
1053         // Check again against just the consensus-critical mandatory script
1054         // verification flags, in case of bugs in the standard flags that cause
1055         // transactions to pass as valid when they're actually invalid. For
1056         // instance the STRICTENC flag was incorrectly allowing certain
1057         // CHECKSIG NOT scripts to pass, even though they were invalid.
1058         //
1059         // There is a similar check in CreateNewBlock() to prevent creating
1060         // invalid blocks, however allowing such transactions into the mempool
1061         // can be exploited as a DoS attack.
1062         if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
1063         {
1064             return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
1065         }
1066
1067         // Store transaction in memory
1068         pool.addUnchecked(hash, entry, !IsInitialBlockDownload());
1069     }
1070
1071     SyncWithWallets(tx, NULL);
1072
1073     return true;
1074 }
1075
1076 /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
1077 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
1078 {
1079     CBlockIndex *pindexSlow = NULL;
1080     {
1081         LOCK(cs_main);
1082         {
1083             if (mempool.lookup(hash, txOut))
1084             {
1085                 return true;
1086             }
1087         }
1088
1089         if (fTxIndex) {
1090             CDiskTxPos postx;
1091             if (pblocktree->ReadTxIndex(hash, postx)) {
1092                 CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
1093                 if (file.IsNull())
1094                     return error("%s: OpenBlockFile failed", __func__);
1095                 CBlockHeader header;
1096                 try {
1097                     file >> header;
1098                     fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
1099                     file >> txOut;
1100                 } catch (const std::exception& e) {
1101                     return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1102                 }
1103                 hashBlock = header.GetHash();
1104                 if (txOut.GetHash() != hash)
1105                     return error("%s: txid mismatch", __func__);
1106                 return true;
1107             }
1108         }
1109
1110         if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
1111             int nHeight = -1;
1112             {
1113                 CCoinsViewCache &view = *pcoinsTip;
1114                 const CCoins* coins = view.AccessCoins(hash);
1115                 if (coins)
1116                     nHeight = coins->nHeight;
1117             }
1118             if (nHeight > 0)
1119                 pindexSlow = chainActive[nHeight];
1120         }
1121     }
1122
1123     if (pindexSlow) {
1124         CBlock block;
1125         if (ReadBlockFromDisk(block, pindexSlow)) {
1126             BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1127                 if (tx.GetHash() == hash) {
1128                     txOut = tx;
1129                     hashBlock = pindexSlow->GetBlockHash();
1130                     return true;
1131                 }
1132             }
1133         }
1134     }
1135
1136     return false;
1137 }
1138
1139
1140
1141
1142
1143
1144 //////////////////////////////////////////////////////////////////////////////
1145 //
1146 // CBlock and CBlockIndex
1147 //
1148
1149 bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
1150 {
1151     // Open history file to append
1152     CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1153     if (fileout.IsNull())
1154         return error("WriteBlockToDisk: OpenBlockFile failed");
1155
1156     // Write index header
1157     unsigned int nSize = fileout.GetSerializeSize(block);
1158     fileout << FLATDATA(messageStart) << nSize;
1159
1160     // Write block
1161     long fileOutPos = ftell(fileout.Get());
1162     if (fileOutPos < 0)
1163         return error("WriteBlockToDisk: ftell failed");
1164     pos.nPos = (unsigned int)fileOutPos;
1165     fileout << block;
1166
1167     return true;
1168 }
1169
1170 bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
1171 {
1172     block.SetNull();
1173
1174     // Open history file to read
1175     CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1176     if (filein.IsNull())
1177         return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
1178
1179     // Read block
1180     try {
1181         filein >> block;
1182     }
1183     catch (const std::exception& e) {
1184         return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
1185     }
1186
1187     // Check the header
1188     if (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
1189         return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
1190
1191     return true;
1192 }
1193
1194 bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
1195 {
1196     if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
1197         return false;
1198     if (block.GetHash() != pindex->GetBlockHash())
1199         return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
1200                 pindex->ToString(), pindex->GetBlockPos().ToString());
1201     return true;
1202 }
1203
1204 CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
1205 {
1206     int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
1207     // Force block reward to zero when right shift is undefined.
1208     if (halvings >= 64)
1209         return 0;
1210
1211     CAmount nSubsidy = 50 * COIN;
1212     // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
1213     nSubsidy >>= halvings;
1214     return nSubsidy;
1215 }
1216
1217 bool IsInitialBlockDownload()
1218 {
1219     const CChainParams& chainParams = Params();
1220     LOCK(cs_main);
1221     if (fImporting || fReindex)
1222         return true;
1223     if (fCheckpointsEnabled && chainActive.Height() < Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints()))
1224         return true;
1225     static bool lockIBDState = false;
1226     if (lockIBDState)
1227         return false;
1228     bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
1229             pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
1230     if (!state)
1231         lockIBDState = true;
1232     return state;
1233 }
1234
1235 bool fLargeWorkForkFound = false;
1236 bool fLargeWorkInvalidChainFound = false;
1237 CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
1238
1239 void CheckForkWarningConditions()
1240 {
1241     AssertLockHeld(cs_main);
1242     // Before we get past initial download, we cannot reliably alert about forks
1243     // (we assume we don't get stuck on a fork before the last checkpoint)
1244     if (IsInitialBlockDownload())
1245         return;
1246
1247     // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
1248     // of our head, drop it
1249     if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
1250         pindexBestForkTip = NULL;
1251
1252     if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
1253     {
1254         if (!fLargeWorkForkFound && pindexBestForkBase)
1255         {
1256             std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
1257                 pindexBestForkBase->phashBlock->ToString() + std::string("'");
1258             CAlert::Notify(warning, true);
1259         }
1260         if (pindexBestForkTip && pindexBestForkBase)
1261         {
1262             LogPrintf("%s: Warning: Large valid fork found\n  forking the chain at height %d (%s)\n  lasting to height %d (%s).\nChain state database corruption likely.\n", __func__,
1263                    pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
1264                    pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
1265             fLargeWorkForkFound = true;
1266         }
1267         else
1268         {
1269             LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
1270             fLargeWorkInvalidChainFound = true;
1271         }
1272     }
1273     else
1274     {
1275         fLargeWorkForkFound = false;
1276         fLargeWorkInvalidChainFound = false;
1277     }
1278 }
1279
1280 void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
1281 {
1282     AssertLockHeld(cs_main);
1283     // If we are on a fork that is sufficiently large, set a warning flag
1284     CBlockIndex* pfork = pindexNewForkTip;
1285     CBlockIndex* plonger = chainActive.Tip();
1286     while (pfork && pfork != plonger)
1287     {
1288         while (plonger && plonger->nHeight > pfork->nHeight)
1289             plonger = plonger->pprev;
1290         if (pfork == plonger)
1291             break;
1292         pfork = pfork->pprev;
1293     }
1294
1295     // We define a condition where we should warn the user about as a fork of at least 7 blocks
1296     // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
1297     // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
1298     // hash rate operating on the fork.
1299     // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
1300     // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
1301     // the 7-block condition and from this always have the most-likely-to-cause-warning fork
1302     if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
1303             pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
1304             chainActive.Height() - pindexNewForkTip->nHeight < 72)
1305     {
1306         pindexBestForkTip = pindexNewForkTip;
1307         pindexBestForkBase = pfork;
1308     }
1309
1310     CheckForkWarningConditions();
1311 }
1312
1313 // Requires cs_main.
1314 void Misbehaving(NodeId pnode, int howmuch)
1315 {
1316     if (howmuch == 0)
1317         return;
1318
1319     CNodeState *state = State(pnode);
1320     if (state == NULL)
1321         return;
1322
1323     state->nMisbehavior += howmuch;
1324     int banscore = GetArg("-banscore", 100);
1325     if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
1326     {
1327         LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1328         state->fShouldBan = true;
1329     } else
1330         LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
1331 }
1332
1333 void static InvalidChainFound(CBlockIndex* pindexNew)
1334 {
1335     if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
1336         pindexBestInvalid = pindexNew;
1337
1338     LogPrintf("%s: invalid block=%s  height=%d  log2_work=%.8g  date=%s\n", __func__,
1339       pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
1340       log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
1341       pindexNew->GetBlockTime()));
1342     LogPrintf("%s:  current best=%s  height=%d  log2_work=%.8g  date=%s\n", __func__,
1343       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
1344       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
1345     CheckForkWarningConditions();
1346 }
1347
1348 void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
1349     int nDoS = 0;
1350     if (state.IsInvalid(nDoS)) {
1351         std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
1352         if (it != mapBlockSource.end() && State(it->second)) {
1353             CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
1354             State(it->second)->rejects.push_back(reject);
1355             if (nDoS > 0)
1356                 Misbehaving(it->second, nDoS);
1357         }
1358     }
1359     if (!state.CorruptionPossible()) {
1360         pindex->nStatus |= BLOCK_FAILED_VALID;
1361         setDirtyBlockIndex.insert(pindex);
1362         setBlockIndexCandidates.erase(pindex);
1363         InvalidChainFound(pindex);
1364     }
1365 }
1366
1367 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
1368 {
1369     // mark inputs spent
1370     if (!tx.IsCoinBase()) {
1371         txundo.vprevout.reserve(tx.vin.size());
1372         BOOST_FOREACH(const CTxIn &txin, tx.vin) {
1373             CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
1374             unsigned nPos = txin.prevout.n;
1375
1376             if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
1377                 assert(false);
1378             // mark an outpoint spent, and construct undo information
1379             txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
1380             coins->Spend(nPos);
1381             if (coins->vout.size() == 0) {
1382                 CTxInUndo& undo = txundo.vprevout.back();
1383                 undo.nHeight = coins->nHeight;
1384                 undo.fCoinBase = coins->fCoinBase;
1385                 undo.nVersion = coins->nVersion;
1386             }
1387         }
1388     }
1389
1390     // add outputs
1391     inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
1392 }
1393
1394 void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
1395 {
1396     CTxUndo txundo;
1397     UpdateCoins(tx, state, inputs, txundo, nHeight);
1398 }
1399
1400 bool CScriptCheck::operator()() {
1401     const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1402     if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
1403         return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
1404     }
1405     return true;
1406 }
1407
1408 bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
1409 {
1410     if (!tx.IsCoinBase())
1411     {
1412         if (pvChecks)
1413             pvChecks->reserve(tx.vin.size());
1414
1415         // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1416         // for an attacker to attempt to split the network.
1417         if (!inputs.HaveInputs(tx))
1418             return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
1419
1420         // While checking, GetBestBlock() refers to the parent block.
1421         // This is also true for mempool checks.
1422         CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
1423         int nSpendHeight = pindexPrev->nHeight + 1;
1424         CAmount nValueIn = 0;
1425         CAmount nFees = 0;
1426         for (unsigned int i = 0; i < tx.vin.size(); i++)
1427         {
1428             const COutPoint &prevout = tx.vin[i].prevout;
1429             const CCoins *coins = inputs.AccessCoins(prevout.hash);
1430             assert(coins);
1431
1432             // If prev is coinbase, check that it's matured
1433             if (coins->IsCoinBase()) {
1434                 if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
1435                     return state.Invalid(
1436                         error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
1437                         REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
1438             }
1439
1440             // Check for negative or overflow input values
1441             nValueIn += coins->vout[prevout.n].nValue;
1442             if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1443                 return state.DoS(100, error("CheckInputs(): txin values out of range"),
1444                                  REJECT_INVALID, "bad-txns-inputvalues-outofrange");
1445
1446         }
1447
1448         if (nValueIn < tx.GetValueOut())
1449             return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
1450                                         tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
1451                              REJECT_INVALID, "bad-txns-in-belowout");
1452
1453         // Tally transaction fees
1454         CAmount nTxFee = nValueIn - tx.GetValueOut();
1455         if (nTxFee < 0)
1456             return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
1457                              REJECT_INVALID, "bad-txns-fee-negative");
1458         nFees += nTxFee;
1459         if (!MoneyRange(nFees))
1460             return state.DoS(100, error("CheckInputs(): nFees out of range"),
1461                              REJECT_INVALID, "bad-txns-fee-outofrange");
1462
1463         // The first loop above does all the inexpensive checks.
1464         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1465         // Helps prevent CPU exhaustion attacks.
1466
1467         // Skip ECDSA signature verification when connecting blocks
1468         // before the last block chain checkpoint. This is safe because block merkle hashes are
1469         // still computed and checked, and any change will be caught at the next checkpoint.
1470         if (fScriptChecks) {
1471             for (unsigned int i = 0; i < tx.vin.size(); i++) {
1472                 const COutPoint &prevout = tx.vin[i].prevout;
1473                 const CCoins* coins = inputs.AccessCoins(prevout.hash);
1474                 assert(coins);
1475
1476                 // Verify signature
1477                 CScriptCheck check(*coins, tx, i, flags, cacheStore);
1478                 if (pvChecks) {
1479                     pvChecks->push_back(CScriptCheck());
1480                     check.swap(pvChecks->back());
1481                 } else if (!check()) {
1482                     if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
1483                         // Check whether the failure was caused by a
1484                         // non-mandatory script verification check, such as
1485                         // non-standard DER encodings or non-null dummy
1486                         // arguments; if so, don't trigger DoS protection to
1487                         // avoid splitting the network between upgraded and
1488                         // non-upgraded nodes.
1489                         CScriptCheck check(*coins, tx, i,
1490                                 flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
1491                         if (check())
1492                             return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
1493                     }
1494                     // Failures of other flags indicate a transaction that is
1495                     // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
1496                     // such nodes as they are not following the protocol. That
1497                     // said during an upgrade careful thought should be taken
1498                     // as to the correct behavior - we may want to continue
1499                     // peering with non-upgraded nodes even after a soft-fork
1500                     // super-majority vote has passed.
1501                     return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
1502                 }
1503             }
1504         }
1505     }
1506
1507     return true;
1508 }
1509
1510 namespace {
1511
1512 bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
1513 {
1514     // Open history file to append
1515     CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
1516     if (fileout.IsNull())
1517         return error("%s: OpenUndoFile failed", __func__);
1518
1519     // Write index header
1520     unsigned int nSize = fileout.GetSerializeSize(blockundo);
1521     fileout << FLATDATA(messageStart) << nSize;
1522
1523     // Write undo data
1524     long fileOutPos = ftell(fileout.Get());
1525     if (fileOutPos < 0)
1526         return error("%s: ftell failed", __func__);
1527     pos.nPos = (unsigned int)fileOutPos;
1528     fileout << blockundo;
1529
1530     // calculate & write checksum
1531     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1532     hasher << hashBlock;
1533     hasher << blockundo;
1534     fileout << hasher.GetHash();
1535
1536     return true;
1537 }
1538
1539 bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
1540 {
1541     // Open history file to read
1542     CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
1543     if (filein.IsNull())
1544         return error("%s: OpenBlockFile failed", __func__);
1545
1546     // Read block
1547     uint256 hashChecksum;
1548     try {
1549         filein >> blockundo;
1550         filein >> hashChecksum;
1551     }
1552     catch (const std::exception& e) {
1553         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1554     }
1555
1556     // Verify checksum
1557     CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
1558     hasher << hashBlock;
1559     hasher << blockundo;
1560     if (hashChecksum != hasher.GetHash())
1561         return error("%s: Checksum mismatch", __func__);
1562
1563     return true;
1564 }
1565
1566 /** Abort with a message */
1567 bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
1568 {
1569     strMiscWarning = strMessage;
1570     LogPrintf("*** %s\n", strMessage);
1571     uiInterface.ThreadSafeMessageBox(
1572         userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
1573         "", CClientUIInterface::MSG_ERROR);
1574     StartShutdown();
1575     return false;
1576 }
1577
1578 bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
1579 {
1580     AbortNode(strMessage, userMessage);
1581     return state.Error(strMessage);
1582 }
1583
1584 } // anon namespace
1585
1586 /**
1587  * Apply the undo operation of a CTxInUndo to the given chain state.
1588  * @param undo The undo object.
1589  * @param view The coins view to which to apply the changes.
1590  * @param out The out point that corresponds to the tx input.
1591  * @return True on success.
1592  */
1593 static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
1594 {
1595     bool fClean = true;
1596
1597     CCoinsModifier coins = view.ModifyCoins(out.hash);
1598     if (undo.nHeight != 0) {
1599         // undo data contains height: this is the last output of the prevout tx being spent
1600         if (!coins->IsPruned())
1601             fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
1602         coins->Clear();
1603         coins->fCoinBase = undo.fCoinBase;
1604         coins->nHeight = undo.nHeight;
1605         coins->nVersion = undo.nVersion;
1606     } else {
1607         if (coins->IsPruned())
1608             fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
1609     }
1610     if (coins->IsAvailable(out.n))
1611         fClean = fClean && error("%s: undo data overwriting existing output", __func__);
1612     if (coins->vout.size() < out.n+1)
1613         coins->vout.resize(out.n+1);
1614     coins->vout[out.n] = undo.txout;
1615
1616     return fClean;
1617 }
1618
1619 bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
1620 {
1621     assert(pindex->GetBlockHash() == view.GetBestBlock());
1622
1623     if (pfClean)
1624         *pfClean = false;
1625
1626     bool fClean = true;
1627
1628     CBlockUndo blockUndo;
1629     CDiskBlockPos pos = pindex->GetUndoPos();
1630     if (pos.IsNull())
1631         return error("DisconnectBlock(): no undo data available");
1632     if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
1633         return error("DisconnectBlock(): failure reading undo data");
1634
1635     if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
1636         return error("DisconnectBlock(): block and undo data inconsistent");
1637
1638     // undo transactions in reverse order
1639     for (int i = block.vtx.size() - 1; i >= 0; i--) {
1640         const CTransaction &tx = block.vtx[i];
1641         uint256 hash = tx.GetHash();
1642
1643         // Check that all outputs are available and match the outputs in the block itself
1644         // exactly.
1645         {
1646         CCoinsModifier outs = view.ModifyCoins(hash);
1647         outs->ClearUnspendable();
1648
1649         CCoins outsBlock(tx, pindex->nHeight);
1650         // The CCoins serialization does not serialize negative numbers.
1651         // No network rules currently depend on the version here, so an inconsistency is harmless
1652         // but it must be corrected before txout nversion ever influences a network rule.
1653         if (outsBlock.nVersion < 0)
1654             outs->nVersion = outsBlock.nVersion;
1655         if (*outs != outsBlock)
1656             fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
1657
1658         // remove outputs
1659         outs->Clear();
1660         }
1661
1662         // restore inputs
1663         if (i > 0) { // not coinbases
1664             const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1665             if (txundo.vprevout.size() != tx.vin.size())
1666                 return error("DisconnectBlock(): transaction and undo data inconsistent");
1667             for (unsigned int j = tx.vin.size(); j-- > 0;) {
1668                 const COutPoint &out = tx.vin[j].prevout;
1669                 const CTxInUndo &undo = txundo.vprevout[j];
1670                 if (!ApplyTxInUndo(undo, view, out))
1671                     fClean = false;
1672             }
1673         }
1674     }
1675
1676     // move best block pointer to prevout block
1677     view.SetBestBlock(pindex->pprev->GetBlockHash());
1678
1679     if (pfClean) {
1680         *pfClean = fClean;
1681         return true;
1682     }
1683
1684     return fClean;
1685 }
1686
1687 void static FlushBlockFile(bool fFinalize = false)
1688 {
1689     LOCK(cs_LastBlockFile);
1690
1691     CDiskBlockPos posOld(nLastBlockFile, 0);
1692
1693     FILE *fileOld = OpenBlockFile(posOld);
1694     if (fileOld) {
1695         if (fFinalize)
1696             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
1697         FileCommit(fileOld);
1698         fclose(fileOld);
1699     }
1700
1701     fileOld = OpenUndoFile(posOld);
1702     if (fileOld) {
1703         if (fFinalize)
1704             TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
1705         FileCommit(fileOld);
1706         fclose(fileOld);
1707     }
1708 }
1709
1710 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1711
1712 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1713
1714 void ThreadScriptCheck() {
1715     RenameThread("bitcoin-scriptch");
1716     scriptcheckqueue.Thread();
1717 }
1718
1719 //
1720 // Called periodically asynchronously; alerts if it smells like
1721 // we're being fed a bad chain (blocks being generated much
1722 // too slowly or too quickly).
1723 //
1724 void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const CChain& chain, int64_t nPowTargetSpacing)
1725 {
1726     if (initialDownloadCheck()) return;
1727
1728     static int64_t lastAlertTime = 0;
1729     int64_t now = GetAdjustedTime();
1730     if (lastAlertTime > now-60*60*24) return; // Alert at most once per day
1731
1732     const int SPAN_HOURS=4;
1733     const int SPAN_SECONDS=SPAN_HOURS*60*60;
1734     int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing;
1735
1736     boost::math::poisson_distribution<double> poisson(BLOCKS_EXPECTED);
1737
1738     std::string strWarning;
1739     int64_t startTime = GetAdjustedTime()-SPAN_SECONDS;
1740
1741     LOCK(cs);
1742     int h = chain.Height();
1743     while (h > 0 && chain[h]->GetBlockTime() >= startTime)
1744         --h;
1745     int nBlocks = chain.Height()-h;
1746
1747     // How likely is it to find that many by chance?
1748     double p = boost::math::pdf(poisson, nBlocks);
1749
1750     LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS);
1751     LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p);
1752
1753     // Aim for one false-positive about every fifty years of normal running:
1754     const int FIFTY_YEARS = 50*365*24*60*60;
1755     double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS);
1756
1757     if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED)
1758     {
1759         // Many fewer blocks than expected: alert!
1760         strWarning = strprintf(_("WARNING: check your network connection, %d blocks received in the last %d hours (%d expected)"),
1761                                nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1762     }
1763     else if (p <= alertThreshold && nBlocks > BLOCKS_EXPECTED)
1764     {
1765         // Many more blocks than expected: alert!
1766         strWarning = strprintf(_("WARNING: abnormally high number of blocks generated, %d blocks received in the last %d hours (%d expected)"),
1767                                nBlocks, SPAN_HOURS, BLOCKS_EXPECTED);
1768     }
1769     if (!strWarning.empty())
1770     {
1771         strMiscWarning = strWarning;
1772         CAlert::Notify(strWarning, true);
1773         lastAlertTime = now;
1774     }
1775 }
1776
1777 static int64_t nTimeVerify = 0;
1778 static int64_t nTimeConnect = 0;
1779 static int64_t nTimeIndex = 0;
1780 static int64_t nTimeCallbacks = 0;
1781 static int64_t nTimeTotal = 0;
1782
1783 bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
1784 {
1785     const CChainParams& chainparams = Params();
1786     AssertLockHeld(cs_main);
1787     // Check it again in case a previous version let a bad block in
1788     if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
1789         return false;
1790
1791     // verify that the view's current state corresponds to the previous block
1792     uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
1793     assert(hashPrevBlock == view.GetBestBlock());
1794
1795     // Special case for the genesis block, skipping connection of its transactions
1796     // (its coinbase is unspendable)
1797     if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
1798         if (!fJustCheck)
1799             view.SetBestBlock(pindex->GetBlockHash());
1800         return true;
1801     }
1802
1803     bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints()));
1804
1805     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1806     // unless those are already completely spent.
1807     // If such overwrites are allowed, coinbases and transactions depending upon those
1808     // can be duplicated to remove the ability to spend the first instance -- even after
1809     // being sent to another address.
1810     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1811     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1812     // already refuses previously-known transaction ids entirely.
1813     // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
1814     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1815     // two in the chain that violate it. This prevents exploiting the issue against nodes during their
1816     // initial block download.
1817     bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
1818                           !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
1819                            (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
1820     if (fEnforceBIP30) {
1821         BOOST_FOREACH(const CTransaction& tx, block.vtx) {
1822             const CCoins* coins = view.AccessCoins(tx.GetHash());
1823             if (coins && !coins->IsPruned())
1824                 return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
1825                                  REJECT_INVALID, "bad-txns-BIP30");
1826         }
1827     }
1828
1829     // BIP16 didn't become active until Apr 1 2012
1830     int64_t nBIP16SwitchTime = 1333238400;
1831     bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
1832
1833     unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
1834
1835     // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
1836     if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, chainparams.GetConsensus().nMajorityEnforceBlockUpgrade, chainparams.GetConsensus())) {
1837         flags |= SCRIPT_VERIFY_DERSIG;
1838     }
1839
1840     CBlockUndo blockundo;
1841
1842     CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1843
1844     int64_t nTimeStart = GetTimeMicros();
1845     CAmount nFees = 0;
1846     int nInputs = 0;
1847     unsigned int nSigOps = 0;
1848     CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
1849     std::vector<std::pair<uint256, CDiskTxPos> > vPos;
1850     vPos.reserve(block.vtx.size());
1851     blockundo.vtxundo.reserve(block.vtx.size() - 1);
1852     for (unsigned int i = 0; i < block.vtx.size(); i++)
1853     {
1854         const CTransaction &tx = block.vtx[i];
1855
1856         nInputs += tx.vin.size();
1857         nSigOps += GetLegacySigOpCount(tx);
1858         if (nSigOps > MAX_BLOCK_SIGOPS)
1859             return state.DoS(100, error("ConnectBlock(): too many sigops"),
1860                              REJECT_INVALID, "bad-blk-sigops");
1861
1862         if (!tx.IsCoinBase())
1863         {
1864             if (!view.HaveInputs(tx))
1865                 return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
1866                                  REJECT_INVALID, "bad-txns-inputs-missingorspent");
1867
1868             if (fStrictPayToScriptHash)
1869             {
1870                 // Add in sigops done by pay-to-script-hash inputs;
1871                 // this is to prevent a "rogue miner" from creating
1872                 // an incredibly-expensive-to-validate block.
1873                 nSigOps += GetP2SHSigOpCount(tx, view);
1874                 if (nSigOps > MAX_BLOCK_SIGOPS)
1875                     return state.DoS(100, error("ConnectBlock(): too many sigops"),
1876                                      REJECT_INVALID, "bad-blk-sigops");
1877             }
1878
1879             nFees += view.GetValueIn(tx)-tx.GetValueOut();
1880
1881             std::vector<CScriptCheck> vChecks;
1882             if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
1883                 return false;
1884             control.Add(vChecks);
1885         }
1886
1887         CTxUndo undoDummy;
1888         if (i > 0) {
1889             blockundo.vtxundo.push_back(CTxUndo());
1890         }
1891         UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
1892
1893         vPos.push_back(std::make_pair(tx.GetHash(), pos));
1894         pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1895     }
1896     int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
1897     LogPrint("bench", "      - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
1898
1899     CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
1900     if (block.vtx[0].GetValueOut() > blockReward)
1901         return state.DoS(100,
1902                          error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
1903                                block.vtx[0].GetValueOut(), blockReward),
1904                                REJECT_INVALID, "bad-cb-amount");
1905
1906     if (!control.Wait())
1907         return state.DoS(100, false);
1908     int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
1909     LogPrint("bench", "    - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
1910
1911     if (fJustCheck)
1912         return true;
1913
1914     // Write undo information to disk
1915     if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
1916     {
1917         if (pindex->GetUndoPos().IsNull()) {
1918             CDiskBlockPos pos;
1919             if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
1920                 return error("ConnectBlock(): FindUndoPos failed");
1921             if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
1922                 return AbortNode(state, "Failed to write undo data");
1923
1924             // update nUndoPos in block index
1925             pindex->nUndoPos = pos.nPos;
1926             pindex->nStatus |= BLOCK_HAVE_UNDO;
1927         }
1928
1929         pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
1930         setDirtyBlockIndex.insert(pindex);
1931     }
1932
1933     if (fTxIndex)
1934         if (!pblocktree->WriteTxIndex(vPos))
1935             return AbortNode(state, "Failed to write transaction index");
1936
1937     // add this block to the view's block chain
1938     view.SetBestBlock(pindex->GetBlockHash());
1939
1940     int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
1941     LogPrint("bench", "    - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
1942
1943     // Watch for changes to the previous coinbase transaction.
1944     static uint256 hashPrevBestCoinBase;
1945     GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
1946     hashPrevBestCoinBase = block.vtx[0].GetHash();
1947
1948     int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
1949     LogPrint("bench", "    - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
1950
1951     return true;
1952 }
1953
1954 enum FlushStateMode {
1955     FLUSH_STATE_NONE,
1956     FLUSH_STATE_IF_NEEDED,
1957     FLUSH_STATE_PERIODIC,
1958     FLUSH_STATE_ALWAYS
1959 };
1960
1961 /**
1962  * Update the on-disk chain state.
1963  * The caches and indexes are flushed depending on the mode we're called with
1964  * if they're too large, if it's been a while since the last write,
1965  * or always and in all cases if we're in prune mode and are deleting files.
1966  */
1967 bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
1968     LOCK2(cs_main, cs_LastBlockFile);
1969     static int64_t nLastWrite = 0;
1970     static int64_t nLastFlush = 0;
1971     static int64_t nLastSetChain = 0;
1972     std::set<int> setFilesToPrune;
1973     bool fFlushForPrune = false;
1974     try {
1975     if (fPruneMode && fCheckForPruning) {
1976         FindFilesToPrune(setFilesToPrune);
1977         fCheckForPruning = false;
1978         if (!setFilesToPrune.empty()) {
1979             fFlushForPrune = true;
1980             if (!fHavePruned) {
1981                 pblocktree->WriteFlag("prunedblockfiles", true);
1982                 fHavePruned = true;
1983             }
1984         }
1985     }
1986     int64_t nNow = GetTimeMicros();
1987     // Avoid writing/flushing immediately after startup.
1988     if (nLastWrite == 0) {
1989         nLastWrite = nNow;
1990     }
1991     if (nLastFlush == 0) {
1992         nLastFlush = nNow;
1993     }
1994     if (nLastSetChain == 0) {
1995         nLastSetChain = nNow;
1996     }
1997     size_t cacheSize = pcoinsTip->DynamicMemoryUsage();
1998     // The cache is large and close to the limit, but we have time now (not in the middle of a block processing).
1999     bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage;
2000     // The cache is over the limit, we have to write now.
2001     bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage;
2002     // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
2003     bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
2004     // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
2005     bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
2006     // Combine all conditions that result in a full cache flush.
2007     bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
2008     // Write blocks and block index to disk.
2009     if (fDoFullFlush || fPeriodicWrite) {
2010         // Depend on nMinDiskSpace to ensure we can write block index
2011         if (!CheckDiskSpace(0))
2012             return state.Error("out of disk space");
2013         // First make sure all block and undo data is flushed to disk.
2014         FlushBlockFile();
2015         // Then update all block file information (which may refer to block and undo files).
2016         {
2017             std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
2018             vFiles.reserve(setDirtyFileInfo.size());
2019             for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
2020                 vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
2021                 setDirtyFileInfo.erase(it++);
2022             }
2023             std::vector<const CBlockIndex*> vBlocks;
2024             vBlocks.reserve(setDirtyBlockIndex.size());
2025             for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
2026                 vBlocks.push_back(*it);
2027                 setDirtyBlockIndex.erase(it++);
2028             }
2029             if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
2030                 return AbortNode(state, "Files to write to block index database");
2031             }
2032         }
2033         // Finally remove any pruned files
2034         if (fFlushForPrune)
2035             UnlinkPrunedFiles(setFilesToPrune);
2036         nLastWrite = nNow;
2037     }
2038     // Flush best chain related state. This can only be done if the blocks / block index write was also done.
2039     if (fDoFullFlush) {
2040         // Typical CCoins structures on disk are around 128 bytes in size.
2041         // Pushing a new one to the database can cause it to be written
2042         // twice (once in the log, and once in the tables). This is already
2043         // an overestimation, as most will delete an existing entry or
2044         // overwrite one. Still, use a conservative safety factor of 2.
2045         if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize()))
2046             return state.Error("out of disk space");
2047         // Flush the chainstate (which may refer to block index entries).
2048         if (!pcoinsTip->Flush())
2049             return AbortNode(state, "Failed to write to coin database");
2050         nLastFlush = nNow;
2051     }
2052     if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) {
2053         // Update best block in wallet (so we can detect restored wallets).
2054         GetMainSignals().SetBestChain(chainActive.GetLocator());
2055         nLastSetChain = nNow;
2056     }
2057     } catch (const std::runtime_error& e) {
2058         return AbortNode(state, std::string("System error while flushing: ") + e.what());
2059     }
2060     return true;
2061 }
2062
2063 void FlushStateToDisk() {
2064     CValidationState state;
2065     FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
2066 }
2067
2068 void PruneAndFlush() {
2069     CValidationState state;
2070     fCheckForPruning = true;
2071     FlushStateToDisk(state, FLUSH_STATE_NONE);
2072 }
2073
2074 /** Update chainActive and related internal data structures. */
2075 void static UpdateTip(CBlockIndex *pindexNew) {
2076     const CChainParams& chainParams = Params();
2077     chainActive.SetTip(pindexNew);
2078
2079     // New best block
2080     nTimeBestReceived = GetTime();
2081     mempool.AddTransactionsUpdated(1);
2082
2083     LogPrintf("%s: new best=%s  height=%d  log2_work=%.8g  tx=%lu  date=%s progress=%f  cache=%.1fMiB(%utx)\n", __func__,
2084       chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
2085       DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
2086       Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
2087
2088     cvBlockChange.notify_all();
2089
2090     // Check the version of the last 100 blocks to see if we need to upgrade:
2091     static bool fWarned = false;
2092     if (!IsInitialBlockDownload() && !fWarned)
2093     {
2094         int nUpgraded = 0;
2095         const CBlockIndex* pindex = chainActive.Tip();
2096         for (int i = 0; i < 100 && pindex != NULL; i++)
2097         {
2098             if (pindex->nVersion > CBlock::CURRENT_VERSION)
2099                 ++nUpgraded;
2100             pindex = pindex->pprev;
2101         }
2102         if (nUpgraded > 0)
2103             LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
2104         if (nUpgraded > 100/2)
2105         {
2106             // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2107             strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
2108             CAlert::Notify(strMiscWarning, true);
2109             fWarned = true;
2110         }
2111     }
2112 }
2113
2114 /** Disconnect chainActive's tip. */
2115 bool static DisconnectTip(CValidationState &state) {
2116     CBlockIndex *pindexDelete = chainActive.Tip();
2117     assert(pindexDelete);
2118     mempool.check(pcoinsTip);
2119     // Read block from disk.
2120     CBlock block;
2121     if (!ReadBlockFromDisk(block, pindexDelete))
2122         return AbortNode(state, "Failed to read block");
2123     // Apply the block atomically to the chain state.
2124     int64_t nStart = GetTimeMicros();
2125     {
2126         CCoinsViewCache view(pcoinsTip);
2127         if (!DisconnectBlock(block, state, pindexDelete, view))
2128             return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
2129         assert(view.Flush());
2130     }
2131     LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
2132     // Write the chain state to disk, if necessary.
2133     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2134         return false;
2135     // Resurrect mempool transactions from the disconnected block.
2136     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2137         // ignore validation errors in resurrected transactions
2138         list<CTransaction> removed;
2139         CValidationState stateDummy;
2140         if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
2141             mempool.remove(tx, removed, true);
2142     }
2143     mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
2144     mempool.check(pcoinsTip);
2145     // Update chainActive and related variables.
2146     UpdateTip(pindexDelete->pprev);
2147     // Let wallets know transactions went from 1-confirmed to
2148     // 0-confirmed or conflicted:
2149     BOOST_FOREACH(const CTransaction &tx, block.vtx) {
2150         SyncWithWallets(tx, NULL);
2151     }
2152     return true;
2153 }
2154
2155 static int64_t nTimeReadFromDisk = 0;
2156 static int64_t nTimeConnectTotal = 0;
2157 static int64_t nTimeFlush = 0;
2158 static int64_t nTimeChainState = 0;
2159 static int64_t nTimePostConnect = 0;
2160
2161 /** 
2162  * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
2163  * corresponding to pindexNew, to bypass loading it again from disk.
2164  */
2165 bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
2166     assert(pindexNew->pprev == chainActive.Tip());
2167     mempool.check(pcoinsTip);
2168     // Read block from disk.
2169     int64_t nTime1 = GetTimeMicros();
2170     CBlock block;
2171     if (!pblock) {
2172         if (!ReadBlockFromDisk(block, pindexNew))
2173             return AbortNode(state, "Failed to read block");
2174         pblock = &block;
2175     }
2176     // Apply the block atomically to the chain state.
2177     int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
2178     int64_t nTime3;
2179     LogPrint("bench", "  - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
2180     {
2181         CCoinsViewCache view(pcoinsTip);
2182         CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
2183         bool rv = ConnectBlock(*pblock, state, pindexNew, view);
2184         GetMainSignals().BlockChecked(*pblock, state);
2185         if (!rv) {
2186             if (state.IsInvalid())
2187                 InvalidBlockFound(pindexNew, state);
2188             return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
2189         }
2190         mapBlockSource.erase(inv.hash);
2191         nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
2192         LogPrint("bench", "  - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
2193         assert(view.Flush());
2194     }
2195     int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
2196     LogPrint("bench", "  - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
2197     // Write the chain state to disk, if necessary.
2198     if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
2199         return false;
2200     int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
2201     LogPrint("bench", "  - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
2202     // Remove conflicting transactions from the mempool.
2203     list<CTransaction> txConflicted;
2204     mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload());
2205     mempool.check(pcoinsTip);
2206     // Update chainActive & related variables.
2207     UpdateTip(pindexNew);
2208     // Tell wallet about transactions that went from mempool
2209     // to conflicted:
2210     BOOST_FOREACH(const CTransaction &tx, txConflicted) {
2211         SyncWithWallets(tx, NULL);
2212     }
2213     // ... and about transactions that got confirmed:
2214     BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
2215         SyncWithWallets(tx, pblock);
2216     }
2217
2218     int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
2219     LogPrint("bench", "  - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
2220     LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
2221     return true;
2222 }
2223
2224 /**
2225  * Return the tip of the chain with the most work in it, that isn't
2226  * known to be invalid (it's however far from certain to be valid).
2227  */
2228 static CBlockIndex* FindMostWorkChain() {
2229     do {
2230         CBlockIndex *pindexNew = NULL;
2231
2232         // Find the best candidate header.
2233         {
2234             std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
2235             if (it == setBlockIndexCandidates.rend())
2236                 return NULL;
2237             pindexNew = *it;
2238         }
2239
2240         // Check whether all blocks on the path between the currently active chain and the candidate are valid.
2241         // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
2242         CBlockIndex *pindexTest = pindexNew;
2243         bool fInvalidAncestor = false;
2244         while (pindexTest && !chainActive.Contains(pindexTest)) {
2245             assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
2246
2247             // Pruned nodes may have entries in setBlockIndexCandidates for
2248             // which block files have been deleted.  Remove those as candidates
2249             // for the most work chain if we come across them; we can't switch
2250             // to a chain unless we have all the non-active-chain parent blocks.
2251             bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
2252             bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
2253             if (fFailedChain || fMissingData) {
2254                 // Candidate chain is not usable (either invalid or missing data)
2255                 if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
2256                     pindexBestInvalid = pindexNew;
2257                 CBlockIndex *pindexFailed = pindexNew;
2258                 // Remove the entire chain from the set.
2259                 while (pindexTest != pindexFailed) {
2260                     if (fFailedChain) {
2261                         pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
2262                     } else if (fMissingData) {
2263                         // If we're missing data, then add back to mapBlocksUnlinked,
2264                         // so that if the block arrives in the future we can try adding
2265                         // to setBlockIndexCandidates again.
2266                         mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
2267                     }
2268                     setBlockIndexCandidates.erase(pindexFailed);
2269                     pindexFailed = pindexFailed->pprev;
2270                 }
2271                 setBlockIndexCandidates.erase(pindexTest);
2272                 fInvalidAncestor = true;
2273                 break;
2274             }
2275             pindexTest = pindexTest->pprev;
2276         }
2277         if (!fInvalidAncestor)
2278             return pindexNew;
2279     } while(true);
2280 }
2281
2282 /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
2283 static void PruneBlockIndexCandidates() {
2284     // Note that we can't delete the current block itself, as we may need to return to it later in case a
2285     // reorganization to a better block fails.
2286     std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
2287     while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
2288         setBlockIndexCandidates.erase(it++);
2289     }
2290     // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
2291     assert(!setBlockIndexCandidates.empty());
2292 }
2293
2294 /**
2295  * Try to make some progress towards making pindexMostWork the active block.
2296  * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
2297  */
2298 static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
2299     AssertLockHeld(cs_main);
2300     bool fInvalidFound = false;
2301     const CBlockIndex *pindexOldTip = chainActive.Tip();
2302     const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
2303
2304     // Disconnect active blocks which are no longer in the best chain.
2305     while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
2306         if (!DisconnectTip(state))
2307             return false;
2308     }
2309
2310     // Build list of new blocks to connect.
2311     std::vector<CBlockIndex*> vpindexToConnect;
2312     bool fContinue = true;
2313     int nHeight = pindexFork ? pindexFork->nHeight : -1;
2314     while (fContinue && nHeight != pindexMostWork->nHeight) {
2315     // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
2316     // a few blocks along the way.
2317     int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
2318     vpindexToConnect.clear();
2319     vpindexToConnect.reserve(nTargetHeight - nHeight);
2320     CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
2321     while (pindexIter && pindexIter->nHeight != nHeight) {
2322         vpindexToConnect.push_back(pindexIter);
2323         pindexIter = pindexIter->pprev;
2324     }
2325     nHeight = nTargetHeight;
2326
2327     // Connect new blocks.
2328     BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
2329         if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
2330             if (state.IsInvalid()) {
2331                 // The block violates a consensus rule.
2332                 if (!state.CorruptionPossible())
2333                     InvalidChainFound(vpindexToConnect.back());
2334                 state = CValidationState();
2335                 fInvalidFound = true;
2336                 fContinue = false;
2337                 break;
2338             } else {
2339                 // A system error occurred (disk space, database error, ...).
2340                 return false;
2341             }
2342         } else {
2343             PruneBlockIndexCandidates();
2344             if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
2345                 // We're in a better position than we were. Return temporarily to release the lock.
2346                 fContinue = false;
2347                 break;
2348             }
2349         }
2350     }
2351     }
2352
2353     // Callbacks/notifications for a new best chain.
2354     if (fInvalidFound)
2355         CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
2356     else
2357         CheckForkWarningConditions();
2358
2359     return true;
2360 }
2361
2362 /**
2363  * Make the best chain active, in multiple steps. The result is either failure
2364  * or an activated best chain. pblock is either NULL or a pointer to a block
2365  * that is already loaded (to avoid loading it again from disk).
2366  */
2367 bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
2368     CBlockIndex *pindexNewTip = NULL;
2369     CBlockIndex *pindexMostWork = NULL;
2370     const CChainParams& chainParams = Params();
2371     do {
2372         boost::this_thread::interruption_point();
2373
2374         bool fInitialDownload;
2375         {
2376             LOCK(cs_main);
2377             pindexMostWork = FindMostWorkChain();
2378
2379             // Whether we have anything to do at all.
2380             if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
2381                 return true;
2382
2383             if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
2384                 return false;
2385
2386             pindexNewTip = chainActive.Tip();
2387             fInitialDownload = IsInitialBlockDownload();
2388         }
2389         // When we reach this point, we switched to a new tip (stored in pindexNewTip).
2390
2391         // Notifications/callbacks that can run without cs_main
2392         if (!fInitialDownload) {
2393             uint256 hashNewTip = pindexNewTip->GetBlockHash();
2394             // Relay inventory, but don't relay old inventory during initial block download.
2395             int nBlockEstimate = 0;
2396             if (fCheckpointsEnabled)
2397                 nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(chainParams.Checkpoints());
2398             // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
2399             // in a stalled download if the block file is pruned before the request.
2400             if (nLocalServices & NODE_NETWORK) {
2401                 LOCK(cs_vNodes);
2402                 BOOST_FOREACH(CNode* pnode, vNodes)
2403                     if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2404                         pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
2405             }
2406             // Notify external listeners about the new tip.
2407             uiInterface.NotifyBlockTip(hashNewTip);
2408         }
2409     } while(pindexMostWork != chainActive.Tip());
2410     CheckBlockIndex();
2411
2412     // Write changes periodically to disk, after relay.
2413     if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
2414         return false;
2415     }
2416
2417     return true;
2418 }
2419
2420 bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
2421     AssertLockHeld(cs_main);
2422
2423     // Mark the block itself as invalid.
2424     pindex->nStatus |= BLOCK_FAILED_VALID;
2425     setDirtyBlockIndex.insert(pindex);
2426     setBlockIndexCandidates.erase(pindex);
2427
2428     while (chainActive.Contains(pindex)) {
2429         CBlockIndex *pindexWalk = chainActive.Tip();
2430         pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
2431         setDirtyBlockIndex.insert(pindexWalk);
2432         setBlockIndexCandidates.erase(pindexWalk);
2433         // ActivateBestChain considers blocks already in chainActive
2434         // unconditionally valid already, so force disconnect away from it.
2435         if (!DisconnectTip(state)) {
2436             return false;
2437         }
2438     }
2439
2440     // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
2441     // add it again.
2442     BlockMap::iterator it = mapBlockIndex.begin();
2443     while (it != mapBlockIndex.end()) {
2444         if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
2445             setBlockIndexCandidates.insert(it->second);
2446         }
2447         it++;
2448     }
2449
2450     InvalidChainFound(pindex);
2451     return true;
2452 }
2453
2454 bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
2455     AssertLockHeld(cs_main);
2456
2457     int nHeight = pindex->nHeight;
2458
2459     // Remove the invalidity flag from this block and all its descendants.
2460     BlockMap::iterator it = mapBlockIndex.begin();
2461     while (it != mapBlockIndex.end()) {
2462         if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
2463             it->second->nStatus &= ~BLOCK_FAILED_MASK;
2464             setDirtyBlockIndex.insert(it->second);
2465             if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
2466                 setBlockIndexCandidates.insert(it->second);
2467             }
2468             if (it->second == pindexBestInvalid) {
2469                 // Reset invalid block marker if it was pointing to one of those.
2470                 pindexBestInvalid = NULL;
2471             }
2472         }
2473         it++;
2474     }
2475
2476     // Remove the invalidity flag from all ancestors too.
2477     while (pindex != NULL) {
2478         if (pindex->nStatus & BLOCK_FAILED_MASK) {
2479             pindex->nStatus &= ~BLOCK_FAILED_MASK;
2480             setDirtyBlockIndex.insert(pindex);
2481         }
2482         pindex = pindex->pprev;
2483     }
2484     return true;
2485 }
2486
2487 CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
2488 {
2489     // Check for duplicate
2490     uint256 hash = block.GetHash();
2491     BlockMap::iterator it = mapBlockIndex.find(hash);
2492     if (it != mapBlockIndex.end())
2493         return it->second;
2494
2495     // Construct new block index object
2496     CBlockIndex* pindexNew = new CBlockIndex(block);
2497     assert(pindexNew);
2498     // We assign the sequence id to blocks only when the full data is available,
2499     // to avoid miners withholding blocks but broadcasting headers, to get a
2500     // competitive advantage.
2501     pindexNew->nSequenceId = 0;
2502     BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2503     pindexNew->phashBlock = &((*mi).first);
2504     BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
2505     if (miPrev != mapBlockIndex.end())
2506     {
2507         pindexNew->pprev = (*miPrev).second;
2508         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2509         pindexNew->BuildSkip();
2510     }
2511     pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
2512     pindexNew->RaiseValidity(BLOCK_VALID_TREE);
2513     if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
2514         pindexBestHeader = pindexNew;
2515
2516     setDirtyBlockIndex.insert(pindexNew);
2517
2518     return pindexNew;
2519 }
2520
2521 /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
2522 bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
2523 {
2524     pindexNew->nTx = block.vtx.size();
2525     pindexNew->nChainTx = 0;
2526     pindexNew->nFile = pos.nFile;
2527     pindexNew->nDataPos = pos.nPos;
2528     pindexNew->nUndoPos = 0;
2529     pindexNew->nStatus |= BLOCK_HAVE_DATA;
2530     pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
2531     setDirtyBlockIndex.insert(pindexNew);
2532
2533     if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
2534         // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
2535         deque<CBlockIndex*> queue;
2536         queue.push_back(pindexNew);
2537
2538         // Recursively process any descendant blocks that now may be eligible to be connected.
2539         while (!queue.empty()) {
2540             CBlockIndex *pindex = queue.front();
2541             queue.pop_front();
2542             pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
2543             {
2544                 LOCK(cs_nBlockSequenceId);
2545                 pindex->nSequenceId = nBlockSequenceId++;
2546             }
2547             if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
2548                 setBlockIndexCandidates.insert(pindex);
2549             }
2550             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
2551             while (range.first != range.second) {
2552                 std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
2553                 queue.push_back(it->second);
2554                 range.first++;
2555                 mapBlocksUnlinked.erase(it);
2556             }
2557         }
2558     } else {
2559         if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
2560             mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
2561         }
2562     }
2563
2564     return true;
2565 }
2566
2567 bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
2568 {
2569     LOCK(cs_LastBlockFile);
2570
2571     unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
2572     if (vinfoBlockFile.size() <= nFile) {
2573         vinfoBlockFile.resize(nFile + 1);
2574     }
2575
2576     if (!fKnown) {
2577         while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2578             LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
2579             FlushBlockFile(true);
2580             nFile++;
2581             if (vinfoBlockFile.size() <= nFile) {
2582                 vinfoBlockFile.resize(nFile + 1);
2583             }
2584         }
2585         pos.nFile = nFile;
2586         pos.nPos = vinfoBlockFile[nFile].nSize;
2587     }
2588
2589     nLastBlockFile = nFile;
2590     vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
2591     if (fKnown)
2592         vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
2593     else
2594         vinfoBlockFile[nFile].nSize += nAddSize;
2595
2596     if (!fKnown) {
2597         unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2598         unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2599         if (nNewChunks > nOldChunks) {
2600             if (fPruneMode)
2601                 fCheckForPruning = true;
2602             if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
2603                 FILE *file = OpenBlockFile(pos);
2604                 if (file) {
2605                     LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2606                     AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2607                     fclose(file);
2608                 }
2609             }
2610             else
2611                 return state.Error("out of disk space");
2612         }
2613     }
2614
2615     setDirtyFileInfo.insert(nFile);
2616     return true;
2617 }
2618
2619 bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2620 {
2621     pos.nFile = nFile;
2622
2623     LOCK(cs_LastBlockFile);
2624
2625     unsigned int nNewSize;
2626     pos.nPos = vinfoBlockFile[nFile].nUndoSize;
2627     nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
2628     setDirtyFileInfo.insert(nFile);
2629
2630     unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2631     unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2632     if (nNewChunks > nOldChunks) {
2633         if (fPruneMode)
2634             fCheckForPruning = true;
2635         if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
2636             FILE *file = OpenUndoFile(pos);
2637             if (file) {
2638                 LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2639                 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2640                 fclose(file);
2641             }
2642         }
2643         else
2644             return state.Error("out of disk space");
2645     }
2646
2647     return true;
2648 }
2649
2650 bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
2651 {
2652     // Check proof of work matches claimed amount
2653     if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
2654         return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
2655                          REJECT_INVALID, "high-hash");
2656
2657     // Check timestamp
2658     if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2659         return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
2660                              REJECT_INVALID, "time-too-new");
2661
2662     return true;
2663 }
2664
2665 bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
2666 {
2667     // These are checks that are independent of context.
2668
2669     // Check that the header is valid (particularly PoW).  This is mostly
2670     // redundant with the call in AcceptBlockHeader.
2671     if (!CheckBlockHeader(block, state, fCheckPOW))
2672         return false;
2673
2674     // Check the merkle root.
2675     if (fCheckMerkleRoot) {
2676         bool mutated;
2677         uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
2678         if (block.hashMerkleRoot != hashMerkleRoot2)
2679             return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
2680                              REJECT_INVALID, "bad-txnmrklroot", true);
2681
2682         // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
2683         // of transactions in a block without affecting the merkle root of a block,
2684         // while still invalidating it.
2685         if (mutated)
2686             return state.DoS(100, error("CheckBlock(): duplicate transaction"),
2687                              REJECT_INVALID, "bad-txns-duplicate", true);
2688     }
2689
2690     // All potential-corruption validation must be done before we do any
2691     // transaction validation, as otherwise we may mark the header as invalid
2692     // because we receive the wrong transactions for it.
2693
2694     // Size limits
2695     if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2696         return state.DoS(100, error("CheckBlock(): size limits failed"),
2697                          REJECT_INVALID, "bad-blk-length");
2698
2699     // First transaction must be coinbase, the rest must not be
2700     if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
2701         return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
2702                          REJECT_INVALID, "bad-cb-missing");
2703     for (unsigned int i = 1; i < block.vtx.size(); i++)
2704         if (block.vtx[i].IsCoinBase())
2705             return state.DoS(100, error("CheckBlock(): more than one coinbase"),
2706                              REJECT_INVALID, "bad-cb-multiple");
2707
2708     // Check transactions
2709     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2710         if (!CheckTransaction(tx, state))
2711             return error("CheckBlock(): CheckTransaction failed");
2712
2713     unsigned int nSigOps = 0;
2714     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2715     {
2716         nSigOps += GetLegacySigOpCount(tx);
2717     }
2718     if (nSigOps > MAX_BLOCK_SIGOPS)
2719         return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
2720                          REJECT_INVALID, "bad-blk-sigops", true);
2721
2722     return true;
2723 }
2724
2725 bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
2726 {
2727     const CChainParams& chainParams = Params();
2728     const Consensus::Params& consensusParams = chainParams.GetConsensus();
2729     uint256 hash = block.GetHash();
2730     if (hash == consensusParams.hashGenesisBlock)
2731         return true;
2732
2733     assert(pindexPrev);
2734
2735     int nHeight = pindexPrev->nHeight+1;
2736
2737     // Check proof of work
2738     if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
2739         return state.DoS(100, error("%s: incorrect proof of work", __func__),
2740                          REJECT_INVALID, "bad-diffbits");
2741
2742     // Check timestamp against prev
2743     if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
2744         return state.Invalid(error("%s: block's timestamp is too early", __func__),
2745                              REJECT_INVALID, "time-too-old");
2746
2747     if(fCheckpointsEnabled)
2748     {
2749         // Check that the block chain matches the known block chain up to a checkpoint
2750         if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash))
2751             return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
2752                              REJECT_CHECKPOINT, "checkpoint mismatch");
2753
2754         // Don't accept any forks from the main chain prior to last checkpoint
2755         CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints());
2756         if (pcheckpoint && nHeight < pcheckpoint->nHeight)
2757             return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
2758     }
2759
2760     // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
2761     if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2762         return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
2763                              REJECT_OBSOLETE, "bad-version");
2764
2765     // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
2766     if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, consensusParams.nMajorityRejectBlockOutdated, consensusParams))
2767         return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
2768                              REJECT_OBSOLETE, "bad-version");
2769
2770     return true;
2771 }
2772
2773 bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
2774 {
2775     const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
2776     const Consensus::Params& consensusParams = Params().GetConsensus();
2777
2778     // Check that all transactions are finalized
2779     BOOST_FOREACH(const CTransaction& tx, block.vtx)
2780         if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
2781             return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
2782         }
2783
2784     // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
2785     // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
2786     if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams))
2787     {
2788         CScript expect = CScript() << nHeight;
2789         if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
2790             !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
2791             return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
2792         }
2793     }
2794
2795     return true;
2796 }
2797
2798 bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
2799 {
2800     const CChainParams& chainparams = Params();
2801     AssertLockHeld(cs_main);
2802     // Check for duplicate
2803     uint256 hash = block.GetHash();
2804     BlockMap::iterator miSelf = mapBlockIndex.find(hash);
2805     CBlockIndex *pindex = NULL;
2806     if (miSelf != mapBlockIndex.end()) {
2807         // Block header is already known.
2808         pindex = miSelf->second;
2809         if (ppindex)
2810             *ppindex = pindex;
2811         if (pindex->nStatus & BLOCK_FAILED_MASK)
2812             return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
2813         return true;
2814     }
2815
2816     if (!CheckBlockHeader(block, state))
2817         return false;
2818
2819     // Get prev block index
2820     CBlockIndex* pindexPrev = NULL;
2821     if (hash != chainparams.GetConsensus().hashGenesisBlock) {
2822         BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
2823         if (mi == mapBlockIndex.end())
2824             return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
2825         pindexPrev = (*mi).second;
2826         if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
2827             return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
2828     }
2829
2830     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2831         return false;
2832
2833     if (pindex == NULL)
2834         pindex = AddToBlockIndex(block);
2835
2836     if (ppindex)
2837         *ppindex = pindex;
2838
2839     return true;
2840 }
2841
2842 bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
2843 {
2844     const CChainParams& chainparams = Params();
2845     AssertLockHeld(cs_main);
2846
2847     CBlockIndex *&pindex = *ppindex;
2848
2849     if (!AcceptBlockHeader(block, state, &pindex))
2850         return false;
2851
2852     // If we're pruning, ensure that we don't allow a peer to dump a copy
2853     // of old blocks.  But we might need blocks that are not on the main chain
2854     // to handle a reorg, even if we've processed once.
2855     if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
2856         // TODO: deal better with duplicate blocks.
2857         // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
2858         return true;
2859     }
2860
2861     if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
2862         if (state.IsInvalid() && !state.CorruptionPossible()) {
2863             pindex->nStatus |= BLOCK_FAILED_VALID;
2864             setDirtyBlockIndex.insert(pindex);
2865         }
2866         return false;
2867     }
2868
2869     int nHeight = pindex->nHeight;
2870
2871     // Write block to history file
2872     try {
2873         unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2874         CDiskBlockPos blockPos;
2875         if (dbp != NULL)
2876             blockPos = *dbp;
2877         if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
2878             return error("AcceptBlock(): FindBlockPos failed");
2879         if (dbp == NULL)
2880             if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
2881                 AbortNode(state, "Failed to write block");
2882         if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
2883             return error("AcceptBlock(): ReceivedBlockTransactions failed");
2884     } catch (const std::runtime_error& e) {
2885         return AbortNode(state, std::string("System error: ") + e.what());
2886     }
2887
2888     if (fCheckForPruning)
2889         FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
2890
2891     return true;
2892 }
2893
2894 static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned nRequired, const Consensus::Params& consensusParams)
2895 {
2896     unsigned int nFound = 0;
2897     for (int i = 0; i < consensusParams.nMajorityWindow && nFound < nRequired && pstart != NULL; i++)
2898     {
2899         if (pstart->nVersion >= minVersion)
2900             ++nFound;
2901         pstart = pstart->pprev;
2902     }
2903     return (nFound >= nRequired);
2904 }
2905
2906
2907 bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
2908 {
2909     // Preliminary checks
2910     bool checked = CheckBlock(*pblock, state);
2911
2912     {
2913         LOCK(cs_main);
2914         MarkBlockAsReceived(pblock->GetHash());
2915         if (!checked) {
2916             return error("%s: CheckBlock FAILED", __func__);
2917         }
2918
2919         // Store to disk
2920         CBlockIndex *pindex = NULL;
2921         bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
2922         if (pindex && pfrom) {
2923             mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
2924         }
2925         CheckBlockIndex();
2926         if (!ret)
2927             return error("%s: AcceptBlock FAILED", __func__);
2928     }
2929
2930     if (!ActivateBestChain(state, pblock))
2931         return error("%s: ActivateBestChain failed", __func__);
2932
2933     return true;
2934 }
2935
2936 bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
2937 {
2938     AssertLockHeld(cs_main);
2939     assert(pindexPrev == chainActive.Tip());
2940
2941     CCoinsViewCache viewNew(pcoinsTip);
2942     CBlockIndex indexDummy(block);
2943     indexDummy.pprev = pindexPrev;
2944     indexDummy.nHeight = pindexPrev->nHeight + 1;
2945
2946     // NOTE: CheckBlockHeader is called by CheckBlock
2947     if (!ContextualCheckBlockHeader(block, state, pindexPrev))
2948         return false;
2949     if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
2950         return false;
2951     if (!ContextualCheckBlock(block, state, pindexPrev))
2952         return false;
2953     if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
2954         return false;
2955     assert(state.IsValid());
2956
2957     return true;
2958 }
2959
2960 /**
2961  * BLOCK PRUNING CODE
2962  */
2963
2964 /* Calculate the amount of disk space the block & undo files currently use */
2965 uint64_t CalculateCurrentUsage()
2966 {
2967     uint64_t retval = 0;
2968     BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
2969         retval += file.nSize + file.nUndoSize;
2970     }
2971     return retval;
2972 }
2973
2974 /* Prune a block file (modify associated database entries)*/
2975 void PruneOneBlockFile(const int fileNumber)
2976 {
2977     for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
2978         CBlockIndex* pindex = it->second;
2979         if (pindex->nFile == fileNumber) {
2980             pindex->nStatus &= ~BLOCK_HAVE_DATA;
2981             pindex->nStatus &= ~BLOCK_HAVE_UNDO;
2982             pindex->nFile = 0;
2983             pindex->nDataPos = 0;
2984             pindex->nUndoPos = 0;
2985             setDirtyBlockIndex.insert(pindex);
2986
2987             // Prune from mapBlocksUnlinked -- any block we prune would have
2988             // to be downloaded again in order to consider its chain, at which
2989             // point it would be considered as a candidate for
2990             // mapBlocksUnlinked or setBlockIndexCandidates.
2991             std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
2992             while (range.first != range.second) {
2993                 std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
2994                 range.first++;
2995                 if (it->second == pindex) {
2996                     mapBlocksUnlinked.erase(it);
2997                 }
2998             }
2999         }
3000     }
3001
3002     vinfoBlockFile[fileNumber].SetNull();
3003     setDirtyFileInfo.insert(fileNumber);
3004 }
3005
3006
3007 void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
3008 {
3009     for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
3010         CDiskBlockPos pos(*it, 0);
3011         boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
3012         boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
3013         LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
3014     }
3015 }
3016
3017 /* Calculate the block/rev files that should be deleted to remain under target*/
3018 void FindFilesToPrune(std::set<int>& setFilesToPrune)
3019 {
3020     LOCK2(cs_main, cs_LastBlockFile);
3021     if (chainActive.Tip() == NULL || nPruneTarget == 0) {
3022         return;
3023     }
3024     if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
3025         return;
3026     }
3027
3028     unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
3029     uint64_t nCurrentUsage = CalculateCurrentUsage();
3030     // We don't check to prune until after we've allocated new space for files
3031     // So we should leave a buffer under our target to account for another allocation
3032     // before the next pruning.
3033     uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
3034     uint64_t nBytesToPrune;
3035     int count=0;
3036
3037     if (nCurrentUsage + nBuffer >= nPruneTarget) {
3038         for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
3039             nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
3040
3041             if (vinfoBlockFile[fileNumber].nSize == 0)
3042                 continue;
3043
3044             if (nCurrentUsage + nBuffer < nPruneTarget)  // are we below our target?
3045                 break;
3046
3047             // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip
3048             if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
3049                 break;
3050
3051             PruneOneBlockFile(fileNumber);
3052             // Queue up the files for removal
3053             setFilesToPrune.insert(fileNumber);
3054             nCurrentUsage -= nBytesToPrune;
3055             count++;
3056         }
3057     }
3058
3059     LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
3060            nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
3061            ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
3062            nLastBlockWeCanPrune, count);
3063 }
3064
3065 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3066 {
3067     uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3068
3069     // Check for nMinDiskSpace bytes (currently 50MB)
3070     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3071         return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
3072
3073     return true;
3074 }
3075
3076 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
3077 {
3078     if (pos.IsNull())
3079         return NULL;
3080     boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
3081     boost::filesystem::create_directories(path.parent_path());
3082     FILE* file = fopen(path.string().c_str(), "rb+");
3083     if (!file && !fReadOnly)
3084         file = fopen(path.string().c_str(), "wb+");
3085     if (!file) {
3086         LogPrintf("Unable to open file %s\n", path.string());
3087         return NULL;
3088     }
3089     if (pos.nPos) {
3090         if (fseek(file, pos.nPos, SEEK_SET)) {
3091             LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
3092             fclose(file);
3093             return NULL;
3094         }
3095     }
3096     return file;
3097 }
3098
3099 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
3100     return OpenDiskFile(pos, "blk", fReadOnly);
3101 }
3102
3103 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
3104     return OpenDiskFile(pos, "rev", fReadOnly);
3105 }
3106
3107 boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
3108 {
3109     return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
3110 }
3111
3112 CBlockIndex * InsertBlockIndex(uint256 hash)
3113 {
3114     if (hash.IsNull())
3115         return NULL;
3116
3117     // Return existing
3118     BlockMap::iterator mi = mapBlockIndex.find(hash);
3119     if (mi != mapBlockIndex.end())
3120         return (*mi).second;
3121
3122     // Create new
3123     CBlockIndex* pindexNew = new CBlockIndex();
3124     if (!pindexNew)
3125         throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
3126     mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
3127     pindexNew->phashBlock = &((*mi).first);
3128
3129     return pindexNew;
3130 }
3131
3132 bool static LoadBlockIndexDB()
3133 {
3134     const CChainParams& chainparams = Params();
3135     if (!pblocktree->LoadBlockIndexGuts())
3136         return false;
3137
3138     boost::this_thread::interruption_point();
3139
3140     // Calculate nChainWork
3141     vector<pair<int, CBlockIndex*> > vSortedByHeight;
3142     vSortedByHeight.reserve(mapBlockIndex.size());
3143     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3144     {
3145         CBlockIndex* pindex = item.second;
3146         vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
3147     }
3148     sort(vSortedByHeight.begin(), vSortedByHeight.end());
3149     BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
3150     {
3151         CBlockIndex* pindex = item.second;
3152         pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
3153         // We can link the chain of blocks for which we've received transactions at some point.
3154         // Pruned nodes may have deleted the block.
3155         if (pindex->nTx > 0) {
3156             if (pindex->pprev) {
3157                 if (pindex->pprev->nChainTx) {
3158                     pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
3159                 } else {
3160                     pindex->nChainTx = 0;
3161                     mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
3162                 }
3163             } else {
3164                 pindex->nChainTx = pindex->nTx;
3165             }
3166         }
3167         if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
3168             setBlockIndexCandidates.insert(pindex);
3169         if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
3170             pindexBestInvalid = pindex;
3171         if (pindex->pprev)
3172             pindex->BuildSkip();
3173         if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
3174             pindexBestHeader = pindex;
3175     }
3176
3177     // Load block file info
3178     pblocktree->ReadLastBlockFile(nLastBlockFile);
3179     vinfoBlockFile.resize(nLastBlockFile + 1);
3180     LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
3181     for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
3182         pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
3183     }
3184     LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
3185     for (int nFile = nLastBlockFile + 1; true; nFile++) {
3186         CBlockFileInfo info;
3187         if (pblocktree->ReadBlockFileInfo(nFile, info)) {
3188             vinfoBlockFile.push_back(info);
3189         } else {
3190             break;
3191         }
3192     }
3193
3194     // Check presence of blk files
3195     LogPrintf("Checking all blk files are present...\n");
3196     set<int> setBlkDataFiles;
3197     BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
3198     {
3199         CBlockIndex* pindex = item.second;
3200         if (pindex->nStatus & BLOCK_HAVE_DATA) {
3201             setBlkDataFiles.insert(pindex->nFile);
3202         }
3203     }
3204     for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
3205     {
3206         CDiskBlockPos pos(*it, 0);
3207         if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
3208             return false;
3209         }
3210     }
3211
3212     // Check whether we have ever pruned block & undo files
3213     pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
3214     if (fHavePruned)
3215         LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
3216
3217     // Check whether we need to continue reindexing
3218     bool fReindexing = false;
3219     pblocktree->ReadReindexing(fReindexing);
3220     fReindex |= fReindexing;
3221
3222     // Check whether we have a transaction index
3223     pblocktree->ReadFlag("txindex", fTxIndex);
3224     LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
3225
3226     // Load pointer to end of best chain
3227     BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
3228     if (it == mapBlockIndex.end())
3229         return true;
3230     chainActive.SetTip(it->second);
3231
3232     PruneBlockIndexCandidates();
3233
3234     LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
3235         chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
3236         DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
3237         Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip()));
3238
3239     return true;
3240 }
3241
3242 CVerifyDB::CVerifyDB()
3243 {
3244     uiInterface.ShowProgress(_("Verifying blocks..."), 0);
3245 }
3246
3247 CVerifyDB::~CVerifyDB()
3248 {
3249     uiInterface.ShowProgress("", 100);
3250 }
3251
3252 bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
3253 {
3254     LOCK(cs_main);
3255     if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
3256         return true;
3257
3258     // Verify blocks in the best chain
3259     if (nCheckDepth <= 0)
3260         nCheckDepth = 1000000000; // suffices until the year 19000
3261     if (nCheckDepth > chainActive.Height())
3262         nCheckDepth = chainActive.Height();
3263     nCheckLevel = std::max(0, std::min(4, nCheckLevel));
3264     LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
3265     CCoinsViewCache coins(coinsview);
3266     CBlockIndex* pindexState = chainActive.Tip();
3267     CBlockIndex* pindexFailure = NULL;
3268     int nGoodTransactions = 0;
3269     CValidationState state;
3270     for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
3271     {
3272         boost::this_thread::interruption_point();
3273         uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
3274         if (pindex->nHeight < chainActive.Height()-nCheckDepth)
3275             break;
3276         CBlock block;
3277         // check level 0: read from disk
3278         if (!ReadBlockFromDisk(block, pindex))
3279             return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3280         // check level 1: verify block validity
3281         if (nCheckLevel >= 1 && !CheckBlock(block, state))
3282             return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3283         // check level 2: verify undo validity
3284         if (nCheckLevel >= 2 && pindex) {
3285             CBlockUndo undo;
3286             CDiskBlockPos pos = pindex->GetUndoPos();
3287             if (!pos.IsNull()) {
3288                 if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
3289                     return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
3290             }
3291         }
3292         // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
3293         if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
3294             bool fClean = true;
3295             if (!DisconnectBlock(block, state, pindex, coins, &fClean))
3296                 return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3297             pindexState = pindex->pprev;
3298             if (!fClean) {
3299                 nGoodTransactions = 0;
3300                 pindexFailure = pindex;
3301             } else
3302                 nGoodTransactions += block.vtx.size();
3303         }
3304         if (ShutdownRequested())
3305             return true;
3306     }
3307     if (pindexFailure)
3308         return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
3309
3310     // check level 4: try reconnecting blocks
3311     if (nCheckLevel >= 4) {
3312         CBlockIndex *pindex = pindexState;
3313         while (pindex != chainActive.Tip()) {
3314             boost::this_thread::interruption_point();
3315             uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
3316             pindex = chainActive.Next(pindex);
3317             CBlock block;
3318             if (!ReadBlockFromDisk(block, pindex))
3319                 return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3320             if (!ConnectBlock(block, state, pindex, coins))
3321                 return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
3322         }
3323     }
3324
3325     LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
3326
3327     return true;
3328 }
3329
3330 void UnloadBlockIndex()
3331 {
3332     LOCK(cs_main);
3333     setBlockIndexCandidates.clear();
3334     chainActive.SetTip(NULL);
3335     pindexBestInvalid = NULL;
3336     pindexBestHeader = NULL;
3337     mempool.clear();
3338     mapOrphanTransactions.clear();
3339     mapOrphanTransactionsByPrev.clear();
3340     nSyncStarted = 0;
3341     mapBlocksUnlinked.clear();
3342     vinfoBlockFile.clear();
3343     nLastBlockFile = 0;
3344     nBlockSequenceId = 1;
3345     mapBlockSource.clear();
3346     mapBlocksInFlight.clear();
3347     nQueuedValidatedHeaders = 0;
3348     nPreferredDownload = 0;
3349     setDirtyBlockIndex.clear();
3350     setDirtyFileInfo.clear();
3351     mapNodeState.clear();
3352
3353     BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
3354         delete entry.second;
3355     }
3356     mapBlockIndex.clear();
3357     fHavePruned = false;
3358 }
3359
3360 bool LoadBlockIndex()
3361 {
3362     // Load block index from databases
3363     if (!fReindex && !LoadBlockIndexDB())
3364         return false;
3365     return true;
3366 }
3367
3368
3369 bool InitBlockIndex() {
3370     const CChainParams& chainparams = Params();
3371     LOCK(cs_main);
3372     // Check whether we're already initialized
3373     if (chainActive.Genesis() != NULL)
3374         return true;
3375
3376     // Use the provided setting for -txindex in the new database
3377     fTxIndex = GetBoolArg("-txindex", false);
3378     pblocktree->WriteFlag("txindex", fTxIndex);
3379     LogPrintf("Initializing databases...\n");
3380
3381     // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
3382     if (!fReindex) {
3383         try {
3384             CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
3385             // Start new block file
3386             unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
3387             CDiskBlockPos blockPos;
3388             CValidationState state;
3389             if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
3390                 return error("LoadBlockIndex(): FindBlockPos failed");
3391             if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart()))
3392                 return error("LoadBlockIndex(): writing genesis block to disk failed");
3393             CBlockIndex *pindex = AddToBlockIndex(block);
3394             if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
3395                 return error("LoadBlockIndex(): genesis block not accepted");
3396             if (!ActivateBestChain(state, &block))
3397                 return error("LoadBlockIndex(): genesis block cannot be activated");
3398             // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
3399             return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
3400         } catch (const std::runtime_error& e) {
3401             return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
3402         }
3403     }
3404
3405     return true;
3406 }
3407
3408
3409
3410 bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
3411 {
3412     const CChainParams& chainparams = Params();
3413     // Map of disk positions for blocks with unknown parent (only used for reindex)
3414     static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
3415     int64_t nStart = GetTimeMillis();
3416
3417     int nLoaded = 0;
3418     try {
3419         // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
3420         CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
3421         uint64_t nRewind = blkdat.GetPos();
3422         while (!blkdat.eof()) {
3423             boost::this_thread::interruption_point();
3424
3425             blkdat.SetPos(nRewind);
3426             nRewind++; // start one byte further next time, in case of failure
3427             blkdat.SetLimit(); // remove former limit
3428             unsigned int nSize = 0;
3429             try {
3430                 // locate a header
3431                 unsigned char buf[MESSAGE_START_SIZE];
3432                 blkdat.FindByte(Params().MessageStart()[0]);
3433                 nRewind = blkdat.GetPos()+1;
3434                 blkdat >> FLATDATA(buf);
3435                 if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
3436                     continue;
3437                 // read size
3438                 blkdat >> nSize;
3439                 if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
3440                     continue;
3441             } catch (const std::exception&) {
3442                 // no valid block header found; don't complain
3443                 break;
3444             }
3445             try {
3446                 // read block
3447                 uint64_t nBlockPos = blkdat.GetPos();
3448                 if (dbp)
3449                     dbp->nPos = nBlockPos;
3450                 blkdat.SetLimit(nBlockPos + nSize);
3451                 blkdat.SetPos(nBlockPos);
3452                 CBlock block;
3453                 blkdat >> block;
3454                 nRewind = blkdat.GetPos();
3455
3456                 // detect out of order blocks, and store them for later
3457                 uint256 hash = block.GetHash();
3458                 if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
3459                     LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
3460                             block.hashPrevBlock.ToString());
3461                     if (dbp)
3462                         mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
3463                     continue;
3464                 }
3465
3466                 // process in case the block isn't known yet
3467                 if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
3468                     CValidationState state;
3469                     if (ProcessNewBlock(state, NULL, &block, dbp))
3470                         nLoaded++;
3471                     if (state.IsError())
3472                         break;
3473                 } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
3474                     LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
3475                 }
3476
3477                 // Recursively process earlier encountered successors of this block
3478                 deque<uint256> queue;
3479                 queue.push_back(hash);
3480                 while (!queue.empty()) {
3481                     uint256 head = queue.front();
3482                     queue.pop_front();
3483                     std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
3484                     while (range.first != range.second) {
3485                         std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
3486                         if (ReadBlockFromDisk(block, it->second))
3487                         {
3488                             LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
3489                                     head.ToString());
3490                             CValidationState dummy;
3491                             if (ProcessNewBlock(dummy, NULL, &block, &it->second))
3492                             {
3493                                 nLoaded++;
3494                                 queue.push_back(block.GetHash());
3495                             }
3496                         }
3497                         range.first++;
3498                         mapBlocksUnknownParent.erase(it);
3499                     }
3500                 }
3501             } catch (const std::exception& e) {
3502                 LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
3503             }
3504         }
3505     } catch (const std::runtime_error& e) {
3506         AbortNode(std::string("System error: ") + e.what());
3507     }
3508     if (nLoaded > 0)
3509         LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
3510     return nLoaded > 0;
3511 }
3512
3513 void static CheckBlockIndex()
3514 {
3515     const Consensus::Params& consensusParams = Params().GetConsensus();
3516     if (!fCheckBlockIndex) {
3517         return;
3518     }
3519
3520     LOCK(cs_main);
3521
3522     // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
3523     // so we have the genesis block in mapBlockIndex but no active chain.  (A few of the tests when
3524     // iterating the block tree require that chainActive has been initialized.)
3525     if (chainActive.Height() < 0) {
3526         assert(mapBlockIndex.size() <= 1);
3527         return;
3528     }
3529
3530     // Build forward-pointing map of the entire block tree.
3531     std::multimap<CBlockIndex*,CBlockIndex*> forward;
3532     for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
3533         forward.insert(std::make_pair(it->second->pprev, it->second));
3534     }
3535
3536     assert(forward.size() == mapBlockIndex.size());
3537
3538     std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
3539     CBlockIndex *pindex = rangeGenesis.first->second;
3540     rangeGenesis.first++;
3541     assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
3542
3543     // Iterate over the entire block tree, using depth-first search.
3544     // Along the way, remember whether there are blocks on the path from genesis
3545     // block being explored which are the first to have certain properties.
3546     size_t nNodes = 0;
3547     int nHeight = 0;
3548     CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
3549     CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
3550     CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
3551     CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
3552     CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
3553     CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
3554     CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
3555     while (pindex != NULL) {
3556         nNodes++;
3557         if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
3558         if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
3559         if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
3560         if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
3561         if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
3562         if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
3563         if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
3564
3565         // Begin: actual consistency checks.
3566         if (pindex->pprev == NULL) {
3567             // Genesis block checks.
3568             assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
3569             assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
3570         }
3571         if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0);  // nSequenceId can't be set for blocks that aren't linked
3572         // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
3573         // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
3574         if (!fHavePruned) {
3575             // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
3576             assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
3577             assert(pindexFirstMissing == pindexFirstNeverProcessed);
3578         } else {
3579             // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
3580             if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
3581         }
3582         if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
3583         assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
3584         // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
3585         assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
3586         assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
3587         assert(pindex->nHeight == nHeight); // nHeight must be consistent.
3588         assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
3589         assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
3590         assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
3591         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
3592         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
3593         if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
3594         if (pindexFirstInvalid == NULL) {
3595             // Checks for not-invalid blocks.
3596             assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
3597         }
3598         if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
3599             if (pindexFirstInvalid == NULL) {
3600                 // If this block sorts at least as good as the current tip and
3601                 // is valid and we have all data for its parents, it must be in
3602                 // setBlockIndexCandidates.  chainActive.Tip() must also be there
3603                 // even if some data has been pruned.
3604                 if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
3605                     assert(setBlockIndexCandidates.count(pindex));
3606                 }
3607                 // If some parent is missing, then it could be that this block was in
3608                 // setBlockIndexCandidates but had to be removed because of the missing data.
3609                 // In this case it must be in mapBlocksUnlinked -- see test below.
3610             }
3611         } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
3612             assert(setBlockIndexCandidates.count(pindex) == 0);
3613         }
3614         // Check whether this block is in mapBlocksUnlinked.
3615         std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
3616         bool foundInUnlinked = false;
3617         while (rangeUnlinked.first != rangeUnlinked.second) {
3618             assert(rangeUnlinked.first->first == pindex->pprev);
3619             if (rangeUnlinked.first->second == pindex) {
3620                 foundInUnlinked = true;
3621                 break;
3622             }
3623             rangeUnlinked.first++;
3624         }
3625         if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
3626             // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
3627             assert(foundInUnlinked);
3628         }
3629         if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
3630         if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
3631         if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
3632             // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
3633             assert(fHavePruned); // We must have pruned.
3634             // This block may have entered mapBlocksUnlinked if:
3635             //  - it has a descendant that at some point had more work than the
3636             //    tip, and
3637             //  - we tried switching to that descendant but were missing
3638             //    data for some intermediate block between chainActive and the
3639             //    tip.
3640             // So if this block is itself better than chainActive.Tip() and it wasn't in
3641             // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
3642             if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
3643                 if (pindexFirstInvalid == NULL) {
3644                     assert(foundInUnlinked);
3645                 }
3646             }
3647         }
3648         // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
3649         // End: actual consistency checks.
3650
3651         // Try descending into the first subnode.
3652         std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
3653         if (range.first != range.second) {
3654             // A subnode was found.
3655             pindex = range.first->second;
3656             nHeight++;
3657             continue;
3658         }
3659         // This is a leaf node.
3660         // Move upwards until we reach a node of which we have not yet visited the last child.
3661         while (pindex) {
3662             // We are going to either move to a parent or a sibling of pindex.
3663             // If pindex was the first with a certain property, unset the corresponding variable.
3664             if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
3665             if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
3666             if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
3667             if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
3668             if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
3669             if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
3670             if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
3671             // Find our parent.
3672             CBlockIndex* pindexPar = pindex->pprev;
3673             // Find which child we just visited.
3674             std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
3675             while (rangePar.first->second != pindex) {
3676                 assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
3677                 rangePar.first++;
3678             }
3679             // Proceed to the next one.
3680             rangePar.first++;
3681             if (rangePar.first != rangePar.second) {
3682                 // Move to the sibling.
3683                 pindex = rangePar.first->second;
3684                 break;
3685             } else {
3686                 // Move up further.
3687                 pindex = pindexPar;
3688                 nHeight--;
3689                 continue;
3690             }
3691         }
3692     }
3693
3694     // Check that we actually traversed the entire map.
3695     assert(nNodes == forward.size());
3696 }
3697
3698 //////////////////////////////////////////////////////////////////////////////
3699 //
3700 // CAlert
3701 //
3702
3703 string GetWarnings(string strFor)
3704 {
3705     int nPriority = 0;
3706     string strStatusBar;
3707     string strRPC;
3708
3709     if (!CLIENT_VERSION_IS_RELEASE)
3710         strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
3711
3712     if (GetBoolArg("-testsafemode", false))
3713         strStatusBar = strRPC = "testsafemode enabled";
3714
3715     // Misc warnings like out of disk space and clock is wrong
3716     if (strMiscWarning != "")
3717     {
3718         nPriority = 1000;
3719         strStatusBar = strMiscWarning;
3720     }
3721
3722     if (fLargeWorkForkFound)
3723     {
3724         nPriority = 2000;
3725         strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
3726     }
3727     else if (fLargeWorkInvalidChainFound)
3728     {
3729         nPriority = 2000;
3730         strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
3731     }
3732
3733     // Alerts
3734     {
3735         LOCK(cs_mapAlerts);
3736         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3737         {
3738             const CAlert& alert = item.second;
3739             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3740             {
3741                 nPriority = alert.nPriority;
3742                 strStatusBar = alert.strStatusBar;
3743             }
3744         }
3745     }
3746
3747     if (strFor == "statusbar")
3748         return strStatusBar;
3749     else if (strFor == "rpc")
3750         return strRPC;
3751     assert(!"GetWarnings(): invalid parameter");
3752     return "error";
3753 }
3754
3755
3756
3757
3758
3759
3760
3761
3762 //////////////////////////////////////////////////////////////////////////////
3763 //
3764 // Messages
3765 //
3766
3767
3768 bool static AlreadyHave(const CInv& inv)
3769 {
3770     switch (inv.type)
3771     {
3772     case MSG_TX:
3773         {
3774             bool txInMap = false;
3775             txInMap = mempool.exists(inv.hash);
3776             return txInMap || mapOrphanTransactions.count(inv.hash) ||
3777                 pcoinsTip->HaveCoins(inv.hash);
3778         }
3779     case MSG_BLOCK:
3780         return mapBlockIndex.count(inv.hash);
3781     }
3782     // Don't know what it is, just say we already got one
3783     return true;
3784 }
3785
3786 void static ProcessGetData(CNode* pfrom)
3787 {
3788     std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
3789
3790     vector<CInv> vNotFound;
3791
3792     LOCK(cs_main);
3793
3794     while (it != pfrom->vRecvGetData.end()) {
3795         // Don't bother if send buffer is too full to respond anyway
3796         if (pfrom->nSendSize >= SendBufferSize())
3797             break;
3798
3799         const CInv &inv = *it;
3800         {
3801             boost::this_thread::interruption_point();
3802             it++;
3803
3804             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3805             {
3806                 bool send = false;
3807                 BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
3808                 if (mi != mapBlockIndex.end())
3809                 {
3810                     if (chainActive.Contains(mi->second)) {
3811                         send = true;
3812                     } else {
3813                         static const int nOneMonth = 30 * 24 * 60 * 60;
3814                         // To prevent fingerprinting attacks, only send blocks outside of the active
3815                         // chain if they are valid, and no more than a month older (both in time, and in
3816                         // best equivalent proof of work) than the best header chain we know about.
3817                         send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
3818                             (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
3819                             (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth);
3820                         if (!send) {
3821                             LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
3822                         }
3823                     }
3824                 }
3825                 // Pruned nodes may have deleted the block, so check whether
3826                 // it's available before trying to send.
3827                 if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
3828                 {
3829                     // Send block from disk
3830                     CBlock block;
3831                     if (!ReadBlockFromDisk(block, (*mi).second))
3832                         assert(!"cannot load block from disk");
3833                     if (inv.type == MSG_BLOCK)
3834                         pfrom->PushMessage("block", block);
3835                     else // MSG_FILTERED_BLOCK)
3836                     {
3837                         LOCK(pfrom->cs_filter);
3838                         if (pfrom->pfilter)
3839                         {
3840                             CMerkleBlock merkleBlock(block, *pfrom->pfilter);
3841                             pfrom->PushMessage("merkleblock", merkleBlock);
3842                             // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
3843                             // This avoids hurting performance by pointlessly requiring a round-trip
3844                             // Note that there is currently no way for a node to request any single transactions we didn't send here -
3845                             // they must either disconnect and retry or request the full block.
3846                             // Thus, the protocol spec specified allows for us to provide duplicate txn here,
3847                             // however we MUST always provide at least what the remote peer needs
3848                             typedef std::pair<unsigned int, uint256> PairType;
3849                             BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
3850                                 if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
3851                                     pfrom->PushMessage("tx", block.vtx[pair.first]);
3852                         }
3853                         // else
3854                             // no response
3855                     }
3856
3857                     // Trigger the peer node to send a getblocks request for the next batch of inventory
3858                     if (inv.hash == pfrom->hashContinue)
3859                     {
3860                         // Bypass PushInventory, this must send even if redundant,
3861                         // and we want it right after the last block so they don't
3862                         // wait for other stuff first.
3863                         vector<CInv> vInv;
3864                         vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
3865                         pfrom->PushMessage("inv", vInv);
3866                         pfrom->hashContinue.SetNull();
3867                     }
3868                 }
3869             }
3870             else if (inv.IsKnownType())
3871             {
3872                 // Send stream from relay memory
3873                 bool pushed = false;
3874                 {
3875                     LOCK(cs_mapRelay);
3876                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3877                     if (mi != mapRelay.end()) {
3878                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3879                         pushed = true;
3880                     }
3881                 }
3882                 if (!pushed && inv.type == MSG_TX) {
3883                     CTransaction tx;
3884                     if (mempool.lookup(inv.hash, tx)) {
3885                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3886                         ss.reserve(1000);
3887                         ss << tx;
3888                         pfrom->PushMessage("tx", ss);
3889                         pushed = true;
3890                     }
3891                 }
3892                 if (!pushed) {
3893                     vNotFound.push_back(inv);
3894                 }
3895             }
3896
3897             // Track requests for our stuff.
3898             GetMainSignals().Inventory(inv.hash);
3899
3900             if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
3901                 break;
3902         }
3903     }
3904
3905     pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
3906
3907     if (!vNotFound.empty()) {
3908         // Let the peer know that we didn't find what it asked for, so it doesn't
3909         // have to wait around forever. Currently only SPV clients actually care
3910         // about this message: it's needed when they are recursively walking the
3911         // dependencies of relevant unconfirmed transactions. SPV clients want to
3912         // do that because they want to know about (and store and rebroadcast and
3913         // risk analyze) the dependencies of transactions relevant to them, without
3914         // having to download the entire memory pool.
3915         pfrom->PushMessage("notfound", vNotFound);
3916     }
3917 }
3918
3919 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
3920 {
3921     const CChainParams& chainparams = Params();
3922     RandAddSeedPerfmon();
3923     LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
3924     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3925     {
3926         LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
3927         return true;
3928     }
3929
3930
3931
3932
3933     if (strCommand == "version")
3934     {
3935         // Each connection can only send one version message
3936         if (pfrom->nVersion != 0)
3937         {
3938             pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
3939             Misbehaving(pfrom->GetId(), 1);
3940             return false;
3941         }
3942
3943         int64_t nTime;
3944         CAddress addrMe;
3945         CAddress addrFrom;
3946         uint64_t nNonce = 1;
3947         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3948         if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
3949         {
3950             // disconnect from peers older than this proto version
3951             LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
3952             pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
3953                                strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
3954             pfrom->fDisconnect = true;
3955             return false;
3956         }
3957
3958         if (pfrom->nVersion == 10300)
3959             pfrom->nVersion = 300;
3960         if (!vRecv.empty())
3961             vRecv >> addrFrom >> nNonce;
3962         if (!vRecv.empty()) {
3963             vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
3964             pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
3965         }
3966         if (!vRecv.empty())
3967             vRecv >> pfrom->nStartingHeight;
3968         if (!vRecv.empty())
3969             vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
3970         else
3971             pfrom->fRelayTxes = true;
3972
3973         // Disconnect if we connected to ourself
3974         if (nNonce == nLocalHostNonce && nNonce > 1)
3975         {
3976             LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
3977             pfrom->fDisconnect = true;
3978             return true;
3979         }
3980
3981         pfrom->addrLocal = addrMe;
3982         if (pfrom->fInbound && addrMe.IsRoutable())
3983         {
3984             SeenLocal(addrMe);
3985         }
3986
3987         // Be shy and don't send version until we hear
3988         if (pfrom->fInbound)
3989             pfrom->PushVersion();
3990
3991         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3992
3993         // Potentially mark this peer as a preferred download peer.
3994         UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
3995
3996         // Change version
3997         pfrom->PushMessage("verack");
3998         pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3999
4000         if (!pfrom->fInbound)
4001         {
4002             // Advertise our address
4003             if (fListen && !IsInitialBlockDownload())
4004             {
4005                 CAddress addr = GetLocalAddress(&pfrom->addr);
4006                 if (addr.IsRoutable())
4007                 {
4008                     pfrom->PushAddress(addr);
4009                 } else if (IsPeerAddrLocalGood(pfrom)) {
4010                     addr.SetIP(pfrom->addrLocal);
4011                     pfrom->PushAddress(addr);
4012                 }
4013             }
4014
4015             // Get recent addresses
4016             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
4017             {
4018                 pfrom->PushMessage("getaddr");
4019                 pfrom->fGetAddr = true;
4020             }
4021             addrman.Good(pfrom->addr);
4022         } else {
4023             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
4024             {
4025                 addrman.Add(addrFrom, addrFrom);
4026                 addrman.Good(addrFrom);
4027             }
4028         }
4029
4030         // Relay alerts
4031         {
4032             LOCK(cs_mapAlerts);
4033             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
4034                 item.second.RelayTo(pfrom);
4035         }
4036
4037         pfrom->fSuccessfullyConnected = true;
4038
4039         string remoteAddr;
4040         if (fLogIPs)
4041             remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
4042
4043         LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
4044                   pfrom->cleanSubVer, pfrom->nVersion,
4045                   pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
4046                   remoteAddr);
4047
4048         int64_t nTimeOffset = nTime - GetTime();
4049         pfrom->nTimeOffset = nTimeOffset;
4050         AddTimeData(pfrom->addr, nTimeOffset);
4051     }
4052
4053
4054     else if (pfrom->nVersion == 0)
4055     {
4056         // Must have a version message before anything else
4057         Misbehaving(pfrom->GetId(), 1);
4058         return false;
4059     }
4060
4061
4062     else if (strCommand == "verack")
4063     {
4064         pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
4065
4066         // Mark this node as currently connected, so we update its timestamp later.
4067         if (pfrom->fNetworkNode) {
4068             LOCK(cs_main);
4069             State(pfrom->GetId())->fCurrentlyConnected = true;
4070         }
4071     }
4072
4073
4074     else if (strCommand == "addr")
4075     {
4076         vector<CAddress> vAddr;
4077         vRecv >> vAddr;
4078
4079         // Don't want addr from older versions unless seeding
4080         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
4081             return true;
4082         if (vAddr.size() > 1000)
4083         {
4084             Misbehaving(pfrom->GetId(), 20);
4085             return error("message addr size() = %u", vAddr.size());
4086         }
4087
4088         // Store the new addresses
4089         vector<CAddress> vAddrOk;
4090         int64_t nNow = GetAdjustedTime();
4091         int64_t nSince = nNow - 10 * 60;
4092         BOOST_FOREACH(CAddress& addr, vAddr)
4093         {
4094             boost::this_thread::interruption_point();
4095
4096             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
4097                 addr.nTime = nNow - 5 * 24 * 60 * 60;
4098             pfrom->AddAddressKnown(addr);
4099             bool fReachable = IsReachable(addr);
4100             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
4101             {
4102                 // Relay to a limited number of other nodes
4103                 {
4104                     LOCK(cs_vNodes);
4105                     // Use deterministic randomness to send to the same nodes for 24 hours
4106                     // at a time so the addrKnowns of the chosen nodes prevent repeats
4107                     static uint256 hashSalt;
4108                     if (hashSalt.IsNull())
4109                         hashSalt = GetRandHash();
4110                     uint64_t hashAddr = addr.GetHash();
4111                     uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
4112                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4113                     multimap<uint256, CNode*> mapMix;
4114                     BOOST_FOREACH(CNode* pnode, vNodes)
4115                     {
4116                         if (pnode->nVersion < CADDR_TIME_VERSION)
4117                             continue;
4118                         unsigned int nPointer;
4119                         memcpy(&nPointer, &pnode, sizeof(nPointer));
4120                         uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
4121                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
4122                         mapMix.insert(make_pair(hashKey, pnode));
4123                     }
4124                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
4125                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
4126                         ((*mi).second)->PushAddress(addr);
4127                 }
4128             }
4129             // Do not store addresses outside our network
4130             if (fReachable)
4131                 vAddrOk.push_back(addr);
4132         }
4133         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
4134         if (vAddr.size() < 1000)
4135             pfrom->fGetAddr = false;
4136         if (pfrom->fOneShot)
4137             pfrom->fDisconnect = true;
4138     }
4139
4140
4141     else if (strCommand == "inv")
4142     {
4143         vector<CInv> vInv;
4144         vRecv >> vInv;
4145         if (vInv.size() > MAX_INV_SZ)
4146         {
4147             Misbehaving(pfrom->GetId(), 20);
4148             return error("message inv size() = %u", vInv.size());
4149         }
4150
4151         LOCK(cs_main);
4152
4153         std::vector<CInv> vToFetch;
4154
4155         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
4156         {
4157             const CInv &inv = vInv[nInv];
4158
4159             boost::this_thread::interruption_point();
4160             pfrom->AddInventoryKnown(inv);
4161
4162             bool fAlreadyHave = AlreadyHave(inv);
4163             LogPrint("net", "got inv: %s  %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
4164
4165             if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
4166                 pfrom->AskFor(inv);
4167
4168             if (inv.type == MSG_BLOCK) {
4169                 UpdateBlockAvailability(pfrom->GetId(), inv.hash);
4170                 if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
4171                     // First request the headers preceding the announced block. In the normal fully-synced
4172                     // case where a new block is announced that succeeds the current tip (no reorganization),
4173                     // there are no such headers.
4174                     // Secondly, and only when we are close to being synced, we request the announced block directly,
4175                     // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
4176                     // time the block arrives, the header chain leading up to it is already validated. Not
4177                     // doing this will result in the received block being rejected as an orphan in case it is
4178                     // not a direct successor.
4179                     pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
4180                     CNodeState *nodestate = State(pfrom->GetId());
4181                     if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
4182                         nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
4183                         vToFetch.push_back(inv);
4184                         // Mark block as in flight already, even though the actual "getdata" message only goes out
4185                         // later (within the same cs_main lock, though).
4186                         MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
4187                     }
4188                     LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
4189                 }
4190             }
4191
4192             // Track requests for our stuff
4193             GetMainSignals().Inventory(inv.hash);
4194
4195             if (pfrom->nSendSize > (SendBufferSize() * 2)) {
4196                 Misbehaving(pfrom->GetId(), 50);
4197                 return error("send buffer size() = %u", pfrom->nSendSize);
4198             }
4199         }
4200
4201         if (!vToFetch.empty())
4202             pfrom->PushMessage("getdata", vToFetch);
4203     }
4204
4205
4206     else if (strCommand == "getdata")
4207     {
4208         vector<CInv> vInv;
4209         vRecv >> vInv;
4210         if (vInv.size() > MAX_INV_SZ)
4211         {
4212             Misbehaving(pfrom->GetId(), 20);
4213             return error("message getdata size() = %u", vInv.size());
4214         }
4215
4216         if (fDebug || (vInv.size() != 1))
4217             LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
4218
4219         if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
4220             LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
4221
4222         pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
4223         ProcessGetData(pfrom);
4224     }
4225
4226
4227     else if (strCommand == "getblocks")
4228     {
4229         CBlockLocator locator;
4230         uint256 hashStop;
4231         vRecv >> locator >> hashStop;
4232
4233         LOCK(cs_main);
4234
4235         // Find the last block the caller has in the main chain
4236         CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
4237
4238         // Send the rest of the chain
4239         if (pindex)
4240             pindex = chainActive.Next(pindex);
4241         int nLimit = 500;
4242         LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
4243         for (; pindex; pindex = chainActive.Next(pindex))
4244         {
4245             if (pindex->GetBlockHash() == hashStop)
4246             {
4247                 LogPrint("net", "  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4248                 break;
4249             }
4250             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
4251             if (--nLimit <= 0)
4252             {
4253                 // When this block is requested, we'll send an inv that'll
4254                 // trigger the peer to getblocks the next batch of inventory.
4255                 LogPrint("net", "  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
4256                 pfrom->hashContinue = pindex->GetBlockHash();
4257                 break;
4258             }
4259         }
4260     }
4261
4262
4263     else if (strCommand == "getheaders")
4264     {
4265         CBlockLocator locator;
4266         uint256 hashStop;
4267         vRecv >> locator >> hashStop;
4268
4269         LOCK(cs_main);
4270
4271         CBlockIndex* pindex = NULL;
4272         if (locator.IsNull())
4273         {
4274             // If locator is null, return the hashStop block
4275             BlockMap::iterator mi = mapBlockIndex.find(hashStop);
4276             if (mi == mapBlockIndex.end())
4277                 return true;
4278             pindex = (*mi).second;
4279         }
4280         else
4281         {
4282             // Find the last block the caller has in the main chain
4283             pindex = FindForkInGlobalIndex(chainActive, locator);
4284             if (pindex)
4285                 pindex = chainActive.Next(pindex);
4286         }
4287
4288         // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
4289         vector<CBlock> vHeaders;
4290         int nLimit = MAX_HEADERS_RESULTS;
4291         LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
4292         for (; pindex; pindex = chainActive.Next(pindex))
4293         {
4294             vHeaders.push_back(pindex->GetBlockHeader());
4295             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
4296                 break;
4297         }
4298         pfrom->PushMessage("headers", vHeaders);
4299     }
4300
4301
4302     else if (strCommand == "tx")
4303     {
4304         vector<uint256> vWorkQueue;
4305         vector<uint256> vEraseQueue;
4306         CTransaction tx;
4307         vRecv >> tx;
4308
4309         CInv inv(MSG_TX, tx.GetHash());
4310         pfrom->AddInventoryKnown(inv);
4311
4312         LOCK(cs_main);
4313
4314         bool fMissingInputs = false;
4315         CValidationState state;
4316
4317         mapAlreadyAskedFor.erase(inv);
4318
4319         if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
4320         {
4321             mempool.check(pcoinsTip);
4322             RelayTransaction(tx);
4323             vWorkQueue.push_back(inv.hash);
4324             vEraseQueue.push_back(inv.hash);
4325
4326             LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
4327                 pfrom->id, pfrom->cleanSubVer,
4328                 tx.GetHash().ToString(),
4329                 mempool.mapTx.size());
4330
4331             // Recursively process any orphan transactions that depended on this one
4332             set<NodeId> setMisbehaving;
4333             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
4334             {
4335                 map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
4336                 if (itByPrev == mapOrphanTransactionsByPrev.end())
4337                     continue;
4338                 for (set<uint256>::iterator mi = itByPrev->second.begin();
4339                      mi != itByPrev->second.end();
4340                      ++mi)
4341                 {
4342                     const uint256& orphanHash = *mi;
4343                     const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
4344                     NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
4345                     bool fMissingInputs2 = false;
4346                     // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
4347                     // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
4348                     // anyone relaying LegitTxX banned)
4349                     CValidationState stateDummy;
4350
4351                     vEraseQueue.push_back(orphanHash);
4352
4353                     if (setMisbehaving.count(fromPeer))
4354                         continue;
4355                     if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
4356                     {
4357                         LogPrint("mempool", "   accepted orphan tx %s\n", orphanHash.ToString());
4358                         RelayTransaction(orphanTx);
4359                         vWorkQueue.push_back(orphanHash);
4360                     }
4361                     else if (!fMissingInputs2)
4362                     {
4363                         int nDos = 0;
4364                         if (stateDummy.IsInvalid(nDos) && nDos > 0)
4365                         {
4366                             // Punish peer that gave us an invalid orphan tx
4367                             Misbehaving(fromPeer, nDos);
4368                             setMisbehaving.insert(fromPeer);
4369                             LogPrint("mempool", "   invalid orphan tx %s\n", orphanHash.ToString());
4370                         }
4371                         // too-little-fee orphan
4372                         LogPrint("mempool", "   removed orphan tx %s\n", orphanHash.ToString());
4373                     }
4374                     mempool.check(pcoinsTip);
4375                 }
4376             }
4377
4378             BOOST_FOREACH(uint256 hash, vEraseQueue)
4379                 EraseOrphanTx(hash);
4380         }
4381         else if (fMissingInputs)
4382         {
4383             AddOrphanTx(tx, pfrom->GetId());
4384
4385             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4386             unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
4387             unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
4388             if (nEvicted > 0)
4389                 LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
4390         } else if (pfrom->fWhitelisted) {
4391             // Always relay transactions received from whitelisted peers, even
4392             // if they are already in the mempool (allowing the node to function
4393             // as a gateway for nodes hidden behind it).
4394             RelayTransaction(tx);
4395         }
4396         int nDoS = 0;
4397         if (state.IsInvalid(nDoS))
4398         {
4399             LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
4400                 pfrom->id, pfrom->cleanSubVer,
4401                 state.GetRejectReason());
4402             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4403                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4404             if (nDoS > 0)
4405                 Misbehaving(pfrom->GetId(), nDoS);
4406         }
4407     }
4408
4409
4410     else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
4411     {
4412         std::vector<CBlockHeader> headers;
4413
4414         // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
4415         unsigned int nCount = ReadCompactSize(vRecv);
4416         if (nCount > MAX_HEADERS_RESULTS) {
4417             Misbehaving(pfrom->GetId(), 20);
4418             return error("headers message size = %u", nCount);
4419         }
4420         headers.resize(nCount);
4421         for (unsigned int n = 0; n < nCount; n++) {
4422             vRecv >> headers[n];
4423             ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
4424         }
4425
4426         LOCK(cs_main);
4427
4428         if (nCount == 0) {
4429             // Nothing interesting. Stop asking this peers for more headers.
4430             return true;
4431         }
4432
4433         CBlockIndex *pindexLast = NULL;
4434         BOOST_FOREACH(const CBlockHeader& header, headers) {
4435             CValidationState state;
4436             if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
4437                 Misbehaving(pfrom->GetId(), 20);
4438                 return error("non-continuous headers sequence");
4439             }
4440             if (!AcceptBlockHeader(header, state, &pindexLast)) {
4441                 int nDoS;
4442                 if (state.IsInvalid(nDoS)) {
4443                     if (nDoS > 0)
4444                         Misbehaving(pfrom->GetId(), nDoS);
4445                     return error("invalid header received");
4446                 }
4447             }
4448         }
4449
4450         if (pindexLast)
4451             UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
4452
4453         if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
4454             // Headers message had its maximum size; the peer may have more headers.
4455             // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
4456             // from there instead.
4457             LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
4458             pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
4459         }
4460
4461         CheckBlockIndex();
4462     }
4463
4464     else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
4465     {
4466         CBlock block;
4467         vRecv >> block;
4468
4469         CInv inv(MSG_BLOCK, block.GetHash());
4470         LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
4471
4472         pfrom->AddInventoryKnown(inv);
4473
4474         CValidationState state;
4475         ProcessNewBlock(state, pfrom, &block);
4476         int nDoS;
4477         if (state.IsInvalid(nDoS)) {
4478             pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
4479                                state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
4480             if (nDoS > 0) {
4481                 LOCK(cs_main);
4482                 Misbehaving(pfrom->GetId(), nDoS);
4483             }
4484         }
4485
4486     }
4487
4488
4489     // This asymmetric behavior for inbound and outbound connections was introduced
4490     // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4491     // to users' AddrMan and later request them by sending getaddr messages.
4492     // Making nodes which are behind NAT and can only make outgoing connections ignore
4493     // the getaddr message mitigates the attack.
4494     else if ((strCommand == "getaddr") && (pfrom->fInbound))
4495     {
4496         pfrom->vAddrToSend.clear();
4497         vector<CAddress> vAddr = addrman.GetAddr();
4498         BOOST_FOREACH(const CAddress &addr, vAddr)
4499             pfrom->PushAddress(addr);
4500     }
4501
4502
4503     else if (strCommand == "mempool")
4504     {
4505         LOCK2(cs_main, pfrom->cs_filter);
4506
4507         std::vector<uint256> vtxid;
4508         mempool.queryHashes(vtxid);
4509         vector<CInv> vInv;
4510         BOOST_FOREACH(uint256& hash, vtxid) {
4511             CInv inv(MSG_TX, hash);
4512             CTransaction tx;
4513             bool fInMemPool = mempool.lookup(hash, tx);
4514             if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
4515             if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
4516                (!pfrom->pfilter))
4517                 vInv.push_back(inv);
4518             if (vInv.size() == MAX_INV_SZ) {
4519                 pfrom->PushMessage("inv", vInv);
4520                 vInv.clear();
4521             }
4522         }
4523         if (vInv.size() > 0)
4524             pfrom->PushMessage("inv", vInv);
4525     }
4526
4527
4528     else if (strCommand == "ping")
4529     {
4530         if (pfrom->nVersion > BIP0031_VERSION)
4531         {
4532             uint64_t nonce = 0;
4533             vRecv >> nonce;
4534             // Echo the message back with the nonce. This allows for two useful features:
4535             //
4536             // 1) A remote node can quickly check if the connection is operational
4537             // 2) Remote nodes can measure the latency of the network thread. If this node
4538             //    is overloaded it won't respond to pings quickly and the remote node can
4539             //    avoid sending us more work, like chain download requests.
4540             //
4541             // The nonce stops the remote getting confused between different pings: without
4542             // it, if the remote node sends a ping once per second and this node takes 5
4543             // seconds to respond to each, the 5th ping the remote sends would appear to
4544             // return very quickly.
4545             pfrom->PushMessage("pong", nonce);
4546         }
4547     }
4548
4549
4550     else if (strCommand == "pong")
4551     {
4552         int64_t pingUsecEnd = nTimeReceived;
4553         uint64_t nonce = 0;
4554         size_t nAvail = vRecv.in_avail();
4555         bool bPingFinished = false;
4556         std::string sProblem;
4557
4558         if (nAvail >= sizeof(nonce)) {
4559             vRecv >> nonce;
4560
4561             // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
4562             if (pfrom->nPingNonceSent != 0) {
4563                 if (nonce == pfrom->nPingNonceSent) {
4564                     // Matching pong received, this ping is no longer outstanding
4565                     bPingFinished = true;
4566                     int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
4567                     if (pingUsecTime > 0) {
4568                         // Successful ping time measurement, replace previous
4569                         pfrom->nPingUsecTime = pingUsecTime;
4570                     } else {
4571                         // This should never happen
4572                         sProblem = "Timing mishap";
4573                     }
4574                 } else {
4575                     // Nonce mismatches are normal when pings are overlapping
4576                     sProblem = "Nonce mismatch";
4577                     if (nonce == 0) {
4578                         // This is most likely a bug in another implementation somewhere; cancel this ping
4579                         bPingFinished = true;
4580                         sProblem = "Nonce zero";
4581                     }
4582                 }
4583             } else {
4584                 sProblem = "Unsolicited pong without ping";
4585             }
4586         } else {
4587             // This is most likely a bug in another implementation somewhere; cancel this ping
4588             bPingFinished = true;
4589             sProblem = "Short payload";
4590         }
4591
4592         if (!(sProblem.empty())) {
4593             LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
4594                 pfrom->id,
4595                 pfrom->cleanSubVer,
4596                 sProblem,
4597                 pfrom->nPingNonceSent,
4598                 nonce,
4599                 nAvail);
4600         }
4601         if (bPingFinished) {
4602             pfrom->nPingNonceSent = 0;
4603         }
4604     }
4605
4606
4607     else if (strCommand == "alert")
4608     {
4609         CAlert alert;
4610         vRecv >> alert;
4611
4612         uint256 alertHash = alert.GetHash();
4613         if (pfrom->setKnown.count(alertHash) == 0)
4614         {
4615             if (alert.ProcessAlert(Params().AlertKey()))
4616             {
4617                 // Relay
4618                 pfrom->setKnown.insert(alertHash);
4619                 {
4620                     LOCK(cs_vNodes);
4621                     BOOST_FOREACH(CNode* pnode, vNodes)
4622                         alert.RelayTo(pnode);
4623                 }
4624             }
4625             else {
4626                 // Small DoS penalty so peers that send us lots of
4627                 // duplicate/expired/invalid-signature/whatever alerts
4628                 // eventually get banned.
4629                 // This isn't a Misbehaving(100) (immediate ban) because the
4630                 // peer might be an older or different implementation with
4631                 // a different signature key, etc.
4632                 Misbehaving(pfrom->GetId(), 10);
4633             }
4634         }
4635     }
4636
4637
4638     else if (strCommand == "filterload")
4639     {
4640         CBloomFilter filter;
4641         vRecv >> filter;
4642
4643         if (!filter.IsWithinSizeConstraints())
4644             // There is no excuse for sending a too-large filter
4645             Misbehaving(pfrom->GetId(), 100);
4646         else
4647         {
4648             LOCK(pfrom->cs_filter);
4649             delete pfrom->pfilter;
4650             pfrom->pfilter = new CBloomFilter(filter);
4651             pfrom->pfilter->UpdateEmptyFull();
4652         }
4653         pfrom->fRelayTxes = true;
4654     }
4655
4656
4657     else if (strCommand == "filteradd")
4658     {
4659         vector<unsigned char> vData;
4660         vRecv >> vData;
4661
4662         // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
4663         // and thus, the maximum size any matched object can have) in a filteradd message
4664         if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
4665         {
4666             Misbehaving(pfrom->GetId(), 100);
4667         } else {
4668             LOCK(pfrom->cs_filter);
4669             if (pfrom->pfilter)
4670                 pfrom->pfilter->insert(vData);
4671             else
4672                 Misbehaving(pfrom->GetId(), 100);
4673         }
4674     }
4675
4676
4677     else if (strCommand == "filterclear")
4678     {
4679         LOCK(pfrom->cs_filter);
4680         delete pfrom->pfilter;
4681         pfrom->pfilter = new CBloomFilter();
4682         pfrom->fRelayTxes = true;
4683     }
4684
4685
4686     else if (strCommand == "reject")
4687     {
4688         if (fDebug) {
4689             try {
4690                 string strMsg; unsigned char ccode; string strReason;
4691                 vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
4692
4693                 ostringstream ss;
4694                 ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
4695
4696                 if (strMsg == "block" || strMsg == "tx")
4697                 {
4698                     uint256 hash;
4699                     vRecv >> hash;
4700                     ss << ": hash " << hash.ToString();
4701                 }
4702                 LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
4703             } catch (const std::ios_base::failure&) {
4704                 // Avoid feedback loops by preventing reject messages from triggering a new reject message.
4705                 LogPrint("net", "Unparseable reject message received\n");
4706             }
4707         }
4708     }
4709
4710     else
4711     {
4712         // Ignore unknown commands for extensibility
4713         LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
4714     }
4715
4716
4717
4718     return true;
4719 }
4720
4721 // requires LOCK(cs_vRecvMsg)
4722 bool ProcessMessages(CNode* pfrom)
4723 {
4724     //if (fDebug)
4725     //    LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
4726
4727     //
4728     // Message format
4729     //  (4) message start
4730     //  (12) command
4731     //  (4) size
4732     //  (4) checksum
4733     //  (x) data
4734     //
4735     bool fOk = true;
4736
4737     if (!pfrom->vRecvGetData.empty())
4738         ProcessGetData(pfrom);
4739
4740     // this maintains the order of responses
4741     if (!pfrom->vRecvGetData.empty()) return fOk;
4742
4743     std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
4744     while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
4745         // Don't bother if send buffer is too full to respond anyway
4746         if (pfrom->nSendSize >= SendBufferSize())
4747             break;
4748
4749         // get next message
4750         CNetMessage& msg = *it;
4751
4752         //if (fDebug)
4753         //    LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
4754         //            msg.hdr.nMessageSize, msg.vRecv.size(),
4755         //            msg.complete() ? "Y" : "N");
4756
4757         // end, if an incomplete message is found
4758         if (!msg.complete())
4759             break;
4760
4761         // at this point, any failure means we can delete the current message
4762         it++;
4763
4764         // Scan for message start
4765         if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
4766             LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
4767             fOk = false;
4768             break;
4769         }
4770
4771         // Read header
4772         CMessageHeader& hdr = msg.hdr;
4773         if (!hdr.IsValid(Params().MessageStart()))
4774         {
4775             LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
4776             continue;
4777         }
4778         string strCommand = hdr.GetCommand();
4779
4780         // Message size
4781         unsigned int nMessageSize = hdr.nMessageSize;
4782
4783         // Checksum
4784         CDataStream& vRecv = msg.vRecv;
4785         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4786         unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
4787         if (nChecksum != hdr.nChecksum)
4788         {
4789             LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
4790                SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
4791             continue;
4792         }
4793
4794         // Process message
4795         bool fRet = false;
4796         try
4797         {
4798             fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
4799             boost::this_thread::interruption_point();
4800         }
4801         catch (const std::ios_base::failure& e)
4802         {
4803             pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
4804             if (strstr(e.what(), "end of data"))
4805             {
4806                 // Allow exceptions from under-length message on vRecv
4807                 LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4808             }
4809             else if (strstr(e.what(), "size too large"))
4810             {
4811                 // Allow exceptions from over-long size
4812                 LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
4813             }
4814             else
4815             {
4816                 PrintExceptionContinue(&e, "ProcessMessages()");
4817             }
4818         }
4819         catch (const boost::thread_interrupted&) {
4820             throw;
4821         }
4822         catch (const std::exception& e) {
4823             PrintExceptionContinue(&e, "ProcessMessages()");
4824         } catch (...) {
4825             PrintExceptionContinue(NULL, "ProcessMessages()");
4826         }
4827
4828         if (!fRet)
4829             LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
4830
4831         break;
4832     }
4833
4834     // In case the connection got shut down, its receive buffer was wiped
4835     if (!pfrom->fDisconnect)
4836         pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
4837
4838     return fOk;
4839 }
4840
4841
4842 bool SendMessages(CNode* pto, bool fSendTrickle)
4843 {
4844     const Consensus::Params& consensusParams = Params().GetConsensus();
4845     {
4846         // Don't send anything until we get its version message
4847         if (pto->nVersion == 0)
4848             return true;
4849
4850         //
4851         // Message: ping
4852         //
4853         bool pingSend = false;
4854         if (pto->fPingQueued) {
4855             // RPC ping request by user
4856             pingSend = true;
4857         }
4858         if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
4859             // Ping automatically sent as a latency probe & keepalive.
4860             pingSend = true;
4861         }
4862         if (pingSend) {
4863             uint64_t nonce = 0;
4864             while (nonce == 0) {
4865                 GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
4866             }
4867             pto->fPingQueued = false;
4868             pto->nPingUsecStart = GetTimeMicros();
4869             if (pto->nVersion > BIP0031_VERSION) {
4870                 pto->nPingNonceSent = nonce;
4871                 pto->PushMessage("ping", nonce);
4872             } else {
4873                 // Peer is too old to support ping command with nonce, pong will never arrive.
4874                 pto->nPingNonceSent = 0;
4875                 pto->PushMessage("ping");
4876             }
4877         }
4878
4879         TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
4880         if (!lockMain)
4881             return true;
4882
4883         // Address refresh broadcast
4884         static int64_t nLastRebroadcast;
4885         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4886         {
4887             LOCK(cs_vNodes);
4888             BOOST_FOREACH(CNode* pnode, vNodes)
4889             {
4890                 // Periodically clear addrKnown to allow refresh broadcasts
4891                 if (nLastRebroadcast)
4892                     pnode->addrKnown.clear();
4893
4894                 // Rebroadcast our address
4895                 AdvertizeLocal(pnode);
4896             }
4897             if (!vNodes.empty())
4898                 nLastRebroadcast = GetTime();
4899         }
4900
4901         //
4902         // Message: addr
4903         //
4904         if (fSendTrickle)
4905         {
4906             vector<CAddress> vAddr;
4907             vAddr.reserve(pto->vAddrToSend.size());
4908             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4909             {
4910                 if (!pto->addrKnown.contains(addr.GetKey()))
4911                 {
4912                     pto->addrKnown.insert(addr.GetKey());
4913                     vAddr.push_back(addr);
4914                     // receiver rejects addr messages larger than 1000
4915                     if (vAddr.size() >= 1000)
4916                     {
4917                         pto->PushMessage("addr", vAddr);
4918                         vAddr.clear();
4919                     }
4920                 }
4921             }
4922             pto->vAddrToSend.clear();
4923             if (!vAddr.empty())
4924                 pto->PushMessage("addr", vAddr);
4925         }
4926
4927         CNodeState &state = *State(pto->GetId());
4928         if (state.fShouldBan) {
4929             if (pto->fWhitelisted)
4930                 LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
4931             else {
4932                 pto->fDisconnect = true;
4933                 if (pto->addr.IsLocal())
4934                     LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
4935                 else
4936                 {
4937                     CNode::Ban(pto->addr);
4938                 }
4939             }
4940             state.fShouldBan = false;
4941         }
4942
4943         BOOST_FOREACH(const CBlockReject& reject, state.rejects)
4944             pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
4945         state.rejects.clear();
4946
4947         // Start block sync
4948         if (pindexBestHeader == NULL)
4949             pindexBestHeader = chainActive.Tip();
4950         bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
4951         if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
4952             // Only actively request headers from a single peer, unless we're close to today.
4953             if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
4954                 state.fSyncStarted = true;
4955                 nSyncStarted++;
4956                 CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
4957                 LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
4958                 pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
4959             }
4960         }
4961
4962         // Resend wallet transactions that haven't gotten in a block yet
4963         // Except during reindex, importing and IBD, when old wallet
4964         // transactions become unconfirmed and spams other nodes.
4965         if (!fReindex && !fImporting && !IsInitialBlockDownload())
4966         {
4967             GetMainSignals().Broadcast(nTimeBestReceived);
4968         }
4969
4970         //
4971         // Message: inventory
4972         //
4973         vector<CInv> vInv;
4974         vector<CInv> vInvWait;
4975         {
4976             LOCK(pto->cs_inventory);
4977             vInv.reserve(pto->vInventoryToSend.size());
4978             vInvWait.reserve(pto->vInventoryToSend.size());
4979             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4980             {
4981                 if (pto->setInventoryKnown.count(inv))
4982                     continue;
4983
4984                 // trickle out tx inv to protect privacy
4985                 if (inv.type == MSG_TX && !fSendTrickle)
4986                 {
4987                     // 1/4 of tx invs blast to all immediately
4988                     static uint256 hashSalt;
4989                     if (hashSalt.IsNull())
4990                         hashSalt = GetRandHash();
4991                     uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
4992                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4993                     bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
4994
4995                     if (fTrickleWait)
4996                     {
4997                         vInvWait.push_back(inv);
4998                         continue;
4999                     }
5000                 }
5001
5002                 // returns true if wasn't already contained in the set
5003                 if (pto->setInventoryKnown.insert(inv).second)
5004                 {
5005                     vInv.push_back(inv);
5006                     if (vInv.size() >= 1000)
5007                     {
5008                         pto->PushMessage("inv", vInv);
5009                         vInv.clear();
5010                     }
5011                 }
5012             }
5013             pto->vInventoryToSend = vInvWait;
5014         }
5015         if (!vInv.empty())
5016             pto->PushMessage("inv", vInv);
5017
5018         // Detect whether we're stalling
5019         int64_t nNow = GetTimeMicros();
5020         if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
5021             // Stalling only triggers when the block download window cannot move. During normal steady state,
5022             // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
5023             // should only happen during initial block download.
5024             LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
5025             pto->fDisconnect = true;
5026         }
5027         // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
5028         // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
5029         // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
5030         // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
5031         // to unreasonably increase our timeout.
5032         // We also compare the block download timeout originally calculated against the time at which we'd disconnect
5033         // if we assumed the block were being requested now (ignoring blocks we've requested from this peer, since we're
5034         // only looking at this peer's oldest request).  This way a large queue in the past doesn't result in a
5035         // permanently large window for this block to be delivered (ie if the number of blocks in flight is decreasing
5036         // more quickly than once every 5 minutes, then we'll shorten the download window for this block).
5037         if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0) {
5038             QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
5039             int64_t nTimeoutIfRequestedNow = GetBlockTimeout(nNow, nQueuedValidatedHeaders - state.nBlocksInFlightValidHeaders);
5040             if (queuedBlock.nTimeDisconnect > nTimeoutIfRequestedNow) {
5041                 LogPrint("net", "Reducing block download timeout for peer=%d block=%s, orig=%d new=%d\n", pto->id, queuedBlock.hash.ToString(), queuedBlock.nTimeDisconnect, nTimeoutIfRequestedNow);
5042                 queuedBlock.nTimeDisconnect = nTimeoutIfRequestedNow;
5043             }
5044             if (queuedBlock.nTimeDisconnect < nNow) {
5045                 LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
5046                 pto->fDisconnect = true;
5047             }
5048         }
5049
5050         //
5051         // Message: getdata (blocks)
5052         //
5053         vector<CInv> vGetData;
5054         if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
5055             vector<CBlockIndex*> vToDownload;
5056             NodeId staller = -1;
5057             FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
5058             BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
5059                 vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
5060                 MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
5061                 LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
5062                     pindex->nHeight, pto->id);
5063             }
5064             if (state.nBlocksInFlight == 0 && staller != -1) {
5065                 if (State(staller)->nStallingSince == 0) {
5066                     State(staller)->nStallingSince = nNow;
5067                     LogPrint("net", "Stall started peer=%d\n", staller);
5068                 }
5069             }
5070         }
5071
5072         //
5073         // Message: getdata (non-blocks)
5074         //
5075         while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
5076         {
5077             const CInv& inv = (*pto->mapAskFor.begin()).second;
5078             if (!AlreadyHave(inv))
5079             {
5080                 if (fDebug)
5081                     LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
5082                 vGetData.push_back(inv);
5083                 if (vGetData.size() >= 1000)
5084                 {
5085                     pto->PushMessage("getdata", vGetData);
5086                     vGetData.clear();
5087                 }
5088             }
5089             pto->mapAskFor.erase(pto->mapAskFor.begin());
5090         }
5091         if (!vGetData.empty())
5092             pto->PushMessage("getdata", vGetData);
5093
5094     }
5095     return true;
5096 }
5097
5098  std::string CBlockFileInfo::ToString() const {
5099      return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
5100  }
5101
5102
5103
5104 class CMainCleanup
5105 {
5106 public:
5107     CMainCleanup() {}
5108     ~CMainCleanup() {
5109         // block headers
5110         BlockMap::iterator it1 = mapBlockIndex.begin();
5111         for (; it1 != mapBlockIndex.end(); it1++)
5112             delete (*it1).second;
5113         mapBlockIndex.clear();
5114
5115         // orphan transactions
5116         mapOrphanTransactions.clear();
5117         mapOrphanTransactionsByPrev.clear();
5118     }
5119 } instance_of_cmaincleanup;
This page took 0.320212 seconds and 4 git commands to generate.