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