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