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