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