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