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