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