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