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