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