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