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