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