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