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