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