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