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