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