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