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