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