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