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