assert condition in previous commit was backwards
[novacoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "checkpoints.h"
7 #include "db.h"
8 #include "net.h"
9 #include "init.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
12
13 using namespace std;
14 using namespace boost;
15
16 //
17 // Global state
18 //
19
20 // Name of client reported in the 'version' message. Report the same name
21 // for both bitcoind and bitcoin-qt, to make it harder for attackers to
22 // target servers or GUI users specifically.
23 const std::string CLIENT_NAME("bitcoin-qt");
24
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
27
28 CCriticalSection cs_main;
29
30 static map<uint256, CTransaction> mapTransactions;
31 CCriticalSection cs_mapTransactions;
32 unsigned int nTransactionsUpdated = 0;
33 map<COutPoint, CInPoint> mapNextTx;
34
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
37 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
38 CBlockIndex* pindexGenesisBlock = NULL;
39 int nBestHeight = -1;
40 CBigNum bnBestChainWork = 0;
41 CBigNum bnBestInvalidWork = 0;
42 uint256 hashBestChain = 0;
43 CBlockIndex* pindexBest = NULL;
44 int64 nTimeBestReceived = 0;
45
46 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
47
48 map<uint256, CBlock*> mapOrphanBlocks;
49 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
50
51 map<uint256, CDataStream*> mapOrphanTransactions;
52 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
53
54
55 double dHashesPerSec;
56 int64 nHPSTimerStart;
57
58 // Settings
59 int fGenerateBitcoins = false;
60 int64 nTransactionFee = 0;
61 int fLimitProcessors = false;
62 int nLimitProcessors = 1;
63 int fMinimizeToTray = true;
64 int fMinimizeOnClose = true;
65 #if USE_UPNP
66 int fUseUPnP = true;
67 #else
68 int fUseUPnP = false;
69 #endif
70
71
72 //////////////////////////////////////////////////////////////////////////////
73 //
74 // dispatching functions
75 //
76
77 // These functions dispatch to one or all registered wallets
78
79
80 void RegisterWallet(CWallet* pwalletIn)
81 {
82     CRITICAL_BLOCK(cs_setpwalletRegistered)
83     {
84         setpwalletRegistered.insert(pwalletIn);
85     }
86 }
87
88 void UnregisterWallet(CWallet* pwalletIn)
89 {
90     CRITICAL_BLOCK(cs_setpwalletRegistered)
91     {
92         setpwalletRegistered.erase(pwalletIn);
93     }
94 }
95
96 // check whether the passed transaction is from us
97 bool static IsFromMe(CTransaction& tx)
98 {
99     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
100         if (pwallet->IsFromMe(tx))
101             return true;
102     return false;
103 }
104
105 // get the wallet transaction with the given hash (if it exists)
106 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
107 {
108     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
109         if (pwallet->GetTransaction(hashTx,wtx))
110             return true;
111     return false;
112 }
113
114 // erases transaction with the given hash from all wallets
115 void static EraseFromWallets(uint256 hash)
116 {
117     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
118         pwallet->EraseFromWallet(hash);
119 }
120
121 // make sure all wallets know about the given transaction, in the given block
122 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
123 {
124     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
126 }
127
128 // notify wallets about a new best chain
129 void static SetBestChain(const CBlockLocator& loc)
130 {
131     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132         pwallet->SetBestChain(loc);
133 }
134
135 // notify wallets about an updated transaction
136 void static UpdatedTransaction(const uint256& hashTx)
137 {
138     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139         pwallet->UpdatedTransaction(hashTx);
140 }
141
142 // dump all wallets
143 void static PrintWallets(const CBlock& block)
144 {
145     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146         pwallet->PrintWallet(block);
147 }
148
149 // notify wallets about an incoming inventory (for request counts)
150 void static Inventory(const uint256& hash)
151 {
152     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153         pwallet->Inventory(hash);
154 }
155
156 // ask wallets to resend their transactions
157 void static ResendWalletTransactions()
158 {
159     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160         pwallet->ResendWalletTransactions();
161 }
162
163
164
165
166
167
168
169 //////////////////////////////////////////////////////////////////////////////
170 //
171 // mapOrphanTransactions
172 //
173
174 void static AddOrphanTx(const CDataStream& vMsg)
175 {
176     CTransaction tx;
177     CDataStream(vMsg) >> tx;
178     uint256 hash = tx.GetHash();
179     if (mapOrphanTransactions.count(hash))
180         return;
181     CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
182     BOOST_FOREACH(const CTxIn& txin, tx.vin)
183         mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
184 }
185
186 void static EraseOrphanTx(uint256 hash)
187 {
188     if (!mapOrphanTransactions.count(hash))
189         return;
190     const CDataStream* pvMsg = mapOrphanTransactions[hash];
191     CTransaction tx;
192     CDataStream(*pvMsg) >> tx;
193     BOOST_FOREACH(const CTxIn& txin, tx.vin)
194     {
195         for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
196              mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
197         {
198             if ((*mi).second == pvMsg)
199                 mapOrphanTransactionsByPrev.erase(mi++);
200             else
201                 mi++;
202         }
203     }
204     delete pvMsg;
205     mapOrphanTransactions.erase(hash);
206 }
207
208
209
210
211
212
213
214
215 //////////////////////////////////////////////////////////////////////////////
216 //
217 // CTransaction and CTxIndex
218 //
219
220 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
221 {
222     SetNull();
223     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
224         return false;
225     if (!ReadFromDisk(txindexRet.pos))
226         return false;
227     if (prevout.n >= vout.size())
228     {
229         SetNull();
230         return false;
231     }
232     return true;
233 }
234
235 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
236 {
237     CTxIndex txindex;
238     return ReadFromDisk(txdb, prevout, txindex);
239 }
240
241 bool CTransaction::ReadFromDisk(COutPoint prevout)
242 {
243     CTxDB txdb("r");
244     CTxIndex txindex;
245     return ReadFromDisk(txdb, prevout, txindex);
246 }
247
248 bool CTransaction::IsStandard() const
249 {
250     BOOST_FOREACH(const CTxIn& txin, vin)
251     {
252         // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
253         // in an OP_EVAL, which is 3 ~80-byte signatures, 3
254         // ~65-byte public keys, plus a few script ops.
255         if (txin.scriptSig.size() > 500)
256             return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
257         if (!txin.scriptSig.IsPushOnly())
258             return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
259     }
260     BOOST_FOREACH(const CTxOut& txout, vout)
261         if (!::IsStandard(txout.scriptPubKey))
262             return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
263     return true;
264 }
265
266 //
267 // Check transaction inputs, and make sure any
268 // OP_EVAL transactions are evaluating IsStandard scripts
269 //
270 // Why bother? To avoid denial-of-service attacks; an attacker
271 // can submit a standard DUP HASH... OP_EVAL transaction,
272 // which will get accepted into blocks. The script being
273 // EVAL'ed can be anything; an attacker could use a very
274 // expensive-to-check-upon-redemption script like:
275 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
276 //
277 bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
278 {
279     if (fTestNet)
280         return true; // Allow non-standard on testnet
281
282     for (int i = 0; i < vin.size(); i++)
283     {
284         COutPoint prevout = vin[i].prevout;
285         assert(mapInputs.count(prevout.hash) > 0);
286         CTransaction& txPrev = mapInputs[prevout.hash].second;
287         assert(prevout.n < txPrev.vout.size());
288
289         vector<vector<unsigned char> > vSolutions;
290         txnouttype whichType;
291         // get the scriptPubKey corresponding to this input:
292         CScript& prevScript = txPrev.vout[prevout.n].scriptPubKey;
293         if (!Solver(prevScript, whichType, vSolutions))
294             return error("nonstandard txin (spending nonstandard txout %s)", prevScript.ToString().c_str());
295         if (whichType == TX_SCRIPTHASH)
296         {
297             vector<vector<unsigned char> > stack;
298             int nUnused;
299             if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, true, nUnused))
300                 return false;
301             CScript subscript(stack.back().begin(), stack.back().end());
302             if (!::IsStandard(subscript))
303                 return error("nonstandard txin (nonstandard OP_EVAL subscript %s)", subscript.ToString().c_str());
304         }
305     }
306
307     return true;
308 }
309
310
311
312 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
313 {
314     if (fClient)
315     {
316         if (hashBlock == 0)
317             return 0;
318     }
319     else
320     {
321         CBlock blockTmp;
322         if (pblock == NULL)
323         {
324             // Load the block this tx is in
325             CTxIndex txindex;
326             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
327                 return 0;
328             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
329                 return 0;
330             pblock = &blockTmp;
331         }
332
333         // Update the tx's hashBlock
334         hashBlock = pblock->GetHash();
335
336         // Locate the transaction
337         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
338             if (pblock->vtx[nIndex] == *(CTransaction*)this)
339                 break;
340         if (nIndex == pblock->vtx.size())
341         {
342             vMerkleBranch.clear();
343             nIndex = -1;
344             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
345             return 0;
346         }
347
348         // Fill in merkle branch
349         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
350     }
351
352     // Is the tx in a block that's in the main chain
353     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
354     if (mi == mapBlockIndex.end())
355         return 0;
356     CBlockIndex* pindex = (*mi).second;
357     if (!pindex || !pindex->IsInMainChain())
358         return 0;
359
360     return pindexBest->nHeight - pindex->nHeight + 1;
361 }
362
363
364
365
366
367
368
369 bool CTransaction::CheckTransaction() const
370 {
371     // Basic checks that don't depend on any context
372     if (vin.empty())
373         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
374     if (vout.empty())
375         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
376     // Size limits
377     if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
378         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
379
380     // Check for negative or overflow output values
381     int64 nValueOut = 0;
382     BOOST_FOREACH(const CTxOut& txout, vout)
383     {
384         if (txout.nValue < 0)
385             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
386         if (txout.nValue > MAX_MONEY)
387             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
388         nValueOut += txout.nValue;
389         if (!MoneyRange(nValueOut))
390             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
391     }
392
393     // Check for duplicate inputs
394     set<COutPoint> vInOutPoints;
395     BOOST_FOREACH(const CTxIn& txin, vin)
396     {
397         if (vInOutPoints.count(txin.prevout))
398             return false;
399         vInOutPoints.insert(txin.prevout);
400     }
401
402     if (IsCoinBase())
403     {
404         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
405             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
406     }
407     else
408     {
409         BOOST_FOREACH(const CTxIn& txin, vin)
410             if (txin.prevout.IsNull())
411                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
412     }
413
414     return true;
415 }
416
417 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
418 {
419     if (pfMissingInputs)
420         *pfMissingInputs = false;
421
422     if (!CheckTransaction())
423         return error("AcceptToMemoryPool() : CheckTransaction failed");
424
425     // Coinbase is only valid in a block, not as a loose transaction
426     if (IsCoinBase())
427         return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
428
429     // To help v0.1.5 clients who would see it as a negative number
430     if ((int64)nLockTime > std::numeric_limits<int>::max())
431         return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
432
433     // Rather not work on nonstandard transactions (unless -testnet)
434     if (!fTestNet && !IsStandard())
435         return error("AcceptToMemoryPool() : nonstandard transaction type");
436
437     // Do we already have it?
438     uint256 hash = GetHash();
439     CRITICAL_BLOCK(cs_mapTransactions)
440         if (mapTransactions.count(hash))
441             return false;
442     if (fCheckInputs)
443         if (txdb.ContainsTx(hash))
444             return false;
445
446     // Check for conflicts with in-memory transactions
447     CTransaction* ptxOld = NULL;
448     for (int i = 0; i < vin.size(); i++)
449     {
450         COutPoint outpoint = vin[i].prevout;
451         if (mapNextTx.count(outpoint))
452         {
453             // Disable replacement feature for now
454             return false;
455
456             // Allow replacing with a newer version of the same transaction
457             if (i != 0)
458                 return false;
459             ptxOld = mapNextTx[outpoint].ptx;
460             if (ptxOld->IsFinal())
461                 return false;
462             if (!IsNewerThan(*ptxOld))
463                 return false;
464             for (int i = 0; i < vin.size(); i++)
465             {
466                 COutPoint outpoint = vin[i].prevout;
467                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
468                     return false;
469             }
470             break;
471         }
472     }
473
474     if (fCheckInputs)
475     {
476         map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
477         map<uint256, CTxIndex> mapUnused;
478         if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
479         {
480             if (pfMissingInputs)
481                 *pfMissingInputs = true;
482             return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
483         }
484
485         // Check for non-standard OP_EVALs in inputs
486         if (!AreInputsStandard(mapInputs))
487             return error("AcceptToMemoryPool() : nonstandard transaction input");
488
489         // Check against previous transactions
490         int64 nFees = 0;
491         int nSigOps = 0;
492         if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
493         {
494             if (pfMissingInputs)
495                 *pfMissingInputs = true;
496             return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
497         }
498         // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
499         // attacks disallow transactions with more than one SigOp per 65 bytes.
500         // 65 bytes because that is the minimum size of an ECDSA signature
501         unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
502         if (nSigOps > nSize / 65 || nSize < 100)
503             return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
504
505         // Don't accept it if it can't get into a block
506         if (nFees < GetMinFee(1000, true, GMF_RELAY))
507             return error("AcceptToMemoryPool() : not enough fees");
508
509         // Continuously rate-limit free transactions
510         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
511         // be annoying or make other's transactions take longer to confirm.
512         if (nFees < MIN_RELAY_TX_FEE)
513         {
514             static CCriticalSection cs;
515             static double dFreeCount;
516             static int64 nLastTime;
517             int64 nNow = GetTime();
518
519             CRITICAL_BLOCK(cs)
520             {
521                 // Use an exponentially decaying ~10-minute window:
522                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
523                 nLastTime = nNow;
524                 // -limitfreerelay unit is thousand-bytes-per-minute
525                 // At default rate it would take over a month to fill 1GB
526                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
527                     return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
528                 if (fDebug)
529                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
530                 dFreeCount += nSize;
531             }
532         }
533     }
534
535     // Store transaction in memory
536     CRITICAL_BLOCK(cs_mapTransactions)
537     {
538         if (ptxOld)
539         {
540             printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
541             ptxOld->RemoveFromMemoryPool();
542         }
543         AddToMemoryPoolUnchecked();
544     }
545
546     ///// are we sure this is ok when loading transactions or restoring block txes
547     // If updated, erase old tx from wallet
548     if (ptxOld)
549         EraseFromWallets(ptxOld->GetHash());
550
551     printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
552     return true;
553 }
554
555 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
556 {
557     CTxDB txdb("r");
558     return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
559 }
560
561 bool CTransaction::AddToMemoryPoolUnchecked()
562 {
563     // Add to memory pool without checking anything.  Don't call this directly,
564     // call AcceptToMemoryPool to properly check the transaction first.
565     CRITICAL_BLOCK(cs_mapTransactions)
566     {
567         uint256 hash = GetHash();
568         mapTransactions[hash] = *this;
569         for (int i = 0; i < vin.size(); i++)
570             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
571         nTransactionsUpdated++;
572     }
573     return true;
574 }
575
576
577 bool CTransaction::RemoveFromMemoryPool()
578 {
579     // Remove transaction from memory pool
580     CRITICAL_BLOCK(cs_mapTransactions)
581     {
582         BOOST_FOREACH(const CTxIn& txin, vin)
583             mapNextTx.erase(txin.prevout);
584         mapTransactions.erase(GetHash());
585         nTransactionsUpdated++;
586     }
587     return true;
588 }
589
590
591
592
593
594
595 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
596 {
597     if (hashBlock == 0 || nIndex == -1)
598         return 0;
599
600     // Find the block it claims to be in
601     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
602     if (mi == mapBlockIndex.end())
603         return 0;
604     CBlockIndex* pindex = (*mi).second;
605     if (!pindex || !pindex->IsInMainChain())
606         return 0;
607
608     // Make sure the merkle branch connects to this block
609     if (!fMerkleVerified)
610     {
611         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
612             return 0;
613         fMerkleVerified = true;
614     }
615
616     pindexRet = pindex;
617     return pindexBest->nHeight - pindex->nHeight + 1;
618 }
619
620
621 int CMerkleTx::GetBlocksToMaturity() const
622 {
623     if (!IsCoinBase())
624         return 0;
625     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
626 }
627
628
629 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
630 {
631     if (fClient)
632     {
633         if (!IsInMainChain() && !ClientConnectInputs())
634             return false;
635         return CTransaction::AcceptToMemoryPool(txdb, false);
636     }
637     else
638     {
639         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
640     }
641 }
642
643 bool CMerkleTx::AcceptToMemoryPool()
644 {
645     CTxDB txdb("r");
646     return AcceptToMemoryPool(txdb);
647 }
648
649
650
651 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
652 {
653     CRITICAL_BLOCK(cs_mapTransactions)
654     {
655         // Add previous supporting transactions first
656         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
657         {
658             if (!tx.IsCoinBase())
659             {
660                 uint256 hash = tx.GetHash();
661                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
662                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
663             }
664         }
665         return AcceptToMemoryPool(txdb, fCheckInputs);
666     }
667     return false;
668 }
669
670 bool CWalletTx::AcceptWalletTransaction() 
671 {
672     CTxDB txdb("r");
673     return AcceptWalletTransaction(txdb);
674 }
675
676 int CTxIndex::GetDepthInMainChain() const
677 {
678     // Read block header
679     CBlock block;
680     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
681         return 0;
682     // Find the block in the index
683     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
684     if (mi == mapBlockIndex.end())
685         return 0;
686     CBlockIndex* pindex = (*mi).second;
687     if (!pindex || !pindex->IsInMainChain())
688         return 0;
689     return 1 + nBestHeight - pindex->nHeight;
690 }
691
692
693
694
695
696
697
698
699
700
701 //////////////////////////////////////////////////////////////////////////////
702 //
703 // CBlock and CBlockIndex
704 //
705
706 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
707 {
708     if (!fReadTransactions)
709     {
710         *this = pindex->GetBlockHeader();
711         return true;
712     }
713     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
714         return false;
715     if (GetHash() != pindex->GetBlockHash())
716         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
717     return true;
718 }
719
720 uint256 static GetOrphanRoot(const CBlock* pblock)
721 {
722     // Work back to the first block in the orphan chain
723     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
724         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
725     return pblock->GetHash();
726 }
727
728 int64 static GetBlockValue(int nHeight, int64 nFees)
729 {
730     int64 nSubsidy = 50 * COIN;
731
732     // Subsidy is cut in half every 4 years
733     nSubsidy >>= (nHeight / 210000);
734
735     return nSubsidy + nFees;
736 }
737
738 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
739 static const int64 nTargetSpacing = 10 * 60;
740 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
741
742 //
743 // minimum amount of work that could possibly be required nTime after
744 // minimum work required was nBase
745 //
746 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
747 {
748     CBigNum bnResult;
749     bnResult.SetCompact(nBase);
750     while (nTime > 0 && bnResult < bnProofOfWorkLimit)
751     {
752         // Maximum 400% adjustment...
753         bnResult *= 4;
754         // ... in best-case exactly 4-times-normal target time
755         nTime -= nTargetTimespan*4;
756     }
757     if (bnResult > bnProofOfWorkLimit)
758         bnResult = bnProofOfWorkLimit;
759     return bnResult.GetCompact();
760 }
761
762 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
763 {
764
765     // Genesis block
766     if (pindexLast == NULL)
767         return bnProofOfWorkLimit.GetCompact();
768
769     // Only change once per interval
770     if ((pindexLast->nHeight+1) % nInterval != 0)
771         return pindexLast->nBits;
772
773     // Go back by what we want to be 14 days worth of blocks
774     const CBlockIndex* pindexFirst = pindexLast;
775     for (int i = 0; pindexFirst && i < nInterval-1; i++)
776         pindexFirst = pindexFirst->pprev;
777     assert(pindexFirst);
778
779     // Limit adjustment step
780     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
781     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
782     if (nActualTimespan < nTargetTimespan/4)
783         nActualTimespan = nTargetTimespan/4;
784     if (nActualTimespan > nTargetTimespan*4)
785         nActualTimespan = nTargetTimespan*4;
786
787     // Retarget
788     CBigNum bnNew;
789     bnNew.SetCompact(pindexLast->nBits);
790     bnNew *= nActualTimespan;
791     bnNew /= nTargetTimespan;
792
793     if (bnNew > bnProofOfWorkLimit)
794         bnNew = bnProofOfWorkLimit;
795
796     /// debug print
797     printf("GetNextWorkRequired RETARGET\n");
798     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
799     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
800     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
801
802     return bnNew.GetCompact();
803 }
804
805 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
806 {
807     CBigNum bnTarget;
808     bnTarget.SetCompact(nBits);
809
810     // Check range
811     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
812         return error("CheckProofOfWork() : nBits below minimum work");
813
814     // Check proof of work matches claimed amount
815     if (hash > bnTarget.getuint256())
816         return error("CheckProofOfWork() : hash doesn't match nBits");
817
818     return true;
819 }
820
821 // Return maximum amount of blocks that other nodes claim to have
822 int GetNumBlocksOfPeers()
823 {
824     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
825 }
826
827 bool IsInitialBlockDownload()
828 {
829     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
830         return true;
831     static int64 nLastUpdate;
832     static CBlockIndex* pindexLastBest;
833     if (pindexBest != pindexLastBest)
834     {
835         pindexLastBest = pindexBest;
836         nLastUpdate = GetTime();
837     }
838     return (GetTime() - nLastUpdate < 10 &&
839             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
840 }
841
842 void static InvalidChainFound(CBlockIndex* pindexNew)
843 {
844     if (pindexNew->bnChainWork > bnBestInvalidWork)
845     {
846         bnBestInvalidWork = pindexNew->bnChainWork;
847         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
848         MainFrameRepaint();
849     }
850     printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
851     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
852     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
853         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
854 }
855
856
857
858
859
860
861
862
863
864
865
866 bool CTransaction::DisconnectInputs(CTxDB& txdb)
867 {
868     // Relinquish previous transactions' spent pointers
869     if (!IsCoinBase())
870     {
871         BOOST_FOREACH(const CTxIn& txin, vin)
872         {
873             COutPoint prevout = txin.prevout;
874
875             // Get prev txindex from disk
876             CTxIndex txindex;
877             if (!txdb.ReadTxIndex(prevout.hash, txindex))
878                 return error("DisconnectInputs() : ReadTxIndex failed");
879
880             if (prevout.n >= txindex.vSpent.size())
881                 return error("DisconnectInputs() : prevout.n out of range");
882
883             // Mark outpoint as not spent
884             txindex.vSpent[prevout.n].SetNull();
885
886             // Write back
887             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
888                 return error("DisconnectInputs() : UpdateTxIndex failed");
889         }
890     }
891
892     // Remove transaction from index
893     if (!txdb.EraseTxIndex(*this))
894         return error("DisconnectInputs() : EraseTxPos failed");
895
896     return true;
897 }
898
899
900 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
901                                bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
902 {
903     if (IsCoinBase())
904         return true; // Coinbase transactions have no inputs to fetch.
905
906     for (int i = 0; i < vin.size(); i++)
907     {
908         COutPoint prevout = vin[i].prevout;
909         if (inputsRet.count(prevout.hash))
910             continue; // Got it already
911
912         // Read txindex
913         CTxIndex& txindex = inputsRet[prevout.hash].first;
914         bool fFound = true;
915         if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
916         {
917             // Get txindex from current proposed changes
918             txindex = mapTestPool.find(prevout.hash)->second;
919         }
920         else
921         {
922             // Read txindex from txdb
923             fFound = txdb.ReadTxIndex(prevout.hash, txindex);
924         }
925         if (!fFound && (fBlock || fMiner))
926             return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
927
928         // Read txPrev
929         CTransaction& txPrev = inputsRet[prevout.hash].second;
930         if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
931         {
932             // Get prev tx from single transactions in memory
933             CRITICAL_BLOCK(cs_mapTransactions)
934             {
935                 if (!mapTransactions.count(prevout.hash))
936                     return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
937                 txPrev = mapTransactions[prevout.hash];
938             }
939             if (!fFound)
940                 txindex.vSpent.resize(txPrev.vout.size());
941         }
942         else
943         {
944             // Get prev tx from disk
945             if (!txPrev.ReadFromDisk(txindex.pos))
946                 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
947         }
948         if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
949             return DoS(100, error("FetchInputs() : %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()));
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& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 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 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)
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 && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
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 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 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 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 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 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 nAdditionalBytes)
1572 {
1573     uint64 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)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 nTime;
1952         CAddress addrMe;
1953         CAddress addrFrom;
1954         uint64 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 nNow = GetAdjustedTime();
2066         int64 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)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 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 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 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 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 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 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 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 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 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 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 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 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 }