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