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