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