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