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