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