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