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