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