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