Revert "Use standard C99 (and Qt) types for 64-bit integers"
[novacoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "checkpoints.h"
7 #include "db.h"
8 #include "net.h"
9 #include "init.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12
13 using namespace std;
14 using namespace boost;
15
16 //
17 // Global state
18 //
19
20 // Name of client reported in the 'version' message. Report the same name
21 // for both bitcoind and bitcoin-qt, to make it harder for attackers to
22 // target servers or GUI users specifically.
23 const std::string CLIENT_NAME("bitcoin-qt");
24
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
27
28 CCriticalSection cs_main;
29
30 static map<uint256, CTransaction> mapTransactions;
31 CCriticalSection cs_mapTransactions;
32 unsigned int nTransactionsUpdated = 0;
33 map<COutPoint, CInPoint> mapNextTx;
34
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
37 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
38 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
39 CBlockIndex* pindexGenesisBlock = NULL;
40 int nBestHeight = -1;
41 CBigNum bnBestChainWork = 0;
42 CBigNum bnBestInvalidWork = 0;
43 uint256 hashBestChain = 0;
44 CBlockIndex* pindexBest = NULL;
45 int64 nTimeBestReceived = 0;
46
47 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
48
49 map<uint256, CBlock*> mapOrphanBlocks;
50 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
51
52 map<uint256, CDataStream*> mapOrphanTransactions;
53 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
54
55
56 double dHashesPerSec;
57 int64 nHPSTimerStart;
58
59 // Settings
60 int fGenerateBitcoins = false;
61 int64 nTransactionFee = 0;
62 int fLimitProcessors = false;
63 int nLimitProcessors = 1;
64 int fMinimizeToTray = true;
65 int fMinimizeOnClose = true;
66 #if USE_UPNP
67 int fUseUPnP = true;
68 #else
69 int fUseUPnP = false;
70 #endif
71
72
73 //////////////////////////////////////////////////////////////////////////////
74 //
75 // dispatching functions
76 //
77
78 // These functions dispatch to one or all registered wallets
79
80
81 void RegisterWallet(CWallet* pwalletIn)
82 {
83     CRITICAL_BLOCK(cs_setpwalletRegistered)
84     {
85         setpwalletRegistered.insert(pwalletIn);
86     }
87 }
88
89 void UnregisterWallet(CWallet* pwalletIn)
90 {
91     CRITICAL_BLOCK(cs_setpwalletRegistered)
92     {
93         setpwalletRegistered.erase(pwalletIn);
94     }
95 }
96
97 // check whether the passed transaction is from us
98 bool static IsFromMe(CTransaction& tx)
99 {
100     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
101         if (pwallet->IsFromMe(tx))
102             return true;
103     return false;
104 }
105
106 // get the wallet transaction with the given hash (if it exists)
107 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
108 {
109     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
110         if (pwallet->GetTransaction(hashTx,wtx))
111             return true;
112     return false;
113 }
114
115 // erases transaction with the given hash from all wallets
116 void static EraseFromWallets(uint256 hash)
117 {
118     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119         pwallet->EraseFromWallet(hash);
120 }
121
122 // make sure all wallets know about the given transaction, in the given block
123 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
124 {
125     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
127 }
128
129 // notify wallets about a new best chain
130 void static SetBestChain(const CBlockLocator& loc)
131 {
132     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133         pwallet->SetBestChain(loc);
134 }
135
136 // notify wallets about an updated transaction
137 void static UpdatedTransaction(const uint256& hashTx)
138 {
139     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140         pwallet->UpdatedTransaction(hashTx);
141 }
142
143 // dump all wallets
144 void static PrintWallets(const CBlock& block)
145 {
146     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147         pwallet->PrintWallet(block);
148 }
149
150 // notify wallets about an incoming inventory (for request counts)
151 void static Inventory(const uint256& hash)
152 {
153     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154         pwallet->Inventory(hash);
155 }
156
157 // ask wallets to resend their transactions
158 void static ResendWalletTransactions()
159 {
160     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161         pwallet->ResendWalletTransactions();
162 }
163
164
165
166
167
168
169
170 //////////////////////////////////////////////////////////////////////////////
171 //
172 // mapOrphanTransactions
173 //
174
175 void static AddOrphanTx(const CDataStream& vMsg)
176 {
177     CTransaction tx;
178     CDataStream(vMsg) >> tx;
179     uint256 hash = tx.GetHash();
180     if (mapOrphanTransactions.count(hash))
181         return;
182     CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
183     BOOST_FOREACH(const CTxIn& txin, tx.vin)
184         mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
185 }
186
187 void static EraseOrphanTx(uint256 hash)
188 {
189     if (!mapOrphanTransactions.count(hash))
190         return;
191     const CDataStream* pvMsg = mapOrphanTransactions[hash];
192     CTransaction tx;
193     CDataStream(*pvMsg) >> tx;
194     BOOST_FOREACH(const CTxIn& txin, tx.vin)
195     {
196         for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
197              mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
198         {
199             if ((*mi).second == pvMsg)
200                 mapOrphanTransactionsByPrev.erase(mi++);
201             else
202                 mi++;
203         }
204     }
205     delete pvMsg;
206     mapOrphanTransactions.erase(hash);
207 }
208
209
210
211
212
213
214
215
216 //////////////////////////////////////////////////////////////////////////////
217 //
218 // CTransaction and CTxIndex
219 //
220
221 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
222 {
223     SetNull();
224     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
225         return false;
226     if (!ReadFromDisk(txindexRet.pos))
227         return false;
228     if (prevout.n >= vout.size())
229     {
230         SetNull();
231         return false;
232     }
233     return true;
234 }
235
236 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
237 {
238     CTxIndex txindex;
239     return ReadFromDisk(txdb, prevout, txindex);
240 }
241
242 bool CTransaction::ReadFromDisk(COutPoint prevout)
243 {
244     CTxDB txdb("r");
245     CTxIndex txindex;
246     return ReadFromDisk(txdb, prevout, txindex);
247 }
248
249 bool CTransaction::IsStandard() const
250 {
251     BOOST_FOREACH(const CTxIn& txin, vin)
252     {
253         // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
254         // in an OP_EVAL, which is 3 ~80-byte signatures, 3
255         // ~65-byte public keys, plus a few script ops.
256         if (txin.scriptSig.size() > 500)
257             return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
258         if (!txin.scriptSig.IsPushOnly())
259             return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
260     }
261     BOOST_FOREACH(const CTxOut& txout, vout)
262         if (!::IsStandard(txout.scriptPubKey))
263             return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
264     return true;
265 }
266
267 //
268 // Check transaction inputs, and make sure any
269 // OP_EVAL transactions are evaluating IsStandard scripts
270 //
271 // Why bother? To avoid denial-of-service attacks; an attacker
272 // can submit a standard DUP HASH... OP_EVAL transaction,
273 // which will get accepted into blocks. The script being
274 // EVAL'ed can be anything; an attacker could use a very
275 // expensive-to-check-upon-redemption script like:
276 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
277 //
278 bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
279 {
280     if (fTestNet)
281         return true; // Allow non-standard on testnet
282
283     for (int i = 0; i < vin.size(); i++)
284     {
285         COutPoint prevout = vin[i].prevout;
286         assert(mapInputs.count(prevout.hash) > 0);
287         CTransaction& txPrev = mapInputs[prevout.hash].second;
288
289         vector<vector<unsigned char> > vSolutions;
290         txnouttype whichType;
291         // get the scriptPubKey corresponding to this input:
292         CScript& prevScript = txPrev.vout[prevout.n].scriptPubKey;
293         if (!Solver(prevScript, whichType, vSolutions))
294             return error("nonstandard txin (spending nonstandard txout %s)", prevScript.ToString().c_str());
295         if (whichType == TX_SCRIPTHASH)
296         {
297             vector<vector<unsigned char> > stack;
298             int nUnused;
299             if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, true, nUnused))
300                 return false;
301             CScript subscript(stack.back().begin(), stack.back().end());
302             if (!::IsStandard(subscript))
303                 return error("nonstandard txin (nonstandard OP_EVAL subscript %s)", subscript.ToString().c_str());
304         }
305     }
306
307     return true;
308 }
309
310
311
312 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
313 {
314     if (fClient)
315     {
316         if (hashBlock == 0)
317             return 0;
318     }
319     else
320     {
321         CBlock blockTmp;
322         if (pblock == NULL)
323         {
324             // Load the block this tx is in
325             CTxIndex txindex;
326             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
327                 return 0;
328             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
329                 return 0;
330             pblock = &blockTmp;
331         }
332
333         // Update the tx's hashBlock
334         hashBlock = pblock->GetHash();
335
336         // Locate the transaction
337         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
338             if (pblock->vtx[nIndex] == *(CTransaction*)this)
339                 break;
340         if (nIndex == pblock->vtx.size())
341         {
342             vMerkleBranch.clear();
343             nIndex = -1;
344             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
345             return 0;
346         }
347
348         // Fill in merkle branch
349         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
350     }
351
352     // Is the tx in a block that's in the main chain
353     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
354     if (mi == mapBlockIndex.end())
355         return 0;
356     CBlockIndex* pindex = (*mi).second;
357     if (!pindex || !pindex->IsInMainChain())
358         return 0;
359
360     return pindexBest->nHeight - pindex->nHeight + 1;
361 }
362
363
364
365
366
367
368
369 bool CTransaction::CheckTransaction() const
370 {
371     // Basic checks that don't depend on any context
372     if (vin.empty())
373         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
374     if (vout.empty())
375         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
376     // Size limits
377     if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
378         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
379
380     // Check for negative or overflow output values
381     int64 nValueOut = 0;
382     BOOST_FOREACH(const CTxOut& txout, vout)
383     {
384         if (txout.nValue < 0)
385             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
386         if (txout.nValue > MAX_MONEY)
387             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
388         nValueOut += txout.nValue;
389         if (!MoneyRange(nValueOut))
390             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
391     }
392
393     // Check for duplicate inputs
394     set<COutPoint> vInOutPoints;
395     BOOST_FOREACH(const CTxIn& txin, vin)
396     {
397         if (vInOutPoints.count(txin.prevout))
398             return false;
399         vInOutPoints.insert(txin.prevout);
400     }
401
402     if (IsCoinBase())
403     {
404         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
405             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
406     }
407     else
408     {
409         BOOST_FOREACH(const CTxIn& txin, vin)
410             if (txin.prevout.IsNull())
411                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
412     }
413
414     return true;
415 }
416
417 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
418 {
419     if (pfMissingInputs)
420         *pfMissingInputs = false;
421
422     if (!CheckTransaction())
423         return error("AcceptToMemoryPool() : CheckTransaction failed");
424
425     // Coinbase is only valid in a block, not as a loose transaction
426     if (IsCoinBase())
427         return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
428
429     // To help v0.1.5 clients who would see it as a negative number
430     if ((int64)nLockTime > std::numeric_limits<int>::max())
431         return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
432
433     // Rather not work on nonstandard transactions (unless -testnet)
434     if (!fTestNet && !IsStandard())
435         return error("AcceptToMemoryPool() : nonstandard transaction type");
436
437     // Do we already have it?
438     uint256 hash = GetHash();
439     CRITICAL_BLOCK(cs_mapTransactions)
440         if (mapTransactions.count(hash))
441             return false;
442     if (fCheckInputs)
443         if (txdb.ContainsTx(hash))
444             return false;
445
446     // Check for conflicts with in-memory transactions
447     CTransaction* ptxOld = NULL;
448     for (int i = 0; i < vin.size(); i++)
449     {
450         COutPoint outpoint = vin[i].prevout;
451         if (mapNextTx.count(outpoint))
452         {
453             // Disable replacement feature for now
454             return false;
455
456             // Allow replacing with a newer version of the same transaction
457             if (i != 0)
458                 return false;
459             ptxOld = mapNextTx[outpoint].ptx;
460             if (ptxOld->IsFinal())
461                 return false;
462             if (!IsNewerThan(*ptxOld))
463                 return false;
464             for (int i = 0; i < vin.size(); i++)
465             {
466                 COutPoint outpoint = vin[i].prevout;
467                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
468                     return false;
469             }
470             break;
471         }
472     }
473
474     if (fCheckInputs)
475     {
476         map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
477         map<uint256, CTxIndex> mapUnused;
478         if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
479         {
480             if (pfMissingInputs)
481                 *pfMissingInputs = true;
482             return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
483         }
484
485         // Check for non-standard OP_EVALs in inputs
486         if (!AreInputsStandard(mapInputs))
487             return error("AcceptToMemoryPool() : nonstandard transaction input");
488
489         // Check against previous transactions
490         int64 nFees = 0;
491         int nSigOps = 0;
492         if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
493         {
494             if (pfMissingInputs)
495                 *pfMissingInputs = true;
496             return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
497         }
498         // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
499         // attacks disallow transactions with more than one SigOp per 65 bytes.
500         // 65 bytes because that is the minimum size of an ECDSA signature
501         unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
502         if (nSigOps > nSize / 65 || nSize < 100)
503             return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
504
505         // Don't accept it if it can't get into a block
506         if (nFees < GetMinFee(1000, true, GMF_RELAY))
507             return error("AcceptToMemoryPool() : not enough fees");
508
509         // Continuously rate-limit free transactions
510         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
511         // be annoying or make other's transactions take longer to confirm.
512         if (nFees < MIN_RELAY_TX_FEE)
513         {
514             static CCriticalSection cs;
515             static double dFreeCount;
516             static int64 nLastTime;
517             int64 nNow = GetTime();
518
519             CRITICAL_BLOCK(cs)
520             {
521                 // Use an exponentially decaying ~10-minute window:
522                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
523                 nLastTime = nNow;
524                 // -limitfreerelay unit is thousand-bytes-per-minute
525                 // At default rate it would take over a month to fill 1GB
526                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
527                     return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
528                 if (fDebug)
529                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
530                 dFreeCount += nSize;
531             }
532         }
533     }
534
535     // Store transaction in memory
536     CRITICAL_BLOCK(cs_mapTransactions)
537     {
538         if (ptxOld)
539         {
540             printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
541             ptxOld->RemoveFromMemoryPool();
542         }
543         AddToMemoryPoolUnchecked();
544     }
545
546     ///// are we sure this is ok when loading transactions or restoring block txes
547     // If updated, erase old tx from wallet
548     if (ptxOld)
549         EraseFromWallets(ptxOld->GetHash());
550
551     printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
552     return true;
553 }
554
555 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
556 {
557     CTxDB txdb("r");
558     return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
559 }
560
561 bool CTransaction::AddToMemoryPoolUnchecked()
562 {
563     // Add to memory pool without checking anything.  Don't call this directly,
564     // call AcceptToMemoryPool to properly check the transaction first.
565     CRITICAL_BLOCK(cs_mapTransactions)
566     {
567         uint256 hash = GetHash();
568         mapTransactions[hash] = *this;
569         for (int i = 0; i < vin.size(); i++)
570             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
571         nTransactionsUpdated++;
572     }
573     return true;
574 }
575
576
577 bool CTransaction::RemoveFromMemoryPool()
578 {
579     // Remove transaction from memory pool
580     CRITICAL_BLOCK(cs_mapTransactions)
581     {
582         BOOST_FOREACH(const CTxIn& txin, vin)
583             mapNextTx.erase(txin.prevout);
584         mapTransactions.erase(GetHash());
585         nTransactionsUpdated++;
586     }
587     return true;
588 }
589
590
591
592
593
594
595 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
596 {
597     if (hashBlock == 0 || nIndex == -1)
598         return 0;
599
600     // Find the block it claims to be in
601     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
602     if (mi == mapBlockIndex.end())
603         return 0;
604     CBlockIndex* pindex = (*mi).second;
605     if (!pindex || !pindex->IsInMainChain())
606         return 0;
607
608     // Make sure the merkle branch connects to this block
609     if (!fMerkleVerified)
610     {
611         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
612             return 0;
613         fMerkleVerified = true;
614     }
615
616     pindexRet = pindex;
617     return pindexBest->nHeight - pindex->nHeight + 1;
618 }
619
620
621 int CMerkleTx::GetBlocksToMaturity() const
622 {
623     if (!IsCoinBase())
624         return 0;
625     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
626 }
627
628
629 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
630 {
631     if (fClient)
632     {
633         if (!IsInMainChain() && !ClientConnectInputs())
634             return false;
635         return CTransaction::AcceptToMemoryPool(txdb, false);
636     }
637     else
638     {
639         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
640     }
641 }
642
643 bool CMerkleTx::AcceptToMemoryPool()
644 {
645     CTxDB txdb("r");
646     return AcceptToMemoryPool(txdb);
647 }
648
649
650
651 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
652 {
653     CRITICAL_BLOCK(cs_mapTransactions)
654     {
655         // Add previous supporting transactions first
656         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
657         {
658             if (!tx.IsCoinBase())
659             {
660                 uint256 hash = tx.GetHash();
661                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
662                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
663             }
664         }
665         return AcceptToMemoryPool(txdb, fCheckInputs);
666     }
667     return false;
668 }
669
670 bool CWalletTx::AcceptWalletTransaction() 
671 {
672     CTxDB txdb("r");
673     return AcceptWalletTransaction(txdb);
674 }
675
676 int CTxIndex::GetDepthInMainChain() const
677 {
678     // Read block header
679     CBlock block;
680     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
681         return 0;
682     // Find the block in the index
683     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
684     if (mi == mapBlockIndex.end())
685         return 0;
686     CBlockIndex* pindex = (*mi).second;
687     if (!pindex || !pindex->IsInMainChain())
688         return 0;
689     return 1 + nBestHeight - pindex->nHeight;
690 }
691
692
693
694
695
696
697
698
699
700
701 //////////////////////////////////////////////////////////////////////////////
702 //
703 // CBlock and CBlockIndex
704 //
705
706 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
707 {
708     if (!fReadTransactions)
709     {
710         *this = pindex->GetBlockHeader();
711         return true;
712     }
713     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
714         return false;
715     if (GetHash() != pindex->GetBlockHash())
716         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
717     return true;
718 }
719
720 uint256 static GetOrphanRoot(const CBlock* pblock)
721 {
722     // Work back to the first block in the orphan chain
723     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
724         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
725     return pblock->GetHash();
726 }
727
728 int64 static GetBlockValue(int nHeight, int64 nFees)
729 {
730     int64 nSubsidy = 50 * COIN;
731
732     // Subsidy is cut in half every 4 years
733     nSubsidy >>= (nHeight / 210000);
734
735     return nSubsidy + nFees;
736 }
737
738 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
739 static const int64 nTargetSpacing = 10 * 60;
740 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
741
742 //
743 // minimum amount of work that could possibly be required nTime after
744 // minimum work required was nBase
745 //
746 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
747 {
748     CBigNum bnResult;
749     bnResult.SetCompact(nBase);
750     while (nTime > 0 && bnResult < bnProofOfWorkLimit)
751     {
752         // Maximum 400% adjustment...
753         bnResult *= 4;
754         // ... in best-case exactly 4-times-normal target time
755         nTime -= nTargetTimespan*4;
756     }
757     if (bnResult > bnProofOfWorkLimit)
758         bnResult = bnProofOfWorkLimit;
759     return bnResult.GetCompact();
760 }
761
762 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
763 {
764
765     // Genesis block
766     if (pindexLast == NULL)
767         return bnProofOfWorkLimit.GetCompact();
768
769     // Only change once per interval
770     if ((pindexLast->nHeight+1) % nInterval != 0)
771         return pindexLast->nBits;
772
773     // Go back by what we want to be 14 days worth of blocks
774     const CBlockIndex* pindexFirst = pindexLast;
775     for (int i = 0; pindexFirst && i < nInterval-1; i++)
776         pindexFirst = pindexFirst->pprev;
777     assert(pindexFirst);
778
779     // Limit adjustment step
780     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
781     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
782     if (nActualTimespan < nTargetTimespan/4)
783         nActualTimespan = nTargetTimespan/4;
784     if (nActualTimespan > nTargetTimespan*4)
785         nActualTimespan = nTargetTimespan*4;
786
787     // Retarget
788     CBigNum bnNew;
789     bnNew.SetCompact(pindexLast->nBits);
790     bnNew *= nActualTimespan;
791     bnNew /= nTargetTimespan;
792
793     if (bnNew > bnProofOfWorkLimit)
794         bnNew = bnProofOfWorkLimit;
795
796     /// debug print
797     printf("GetNextWorkRequired RETARGET\n");
798     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
799     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
800     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
801
802     return bnNew.GetCompact();
803 }
804
805 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
806 {
807     CBigNum bnTarget;
808     bnTarget.SetCompact(nBits);
809
810     // Check range
811     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
812         return error("CheckProofOfWork() : nBits below minimum work");
813
814     // Check proof of work matches claimed amount
815     if (hash > bnTarget.getuint256())
816         return error("CheckProofOfWork() : hash doesn't match nBits");
817
818     return true;
819 }
820
821 // Return maximum amount of blocks that other nodes claim to have
822 int GetNumBlocksOfPeers()
823 {
824     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
825 }
826
827 bool IsInitialBlockDownload()
828 {
829     if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
830         return true;
831     static int64 nLastUpdate;
832     static CBlockIndex* pindexLastBest;
833     if (pindexBest != pindexLastBest)
834     {
835         pindexLastBest = pindexBest;
836         nLastUpdate = GetTime();
837     }
838     return (GetTime() - nLastUpdate < 10 &&
839             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
840 }
841
842 void static InvalidChainFound(CBlockIndex* pindexNew)
843 {
844     if (pindexNew->bnChainWork > bnBestInvalidWork)
845     {
846         bnBestInvalidWork = pindexNew->bnChainWork;
847         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
848         MainFrameRepaint();
849     }
850     printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
851     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
852     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
853         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
854 }
855
856
857
858
859
860
861
862
863
864
865
866 bool CTransaction::DisconnectInputs(CTxDB& txdb)
867 {
868     // Relinquish previous transactions' spent pointers
869     if (!IsCoinBase())
870     {
871         BOOST_FOREACH(const CTxIn& txin, vin)
872         {
873             COutPoint prevout = txin.prevout;
874
875             // Get prev txindex from disk
876             CTxIndex txindex;
877             if (!txdb.ReadTxIndex(prevout.hash, txindex))
878                 return error("DisconnectInputs() : ReadTxIndex failed");
879
880             if (prevout.n >= txindex.vSpent.size())
881                 return error("DisconnectInputs() : prevout.n out of range");
882
883             // Mark outpoint as not spent
884             txindex.vSpent[prevout.n].SetNull();
885
886             // Write back
887             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
888                 return error("DisconnectInputs() : UpdateTxIndex failed");
889         }
890     }
891
892     // Remove transaction from index
893     if (!txdb.EraseTxIndex(*this))
894         return error("DisconnectInputs() : EraseTxPos failed");
895
896     return true;
897 }
898
899
900 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
901                                bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
902 {
903     if (IsCoinBase())
904         return true; // Coinbase transactions have no inputs to fetch.
905
906     for (int i = 0; i < vin.size(); i++)
907     {
908         COutPoint prevout = vin[i].prevout;
909         if (inputsRet.count(prevout.hash))
910             continue; // Got it already
911
912         // Read txindex
913         CTxIndex& txindex = inputsRet[prevout.hash].first;
914         bool fFound = true;
915         if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
916         {
917             // Get txindex from current proposed changes
918             txindex = mapTestPool.find(prevout.hash)->second;
919         }
920         else
921         {
922             // Read txindex from txdb
923             fFound = txdb.ReadTxIndex(prevout.hash, txindex);
924         }
925         if (!fFound && (fBlock || fMiner))
926             return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
927
928         // Read txPrev
929         CTransaction& txPrev = inputsRet[prevout.hash].second;
930         if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
931         {
932             // Get prev tx from single transactions in memory
933             CRITICAL_BLOCK(cs_mapTransactions)
934             {
935                 if (!mapTransactions.count(prevout.hash))
936                     return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
937                 txPrev = mapTransactions[prevout.hash];
938             }
939             if (!fFound)
940                 txindex.vSpent.resize(txPrev.vout.size());
941         }
942         else
943         {
944             // Get prev tx from disk
945             if (!txPrev.ReadFromDisk(txindex.pos))
946                 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
947         }
948     }
949     return true;
950 }
951
952 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
953                                  map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
954                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
955 {
956     // Take over previous transactions' spent pointers
957     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
958     // fMiner is true when called from the internal bitcoin miner
959     // ... both are false when called from CTransaction::AcceptToMemoryPool
960     if (!IsCoinBase())
961     {
962         int64 nValueIn = 0;
963         for (int i = 0; i < vin.size(); i++)
964         {
965             COutPoint prevout = vin[i].prevout;
966             assert(inputs.count(prevout.hash) > 0);
967             CTxIndex& txindex = inputs[prevout.hash].first;
968             CTransaction& txPrev = inputs[prevout.hash].second;
969
970             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
971                 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
972
973             // If prev is coinbase, check that it's matured
974             if (txPrev.IsCoinBase())
975                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
976                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
977                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
978
979             // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
980             // (before the last blockchain checkpoint). This is safe because block merkle hashes are
981             // still computed and checked, and any change will be caught at the next checkpoint.
982             if (!(fBlock && IsInitialBlockDownload()))
983             {
984                 bool fStrictOpEval = true;
985                 // This code should be removed when OP_EVAL has
986                 // a majority of hashing power on the network.
987                 if (fBlock)
988                 {
989                     // To avoid being on the short end of a block-chain split,
990                     // interpret OP_EVAL as a NO_OP until blocks with timestamps
991                     // after opevaltime:
992                     int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
993                     fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
994                 }
995                 // if !fBlock, then always be strict-- don't accept
996                 // invalid-under-new-rules OP_EVAL transactions into
997                 // our memory pool (don't relay them, don't include them
998                 // in blocks we mine).
999
1000                 // Verify signature
1001                 if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
1002                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1003             }
1004
1005             // Check for conflicts (double-spend)
1006             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1007             // for an attacker to attempt to split the network.
1008             if (!txindex.vSpent[prevout.n].IsNull())
1009                 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1010
1011             // Check for negative or overflow input values
1012             nValueIn += txPrev.vout[prevout.n].nValue;
1013             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1014                 return DoS(100, error("ConnectInputs() : txin values out of range"));
1015
1016             // Mark outpoints as spent
1017             txindex.vSpent[prevout.n] = posThisTx;
1018
1019             // Write back
1020             if (fBlock || fMiner)
1021             {
1022                 mapTestPool[prevout.hash] = txindex;
1023             }
1024         }
1025
1026         if (nValueIn < GetValueOut())
1027             return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1028
1029         // Tally transaction fees
1030         int64 nTxFee = nValueIn - GetValueOut();
1031         if (nTxFee < 0)
1032             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1033         if (nTxFee < nMinFee)
1034             return false;
1035         nFees += nTxFee;
1036         if (!MoneyRange(nFees))
1037             return DoS(100, error("ConnectInputs() : nFees out of range"));
1038     }
1039
1040     if (fBlock)
1041     {
1042         // Add transaction to changes
1043         mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1044     }
1045     else if (fMiner)
1046     {
1047         // Add transaction to test pool
1048         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1049     }
1050
1051     return true;
1052 }
1053
1054
1055 bool CTransaction::ClientConnectInputs()
1056 {
1057     if (IsCoinBase())
1058         return false;
1059
1060     // Take over previous transactions' spent pointers
1061     CRITICAL_BLOCK(cs_mapTransactions)
1062     {
1063         int64 nValueIn = 0;
1064         for (int i = 0; i < vin.size(); i++)
1065         {
1066             // Get prev tx from single transactions in memory
1067             COutPoint prevout = vin[i].prevout;
1068             if (!mapTransactions.count(prevout.hash))
1069                 return false;
1070             CTransaction& txPrev = mapTransactions[prevout.hash];
1071
1072             if (prevout.n >= txPrev.vout.size())
1073                 return false;
1074
1075             // Verify signature
1076             int nUnused = 0;
1077             if (!VerifySignature(txPrev, *this, i, nUnused, false))
1078                 return error("ConnectInputs() : VerifySignature failed");
1079
1080             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1081             ///// this has to go away now that posNext is gone
1082             // // Check for conflicts
1083             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1084             //     return error("ConnectInputs() : prev tx already used");
1085             //
1086             // // Flag outpoints as used
1087             // txPrev.vout[prevout.n].posNext = posThisTx;
1088
1089             nValueIn += txPrev.vout[prevout.n].nValue;
1090
1091             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1092                 return error("ClientConnectInputs() : txin values out of range");
1093         }
1094         if (GetValueOut() > nValueIn)
1095             return false;
1096     }
1097
1098     return true;
1099 }
1100
1101
1102
1103
1104 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1105 {
1106     // Disconnect in reverse order
1107     for (int i = vtx.size()-1; i >= 0; i--)
1108         if (!vtx[i].DisconnectInputs(txdb))
1109             return false;
1110
1111     // Update block index on disk without changing it in memory.
1112     // The memory index structure will be changed after the db commits.
1113     if (pindex->pprev)
1114     {
1115         CDiskBlockIndex blockindexPrev(pindex->pprev);
1116         blockindexPrev.hashNext = 0;
1117         if (!txdb.WriteBlockIndex(blockindexPrev))
1118             return error("DisconnectBlock() : WriteBlockIndex failed");
1119     }
1120
1121     return true;
1122 }
1123
1124 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1125 {
1126     // Check it again in case a previous version let a bad block in
1127     if (!CheckBlock())
1128         return false;
1129
1130     //// issue here: it doesn't know the version
1131     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1132
1133     map<uint256, CTxIndex> mapQueuedChanges;
1134     int64 nFees = 0;
1135     int nSigOps = 0;
1136     BOOST_FOREACH(CTransaction& tx, vtx)
1137     {
1138         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1139         nTxPos += ::GetSerializeSize(tx, SER_DISK);
1140
1141         map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1142         if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1143             return false;
1144         if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1145             return false;
1146         if (nSigOps > MAX_BLOCK_SIGOPS)
1147             return DoS(100, error("ConnectBlock() : too many sigops"));
1148     }
1149
1150     // Write queued txindex changes
1151     for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1152     {
1153         if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1154             return error("ConnectBlock() : UpdateTxIndex failed");
1155     }
1156
1157     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1158         return false;
1159
1160     // Update block index on disk without changing it in memory.
1161     // The memory index structure will be changed after the db commits.
1162     if (pindex->pprev)
1163     {
1164         CDiskBlockIndex blockindexPrev(pindex->pprev);
1165         blockindexPrev.hashNext = pindex->GetBlockHash();
1166         if (!txdb.WriteBlockIndex(blockindexPrev))
1167             return error("ConnectBlock() : WriteBlockIndex failed");
1168     }
1169
1170     // Watch for transactions paying to me
1171     BOOST_FOREACH(CTransaction& tx, vtx)
1172         SyncWithWallets(tx, this, true);
1173
1174     return true;
1175 }
1176
1177 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1178 {
1179     printf("REORGANIZE\n");
1180
1181     // Find the fork
1182     CBlockIndex* pfork = pindexBest;
1183     CBlockIndex* plonger = pindexNew;
1184     while (pfork != plonger)
1185     {
1186         while (plonger->nHeight > pfork->nHeight)
1187             if (!(plonger = plonger->pprev))
1188                 return error("Reorganize() : plonger->pprev is null");
1189         if (pfork == plonger)
1190             break;
1191         if (!(pfork = pfork->pprev))
1192             return error("Reorganize() : pfork->pprev is null");
1193     }
1194
1195     // List of what to disconnect
1196     vector<CBlockIndex*> vDisconnect;
1197     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1198         vDisconnect.push_back(pindex);
1199
1200     // List of what to connect
1201     vector<CBlockIndex*> vConnect;
1202     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1203         vConnect.push_back(pindex);
1204     reverse(vConnect.begin(), vConnect.end());
1205
1206     // Disconnect shorter branch
1207     vector<CTransaction> vResurrect;
1208     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1209     {
1210         CBlock block;
1211         if (!block.ReadFromDisk(pindex))
1212             return error("Reorganize() : ReadFromDisk for disconnect failed");
1213         if (!block.DisconnectBlock(txdb, pindex))
1214             return error("Reorganize() : DisconnectBlock failed");
1215
1216         // Queue memory transactions to resurrect
1217         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1218             if (!tx.IsCoinBase())
1219                 vResurrect.push_back(tx);
1220     }
1221
1222     // Connect longer branch
1223     vector<CTransaction> vDelete;
1224     for (int i = 0; i < vConnect.size(); i++)
1225     {
1226         CBlockIndex* pindex = vConnect[i];
1227         CBlock block;
1228         if (!block.ReadFromDisk(pindex))
1229             return error("Reorganize() : ReadFromDisk for connect failed");
1230         if (!block.ConnectBlock(txdb, pindex))
1231         {
1232             // Invalid block
1233             txdb.TxnAbort();
1234             return error("Reorganize() : ConnectBlock failed");
1235         }
1236
1237         // Queue memory transactions to delete
1238         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1239             vDelete.push_back(tx);
1240     }
1241     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1242         return error("Reorganize() : WriteHashBestChain failed");
1243
1244     // Make sure it's successfully written to disk before changing memory structure
1245     if (!txdb.TxnCommit())
1246         return error("Reorganize() : TxnCommit failed");
1247
1248     // Disconnect shorter branch
1249     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1250         if (pindex->pprev)
1251             pindex->pprev->pnext = NULL;
1252
1253     // Connect longer branch
1254     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1255         if (pindex->pprev)
1256             pindex->pprev->pnext = pindex;
1257
1258     // Resurrect memory transactions that were in the disconnected branch
1259     BOOST_FOREACH(CTransaction& tx, vResurrect)
1260         tx.AcceptToMemoryPool(txdb, false);
1261
1262     // Delete redundant memory transactions that are in the connected branch
1263     BOOST_FOREACH(CTransaction& tx, vDelete)
1264         tx.RemoveFromMemoryPool();
1265
1266     return true;
1267 }
1268
1269
1270 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1271 {
1272     uint256 hash = GetHash();
1273
1274     txdb.TxnBegin();
1275     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1276     {
1277         txdb.WriteHashBestChain(hash);
1278         if (!txdb.TxnCommit())
1279             return error("SetBestChain() : TxnCommit failed");
1280         pindexGenesisBlock = pindexNew;
1281     }
1282     else if (hashPrevBlock == hashBestChain)
1283     {
1284         // Adding to current best branch
1285         if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1286         {
1287             txdb.TxnAbort();
1288             InvalidChainFound(pindexNew);
1289             return error("SetBestChain() : ConnectBlock failed");
1290         }
1291         if (!txdb.TxnCommit())
1292             return error("SetBestChain() : TxnCommit failed");
1293
1294         // Add to current best branch
1295         pindexNew->pprev->pnext = pindexNew;
1296
1297         // Delete redundant memory transactions
1298         BOOST_FOREACH(CTransaction& tx, vtx)
1299             tx.RemoveFromMemoryPool();
1300     }
1301     else
1302     {
1303         // New best branch
1304         if (!Reorganize(txdb, pindexNew))
1305         {
1306             txdb.TxnAbort();
1307             InvalidChainFound(pindexNew);
1308             return error("SetBestChain() : Reorganize failed");
1309         }
1310     }
1311
1312     // Update best block in wallet (so we can detect restored wallets)
1313     if (!IsInitialBlockDownload())
1314     {
1315         const CBlockLocator locator(pindexNew);
1316         ::SetBestChain(locator);
1317     }
1318
1319     // New best block
1320     hashBestChain = hash;
1321     pindexBest = pindexNew;
1322     nBestHeight = pindexBest->nHeight;
1323     bnBestChainWork = pindexNew->bnChainWork;
1324     nTimeBestReceived = GetTime();
1325     nTransactionsUpdated++;
1326     printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1327
1328     return true;
1329 }
1330
1331
1332 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1333 {
1334     // Check for duplicate
1335     uint256 hash = GetHash();
1336     if (mapBlockIndex.count(hash))
1337         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1338
1339     // Construct new block index object
1340     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1341     if (!pindexNew)
1342         return error("AddToBlockIndex() : new CBlockIndex failed");
1343     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1344     pindexNew->phashBlock = &((*mi).first);
1345     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1346     if (miPrev != mapBlockIndex.end())
1347     {
1348         pindexNew->pprev = (*miPrev).second;
1349         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1350     }
1351     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1352
1353     CTxDB txdb;
1354     txdb.TxnBegin();
1355     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1356     if (!txdb.TxnCommit())
1357         return false;
1358
1359     // New best
1360     if (pindexNew->bnChainWork > bnBestChainWork)
1361         if (!SetBestChain(txdb, pindexNew))
1362             return false;
1363
1364     txdb.Close();
1365
1366     if (pindexNew == pindexBest)
1367     {
1368         // Notify UI to display prev block's coinbase if it was ours
1369         static uint256 hashPrevBestCoinBase;
1370         UpdatedTransaction(hashPrevBestCoinBase);
1371         hashPrevBestCoinBase = vtx[0].GetHash();
1372     }
1373
1374     MainFrameRepaint();
1375     return true;
1376 }
1377
1378
1379
1380
1381 bool CBlock::CheckBlock() const
1382 {
1383     // These are checks that are independent of context
1384     // that can be verified before saving an orphan block.
1385
1386     // Size limits
1387     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1388         return DoS(100, error("CheckBlock() : size limits failed"));
1389
1390     // Check proof of work matches claimed amount
1391     if (!CheckProofOfWork(GetHash(), nBits))
1392         return DoS(50, error("CheckBlock() : proof of work failed"));
1393
1394     // Check timestamp
1395     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1396         return error("CheckBlock() : block timestamp too far in the future");
1397
1398     // First transaction must be coinbase, the rest must not be
1399     if (vtx.empty() || !vtx[0].IsCoinBase())
1400         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1401     for (int i = 1; i < vtx.size(); i++)
1402         if (vtx[i].IsCoinBase())
1403             return DoS(100, error("CheckBlock() : more than one coinbase"));
1404
1405     // Check transactions
1406     BOOST_FOREACH(const CTransaction& tx, vtx)
1407         if (!tx.CheckTransaction())
1408             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1409
1410     // This code should be removed when a compatibility-breaking block chain split has passed.
1411     // Compatibility check for old clients that counted sigops differently:
1412     int nSigOps = 0;
1413     BOOST_FOREACH(const CTransaction& tx, vtx)
1414     {
1415         BOOST_FOREACH(const CTxIn& txin, tx.vin)
1416         {
1417             nSigOps += txin.scriptSig.GetSigOpCount();
1418         }
1419         BOOST_FOREACH(const CTxOut& txout, tx.vout)
1420         {
1421             nSigOps += txout.scriptPubKey.GetSigOpCount();
1422         }
1423     }
1424     if (nSigOps > MAX_BLOCK_SIGOPS)
1425         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1426
1427     // Check merkleroot
1428     if (hashMerkleRoot != BuildMerkleTree())
1429         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1430
1431     return true;
1432 }
1433
1434 bool CBlock::AcceptBlock()
1435 {
1436     // Check for duplicate
1437     uint256 hash = GetHash();
1438     if (mapBlockIndex.count(hash))
1439         return error("AcceptBlock() : block already in mapBlockIndex");
1440
1441     // Get prev block index
1442     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1443     if (mi == mapBlockIndex.end())
1444         return DoS(10, error("AcceptBlock() : prev block not found"));
1445     CBlockIndex* pindexPrev = (*mi).second;
1446     int nHeight = pindexPrev->nHeight+1;
1447
1448     // Check proof of work
1449     if (nBits != GetNextWorkRequired(pindexPrev))
1450         return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1451
1452     // Check timestamp against prev
1453     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1454         return error("AcceptBlock() : block's timestamp is too early");
1455
1456     // Check that all transactions are finalized
1457     BOOST_FOREACH(const CTransaction& tx, vtx)
1458         if (!tx.IsFinal(nHeight, GetBlockTime()))
1459             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1460
1461     // Check that the block chain matches the known block chain up to a checkpoint
1462     if (!Checkpoints::CheckBlock(nHeight, hash))
1463         return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1464
1465     // Write block to history file
1466     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1467         return error("AcceptBlock() : out of disk space");
1468     unsigned int nFile = -1;
1469     unsigned int nBlockPos = 0;
1470     if (!WriteToDisk(nFile, nBlockPos))
1471         return error("AcceptBlock() : WriteToDisk failed");
1472     if (!AddToBlockIndex(nFile, nBlockPos))
1473         return error("AcceptBlock() : AddToBlockIndex failed");
1474
1475     // Relay inventory, but don't relay old inventory during initial block download
1476     if (hashBestChain == hash)
1477         CRITICAL_BLOCK(cs_vNodes)
1478             BOOST_FOREACH(CNode* pnode, vNodes)
1479                 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1480                     pnode->PushInventory(CInv(MSG_BLOCK, hash));
1481
1482     return true;
1483 }
1484
1485 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1486 {
1487     // Check for duplicate
1488     uint256 hash = pblock->GetHash();
1489     if (mapBlockIndex.count(hash))
1490         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1491     if (mapOrphanBlocks.count(hash))
1492         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1493
1494     // Preliminary checks
1495     if (!pblock->CheckBlock())
1496         return error("ProcessBlock() : CheckBlock FAILED");
1497
1498     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1499     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1500     {
1501         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1502         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1503         if (deltaTime < 0)
1504         {
1505             pfrom->Misbehaving(100);
1506             return error("ProcessBlock() : block with timestamp before last checkpoint");
1507         }
1508         CBigNum bnNewBlock;
1509         bnNewBlock.SetCompact(pblock->nBits);
1510         CBigNum bnRequired;
1511         bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1512         if (bnNewBlock > bnRequired)
1513         {
1514             pfrom->Misbehaving(100);
1515             return error("ProcessBlock() : block with too little proof-of-work");
1516         }
1517     }
1518
1519
1520     // If don't already have its previous block, shunt it off to holding area until we get it
1521     if (!mapBlockIndex.count(pblock->hashPrevBlock))
1522     {
1523         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1524         CBlock* pblock2 = new CBlock(*pblock);
1525         mapOrphanBlocks.insert(make_pair(hash, pblock2));
1526         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1527
1528         // Ask this guy to fill in what we're missing
1529         if (pfrom)
1530             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1531         return true;
1532     }
1533
1534     // Store to disk
1535     if (!pblock->AcceptBlock())
1536         return error("ProcessBlock() : AcceptBlock FAILED");
1537
1538     // Recursively process any orphan blocks that depended on this one
1539     vector<uint256> vWorkQueue;
1540     vWorkQueue.push_back(hash);
1541     for (int i = 0; i < vWorkQueue.size(); i++)
1542     {
1543         uint256 hashPrev = vWorkQueue[i];
1544         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1545              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1546              ++mi)
1547         {
1548             CBlock* pblockOrphan = (*mi).second;
1549             if (pblockOrphan->AcceptBlock())
1550                 vWorkQueue.push_back(pblockOrphan->GetHash());
1551             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1552             delete pblockOrphan;
1553         }
1554         mapOrphanBlocksByPrev.erase(hashPrev);
1555     }
1556
1557     printf("ProcessBlock: ACCEPTED\n");
1558     return true;
1559 }
1560
1561
1562
1563
1564
1565
1566
1567
1568 bool CheckDiskSpace(uint64 nAdditionalBytes)
1569 {
1570     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1571
1572     // Check for 15MB because database could create another 10MB log file at any time
1573     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1574     {
1575         fShutdown = true;
1576         string strMessage = _("Warning: Disk space is low  ");
1577         strMiscWarning = strMessage;
1578         printf("*** %s\n", strMessage.c_str());
1579         ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1580         CreateThread(Shutdown, NULL);
1581         return false;
1582     }
1583     return true;
1584 }
1585
1586 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1587 {
1588     if (nFile == -1)
1589         return NULL;
1590     FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1591     if (!file)
1592         return NULL;
1593     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1594     {
1595         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1596         {
1597             fclose(file);
1598             return NULL;
1599         }
1600     }
1601     return file;
1602 }
1603
1604 static unsigned int nCurrentBlockFile = 1;
1605
1606 FILE* AppendBlockFile(unsigned int& nFileRet)
1607 {
1608     nFileRet = 0;
1609     loop
1610     {
1611         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1612         if (!file)
1613             return NULL;
1614         if (fseek(file, 0, SEEK_END) != 0)
1615             return NULL;
1616         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1617         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1618         {
1619             nFileRet = nCurrentBlockFile;
1620             return file;
1621         }
1622         fclose(file);
1623         nCurrentBlockFile++;
1624     }
1625 }
1626
1627 bool LoadBlockIndex(bool fAllowNew)
1628 {
1629     if (fTestNet)
1630     {
1631         hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1632         bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1633         pchMessageStart[0] = 0xfa;
1634         pchMessageStart[1] = 0xbf;
1635         pchMessageStart[2] = 0xb5;
1636         pchMessageStart[3] = 0xda;
1637     }
1638
1639     //
1640     // Load block index
1641     //
1642     CTxDB txdb("cr");
1643     if (!txdb.LoadBlockIndex())
1644         return false;
1645     txdb.Close();
1646
1647     //
1648     // Init with genesis block
1649     //
1650     if (mapBlockIndex.empty())
1651     {
1652         if (!fAllowNew)
1653             return false;
1654
1655         // Genesis Block:
1656         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1657         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1658         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1659         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1660         //   vMerkleTree: 4a5e1e
1661
1662         // Genesis block
1663         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1664         CTransaction txNew;
1665         txNew.vin.resize(1);
1666         txNew.vout.resize(1);
1667         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1668         txNew.vout[0].nValue = 50 * COIN;
1669         txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1670         CBlock block;
1671         block.vtx.push_back(txNew);
1672         block.hashPrevBlock = 0;
1673         block.hashMerkleRoot = block.BuildMerkleTree();
1674         block.nVersion = 1;
1675         block.nTime    = 1231006505;
1676         block.nBits    = 0x1d00ffff;
1677         block.nNonce   = 2083236893;
1678
1679         if (fTestNet)
1680         {
1681             block.nTime    = 1296688602;
1682             block.nBits    = 0x1d07fff8;
1683             block.nNonce   = 384568319;
1684         }
1685
1686         //// debug print
1687         printf("%s\n", block.GetHash().ToString().c_str());
1688         printf("%s\n", hashGenesisBlock.ToString().c_str());
1689         printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1690         assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1691         block.print();
1692         assert(block.GetHash() == hashGenesisBlock);
1693
1694         // Start new block file
1695         unsigned int nFile;
1696         unsigned int nBlockPos;
1697         if (!block.WriteToDisk(nFile, nBlockPos))
1698             return error("LoadBlockIndex() : writing genesis block to disk failed");
1699         if (!block.AddToBlockIndex(nFile, nBlockPos))
1700             return error("LoadBlockIndex() : genesis block not accepted");
1701     }
1702
1703     return true;
1704 }
1705
1706
1707
1708 void PrintBlockTree()
1709 {
1710     // precompute tree structure
1711     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1712     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1713     {
1714         CBlockIndex* pindex = (*mi).second;
1715         mapNext[pindex->pprev].push_back(pindex);
1716         // test
1717         //while (rand() % 3 == 0)
1718         //    mapNext[pindex->pprev].push_back(pindex);
1719     }
1720
1721     vector<pair<int, CBlockIndex*> > vStack;
1722     vStack.push_back(make_pair(0, pindexGenesisBlock));
1723
1724     int nPrevCol = 0;
1725     while (!vStack.empty())
1726     {
1727         int nCol = vStack.back().first;
1728         CBlockIndex* pindex = vStack.back().second;
1729         vStack.pop_back();
1730
1731         // print split or gap
1732         if (nCol > nPrevCol)
1733         {
1734             for (int i = 0; i < nCol-1; i++)
1735                 printf("| ");
1736             printf("|\\\n");
1737         }
1738         else if (nCol < nPrevCol)
1739         {
1740             for (int i = 0; i < nCol; i++)
1741                 printf("| ");
1742             printf("|\n");
1743        }
1744         nPrevCol = nCol;
1745
1746         // print columns
1747         for (int i = 0; i < nCol; i++)
1748             printf("| ");
1749
1750         // print item
1751         CBlock block;
1752         block.ReadFromDisk(pindex);
1753         printf("%d (%u,%u) %s  %s  tx %d",
1754             pindex->nHeight,
1755             pindex->nFile,
1756             pindex->nBlockPos,
1757             block.GetHash().ToString().substr(0,20).c_str(),
1758             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1759             block.vtx.size());
1760
1761         PrintWallets(block);
1762
1763         // put the main timechain first
1764         vector<CBlockIndex*>& vNext = mapNext[pindex];
1765         for (int i = 0; i < vNext.size(); i++)
1766         {
1767             if (vNext[i]->pnext)
1768             {
1769                 swap(vNext[0], vNext[i]);
1770                 break;
1771             }
1772         }
1773
1774         // iterate children
1775         for (int i = 0; i < vNext.size(); i++)
1776             vStack.push_back(make_pair(nCol+i, vNext[i]));
1777     }
1778 }
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789 //////////////////////////////////////////////////////////////////////////////
1790 //
1791 // CAlert
1792 //
1793
1794 map<uint256, CAlert> mapAlerts;
1795 CCriticalSection cs_mapAlerts;
1796
1797 string GetWarnings(string strFor)
1798 {
1799     int nPriority = 0;
1800     string strStatusBar;
1801     string strRPC;
1802     if (GetBoolArg("-testsafemode"))
1803         strRPC = "test";
1804
1805     // Misc warnings like out of disk space and clock is wrong
1806     if (strMiscWarning != "")
1807     {
1808         nPriority = 1000;
1809         strStatusBar = strMiscWarning;
1810     }
1811
1812     // Longer invalid proof-of-work chain
1813     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1814     {
1815         nPriority = 2000;
1816         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
1817     }
1818
1819     // Alerts
1820     CRITICAL_BLOCK(cs_mapAlerts)
1821     {
1822         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1823         {
1824             const CAlert& alert = item.second;
1825             if (alert.AppliesToMe() && alert.nPriority > nPriority)
1826             {
1827                 nPriority = alert.nPriority;
1828                 strStatusBar = alert.strStatusBar;
1829             }
1830         }
1831     }
1832
1833     if (strFor == "statusbar")
1834         return strStatusBar;
1835     else if (strFor == "rpc")
1836         return strRPC;
1837     assert(!"GetWarnings() : invalid parameter");
1838     return "error";
1839 }
1840
1841 bool CAlert::ProcessAlert()
1842 {
1843     if (!CheckSignature())
1844         return false;
1845     if (!IsInEffect())
1846         return false;
1847
1848     CRITICAL_BLOCK(cs_mapAlerts)
1849     {
1850         // Cancel previous alerts
1851         for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1852         {
1853             const CAlert& alert = (*mi).second;
1854             if (Cancels(alert))
1855             {
1856                 printf("cancelling alert %d\n", alert.nID);
1857                 mapAlerts.erase(mi++);
1858             }
1859             else if (!alert.IsInEffect())
1860             {
1861                 printf("expiring alert %d\n", alert.nID);
1862                 mapAlerts.erase(mi++);
1863             }
1864             else
1865                 mi++;
1866         }
1867
1868         // Check if this alert has been cancelled
1869         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1870         {
1871             const CAlert& alert = item.second;
1872             if (alert.Cancels(*this))
1873             {
1874                 printf("alert already cancelled by %d\n", alert.nID);
1875                 return false;
1876             }
1877         }
1878
1879         // Add to mapAlerts
1880         mapAlerts.insert(make_pair(GetHash(), *this));
1881     }
1882
1883     printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1884     MainFrameRepaint();
1885     return true;
1886 }
1887
1888
1889
1890
1891
1892
1893
1894
1895 //////////////////////////////////////////////////////////////////////////////
1896 //
1897 // Messages
1898 //
1899
1900
1901 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1902 {
1903     switch (inv.type)
1904     {
1905     case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1906     case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1907     }
1908     // Don't know what it is, just say we already got one
1909     return true;
1910 }
1911
1912
1913
1914
1915 // The message start string is designed to be unlikely to occur in normal data.
1916 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1917 // a large 4-byte int at any alignment.
1918 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1919
1920
1921 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1922 {
1923     static map<unsigned int, vector<unsigned char> > mapReuseKey;
1924     RandAddSeedPerfmon();
1925     if (fDebug) {
1926         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1927         printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1928     }
1929     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1930     {
1931         printf("dropmessagestest DROPPING RECV MESSAGE\n");
1932         return true;
1933     }
1934
1935
1936
1937
1938
1939     if (strCommand == "version")
1940     {
1941         // Each connection can only send one version message
1942         if (pfrom->nVersion != 0)
1943         {
1944             pfrom->Misbehaving(1);
1945             return false;
1946         }
1947
1948         int64 nTime;
1949         CAddress addrMe;
1950         CAddress addrFrom;
1951         uint64 nNonce = 1;
1952         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1953         if (pfrom->nVersion == 10300)
1954             pfrom->nVersion = 300;
1955         if (pfrom->nVersion >= 106 && !vRecv.empty())
1956             vRecv >> addrFrom >> nNonce;
1957         if (pfrom->nVersion >= 106 && !vRecv.empty())
1958             vRecv >> pfrom->strSubVer;
1959         if (pfrom->nVersion >= 209 && !vRecv.empty())
1960             vRecv >> pfrom->nStartingHeight;
1961
1962         if (pfrom->nVersion == 0)
1963             return false;
1964
1965         // Disconnect if we connected to ourself
1966         if (nNonce == nLocalHostNonce && nNonce > 1)
1967         {
1968             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1969             pfrom->fDisconnect = true;
1970             return true;
1971         }
1972
1973         // Be shy and don't send version until we hear
1974         if (pfrom->fInbound)
1975             pfrom->PushVersion();
1976
1977         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1978
1979         AddTimeData(pfrom->addr.ip, nTime);
1980
1981         // Change version
1982         if (pfrom->nVersion >= 209)
1983             pfrom->PushMessage("verack");
1984         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1985         if (pfrom->nVersion < 209)
1986             pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1987
1988         if (!pfrom->fInbound)
1989         {
1990             // Advertise our address
1991             if (addrLocalHost.IsRoutable() && !fUseProxy)
1992             {
1993                 CAddress addr(addrLocalHost);
1994                 addr.nTime = GetAdjustedTime();
1995                 pfrom->PushAddress(addr);
1996             }
1997
1998             // Get recent addresses
1999             if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2000             {
2001                 pfrom->PushMessage("getaddr");
2002                 pfrom->fGetAddr = true;
2003             }
2004         }
2005
2006         // Ask the first connected node for block updates
2007         static int nAskedForBlocks = 0;
2008         if (!pfrom->fClient &&
2009             (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2010              (nAskedForBlocks < 1 || vNodes.size() <= 1))
2011         {
2012             nAskedForBlocks++;
2013             pfrom->PushGetBlocks(pindexBest, uint256(0));
2014         }
2015
2016         // Relay alerts
2017         CRITICAL_BLOCK(cs_mapAlerts)
2018             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2019                 item.second.RelayTo(pfrom);
2020
2021         pfrom->fSuccessfullyConnected = true;
2022
2023         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2024
2025         cPeerBlockCounts.input(pfrom->nStartingHeight);
2026     }
2027
2028
2029     else if (pfrom->nVersion == 0)
2030     {
2031         // Must have a version message before anything else
2032         pfrom->Misbehaving(1);
2033         return false;
2034     }
2035
2036
2037     else if (strCommand == "verack")
2038     {
2039         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2040     }
2041
2042
2043     else if (strCommand == "addr")
2044     {
2045         vector<CAddress> vAddr;
2046         vRecv >> vAddr;
2047
2048         // Don't want addr from older versions unless seeding
2049         if (pfrom->nVersion < 209)
2050             return true;
2051         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2052             return true;
2053         if (vAddr.size() > 1000)
2054         {
2055             pfrom->Misbehaving(20);
2056             return error("message addr size() = %d", vAddr.size());
2057         }
2058
2059         // Store the new addresses
2060         CAddrDB addrDB;
2061         addrDB.TxnBegin();
2062         int64 nNow = GetAdjustedTime();
2063         int64 nSince = nNow - 10 * 60;
2064         BOOST_FOREACH(CAddress& addr, vAddr)
2065         {
2066             if (fShutdown)
2067                 return true;
2068             // ignore IPv6 for now, since it isn't implemented anyway
2069             if (!addr.IsIPv4())
2070                 continue;
2071             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2072                 addr.nTime = nNow - 5 * 24 * 60 * 60;
2073             AddAddress(addr, 2 * 60 * 60, &addrDB);
2074             pfrom->AddAddressKnown(addr);
2075             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2076             {
2077                 // Relay to a limited number of other nodes
2078                 CRITICAL_BLOCK(cs_vNodes)
2079                 {
2080                     // Use deterministic randomness to send to the same nodes for 24 hours
2081                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2082                     static uint256 hashSalt;
2083                     if (hashSalt == 0)
2084                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2085                     uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2086                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2087                     multimap<uint256, CNode*> mapMix;
2088                     BOOST_FOREACH(CNode* pnode, vNodes)
2089                     {
2090                         if (pnode->nVersion < 31402)
2091                             continue;
2092                         unsigned int nPointer;
2093                         memcpy(&nPointer, &pnode, sizeof(nPointer));
2094                         uint256 hashKey = hashRand ^ nPointer;
2095                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
2096                         mapMix.insert(make_pair(hashKey, pnode));
2097                     }
2098                     int nRelayNodes = 2;
2099                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2100                         ((*mi).second)->PushAddress(addr);
2101                 }
2102             }
2103         }
2104         addrDB.TxnCommit();  // Save addresses (it's ok if this fails)
2105         if (vAddr.size() < 1000)
2106             pfrom->fGetAddr = false;
2107     }
2108
2109
2110     else if (strCommand == "inv")
2111     {
2112         vector<CInv> vInv;
2113         vRecv >> vInv;
2114         if (vInv.size() > 50000)
2115         {
2116             pfrom->Misbehaving(20);
2117             return error("message inv size() = %d", vInv.size());
2118         }
2119
2120         CTxDB txdb("r");
2121         BOOST_FOREACH(const CInv& inv, vInv)
2122         {
2123             if (fShutdown)
2124                 return true;
2125             pfrom->AddInventoryKnown(inv);
2126
2127             bool fAlreadyHave = AlreadyHave(txdb, inv);
2128             if (fDebug)
2129                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2130
2131             if (!fAlreadyHave)
2132                 pfrom->AskFor(inv);
2133             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2134                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2135
2136             // Track requests for our stuff
2137             Inventory(inv.hash);
2138         }
2139     }
2140
2141
2142     else if (strCommand == "getdata")
2143     {
2144         vector<CInv> vInv;
2145         vRecv >> vInv;
2146         if (vInv.size() > 50000)
2147         {
2148             pfrom->Misbehaving(20);
2149             return error("message getdata size() = %d", vInv.size());
2150         }
2151
2152         BOOST_FOREACH(const CInv& inv, vInv)
2153         {
2154             if (fShutdown)
2155                 return true;
2156             printf("received getdata for: %s\n", inv.ToString().c_str());
2157
2158             if (inv.type == MSG_BLOCK)
2159             {
2160                 // Send block from disk
2161                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2162                 if (mi != mapBlockIndex.end())
2163                 {
2164                     CBlock block;
2165                     block.ReadFromDisk((*mi).second);
2166                     pfrom->PushMessage("block", block);
2167
2168                     // Trigger them to send a getblocks request for the next batch of inventory
2169                     if (inv.hash == pfrom->hashContinue)
2170                     {
2171                         // Bypass PushInventory, this must send even if redundant,
2172                         // and we want it right after the last block so they don't
2173                         // wait for other stuff first.
2174                         vector<CInv> vInv;
2175                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2176                         pfrom->PushMessage("inv", vInv);
2177                         pfrom->hashContinue = 0;
2178                     }
2179                 }
2180             }
2181             else if (inv.IsKnownType())
2182             {
2183                 // Send stream from relay memory
2184                 CRITICAL_BLOCK(cs_mapRelay)
2185                 {
2186                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2187                     if (mi != mapRelay.end())
2188                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2189                 }
2190             }
2191
2192             // Track requests for our stuff
2193             Inventory(inv.hash);
2194         }
2195     }
2196
2197
2198     else if (strCommand == "getblocks")
2199     {
2200         CBlockLocator locator;
2201         uint256 hashStop;
2202         vRecv >> locator >> hashStop;
2203
2204         // Find the last block the caller has in the main chain
2205         CBlockIndex* pindex = locator.GetBlockIndex();
2206
2207         // Send the rest of the chain
2208         if (pindex)
2209             pindex = pindex->pnext;
2210         int nLimit = 500 + locator.GetDistanceBack();
2211         unsigned int nBytes = 0;
2212         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2213         for (; pindex; pindex = pindex->pnext)
2214         {
2215             if (pindex->GetBlockHash() == hashStop)
2216             {
2217                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2218                 break;
2219             }
2220             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2221             CBlock block;
2222             block.ReadFromDisk(pindex, true);
2223             nBytes += block.GetSerializeSize(SER_NETWORK);
2224             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2225             {
2226                 // When this block is requested, we'll send an inv that'll make them
2227                 // getblocks the next batch of inventory.
2228                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2229                 pfrom->hashContinue = pindex->GetBlockHash();
2230                 break;
2231             }
2232         }
2233     }
2234
2235
2236     else if (strCommand == "getheaders")
2237     {
2238         CBlockLocator locator;
2239         uint256 hashStop;
2240         vRecv >> locator >> hashStop;
2241
2242         CBlockIndex* pindex = NULL;
2243         if (locator.IsNull())
2244         {
2245             // If locator is null, return the hashStop block
2246             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2247             if (mi == mapBlockIndex.end())
2248                 return true;
2249             pindex = (*mi).second;
2250         }
2251         else
2252         {
2253             // Find the last block the caller has in the main chain
2254             pindex = locator.GetBlockIndex();
2255             if (pindex)
2256                 pindex = pindex->pnext;
2257         }
2258
2259         vector<CBlock> vHeaders;
2260         int nLimit = 2000 + locator.GetDistanceBack();
2261         printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2262         for (; pindex; pindex = pindex->pnext)
2263         {
2264             vHeaders.push_back(pindex->GetBlockHeader());
2265             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2266                 break;
2267         }
2268         pfrom->PushMessage("headers", vHeaders);
2269     }
2270
2271
2272     else if (strCommand == "tx")
2273     {
2274         vector<uint256> vWorkQueue;
2275         CDataStream vMsg(vRecv);
2276         CTransaction tx;
2277         vRecv >> tx;
2278
2279         CInv inv(MSG_TX, tx.GetHash());
2280         pfrom->AddInventoryKnown(inv);
2281
2282         bool fMissingInputs = false;
2283         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2284         {
2285             SyncWithWallets(tx, NULL, true);
2286             RelayMessage(inv, vMsg);
2287             mapAlreadyAskedFor.erase(inv);
2288             vWorkQueue.push_back(inv.hash);
2289
2290             // Recursively process any orphan transactions that depended on this one
2291             for (int i = 0; i < vWorkQueue.size(); i++)
2292             {
2293                 uint256 hashPrev = vWorkQueue[i];
2294                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2295                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2296                      ++mi)
2297                 {
2298                     const CDataStream& vMsg = *((*mi).second);
2299                     CTransaction tx;
2300                     CDataStream(vMsg) >> tx;
2301                     CInv inv(MSG_TX, tx.GetHash());
2302
2303                     if (tx.AcceptToMemoryPool(true))
2304                     {
2305                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2306                         SyncWithWallets(tx, NULL, true);
2307                         RelayMessage(inv, vMsg);
2308                         mapAlreadyAskedFor.erase(inv);
2309                         vWorkQueue.push_back(inv.hash);
2310                     }
2311                 }
2312             }
2313
2314             BOOST_FOREACH(uint256 hash, vWorkQueue)
2315                 EraseOrphanTx(hash);
2316         }
2317         else if (fMissingInputs)
2318         {
2319             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2320             AddOrphanTx(vMsg);
2321         }
2322         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2323     }
2324
2325
2326     else if (strCommand == "block")
2327     {
2328         CBlock block;
2329         vRecv >> block;
2330
2331         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2332         // block.print();
2333
2334         CInv inv(MSG_BLOCK, block.GetHash());
2335         pfrom->AddInventoryKnown(inv);
2336
2337         if (ProcessBlock(pfrom, &block))
2338             mapAlreadyAskedFor.erase(inv);
2339         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2340     }
2341
2342
2343     else if (strCommand == "getaddr")
2344     {
2345         // Nodes rebroadcast an addr every 24 hours
2346         pfrom->vAddrToSend.clear();
2347         int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2348         CRITICAL_BLOCK(cs_mapAddresses)
2349         {
2350             unsigned int nCount = 0;
2351             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2352             {
2353                 const CAddress& addr = item.second;
2354                 if (addr.nTime > nSince)
2355                     nCount++;
2356             }
2357             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2358             {
2359                 const CAddress& addr = item.second;
2360                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2361                     pfrom->PushAddress(addr);
2362             }
2363         }
2364     }
2365
2366
2367     else if (strCommand == "checkorder")
2368     {
2369         uint256 hashReply;
2370         vRecv >> hashReply;
2371
2372         if (!GetBoolArg("-allowreceivebyip"))
2373         {
2374             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2375             return true;
2376         }
2377
2378         CWalletTx order;
2379         vRecv >> order;
2380
2381         /// we have a chance to check the order here
2382
2383         // Keep giving the same key to the same ip until they use it
2384         if (!mapReuseKey.count(pfrom->addr.ip))
2385             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2386
2387         // Send back approval of order and pubkey to use
2388         CScript scriptPubKey;
2389         scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2390         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2391     }
2392
2393
2394     else if (strCommand == "reply")
2395     {
2396         uint256 hashReply;
2397         vRecv >> hashReply;
2398
2399         CRequestTracker tracker;
2400         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2401         {
2402             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2403             if (mi != pfrom->mapRequests.end())
2404             {
2405                 tracker = (*mi).second;
2406                 pfrom->mapRequests.erase(mi);
2407             }
2408         }
2409         if (!tracker.IsNull())
2410             tracker.fn(tracker.param1, vRecv);
2411     }
2412
2413
2414     else if (strCommand == "ping")
2415     {
2416     }
2417
2418
2419     else if (strCommand == "alert")
2420     {
2421         CAlert alert;
2422         vRecv >> alert;
2423
2424         if (alert.ProcessAlert())
2425         {
2426             // Relay
2427             pfrom->setKnown.insert(alert.GetHash());
2428             CRITICAL_BLOCK(cs_vNodes)
2429                 BOOST_FOREACH(CNode* pnode, vNodes)
2430                     alert.RelayTo(pnode);
2431         }
2432     }
2433
2434
2435     else
2436     {
2437         // Ignore unknown commands for extensibility
2438     }
2439
2440
2441     // Update the last seen time for this node's address
2442     if (pfrom->fNetworkNode)
2443         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2444             AddressCurrentlyConnected(pfrom->addr);
2445
2446
2447     return true;
2448 }
2449
2450 bool ProcessMessages(CNode* pfrom)
2451 {
2452     CDataStream& vRecv = pfrom->vRecv;
2453     if (vRecv.empty())
2454         return true;
2455     //if (fDebug)
2456     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2457
2458     //
2459     // Message format
2460     //  (4) message start
2461     //  (12) command
2462     //  (4) size
2463     //  (4) checksum
2464     //  (x) data
2465     //
2466
2467     loop
2468     {
2469         // Scan for message start
2470         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2471         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2472         if (vRecv.end() - pstart < nHeaderSize)
2473         {
2474             if (vRecv.size() > nHeaderSize)
2475             {
2476                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2477                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2478             }
2479             break;
2480         }
2481         if (pstart - vRecv.begin() > 0)
2482             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2483         vRecv.erase(vRecv.begin(), pstart);
2484
2485         // Read header
2486         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2487         CMessageHeader hdr;
2488         vRecv >> hdr;
2489         if (!hdr.IsValid())
2490         {
2491             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2492             continue;
2493         }
2494         string strCommand = hdr.GetCommand();
2495
2496         // Message size
2497         unsigned int nMessageSize = hdr.nMessageSize;
2498         if (nMessageSize > MAX_SIZE)
2499         {
2500             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2501             continue;
2502         }
2503         if (nMessageSize > vRecv.size())
2504         {
2505             // Rewind and wait for rest of message
2506             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2507             break;
2508         }
2509
2510         // Checksum
2511         if (vRecv.GetVersion() >= 209)
2512         {
2513             uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2514             unsigned int nChecksum = 0;
2515             memcpy(&nChecksum, &hash, sizeof(nChecksum));
2516             if (nChecksum != hdr.nChecksum)
2517             {
2518                 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2519                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2520                 continue;
2521             }
2522         }
2523
2524         // Copy message to its own buffer
2525         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2526         vRecv.ignore(nMessageSize);
2527
2528         // Process message
2529         bool fRet = false;
2530         try
2531         {
2532             CRITICAL_BLOCK(cs_main)
2533                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2534             if (fShutdown)
2535                 return true;
2536         }
2537         catch (std::ios_base::failure& e)
2538         {
2539             if (strstr(e.what(), "end of data"))
2540             {
2541                 // Allow exceptions from underlength message on vRecv
2542                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2543             }
2544             else if (strstr(e.what(), "size too large"))
2545             {
2546                 // Allow exceptions from overlong size
2547                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2548             }
2549             else
2550             {
2551                 PrintExceptionContinue(&e, "ProcessMessage()");
2552             }
2553         }
2554         catch (std::exception& e) {
2555             PrintExceptionContinue(&e, "ProcessMessage()");
2556         } catch (...) {
2557             PrintExceptionContinue(NULL, "ProcessMessage()");
2558         }
2559
2560         if (!fRet)
2561             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2562     }
2563
2564     vRecv.Compact();
2565     return true;
2566 }
2567
2568
2569 bool SendMessages(CNode* pto, bool fSendTrickle)
2570 {
2571     CRITICAL_BLOCK(cs_main)
2572     {
2573         // Don't send anything until we get their version message
2574         if (pto->nVersion == 0)
2575             return true;
2576
2577         // Keep-alive ping
2578         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2579             pto->PushMessage("ping");
2580
2581         // Resend wallet transactions that haven't gotten in a block yet
2582         ResendWalletTransactions();
2583
2584         // Address refresh broadcast
2585         static int64 nLastRebroadcast;
2586         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2587         {
2588             nLastRebroadcast = GetTime();
2589             CRITICAL_BLOCK(cs_vNodes)
2590             {
2591                 BOOST_FOREACH(CNode* pnode, vNodes)
2592                 {
2593                     // Periodically clear setAddrKnown to allow refresh broadcasts
2594                     pnode->setAddrKnown.clear();
2595
2596                     // Rebroadcast our address
2597                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2598                     {
2599                         CAddress addr(addrLocalHost);
2600                         addr.nTime = GetAdjustedTime();
2601                         pnode->PushAddress(addr);
2602                     }
2603                 }
2604             }
2605         }
2606
2607         // Clear out old addresses periodically so it's not too much work at once
2608         static int64 nLastClear;
2609         if (nLastClear == 0)
2610             nLastClear = GetTime();
2611         if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2612         {
2613             nLastClear = GetTime();
2614             CRITICAL_BLOCK(cs_mapAddresses)
2615             {
2616                 CAddrDB addrdb;
2617                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2618                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2619                      mi != mapAddresses.end();)
2620                 {
2621                     const CAddress& addr = (*mi).second;
2622                     if (addr.nTime < nSince)
2623                     {
2624                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2625                             break;
2626                         addrdb.EraseAddress(addr);
2627                         mapAddresses.erase(mi++);
2628                     }
2629                     else
2630                         mi++;
2631                 }
2632             }
2633         }
2634
2635
2636         //
2637         // Message: addr
2638         //
2639         if (fSendTrickle)
2640         {
2641             vector<CAddress> vAddr;
2642             vAddr.reserve(pto->vAddrToSend.size());
2643             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2644             {
2645                 // returns true if wasn't already contained in the set
2646                 if (pto->setAddrKnown.insert(addr).second)
2647                 {
2648                     vAddr.push_back(addr);
2649                     // receiver rejects addr messages larger than 1000
2650                     if (vAddr.size() >= 1000)
2651                     {
2652                         pto->PushMessage("addr", vAddr);
2653                         vAddr.clear();
2654                     }
2655                 }
2656             }
2657             pto->vAddrToSend.clear();
2658             if (!vAddr.empty())
2659                 pto->PushMessage("addr", vAddr);
2660         }
2661
2662
2663         //
2664         // Message: inventory
2665         //
2666         vector<CInv> vInv;
2667         vector<CInv> vInvWait;
2668         CRITICAL_BLOCK(pto->cs_inventory)
2669         {
2670             vInv.reserve(pto->vInventoryToSend.size());
2671             vInvWait.reserve(pto->vInventoryToSend.size());
2672             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2673             {
2674                 if (pto->setInventoryKnown.count(inv))
2675                     continue;
2676
2677                 // trickle out tx inv to protect privacy
2678                 if (inv.type == MSG_TX && !fSendTrickle)
2679                 {
2680                     // 1/4 of tx invs blast to all immediately
2681                     static uint256 hashSalt;
2682                     if (hashSalt == 0)
2683                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2684                     uint256 hashRand = inv.hash ^ hashSalt;
2685                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2686                     bool fTrickleWait = ((hashRand & 3) != 0);
2687
2688                     // always trickle our own transactions
2689                     if (!fTrickleWait)
2690                     {
2691                         CWalletTx wtx;
2692                         if (GetTransaction(inv.hash, wtx))
2693                             if (wtx.fFromMe)
2694                                 fTrickleWait = true;
2695                     }
2696
2697                     if (fTrickleWait)
2698                     {
2699                         vInvWait.push_back(inv);
2700                         continue;
2701                     }
2702                 }
2703
2704                 // returns true if wasn't already contained in the set
2705                 if (pto->setInventoryKnown.insert(inv).second)
2706                 {
2707                     vInv.push_back(inv);
2708                     if (vInv.size() >= 1000)
2709                     {
2710                         pto->PushMessage("inv", vInv);
2711                         vInv.clear();
2712                     }
2713                 }
2714             }
2715             pto->vInventoryToSend = vInvWait;
2716         }
2717         if (!vInv.empty())
2718             pto->PushMessage("inv", vInv);
2719
2720
2721         //
2722         // Message: getdata
2723         //
2724         vector<CInv> vGetData;
2725         int64 nNow = GetTime() * 1000000;
2726         CTxDB txdb("r");
2727         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2728         {
2729             const CInv& inv = (*pto->mapAskFor.begin()).second;
2730             if (!AlreadyHave(txdb, inv))
2731             {
2732                 printf("sending getdata: %s\n", inv.ToString().c_str());
2733                 vGetData.push_back(inv);
2734                 if (vGetData.size() >= 1000)
2735                 {
2736                     pto->PushMessage("getdata", vGetData);
2737                     vGetData.clear();
2738                 }
2739             }
2740             mapAlreadyAskedFor[inv] = nNow;
2741             pto->mapAskFor.erase(pto->mapAskFor.begin());
2742         }
2743         if (!vGetData.empty())
2744             pto->PushMessage("getdata", vGetData);
2745
2746     }
2747     return true;
2748 }
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763 //////////////////////////////////////////////////////////////////////////////
2764 //
2765 // BitcoinMiner
2766 //
2767
2768 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2769 {
2770     unsigned char* pdata = (unsigned char*)pbuffer;
2771     unsigned int blocks = 1 + ((len + 8) / 64);
2772     unsigned char* pend = pdata + 64 * blocks;
2773     memset(pdata + len, 0, 64 * blocks - len);
2774     pdata[len] = 0x80;
2775     unsigned int bits = len * 8;
2776     pend[-1] = (bits >> 0) & 0xff;
2777     pend[-2] = (bits >> 8) & 0xff;
2778     pend[-3] = (bits >> 16) & 0xff;
2779     pend[-4] = (bits >> 24) & 0xff;
2780     return blocks;
2781 }
2782
2783 static const unsigned int pSHA256InitState[8] =
2784 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2785
2786 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2787 {
2788     SHA256_CTX ctx;
2789     unsigned char data[64];
2790
2791     SHA256_Init(&ctx);
2792
2793     for (int i = 0; i < 16; i++)
2794         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2795
2796     for (int i = 0; i < 8; i++)
2797         ctx.h[i] = ((uint32_t*)pinit)[i];
2798
2799     SHA256_Update(&ctx, data, sizeof(data));
2800     for (int i = 0; i < 8; i++) 
2801         ((uint32_t*)pstate)[i] = ctx.h[i];
2802 }
2803
2804 //
2805 // ScanHash scans nonces looking for a hash with at least some zero bits.
2806 // It operates on big endian data.  Caller does the byte reversing.
2807 // All input buffers are 16-byte aligned.  nNonce is usually preserved
2808 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2809 // the block is rebuilt and nNonce starts over at zero.
2810 //
2811 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2812 {
2813     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2814     for (;;)
2815     {
2816         // Crypto++ SHA-256
2817         // Hash pdata using pmidstate as the starting state into
2818         // preformatted buffer phash1, then hash phash1 into phash
2819         nNonce++;
2820         SHA256Transform(phash1, pdata, pmidstate);
2821         SHA256Transform(phash, phash1, pSHA256InitState);
2822
2823         // Return the nonce if the hash has at least some zero bits,
2824         // caller will check if it has enough to reach the target
2825         if (((unsigned short*)phash)[14] == 0)
2826             return nNonce;
2827
2828         // If nothing found after trying for a while, return -1
2829         if ((nNonce & 0xffff) == 0)
2830         {
2831             nHashesDone = 0xffff+1;
2832             return -1;
2833         }
2834     }
2835 }
2836
2837 // Some explaining would be appreciated
2838 class COrphan
2839 {
2840 public:
2841     CTransaction* ptx;
2842     set<uint256> setDependsOn;
2843     double dPriority;
2844
2845     COrphan(CTransaction* ptxIn)
2846     {
2847         ptx = ptxIn;
2848         dPriority = 0;
2849     }
2850
2851     void print() const
2852     {
2853         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2854         BOOST_FOREACH(uint256 hash, setDependsOn)
2855             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2856     }
2857 };
2858
2859
2860 CBlock* CreateNewBlock(CReserveKey& reservekey)
2861 {
2862     CBlockIndex* pindexPrev = pindexBest;
2863
2864     // Create new block
2865     auto_ptr<CBlock> pblock(new CBlock());
2866     if (!pblock.get())
2867         return NULL;
2868
2869     // Create coinbase tx
2870     CTransaction txNew;
2871     txNew.vin.resize(1);
2872     txNew.vin[0].prevout.SetNull();
2873     txNew.vout.resize(1);
2874     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2875
2876     // Add our coinbase tx as first transaction
2877     pblock->vtx.push_back(txNew);
2878
2879     // Collect memory pool transactions into the block
2880     int64 nFees = 0;
2881     CRITICAL_BLOCK(cs_main)
2882     CRITICAL_BLOCK(cs_mapTransactions)
2883     {
2884         CTxDB txdb("r");
2885
2886         // Priority order to process transactions
2887         list<COrphan> vOrphan; // list memory doesn't move
2888         map<uint256, vector<COrphan*> > mapDependers;
2889         multimap<double, CTransaction*> mapPriority;
2890         for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2891         {
2892             CTransaction& tx = (*mi).second;
2893             if (tx.IsCoinBase() || !tx.IsFinal())
2894                 continue;
2895
2896             COrphan* porphan = NULL;
2897             double dPriority = 0;
2898             BOOST_FOREACH(const CTxIn& txin, tx.vin)
2899             {
2900                 // Read prev transaction
2901                 CTransaction txPrev;
2902                 CTxIndex txindex;
2903                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2904                 {
2905                     // Has to wait for dependencies
2906                     if (!porphan)
2907                     {
2908                         // Use list for automatic deletion
2909                         vOrphan.push_back(COrphan(&tx));
2910                         porphan = &vOrphan.back();
2911                     }
2912                     mapDependers[txin.prevout.hash].push_back(porphan);
2913                     porphan->setDependsOn.insert(txin.prevout.hash);
2914                     continue;
2915                 }
2916                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2917
2918                 // Read block header
2919                 int nConf = txindex.GetDepthInMainChain();
2920
2921                 dPriority += (double)nValueIn * nConf;
2922
2923                 if (fDebug && GetBoolArg("-printpriority"))
2924                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2925             }
2926
2927             // Priority is sum(valuein * age) / txsize
2928             dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2929
2930             if (porphan)
2931                 porphan->dPriority = dPriority;
2932             else
2933                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2934
2935             if (fDebug && GetBoolArg("-printpriority"))
2936             {
2937                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2938                 if (porphan)
2939                     porphan->print();
2940                 printf("\n");
2941             }
2942         }
2943
2944         // Collect transactions into block
2945         map<uint256, CTxIndex> mapTestPool;
2946         uint64 nBlockSize = 1000;
2947         int nBlockSigOps = 100;
2948         while (!mapPriority.empty())
2949         {
2950             // Take highest priority transaction off priority queue
2951             double dPriority = -(*mapPriority.begin()).first;
2952             CTransaction& tx = *(*mapPriority.begin()).second;
2953             mapPriority.erase(mapPriority.begin());
2954
2955             // Size limits
2956             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2957             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2958                 continue;
2959
2960             // Transaction fee required depends on block size
2961             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2962             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
2963
2964             // Connecting shouldn't fail due to dependency on other memory pool transactions
2965             // because we're already processing them in order of dependency
2966             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2967             map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2968             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2969                 continue;
2970             int nTxSigOps = 0;
2971             if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2972                 continue;
2973             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2974                 continue;
2975             swap(mapTestPool, mapTestPoolTmp);
2976
2977             // Added
2978             pblock->vtx.push_back(tx);
2979             nBlockSize += nTxSize;
2980             nBlockSigOps += nTxSigOps;
2981
2982             // Add transactions that depend on this one to the priority queue
2983             uint256 hash = tx.GetHash();
2984             if (mapDependers.count(hash))
2985             {
2986                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2987                 {
2988                     if (!porphan->setDependsOn.empty())
2989                     {
2990                         porphan->setDependsOn.erase(hash);
2991                         if (porphan->setDependsOn.empty())
2992                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2993                     }
2994                 }
2995             }
2996         }
2997     }
2998     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2999
3000     // Fill in header
3001     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3002     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3003     pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3004     pblock->nBits          = GetNextWorkRequired(pindexPrev);
3005     pblock->nNonce         = 0;
3006
3007     return pblock.release();
3008 }
3009
3010
3011 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3012 {
3013     // Update nExtraNonce
3014     static uint256 hashPrevBlock;
3015     if (hashPrevBlock != pblock->hashPrevBlock)
3016     {
3017         nExtraNonce = 0;
3018         hashPrevBlock = pblock->hashPrevBlock;
3019     }
3020     ++nExtraNonce;
3021     pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3022
3023     // Put "OP_EVAL" in the coinbase so everybody can tell when
3024     // a majority of miners support it
3025     const char* pOpEvalName = GetOpName(OP_EVAL);
3026     pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3027     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3028
3029     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3030 }
3031
3032
3033 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3034 {
3035     //
3036     // Prebuild hash buffers
3037     //
3038     struct
3039     {
3040         struct unnamed2
3041         {
3042             int nVersion;
3043             uint256 hashPrevBlock;
3044             uint256 hashMerkleRoot;
3045             unsigned int nTime;
3046             unsigned int nBits;
3047             unsigned int nNonce;
3048         }
3049         block;
3050         unsigned char pchPadding0[64];
3051         uint256 hash1;
3052         unsigned char pchPadding1[64];
3053     }
3054     tmp;
3055     memset(&tmp, 0, sizeof(tmp));
3056
3057     tmp.block.nVersion       = pblock->nVersion;
3058     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
3059     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3060     tmp.block.nTime          = pblock->nTime;
3061     tmp.block.nBits          = pblock->nBits;
3062     tmp.block.nNonce         = pblock->nNonce;
3063
3064     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3065     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3066
3067     // Byte swap all the input buffer
3068     for (int i = 0; i < sizeof(tmp)/4; i++)
3069         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3070
3071     // Precalc the first half of the first hash, which stays constant
3072     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3073
3074     memcpy(pdata, &tmp.block, 128);
3075     memcpy(phash1, &tmp.hash1, 64);
3076 }
3077
3078
3079 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3080 {
3081     uint256 hash = pblock->GetHash();
3082     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3083
3084     if (hash > hashTarget)
3085         return false;
3086
3087     //// debug print
3088     printf("BitcoinMiner:\n");
3089     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3090     pblock->print();
3091     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3092     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3093
3094     // Found a solution
3095     CRITICAL_BLOCK(cs_main)
3096     {
3097         if (pblock->hashPrevBlock != hashBestChain)
3098             return error("BitcoinMiner : generated block is stale");
3099
3100         // Remove key from key pool
3101         reservekey.KeepKey();
3102
3103         // Track how many getdata requests this block gets
3104         CRITICAL_BLOCK(wallet.cs_wallet)
3105             wallet.mapRequestCount[pblock->GetHash()] = 0;
3106
3107         // Process this block the same as if we had received it from another node
3108         if (!ProcessBlock(NULL, pblock))
3109             return error("BitcoinMiner : ProcessBlock, block not accepted");
3110     }
3111
3112     return true;
3113 }
3114
3115 void static ThreadBitcoinMiner(void* parg);
3116
3117 void static BitcoinMiner(CWallet *pwallet)
3118 {
3119     printf("BitcoinMiner started\n");
3120     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3121
3122     // Each thread has its own key and counter
3123     CReserveKey reservekey(pwallet);
3124     unsigned int nExtraNonce = 0;
3125
3126     while (fGenerateBitcoins)
3127     {
3128         if (AffinityBugWorkaround(ThreadBitcoinMiner))
3129             return;
3130         if (fShutdown)
3131             return;
3132         while (vNodes.empty() || IsInitialBlockDownload())
3133         {
3134             Sleep(1000);
3135             if (fShutdown)
3136                 return;
3137             if (!fGenerateBitcoins)
3138                 return;
3139         }
3140
3141
3142         //
3143         // Create new block
3144         //
3145         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3146         CBlockIndex* pindexPrev = pindexBest;
3147
3148         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3149         if (!pblock.get())
3150             return;
3151         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3152
3153         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3154
3155
3156         //
3157         // Prebuild hash buffers
3158         //
3159         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3160         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3161         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3162
3163         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3164
3165         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3166         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3167
3168
3169         //
3170         // Search
3171         //
3172         int64 nStart = GetTime();
3173         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3174         uint256 hashbuf[2];
3175         uint256& hash = *alignup<16>(hashbuf);
3176         loop
3177         {
3178             unsigned int nHashesDone = 0;
3179             unsigned int nNonceFound;
3180
3181             // Crypto++ SHA-256
3182             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3183                                             (char*)&hash, nHashesDone);
3184
3185             // Check if something found
3186             if (nNonceFound != -1)
3187             {
3188                 for (int i = 0; i < sizeof(hash)/4; i++)
3189                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3190
3191                 if (hash <= hashTarget)
3192                 {
3193                     // Found a solution
3194                     pblock->nNonce = ByteReverse(nNonceFound);
3195                     assert(hash == pblock->GetHash());
3196
3197                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3198                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3199                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3200                     break;
3201                 }
3202             }
3203
3204             // Meter hashes/sec
3205             static int64 nHashCounter;
3206             if (nHPSTimerStart == 0)
3207             {
3208                 nHPSTimerStart = GetTimeMillis();
3209                 nHashCounter = 0;
3210             }
3211             else
3212                 nHashCounter += nHashesDone;
3213             if (GetTimeMillis() - nHPSTimerStart > 4000)
3214             {
3215                 static CCriticalSection cs;
3216                 CRITICAL_BLOCK(cs)
3217                 {
3218                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3219                     {
3220                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3221                         nHPSTimerStart = GetTimeMillis();
3222                         nHashCounter = 0;
3223                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3224                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3225                         static int64 nLogTime;
3226                         if (GetTime() - nLogTime > 30 * 60)
3227                         {
3228                             nLogTime = GetTime();
3229                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3230                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3231                         }
3232                     }
3233                 }
3234             }
3235
3236             // Check for stop or if block needs to be rebuilt
3237             if (fShutdown)
3238                 return;
3239             if (!fGenerateBitcoins)
3240                 return;
3241             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3242                 return;
3243             if (vNodes.empty())
3244                 break;
3245             if (nBlockNonce >= 0xffff0000)
3246                 break;
3247             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3248                 break;
3249             if (pindexPrev != pindexBest)
3250                 break;
3251
3252             // Update nTime every few seconds
3253             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3254             nBlockTime = ByteReverse(pblock->nTime);
3255         }
3256     }
3257 }
3258
3259 void static ThreadBitcoinMiner(void* parg)
3260 {
3261     CWallet* pwallet = (CWallet*)parg;
3262     try
3263     {
3264         vnThreadsRunning[3]++;
3265         BitcoinMiner(pwallet);
3266         vnThreadsRunning[3]--;
3267     }
3268     catch (std::exception& e) {
3269         vnThreadsRunning[3]--;
3270         PrintException(&e, "ThreadBitcoinMiner()");
3271     } catch (...) {
3272         vnThreadsRunning[3]--;
3273         PrintException(NULL, "ThreadBitcoinMiner()");
3274     }
3275     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3276     nHPSTimerStart = 0;
3277     if (vnThreadsRunning[3] == 0)
3278         dHashesPerSec = 0;
3279     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3280 }
3281
3282
3283 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3284 {
3285     if (fGenerateBitcoins != fGenerate)
3286     {
3287         fGenerateBitcoins = fGenerate;
3288         WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3289         MainFrameRepaint();
3290     }
3291     if (fGenerateBitcoins)
3292     {
3293         int nProcessors = boost::thread::hardware_concurrency();
3294         printf("%d processors\n", nProcessors);
3295         if (nProcessors < 1)
3296             nProcessors = 1;
3297         if (fLimitProcessors && nProcessors > nLimitProcessors)
3298             nProcessors = nLimitProcessors;
3299         int nAddThreads = nProcessors - vnThreadsRunning[3];
3300         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3301         for (int i = 0; i < nAddThreads; i++)
3302         {
3303             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3304                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3305             Sleep(10);
3306         }
3307     }
3308 }