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