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