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