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