Network stack refactor
[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     }
949
950     // Make sure all prevout.n's are valid:
951     for (int i = 0; i < vin.size(); i++)
952     {
953         const COutPoint prevout = vin[i].prevout;
954         const CTxIndex& txindex = inputsRet[prevout.hash].first;
955         const CTransaction& txPrev = inputsRet[prevout.hash].second;
956         if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
957             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()));
958     }
959
960     return true;
961 }
962
963 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
964                                  map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
965                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
966 {
967     // Take over previous transactions' spent pointers
968     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
969     // fMiner is true when called from the internal bitcoin miner
970     // ... both are false when called from CTransaction::AcceptToMemoryPool
971     if (!IsCoinBase())
972     {
973         int64 nValueIn = 0;
974         for (int i = 0; i < vin.size(); i++)
975         {
976             COutPoint prevout = vin[i].prevout;
977             assert(inputs.count(prevout.hash) > 0);
978             CTxIndex& txindex = inputs[prevout.hash].first;
979             CTransaction& txPrev = inputs[prevout.hash].second;
980
981             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
982                 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()));
983
984             // If prev is coinbase, check that it's matured
985             if (txPrev.IsCoinBase())
986                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
987                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
988                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
989
990             // Skip ECDSA signature verification when connecting blocks (fBlock=true)
991             // before the last blockchain checkpoint. This is safe because block merkle hashes are
992             // still computed and checked, and any change will be caught at the next checkpoint.
993             if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
994             {
995                 bool fStrictOpEval = true;
996                 // This code should be removed when OP_EVAL has
997                 // a majority of hashing power on the network.
998                 if (fBlock)
999                 {
1000                     // To avoid being on the short end of a block-chain split,
1001                     // interpret OP_EVAL as a NO_OP until blocks with timestamps
1002                     // after opevaltime:
1003                     int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
1004                     fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
1005                 }
1006                 // if !fBlock, then always be strict-- don't accept
1007                 // invalid-under-new-rules OP_EVAL transactions into
1008                 // our memory pool (don't relay them, don't include them
1009                 // in blocks we mine).
1010
1011                 // Verify signature
1012                 if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
1013                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1014             }
1015
1016             // Check for conflicts (double-spend)
1017             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1018             // for an attacker to attempt to split the network.
1019             if (!txindex.vSpent[prevout.n].IsNull())
1020                 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());
1021
1022             // Check for negative or overflow input values
1023             nValueIn += txPrev.vout[prevout.n].nValue;
1024             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1025                 return DoS(100, error("ConnectInputs() : txin values out of range"));
1026
1027             // Mark outpoints as spent
1028             txindex.vSpent[prevout.n] = posThisTx;
1029
1030             // Write back
1031             if (fBlock || fMiner)
1032             {
1033                 mapTestPool[prevout.hash] = txindex;
1034             }
1035         }
1036
1037         if (nValueIn < GetValueOut())
1038             return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1039
1040         // Tally transaction fees
1041         int64 nTxFee = nValueIn - GetValueOut();
1042         if (nTxFee < 0)
1043             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1044         if (nTxFee < nMinFee)
1045             return false;
1046         nFees += nTxFee;
1047         if (!MoneyRange(nFees))
1048             return DoS(100, error("ConnectInputs() : nFees out of range"));
1049     }
1050
1051     if (fBlock)
1052     {
1053         // Add transaction to changes
1054         mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1055     }
1056     else if (fMiner)
1057     {
1058         // Add transaction to test pool
1059         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1060     }
1061
1062     return true;
1063 }
1064
1065
1066 bool CTransaction::ClientConnectInputs()
1067 {
1068     if (IsCoinBase())
1069         return false;
1070
1071     // Take over previous transactions' spent pointers
1072     CRITICAL_BLOCK(cs_mapTransactions)
1073     {
1074         int64 nValueIn = 0;
1075         for (int i = 0; i < vin.size(); i++)
1076         {
1077             // Get prev tx from single transactions in memory
1078             COutPoint prevout = vin[i].prevout;
1079             if (!mapTransactions.count(prevout.hash))
1080                 return false;
1081             CTransaction& txPrev = mapTransactions[prevout.hash];
1082
1083             if (prevout.n >= txPrev.vout.size())
1084                 return false;
1085
1086             // Verify signature
1087             int nUnused = 0;
1088             if (!VerifySignature(txPrev, *this, i, nUnused, false))
1089                 return error("ConnectInputs() : VerifySignature failed");
1090
1091             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1092             ///// this has to go away now that posNext is gone
1093             // // Check for conflicts
1094             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1095             //     return error("ConnectInputs() : prev tx already used");
1096             //
1097             // // Flag outpoints as used
1098             // txPrev.vout[prevout.n].posNext = posThisTx;
1099
1100             nValueIn += txPrev.vout[prevout.n].nValue;
1101
1102             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1103                 return error("ClientConnectInputs() : txin values out of range");
1104         }
1105         if (GetValueOut() > nValueIn)
1106             return false;
1107     }
1108
1109     return true;
1110 }
1111
1112
1113
1114
1115 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1116 {
1117     // Disconnect in reverse order
1118     for (int i = vtx.size()-1; i >= 0; i--)
1119         if (!vtx[i].DisconnectInputs(txdb))
1120             return false;
1121
1122     // Update block index on disk without changing it in memory.
1123     // The memory index structure will be changed after the db commits.
1124     if (pindex->pprev)
1125     {
1126         CDiskBlockIndex blockindexPrev(pindex->pprev);
1127         blockindexPrev.hashNext = 0;
1128         if (!txdb.WriteBlockIndex(blockindexPrev))
1129             return error("DisconnectBlock() : WriteBlockIndex failed");
1130     }
1131
1132     return true;
1133 }
1134
1135 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1136 {
1137     // Check it again in case a previous version let a bad block in
1138     if (!CheckBlock())
1139         return false;
1140
1141     //// issue here: it doesn't know the version
1142     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1143
1144     map<uint256, CTxIndex> mapQueuedChanges;
1145     int64 nFees = 0;
1146     int nSigOps = 0;
1147     BOOST_FOREACH(CTransaction& tx, vtx)
1148     {
1149         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1150         nTxPos += ::GetSerializeSize(tx, SER_DISK);
1151
1152         map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1153         if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1154             return false;
1155         if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1156             return false;
1157         if (nSigOps > MAX_BLOCK_SIGOPS)
1158             return DoS(100, error("ConnectBlock() : too many sigops"));
1159     }
1160
1161     // Write queued txindex changes
1162     for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1163     {
1164         if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1165             return error("ConnectBlock() : UpdateTxIndex failed");
1166     }
1167
1168     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1169         return false;
1170
1171     // Update block index on disk without changing it in memory.
1172     // The memory index structure will be changed after the db commits.
1173     if (pindex->pprev)
1174     {
1175         CDiskBlockIndex blockindexPrev(pindex->pprev);
1176         blockindexPrev.hashNext = pindex->GetBlockHash();
1177         if (!txdb.WriteBlockIndex(blockindexPrev))
1178             return error("ConnectBlock() : WriteBlockIndex failed");
1179     }
1180
1181     // Watch for transactions paying to me
1182     BOOST_FOREACH(CTransaction& tx, vtx)
1183         SyncWithWallets(tx, this, true);
1184
1185     return true;
1186 }
1187
1188 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1189 {
1190     printf("REORGANIZE\n");
1191
1192     // Find the fork
1193     CBlockIndex* pfork = pindexBest;
1194     CBlockIndex* plonger = pindexNew;
1195     while (pfork != plonger)
1196     {
1197         while (plonger->nHeight > pfork->nHeight)
1198             if (!(plonger = plonger->pprev))
1199                 return error("Reorganize() : plonger->pprev is null");
1200         if (pfork == plonger)
1201             break;
1202         if (!(pfork = pfork->pprev))
1203             return error("Reorganize() : pfork->pprev is null");
1204     }
1205
1206     // List of what to disconnect
1207     vector<CBlockIndex*> vDisconnect;
1208     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1209         vDisconnect.push_back(pindex);
1210
1211     // List of what to connect
1212     vector<CBlockIndex*> vConnect;
1213     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1214         vConnect.push_back(pindex);
1215     reverse(vConnect.begin(), vConnect.end());
1216
1217     // Disconnect shorter branch
1218     vector<CTransaction> vResurrect;
1219     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1220     {
1221         CBlock block;
1222         if (!block.ReadFromDisk(pindex))
1223             return error("Reorganize() : ReadFromDisk for disconnect failed");
1224         if (!block.DisconnectBlock(txdb, pindex))
1225             return error("Reorganize() : DisconnectBlock failed");
1226
1227         // Queue memory transactions to resurrect
1228         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1229             if (!tx.IsCoinBase())
1230                 vResurrect.push_back(tx);
1231     }
1232
1233     // Connect longer branch
1234     vector<CTransaction> vDelete;
1235     for (int i = 0; i < vConnect.size(); i++)
1236     {
1237         CBlockIndex* pindex = vConnect[i];
1238         CBlock block;
1239         if (!block.ReadFromDisk(pindex))
1240             return error("Reorganize() : ReadFromDisk for connect failed");
1241         if (!block.ConnectBlock(txdb, pindex))
1242         {
1243             // Invalid block
1244             txdb.TxnAbort();
1245             return error("Reorganize() : ConnectBlock failed");
1246         }
1247
1248         // Queue memory transactions to delete
1249         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1250             vDelete.push_back(tx);
1251     }
1252     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1253         return error("Reorganize() : WriteHashBestChain failed");
1254
1255     // Make sure it's successfully written to disk before changing memory structure
1256     if (!txdb.TxnCommit())
1257         return error("Reorganize() : TxnCommit failed");
1258
1259     // Disconnect shorter branch
1260     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1261         if (pindex->pprev)
1262             pindex->pprev->pnext = NULL;
1263
1264     // Connect longer branch
1265     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1266         if (pindex->pprev)
1267             pindex->pprev->pnext = pindex;
1268
1269     // Resurrect memory transactions that were in the disconnected branch
1270     BOOST_FOREACH(CTransaction& tx, vResurrect)
1271         tx.AcceptToMemoryPool(txdb, false);
1272
1273     // Delete redundant memory transactions that are in the connected branch
1274     BOOST_FOREACH(CTransaction& tx, vDelete)
1275         tx.RemoveFromMemoryPool();
1276
1277     return true;
1278 }
1279
1280
1281 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1282 {
1283     uint256 hash = GetHash();
1284
1285     txdb.TxnBegin();
1286     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1287     {
1288         txdb.WriteHashBestChain(hash);
1289         if (!txdb.TxnCommit())
1290             return error("SetBestChain() : TxnCommit failed");
1291         pindexGenesisBlock = pindexNew;
1292     }
1293     else if (hashPrevBlock == hashBestChain)
1294     {
1295         // Adding to current best branch
1296         if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1297         {
1298             txdb.TxnAbort();
1299             InvalidChainFound(pindexNew);
1300             return error("SetBestChain() : ConnectBlock failed");
1301         }
1302         if (!txdb.TxnCommit())
1303             return error("SetBestChain() : TxnCommit failed");
1304
1305         // Add to current best branch
1306         pindexNew->pprev->pnext = pindexNew;
1307
1308         // Delete redundant memory transactions
1309         BOOST_FOREACH(CTransaction& tx, vtx)
1310             tx.RemoveFromMemoryPool();
1311     }
1312     else
1313     {
1314         // New best branch
1315         if (!Reorganize(txdb, pindexNew))
1316         {
1317             txdb.TxnAbort();
1318             InvalidChainFound(pindexNew);
1319             return error("SetBestChain() : Reorganize failed");
1320         }
1321     }
1322
1323     // Update best block in wallet (so we can detect restored wallets)
1324     if (!IsInitialBlockDownload())
1325     {
1326         const CBlockLocator locator(pindexNew);
1327         ::SetBestChain(locator);
1328     }
1329
1330     // New best block
1331     hashBestChain = hash;
1332     pindexBest = pindexNew;
1333     nBestHeight = pindexBest->nHeight;
1334     bnBestChainWork = pindexNew->bnChainWork;
1335     nTimeBestReceived = GetTime();
1336     nTransactionsUpdated++;
1337     printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1338
1339     return true;
1340 }
1341
1342
1343 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1344 {
1345     // Check for duplicate
1346     uint256 hash = GetHash();
1347     if (mapBlockIndex.count(hash))
1348         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1349
1350     // Construct new block index object
1351     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1352     if (!pindexNew)
1353         return error("AddToBlockIndex() : new CBlockIndex failed");
1354     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1355     pindexNew->phashBlock = &((*mi).first);
1356     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1357     if (miPrev != mapBlockIndex.end())
1358     {
1359         pindexNew->pprev = (*miPrev).second;
1360         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1361     }
1362     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1363
1364     CTxDB txdb;
1365     txdb.TxnBegin();
1366     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1367     if (!txdb.TxnCommit())
1368         return false;
1369
1370     // New best
1371     if (pindexNew->bnChainWork > bnBestChainWork)
1372         if (!SetBestChain(txdb, pindexNew))
1373             return false;
1374
1375     txdb.Close();
1376
1377     if (pindexNew == pindexBest)
1378     {
1379         // Notify UI to display prev block's coinbase if it was ours
1380         static uint256 hashPrevBestCoinBase;
1381         UpdatedTransaction(hashPrevBestCoinBase);
1382         hashPrevBestCoinBase = vtx[0].GetHash();
1383     }
1384
1385     MainFrameRepaint();
1386     return true;
1387 }
1388
1389
1390
1391
1392 bool CBlock::CheckBlock() const
1393 {
1394     // These are checks that are independent of context
1395     // that can be verified before saving an orphan block.
1396
1397     // Size limits
1398     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1399         return DoS(100, error("CheckBlock() : size limits failed"));
1400
1401     // Check proof of work matches claimed amount
1402     if (!CheckProofOfWork(GetHash(), nBits))
1403         return DoS(50, error("CheckBlock() : proof of work failed"));
1404
1405     // Check timestamp
1406     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1407         return error("CheckBlock() : block timestamp too far in the future");
1408
1409     // First transaction must be coinbase, the rest must not be
1410     if (vtx.empty() || !vtx[0].IsCoinBase())
1411         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1412     for (int i = 1; i < vtx.size(); i++)
1413         if (vtx[i].IsCoinBase())
1414             return DoS(100, error("CheckBlock() : more than one coinbase"));
1415
1416     // Check transactions
1417     BOOST_FOREACH(const CTransaction& tx, vtx)
1418         if (!tx.CheckTransaction())
1419             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1420
1421     // This code should be removed when a compatibility-breaking block chain split has passed.
1422     // Compatibility check for old clients that counted sigops differently:
1423     int nSigOps = 0;
1424     BOOST_FOREACH(const CTransaction& tx, vtx)
1425     {
1426         BOOST_FOREACH(const CTxIn& txin, tx.vin)
1427         {
1428             nSigOps += txin.scriptSig.GetSigOpCount();
1429         }
1430         BOOST_FOREACH(const CTxOut& txout, tx.vout)
1431         {
1432             nSigOps += txout.scriptPubKey.GetSigOpCount();
1433         }
1434     }
1435     if (nSigOps > MAX_BLOCK_SIGOPS)
1436         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1437
1438     // Check merkleroot
1439     if (hashMerkleRoot != BuildMerkleTree())
1440         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1441
1442     return true;
1443 }
1444
1445 bool CBlock::AcceptBlock()
1446 {
1447     // Check for duplicate
1448     uint256 hash = GetHash();
1449     if (mapBlockIndex.count(hash))
1450         return error("AcceptBlock() : block already in mapBlockIndex");
1451
1452     // Get prev block index
1453     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1454     if (mi == mapBlockIndex.end())
1455         return DoS(10, error("AcceptBlock() : prev block not found"));
1456     CBlockIndex* pindexPrev = (*mi).second;
1457     int nHeight = pindexPrev->nHeight+1;
1458
1459     // Check proof of work
1460     if (nBits != GetNextWorkRequired(pindexPrev))
1461         return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1462
1463     // Check timestamp against prev
1464     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1465         return error("AcceptBlock() : block's timestamp is too early");
1466
1467     // Check that all transactions are finalized
1468     BOOST_FOREACH(const CTransaction& tx, vtx)
1469         if (!tx.IsFinal(nHeight, GetBlockTime()))
1470             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1471
1472     // Check that the block chain matches the known block chain up to a checkpoint
1473     if (!Checkpoints::CheckBlock(nHeight, hash))
1474         return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1475
1476     // Write block to history file
1477     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1478         return error("AcceptBlock() : out of disk space");
1479     unsigned int nFile = -1;
1480     unsigned int nBlockPos = 0;
1481     if (!WriteToDisk(nFile, nBlockPos))
1482         return error("AcceptBlock() : WriteToDisk failed");
1483     if (!AddToBlockIndex(nFile, nBlockPos))
1484         return error("AcceptBlock() : AddToBlockIndex failed");
1485
1486     // Relay inventory, but don't relay old inventory during initial block download
1487     if (hashBestChain == hash)
1488         CRITICAL_BLOCK(cs_vNodes)
1489             BOOST_FOREACH(CNode* pnode, vNodes)
1490                 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1491                     pnode->PushInventory(CInv(MSG_BLOCK, hash));
1492
1493     return true;
1494 }
1495
1496 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1497 {
1498     // Check for duplicate
1499     uint256 hash = pblock->GetHash();
1500     if (mapBlockIndex.count(hash))
1501         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1502     if (mapOrphanBlocks.count(hash))
1503         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1504
1505     // Preliminary checks
1506     if (!pblock->CheckBlock())
1507         return error("ProcessBlock() : CheckBlock FAILED");
1508
1509     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1510     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1511     {
1512         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1513         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1514         if (deltaTime < 0)
1515         {
1516             pfrom->Misbehaving(100);
1517             return error("ProcessBlock() : block with timestamp before last checkpoint");
1518         }
1519         CBigNum bnNewBlock;
1520         bnNewBlock.SetCompact(pblock->nBits);
1521         CBigNum bnRequired;
1522         bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1523         if (bnNewBlock > bnRequired)
1524         {
1525             pfrom->Misbehaving(100);
1526             return error("ProcessBlock() : block with too little proof-of-work");
1527         }
1528     }
1529
1530
1531     // If don't already have its previous block, shunt it off to holding area until we get it
1532     if (!mapBlockIndex.count(pblock->hashPrevBlock))
1533     {
1534         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1535         CBlock* pblock2 = new CBlock(*pblock);
1536         mapOrphanBlocks.insert(make_pair(hash, pblock2));
1537         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1538
1539         // Ask this guy to fill in what we're missing
1540         if (pfrom)
1541             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1542         return true;
1543     }
1544
1545     // Store to disk
1546     if (!pblock->AcceptBlock())
1547         return error("ProcessBlock() : AcceptBlock FAILED");
1548
1549     // Recursively process any orphan blocks that depended on this one
1550     vector<uint256> vWorkQueue;
1551     vWorkQueue.push_back(hash);
1552     for (int i = 0; i < vWorkQueue.size(); i++)
1553     {
1554         uint256 hashPrev = vWorkQueue[i];
1555         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1556              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1557              ++mi)
1558         {
1559             CBlock* pblockOrphan = (*mi).second;
1560             if (pblockOrphan->AcceptBlock())
1561                 vWorkQueue.push_back(pblockOrphan->GetHash());
1562             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1563             delete pblockOrphan;
1564         }
1565         mapOrphanBlocksByPrev.erase(hashPrev);
1566     }
1567
1568     printf("ProcessBlock: ACCEPTED\n");
1569     return true;
1570 }
1571
1572
1573
1574
1575
1576
1577
1578
1579 bool CheckDiskSpace(uint64 nAdditionalBytes)
1580 {
1581     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1582
1583     // Check for 15MB because database could create another 10MB log file at any time
1584     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1585     {
1586         fShutdown = true;
1587         string strMessage = _("Warning: Disk space is low  ");
1588         strMiscWarning = strMessage;
1589         printf("*** %s\n", strMessage.c_str());
1590         ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1591         CreateThread(Shutdown, NULL);
1592         return false;
1593     }
1594     return true;
1595 }
1596
1597 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1598 {
1599     if (nFile == -1)
1600         return NULL;
1601     FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1602     if (!file)
1603         return NULL;
1604     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1605     {
1606         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1607         {
1608             fclose(file);
1609             return NULL;
1610         }
1611     }
1612     return file;
1613 }
1614
1615 static unsigned int nCurrentBlockFile = 1;
1616
1617 FILE* AppendBlockFile(unsigned int& nFileRet)
1618 {
1619     nFileRet = 0;
1620     loop
1621     {
1622         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1623         if (!file)
1624             return NULL;
1625         if (fseek(file, 0, SEEK_END) != 0)
1626             return NULL;
1627         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1628         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1629         {
1630             nFileRet = nCurrentBlockFile;
1631             return file;
1632         }
1633         fclose(file);
1634         nCurrentBlockFile++;
1635     }
1636 }
1637
1638 bool LoadBlockIndex(bool fAllowNew)
1639 {
1640     if (fTestNet)
1641     {
1642         hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1643         bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1644         pchMessageStart[0] = 0xfa;
1645         pchMessageStart[1] = 0xbf;
1646         pchMessageStart[2] = 0xb5;
1647         pchMessageStart[3] = 0xda;
1648     }
1649
1650     //
1651     // Load block index
1652     //
1653     CTxDB txdb("cr");
1654     if (!txdb.LoadBlockIndex())
1655         return false;
1656     txdb.Close();
1657
1658     //
1659     // Init with genesis block
1660     //
1661     if (mapBlockIndex.empty())
1662     {
1663         if (!fAllowNew)
1664             return false;
1665
1666         // Genesis Block:
1667         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1668         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1669         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1670         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1671         //   vMerkleTree: 4a5e1e
1672
1673         // Genesis block
1674         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1675         CTransaction txNew;
1676         txNew.vin.resize(1);
1677         txNew.vout.resize(1);
1678         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1679         txNew.vout[0].nValue = 50 * COIN;
1680         txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1681         CBlock block;
1682         block.vtx.push_back(txNew);
1683         block.hashPrevBlock = 0;
1684         block.hashMerkleRoot = block.BuildMerkleTree();
1685         block.nVersion = 1;
1686         block.nTime    = 1231006505;
1687         block.nBits    = 0x1d00ffff;
1688         block.nNonce   = 2083236893;
1689
1690         if (fTestNet)
1691         {
1692             block.nTime    = 1296688602;
1693             block.nBits    = 0x1d07fff8;
1694             block.nNonce   = 384568319;
1695         }
1696
1697         //// debug print
1698         printf("%s\n", block.GetHash().ToString().c_str());
1699         printf("%s\n", hashGenesisBlock.ToString().c_str());
1700         printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1701         assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1702         block.print();
1703         assert(block.GetHash() == hashGenesisBlock);
1704
1705         // Start new block file
1706         unsigned int nFile;
1707         unsigned int nBlockPos;
1708         if (!block.WriteToDisk(nFile, nBlockPos))
1709             return error("LoadBlockIndex() : writing genesis block to disk failed");
1710         if (!block.AddToBlockIndex(nFile, nBlockPos))
1711             return error("LoadBlockIndex() : genesis block not accepted");
1712     }
1713
1714     return true;
1715 }
1716
1717
1718
1719 void PrintBlockTree()
1720 {
1721     // precompute tree structure
1722     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1723     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1724     {
1725         CBlockIndex* pindex = (*mi).second;
1726         mapNext[pindex->pprev].push_back(pindex);
1727         // test
1728         //while (rand() % 3 == 0)
1729         //    mapNext[pindex->pprev].push_back(pindex);
1730     }
1731
1732     vector<pair<int, CBlockIndex*> > vStack;
1733     vStack.push_back(make_pair(0, pindexGenesisBlock));
1734
1735     int nPrevCol = 0;
1736     while (!vStack.empty())
1737     {
1738         int nCol = vStack.back().first;
1739         CBlockIndex* pindex = vStack.back().second;
1740         vStack.pop_back();
1741
1742         // print split or gap
1743         if (nCol > nPrevCol)
1744         {
1745             for (int i = 0; i < nCol-1; i++)
1746                 printf("| ");
1747             printf("|\\\n");
1748         }
1749         else if (nCol < nPrevCol)
1750         {
1751             for (int i = 0; i < nCol; i++)
1752                 printf("| ");
1753             printf("|\n");
1754        }
1755         nPrevCol = nCol;
1756
1757         // print columns
1758         for (int i = 0; i < nCol; i++)
1759             printf("| ");
1760
1761         // print item
1762         CBlock block;
1763         block.ReadFromDisk(pindex);
1764         printf("%d (%u,%u) %s  %s  tx %d",
1765             pindex->nHeight,
1766             pindex->nFile,
1767             pindex->nBlockPos,
1768             block.GetHash().ToString().substr(0,20).c_str(),
1769             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1770             block.vtx.size());
1771
1772         PrintWallets(block);
1773
1774         // put the main timechain first
1775         vector<CBlockIndex*>& vNext = mapNext[pindex];
1776         for (int i = 0; i < vNext.size(); i++)
1777         {
1778             if (vNext[i]->pnext)
1779             {
1780                 swap(vNext[0], vNext[i]);
1781                 break;
1782             }
1783         }
1784
1785         // iterate children
1786         for (int i = 0; i < vNext.size(); i++)
1787             vStack.push_back(make_pair(nCol+i, vNext[i]));
1788     }
1789 }
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800 //////////////////////////////////////////////////////////////////////////////
1801 //
1802 // CAlert
1803 //
1804
1805 map<uint256, CAlert> mapAlerts;
1806 CCriticalSection cs_mapAlerts;
1807
1808 string GetWarnings(string strFor)
1809 {
1810     int nPriority = 0;
1811     string strStatusBar;
1812     string strRPC;
1813     if (GetBoolArg("-testsafemode"))
1814         strRPC = "test";
1815
1816     // Misc warnings like out of disk space and clock is wrong
1817     if (strMiscWarning != "")
1818     {
1819         nPriority = 1000;
1820         strStatusBar = strMiscWarning;
1821     }
1822
1823     // Longer invalid proof-of-work chain
1824     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1825     {
1826         nPriority = 2000;
1827         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
1828     }
1829
1830     // Alerts
1831     CRITICAL_BLOCK(cs_mapAlerts)
1832     {
1833         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1834         {
1835             const CAlert& alert = item.second;
1836             if (alert.AppliesToMe() && alert.nPriority > nPriority)
1837             {
1838                 nPriority = alert.nPriority;
1839                 strStatusBar = alert.strStatusBar;
1840             }
1841         }
1842     }
1843
1844     if (strFor == "statusbar")
1845         return strStatusBar;
1846     else if (strFor == "rpc")
1847         return strRPC;
1848     assert(!"GetWarnings() : invalid parameter");
1849     return "error";
1850 }
1851
1852 bool CAlert::ProcessAlert()
1853 {
1854     if (!CheckSignature())
1855         return false;
1856     if (!IsInEffect())
1857         return false;
1858
1859     CRITICAL_BLOCK(cs_mapAlerts)
1860     {
1861         // Cancel previous alerts
1862         for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1863         {
1864             const CAlert& alert = (*mi).second;
1865             if (Cancels(alert))
1866             {
1867                 printf("cancelling alert %d\n", alert.nID);
1868                 mapAlerts.erase(mi++);
1869             }
1870             else if (!alert.IsInEffect())
1871             {
1872                 printf("expiring alert %d\n", alert.nID);
1873                 mapAlerts.erase(mi++);
1874             }
1875             else
1876                 mi++;
1877         }
1878
1879         // Check if this alert has been cancelled
1880         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1881         {
1882             const CAlert& alert = item.second;
1883             if (alert.Cancels(*this))
1884             {
1885                 printf("alert already cancelled by %d\n", alert.nID);
1886                 return false;
1887             }
1888         }
1889
1890         // Add to mapAlerts
1891         mapAlerts.insert(make_pair(GetHash(), *this));
1892     }
1893
1894     printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1895     MainFrameRepaint();
1896     return true;
1897 }
1898
1899
1900
1901
1902
1903
1904
1905
1906 //////////////////////////////////////////////////////////////////////////////
1907 //
1908 // Messages
1909 //
1910
1911
1912 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1913 {
1914     switch (inv.type)
1915     {
1916     case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1917     case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1918     }
1919     // Don't know what it is, just say we already got one
1920     return true;
1921 }
1922
1923
1924
1925
1926 // The message start string is designed to be unlikely to occur in normal data.
1927 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1928 // a large 4-byte int at any alignment.
1929 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1930
1931
1932 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1933 {
1934     static map<CService, vector<unsigned char> > mapReuseKey;
1935     RandAddSeedPerfmon();
1936     if (fDebug) {
1937         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1938         printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1939     }
1940     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1941     {
1942         printf("dropmessagestest DROPPING RECV MESSAGE\n");
1943         return true;
1944     }
1945
1946
1947
1948
1949
1950     if (strCommand == "version")
1951     {
1952         // Each connection can only send one version message
1953         if (pfrom->nVersion != 0)
1954         {
1955             pfrom->Misbehaving(1);
1956             return false;
1957         }
1958
1959         int64 nTime;
1960         CAddress addrMe;
1961         CAddress addrFrom;
1962         uint64 nNonce = 1;
1963         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1964         if (pfrom->nVersion == 10300)
1965             pfrom->nVersion = 300;
1966         if (pfrom->nVersion >= 106 && !vRecv.empty())
1967             vRecv >> addrFrom >> nNonce;
1968         if (pfrom->nVersion >= 106 && !vRecv.empty())
1969             vRecv >> pfrom->strSubVer;
1970         if (pfrom->nVersion >= 209 && !vRecv.empty())
1971             vRecv >> pfrom->nStartingHeight;
1972
1973         if (pfrom->nVersion == 0)
1974             return false;
1975
1976         // Disconnect if we connected to ourself
1977         if (nNonce == nLocalHostNonce && nNonce > 1)
1978         {
1979             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1980             pfrom->fDisconnect = true;
1981             return true;
1982         }
1983
1984         // Be shy and don't send version until we hear
1985         if (pfrom->fInbound)
1986             pfrom->PushVersion();
1987
1988         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1989
1990         AddTimeData(pfrom->addr, nTime);
1991
1992         // Change version
1993         if (pfrom->nVersion >= 209)
1994             pfrom->PushMessage("verack");
1995         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1996         if (pfrom->nVersion < 209)
1997             pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1998
1999         if (!pfrom->fInbound)
2000         {
2001             // Advertise our address
2002             if (addrLocalHost.IsRoutable() && !fUseProxy)
2003             {
2004                 CAddress addr(addrLocalHost);
2005                 addr.nTime = GetAdjustedTime();
2006                 pfrom->PushAddress(addr);
2007             }
2008
2009             // Get recent addresses
2010             if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2011             {
2012                 pfrom->PushMessage("getaddr");
2013                 pfrom->fGetAddr = true;
2014             }
2015         }
2016
2017         // Ask the first connected node for block updates
2018         static int nAskedForBlocks = 0;
2019         if (!pfrom->fClient &&
2020             (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2021              (nAskedForBlocks < 1 || vNodes.size() <= 1))
2022         {
2023             nAskedForBlocks++;
2024             pfrom->PushGetBlocks(pindexBest, uint256(0));
2025         }
2026
2027         // Relay alerts
2028         CRITICAL_BLOCK(cs_mapAlerts)
2029             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2030                 item.second.RelayTo(pfrom);
2031
2032         pfrom->fSuccessfullyConnected = true;
2033
2034         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2035
2036         cPeerBlockCounts.input(pfrom->nStartingHeight);
2037     }
2038
2039
2040     else if (pfrom->nVersion == 0)
2041     {
2042         // Must have a version message before anything else
2043         pfrom->Misbehaving(1);
2044         return false;
2045     }
2046
2047
2048     else if (strCommand == "verack")
2049     {
2050         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2051     }
2052
2053
2054     else if (strCommand == "addr")
2055     {
2056         vector<CAddress> vAddr;
2057         vRecv >> vAddr;
2058
2059         // Don't want addr from older versions unless seeding
2060         if (pfrom->nVersion < 209)
2061             return true;
2062         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2063             return true;
2064         if (vAddr.size() > 1000)
2065         {
2066             pfrom->Misbehaving(20);
2067             return error("message addr size() = %d", vAddr.size());
2068         }
2069
2070         // Store the new addresses
2071         CAddrDB addrDB;
2072         addrDB.TxnBegin();
2073         int64 nNow = GetAdjustedTime();
2074         int64 nSince = nNow - 10 * 60;
2075         BOOST_FOREACH(CAddress& addr, vAddr)
2076         {
2077             if (fShutdown)
2078                 return true;
2079             // ignore IPv6 for now, since it isn't implemented anyway
2080             if (!addr.IsIPv4())
2081                 continue;
2082             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2083                 addr.nTime = nNow - 5 * 24 * 60 * 60;
2084             AddAddress(addr, 2 * 60 * 60, &addrDB);
2085             pfrom->AddAddressKnown(addr);
2086             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2087             {
2088                 // Relay to a limited number of other nodes
2089                 CRITICAL_BLOCK(cs_vNodes)
2090                 {
2091                     // Use deterministic randomness to send to the same nodes for 24 hours
2092                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2093                     static uint256 hashSalt;
2094                     if (hashSalt == 0)
2095                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2096                     int64 hashAddr = addr.GetHash();
2097                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2098                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2099                     multimap<uint256, CNode*> mapMix;
2100                     BOOST_FOREACH(CNode* pnode, vNodes)
2101                     {
2102                         if (pnode->nVersion < 31402)
2103                             continue;
2104                         unsigned int nPointer;
2105                         memcpy(&nPointer, &pnode, sizeof(nPointer));
2106                         uint256 hashKey = hashRand ^ nPointer;
2107                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
2108                         mapMix.insert(make_pair(hashKey, pnode));
2109                     }
2110                     int nRelayNodes = 2;
2111                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2112                         ((*mi).second)->PushAddress(addr);
2113                 }
2114             }
2115         }
2116         addrDB.TxnCommit();  // Save addresses (it's ok if this fails)
2117         if (vAddr.size() < 1000)
2118             pfrom->fGetAddr = false;
2119     }
2120
2121
2122     else if (strCommand == "inv")
2123     {
2124         vector<CInv> vInv;
2125         vRecv >> vInv;
2126         if (vInv.size() > 50000)
2127         {
2128             pfrom->Misbehaving(20);
2129             return error("message inv size() = %d", vInv.size());
2130         }
2131
2132         CTxDB txdb("r");
2133         BOOST_FOREACH(const CInv& inv, vInv)
2134         {
2135             if (fShutdown)
2136                 return true;
2137             pfrom->AddInventoryKnown(inv);
2138
2139             bool fAlreadyHave = AlreadyHave(txdb, inv);
2140             if (fDebug)
2141                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2142
2143             if (!fAlreadyHave)
2144                 pfrom->AskFor(inv);
2145             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2146                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2147
2148             // Track requests for our stuff
2149             Inventory(inv.hash);
2150         }
2151     }
2152
2153
2154     else if (strCommand == "getdata")
2155     {
2156         vector<CInv> vInv;
2157         vRecv >> vInv;
2158         if (vInv.size() > 50000)
2159         {
2160             pfrom->Misbehaving(20);
2161             return error("message getdata size() = %d", vInv.size());
2162         }
2163
2164         BOOST_FOREACH(const CInv& inv, vInv)
2165         {
2166             if (fShutdown)
2167                 return true;
2168             printf("received getdata for: %s\n", inv.ToString().c_str());
2169
2170             if (inv.type == MSG_BLOCK)
2171             {
2172                 // Send block from disk
2173                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2174                 if (mi != mapBlockIndex.end())
2175                 {
2176                     CBlock block;
2177                     block.ReadFromDisk((*mi).second);
2178                     pfrom->PushMessage("block", block);
2179
2180                     // Trigger them to send a getblocks request for the next batch of inventory
2181                     if (inv.hash == pfrom->hashContinue)
2182                     {
2183                         // Bypass PushInventory, this must send even if redundant,
2184                         // and we want it right after the last block so they don't
2185                         // wait for other stuff first.
2186                         vector<CInv> vInv;
2187                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2188                         pfrom->PushMessage("inv", vInv);
2189                         pfrom->hashContinue = 0;
2190                     }
2191                 }
2192             }
2193             else if (inv.IsKnownType())
2194             {
2195                 // Send stream from relay memory
2196                 CRITICAL_BLOCK(cs_mapRelay)
2197                 {
2198                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2199                     if (mi != mapRelay.end())
2200                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2201                 }
2202             }
2203
2204             // Track requests for our stuff
2205             Inventory(inv.hash);
2206         }
2207     }
2208
2209
2210     else if (strCommand == "getblocks")
2211     {
2212         CBlockLocator locator;
2213         uint256 hashStop;
2214         vRecv >> locator >> hashStop;
2215
2216         // Find the last block the caller has in the main chain
2217         CBlockIndex* pindex = locator.GetBlockIndex();
2218
2219         // Send the rest of the chain
2220         if (pindex)
2221             pindex = pindex->pnext;
2222         int nLimit = 500 + locator.GetDistanceBack();
2223         unsigned int nBytes = 0;
2224         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2225         for (; pindex; pindex = pindex->pnext)
2226         {
2227             if (pindex->GetBlockHash() == hashStop)
2228             {
2229                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2230                 break;
2231             }
2232             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2233             CBlock block;
2234             block.ReadFromDisk(pindex, true);
2235             nBytes += block.GetSerializeSize(SER_NETWORK);
2236             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2237             {
2238                 // When this block is requested, we'll send an inv that'll make them
2239                 // getblocks the next batch of inventory.
2240                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2241                 pfrom->hashContinue = pindex->GetBlockHash();
2242                 break;
2243             }
2244         }
2245     }
2246
2247
2248     else if (strCommand == "getheaders")
2249     {
2250         CBlockLocator locator;
2251         uint256 hashStop;
2252         vRecv >> locator >> hashStop;
2253
2254         CBlockIndex* pindex = NULL;
2255         if (locator.IsNull())
2256         {
2257             // If locator is null, return the hashStop block
2258             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2259             if (mi == mapBlockIndex.end())
2260                 return true;
2261             pindex = (*mi).second;
2262         }
2263         else
2264         {
2265             // Find the last block the caller has in the main chain
2266             pindex = locator.GetBlockIndex();
2267             if (pindex)
2268                 pindex = pindex->pnext;
2269         }
2270
2271         vector<CBlock> vHeaders;
2272         int nLimit = 2000 + locator.GetDistanceBack();
2273         printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2274         for (; pindex; pindex = pindex->pnext)
2275         {
2276             vHeaders.push_back(pindex->GetBlockHeader());
2277             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2278                 break;
2279         }
2280         pfrom->PushMessage("headers", vHeaders);
2281     }
2282
2283
2284     else if (strCommand == "tx")
2285     {
2286         vector<uint256> vWorkQueue;
2287         CDataStream vMsg(vRecv);
2288         CTransaction tx;
2289         vRecv >> tx;
2290
2291         CInv inv(MSG_TX, tx.GetHash());
2292         pfrom->AddInventoryKnown(inv);
2293
2294         bool fMissingInputs = false;
2295         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2296         {
2297             SyncWithWallets(tx, NULL, true);
2298             RelayMessage(inv, vMsg);
2299             mapAlreadyAskedFor.erase(inv);
2300             vWorkQueue.push_back(inv.hash);
2301
2302             // Recursively process any orphan transactions that depended on this one
2303             for (int i = 0; i < vWorkQueue.size(); i++)
2304             {
2305                 uint256 hashPrev = vWorkQueue[i];
2306                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2307                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2308                      ++mi)
2309                 {
2310                     const CDataStream& vMsg = *((*mi).second);
2311                     CTransaction tx;
2312                     CDataStream(vMsg) >> tx;
2313                     CInv inv(MSG_TX, tx.GetHash());
2314
2315                     if (tx.AcceptToMemoryPool(true))
2316                     {
2317                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2318                         SyncWithWallets(tx, NULL, true);
2319                         RelayMessage(inv, vMsg);
2320                         mapAlreadyAskedFor.erase(inv);
2321                         vWorkQueue.push_back(inv.hash);
2322                     }
2323                 }
2324             }
2325
2326             BOOST_FOREACH(uint256 hash, vWorkQueue)
2327                 EraseOrphanTx(hash);
2328         }
2329         else if (fMissingInputs)
2330         {
2331             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2332             AddOrphanTx(vMsg);
2333         }
2334         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2335     }
2336
2337
2338     else if (strCommand == "block")
2339     {
2340         CBlock block;
2341         vRecv >> block;
2342
2343         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2344         // block.print();
2345
2346         CInv inv(MSG_BLOCK, block.GetHash());
2347         pfrom->AddInventoryKnown(inv);
2348
2349         if (ProcessBlock(pfrom, &block))
2350             mapAlreadyAskedFor.erase(inv);
2351         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2352     }
2353
2354
2355     else if (strCommand == "getaddr")
2356     {
2357         // Nodes rebroadcast an addr every 24 hours
2358         pfrom->vAddrToSend.clear();
2359         int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2360         CRITICAL_BLOCK(cs_mapAddresses)
2361         {
2362             unsigned int nCount = 0;
2363             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2364             {
2365                 const CAddress& addr = item.second;
2366                 if (addr.nTime > nSince)
2367                     nCount++;
2368             }
2369             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2370             {
2371                 const CAddress& addr = item.second;
2372                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2373                     pfrom->PushAddress(addr);
2374             }
2375         }
2376     }
2377
2378
2379     else if (strCommand == "checkorder")
2380     {
2381         uint256 hashReply;
2382         vRecv >> hashReply;
2383
2384         if (!GetBoolArg("-allowreceivebyip"))
2385         {
2386             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2387             return true;
2388         }
2389
2390         CWalletTx order;
2391         vRecv >> order;
2392
2393         /// we have a chance to check the order here
2394
2395         // Keep giving the same key to the same ip until they use it
2396         if (!mapReuseKey.count(pfrom->addr))
2397             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
2398
2399         // Send back approval of order and pubkey to use
2400         CScript scriptPubKey;
2401         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
2402         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2403     }
2404
2405
2406     else if (strCommand == "reply")
2407     {
2408         uint256 hashReply;
2409         vRecv >> hashReply;
2410
2411         CRequestTracker tracker;
2412         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2413         {
2414             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2415             if (mi != pfrom->mapRequests.end())
2416             {
2417                 tracker = (*mi).second;
2418                 pfrom->mapRequests.erase(mi);
2419             }
2420         }
2421         if (!tracker.IsNull())
2422             tracker.fn(tracker.param1, vRecv);
2423     }
2424
2425
2426     else if (strCommand == "ping")
2427     {
2428     }
2429
2430
2431     else if (strCommand == "alert")
2432     {
2433         CAlert alert;
2434         vRecv >> alert;
2435
2436         if (alert.ProcessAlert())
2437         {
2438             // Relay
2439             pfrom->setKnown.insert(alert.GetHash());
2440             CRITICAL_BLOCK(cs_vNodes)
2441                 BOOST_FOREACH(CNode* pnode, vNodes)
2442                     alert.RelayTo(pnode);
2443         }
2444     }
2445
2446
2447     else
2448     {
2449         // Ignore unknown commands for extensibility
2450     }
2451
2452
2453     // Update the last seen time for this node's address
2454     if (pfrom->fNetworkNode)
2455         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2456             AddressCurrentlyConnected(pfrom->addr);
2457
2458
2459     return true;
2460 }
2461
2462 bool ProcessMessages(CNode* pfrom)
2463 {
2464     CDataStream& vRecv = pfrom->vRecv;
2465     if (vRecv.empty())
2466         return true;
2467     //if (fDebug)
2468     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2469
2470     //
2471     // Message format
2472     //  (4) message start
2473     //  (12) command
2474     //  (4) size
2475     //  (4) checksum
2476     //  (x) data
2477     //
2478
2479     loop
2480     {
2481         // Scan for message start
2482         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2483         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2484         if (vRecv.end() - pstart < nHeaderSize)
2485         {
2486             if (vRecv.size() > nHeaderSize)
2487             {
2488                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2489                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2490             }
2491             break;
2492         }
2493         if (pstart - vRecv.begin() > 0)
2494             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2495         vRecv.erase(vRecv.begin(), pstart);
2496
2497         // Read header
2498         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2499         CMessageHeader hdr;
2500         vRecv >> hdr;
2501         if (!hdr.IsValid())
2502         {
2503             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2504             continue;
2505         }
2506         string strCommand = hdr.GetCommand();
2507
2508         // Message size
2509         unsigned int nMessageSize = hdr.nMessageSize;
2510         if (nMessageSize > MAX_SIZE)
2511         {
2512             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2513             continue;
2514         }
2515         if (nMessageSize > vRecv.size())
2516         {
2517             // Rewind and wait for rest of message
2518             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2519             break;
2520         }
2521
2522         // Checksum
2523         if (vRecv.GetVersion() >= 209)
2524         {
2525             uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2526             unsigned int nChecksum = 0;
2527             memcpy(&nChecksum, &hash, sizeof(nChecksum));
2528             if (nChecksum != hdr.nChecksum)
2529             {
2530                 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2531                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2532                 continue;
2533             }
2534         }
2535
2536         // Copy message to its own buffer
2537         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2538         vRecv.ignore(nMessageSize);
2539
2540         // Process message
2541         bool fRet = false;
2542         try
2543         {
2544             CRITICAL_BLOCK(cs_main)
2545                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2546             if (fShutdown)
2547                 return true;
2548         }
2549         catch (std::ios_base::failure& e)
2550         {
2551             if (strstr(e.what(), "end of data"))
2552             {
2553                 // Allow exceptions from underlength message on vRecv
2554                 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());
2555             }
2556             else if (strstr(e.what(), "size too large"))
2557             {
2558                 // Allow exceptions from overlong size
2559                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2560             }
2561             else
2562             {
2563                 PrintExceptionContinue(&e, "ProcessMessage()");
2564             }
2565         }
2566         catch (std::exception& e) {
2567             PrintExceptionContinue(&e, "ProcessMessage()");
2568         } catch (...) {
2569             PrintExceptionContinue(NULL, "ProcessMessage()");
2570         }
2571
2572         if (!fRet)
2573             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2574     }
2575
2576     vRecv.Compact();
2577     return true;
2578 }
2579
2580
2581 bool SendMessages(CNode* pto, bool fSendTrickle)
2582 {
2583     CRITICAL_BLOCK(cs_main)
2584     {
2585         // Don't send anything until we get their version message
2586         if (pto->nVersion == 0)
2587             return true;
2588
2589         // Keep-alive ping
2590         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2591             pto->PushMessage("ping");
2592
2593         // Resend wallet transactions that haven't gotten in a block yet
2594         ResendWalletTransactions();
2595
2596         // Address refresh broadcast
2597         static int64 nLastRebroadcast;
2598         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2599         {
2600             nLastRebroadcast = GetTime();
2601             CRITICAL_BLOCK(cs_vNodes)
2602             {
2603                 BOOST_FOREACH(CNode* pnode, vNodes)
2604                 {
2605                     // Periodically clear setAddrKnown to allow refresh broadcasts
2606                     pnode->setAddrKnown.clear();
2607
2608                     // Rebroadcast our address
2609                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2610                     {
2611                         CAddress addr(addrLocalHost);
2612                         addr.nTime = GetAdjustedTime();
2613                         pnode->PushAddress(addr);
2614                     }
2615                 }
2616             }
2617         }
2618
2619         // Clear out old addresses periodically so it's not too much work at once
2620         static int64 nLastClear;
2621         if (nLastClear == 0)
2622             nLastClear = GetTime();
2623         if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2624         {
2625             nLastClear = GetTime();
2626             CRITICAL_BLOCK(cs_mapAddresses)
2627             {
2628                 CAddrDB addrdb;
2629                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2630                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2631                      mi != mapAddresses.end();)
2632                 {
2633                     const CAddress& addr = (*mi).second;
2634                     if (addr.nTime < nSince)
2635                     {
2636                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2637                             break;
2638                         addrdb.EraseAddress(addr);
2639                         mapAddresses.erase(mi++);
2640                     }
2641                     else
2642                         mi++;
2643                 }
2644             }
2645         }
2646
2647
2648         //
2649         // Message: addr
2650         //
2651         if (fSendTrickle)
2652         {
2653             vector<CAddress> vAddr;
2654             vAddr.reserve(pto->vAddrToSend.size());
2655             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2656             {
2657                 // returns true if wasn't already contained in the set
2658                 if (pto->setAddrKnown.insert(addr).second)
2659                 {
2660                     vAddr.push_back(addr);
2661                     // receiver rejects addr messages larger than 1000
2662                     if (vAddr.size() >= 1000)
2663                     {
2664                         pto->PushMessage("addr", vAddr);
2665                         vAddr.clear();
2666                     }
2667                 }
2668             }
2669             pto->vAddrToSend.clear();
2670             if (!vAddr.empty())
2671                 pto->PushMessage("addr", vAddr);
2672         }
2673
2674
2675         //
2676         // Message: inventory
2677         //
2678         vector<CInv> vInv;
2679         vector<CInv> vInvWait;
2680         CRITICAL_BLOCK(pto->cs_inventory)
2681         {
2682             vInv.reserve(pto->vInventoryToSend.size());
2683             vInvWait.reserve(pto->vInventoryToSend.size());
2684             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2685             {
2686                 if (pto->setInventoryKnown.count(inv))
2687                     continue;
2688
2689                 // trickle out tx inv to protect privacy
2690                 if (inv.type == MSG_TX && !fSendTrickle)
2691                 {
2692                     // 1/4 of tx invs blast to all immediately
2693                     static uint256 hashSalt;
2694                     if (hashSalt == 0)
2695                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2696                     uint256 hashRand = inv.hash ^ hashSalt;
2697                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2698                     bool fTrickleWait = ((hashRand & 3) != 0);
2699
2700                     // always trickle our own transactions
2701                     if (!fTrickleWait)
2702                     {
2703                         CWalletTx wtx;
2704                         if (GetTransaction(inv.hash, wtx))
2705                             if (wtx.fFromMe)
2706                                 fTrickleWait = true;
2707                     }
2708
2709                     if (fTrickleWait)
2710                     {
2711                         vInvWait.push_back(inv);
2712                         continue;
2713                     }
2714                 }
2715
2716                 // returns true if wasn't already contained in the set
2717                 if (pto->setInventoryKnown.insert(inv).second)
2718                 {
2719                     vInv.push_back(inv);
2720                     if (vInv.size() >= 1000)
2721                     {
2722                         pto->PushMessage("inv", vInv);
2723                         vInv.clear();
2724                     }
2725                 }
2726             }
2727             pto->vInventoryToSend = vInvWait;
2728         }
2729         if (!vInv.empty())
2730             pto->PushMessage("inv", vInv);
2731
2732
2733         //
2734         // Message: getdata
2735         //
2736         vector<CInv> vGetData;
2737         int64 nNow = GetTime() * 1000000;
2738         CTxDB txdb("r");
2739         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2740         {
2741             const CInv& inv = (*pto->mapAskFor.begin()).second;
2742             if (!AlreadyHave(txdb, inv))
2743             {
2744                 printf("sending getdata: %s\n", inv.ToString().c_str());
2745                 vGetData.push_back(inv);
2746                 if (vGetData.size() >= 1000)
2747                 {
2748                     pto->PushMessage("getdata", vGetData);
2749                     vGetData.clear();
2750                 }
2751             }
2752             mapAlreadyAskedFor[inv] = nNow;
2753             pto->mapAskFor.erase(pto->mapAskFor.begin());
2754         }
2755         if (!vGetData.empty())
2756             pto->PushMessage("getdata", vGetData);
2757
2758     }
2759     return true;
2760 }
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775 //////////////////////////////////////////////////////////////////////////////
2776 //
2777 // BitcoinMiner
2778 //
2779
2780 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2781 {
2782     unsigned char* pdata = (unsigned char*)pbuffer;
2783     unsigned int blocks = 1 + ((len + 8) / 64);
2784     unsigned char* pend = pdata + 64 * blocks;
2785     memset(pdata + len, 0, 64 * blocks - len);
2786     pdata[len] = 0x80;
2787     unsigned int bits = len * 8;
2788     pend[-1] = (bits >> 0) & 0xff;
2789     pend[-2] = (bits >> 8) & 0xff;
2790     pend[-3] = (bits >> 16) & 0xff;
2791     pend[-4] = (bits >> 24) & 0xff;
2792     return blocks;
2793 }
2794
2795 static const unsigned int pSHA256InitState[8] =
2796 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2797
2798 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2799 {
2800     SHA256_CTX ctx;
2801     unsigned char data[64];
2802
2803     SHA256_Init(&ctx);
2804
2805     for (int i = 0; i < 16; i++)
2806         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2807
2808     for (int i = 0; i < 8; i++)
2809         ctx.h[i] = ((uint32_t*)pinit)[i];
2810
2811     SHA256_Update(&ctx, data, sizeof(data));
2812     for (int i = 0; i < 8; i++) 
2813         ((uint32_t*)pstate)[i] = ctx.h[i];
2814 }
2815
2816 //
2817 // ScanHash scans nonces looking for a hash with at least some zero bits.
2818 // It operates on big endian data.  Caller does the byte reversing.
2819 // All input buffers are 16-byte aligned.  nNonce is usually preserved
2820 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2821 // the block is rebuilt and nNonce starts over at zero.
2822 //
2823 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2824 {
2825     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2826     for (;;)
2827     {
2828         // Crypto++ SHA-256
2829         // Hash pdata using pmidstate as the starting state into
2830         // preformatted buffer phash1, then hash phash1 into phash
2831         nNonce++;
2832         SHA256Transform(phash1, pdata, pmidstate);
2833         SHA256Transform(phash, phash1, pSHA256InitState);
2834
2835         // Return the nonce if the hash has at least some zero bits,
2836         // caller will check if it has enough to reach the target
2837         if (((unsigned short*)phash)[14] == 0)
2838             return nNonce;
2839
2840         // If nothing found after trying for a while, return -1
2841         if ((nNonce & 0xffff) == 0)
2842         {
2843             nHashesDone = 0xffff+1;
2844             return -1;
2845         }
2846     }
2847 }
2848
2849 // Some explaining would be appreciated
2850 class COrphan
2851 {
2852 public:
2853     CTransaction* ptx;
2854     set<uint256> setDependsOn;
2855     double dPriority;
2856
2857     COrphan(CTransaction* ptxIn)
2858     {
2859         ptx = ptxIn;
2860         dPriority = 0;
2861     }
2862
2863     void print() const
2864     {
2865         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2866         BOOST_FOREACH(uint256 hash, setDependsOn)
2867             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2868     }
2869 };
2870
2871
2872 CBlock* CreateNewBlock(CReserveKey& reservekey)
2873 {
2874     CBlockIndex* pindexPrev = pindexBest;
2875
2876     // Create new block
2877     auto_ptr<CBlock> pblock(new CBlock());
2878     if (!pblock.get())
2879         return NULL;
2880
2881     // Create coinbase tx
2882     CTransaction txNew;
2883     txNew.vin.resize(1);
2884     txNew.vin[0].prevout.SetNull();
2885     txNew.vout.resize(1);
2886     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2887
2888     // Add our coinbase tx as first transaction
2889     pblock->vtx.push_back(txNew);
2890
2891     // Collect memory pool transactions into the block
2892     int64 nFees = 0;
2893     CRITICAL_BLOCK(cs_main)
2894     CRITICAL_BLOCK(cs_mapTransactions)
2895     {
2896         CTxDB txdb("r");
2897
2898         // Priority order to process transactions
2899         list<COrphan> vOrphan; // list memory doesn't move
2900         map<uint256, vector<COrphan*> > mapDependers;
2901         multimap<double, CTransaction*> mapPriority;
2902         for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2903         {
2904             CTransaction& tx = (*mi).second;
2905             if (tx.IsCoinBase() || !tx.IsFinal())
2906                 continue;
2907
2908             COrphan* porphan = NULL;
2909             double dPriority = 0;
2910             BOOST_FOREACH(const CTxIn& txin, tx.vin)
2911             {
2912                 // Read prev transaction
2913                 CTransaction txPrev;
2914                 CTxIndex txindex;
2915                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2916                 {
2917                     // Has to wait for dependencies
2918                     if (!porphan)
2919                     {
2920                         // Use list for automatic deletion
2921                         vOrphan.push_back(COrphan(&tx));
2922                         porphan = &vOrphan.back();
2923                     }
2924                     mapDependers[txin.prevout.hash].push_back(porphan);
2925                     porphan->setDependsOn.insert(txin.prevout.hash);
2926                     continue;
2927                 }
2928                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2929
2930                 // Read block header
2931                 int nConf = txindex.GetDepthInMainChain();
2932
2933                 dPriority += (double)nValueIn * nConf;
2934
2935                 if (fDebug && GetBoolArg("-printpriority"))
2936                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2937             }
2938
2939             // Priority is sum(valuein * age) / txsize
2940             dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2941
2942             if (porphan)
2943                 porphan->dPriority = dPriority;
2944             else
2945                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2946
2947             if (fDebug && GetBoolArg("-printpriority"))
2948             {
2949                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2950                 if (porphan)
2951                     porphan->print();
2952                 printf("\n");
2953             }
2954         }
2955
2956         // Collect transactions into block
2957         map<uint256, CTxIndex> mapTestPool;
2958         uint64 nBlockSize = 1000;
2959         int nBlockSigOps = 100;
2960         while (!mapPriority.empty())
2961         {
2962             // Take highest priority transaction off priority queue
2963             double dPriority = -(*mapPriority.begin()).first;
2964             CTransaction& tx = *(*mapPriority.begin()).second;
2965             mapPriority.erase(mapPriority.begin());
2966
2967             // Size limits
2968             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2969             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2970                 continue;
2971
2972             // Transaction fee required depends on block size
2973             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2974             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
2975
2976             // Connecting shouldn't fail due to dependency on other memory pool transactions
2977             // because we're already processing them in order of dependency
2978             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2979             map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2980             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2981                 continue;
2982             int nTxSigOps = 0;
2983             if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2984                 continue;
2985             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2986                 continue;
2987             swap(mapTestPool, mapTestPoolTmp);
2988
2989             // Added
2990             pblock->vtx.push_back(tx);
2991             nBlockSize += nTxSize;
2992             nBlockSigOps += nTxSigOps;
2993
2994             // Add transactions that depend on this one to the priority queue
2995             uint256 hash = tx.GetHash();
2996             if (mapDependers.count(hash))
2997             {
2998                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2999                 {
3000                     if (!porphan->setDependsOn.empty())
3001                     {
3002                         porphan->setDependsOn.erase(hash);
3003                         if (porphan->setDependsOn.empty())
3004                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3005                     }
3006                 }
3007             }
3008         }
3009     }
3010     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3011
3012     // Fill in header
3013     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
3014     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3015     pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3016     pblock->nBits          = GetNextWorkRequired(pindexPrev);
3017     pblock->nNonce         = 0;
3018
3019     return pblock.release();
3020 }
3021
3022
3023 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3024 {
3025     // Update nExtraNonce
3026     static uint256 hashPrevBlock;
3027     if (hashPrevBlock != pblock->hashPrevBlock)
3028     {
3029         nExtraNonce = 0;
3030         hashPrevBlock = pblock->hashPrevBlock;
3031     }
3032     ++nExtraNonce;
3033     pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3034
3035     // Put "OP_EVAL" in the coinbase so everybody can tell when
3036     // a majority of miners support it
3037     const char* pOpEvalName = GetOpName(OP_EVAL);
3038     pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3039     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3040
3041     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3042 }
3043
3044
3045 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3046 {
3047     //
3048     // Prebuild hash buffers
3049     //
3050     struct
3051     {
3052         struct unnamed2
3053         {
3054             int nVersion;
3055             uint256 hashPrevBlock;
3056             uint256 hashMerkleRoot;
3057             unsigned int nTime;
3058             unsigned int nBits;
3059             unsigned int nNonce;
3060         }
3061         block;
3062         unsigned char pchPadding0[64];
3063         uint256 hash1;
3064         unsigned char pchPadding1[64];
3065     }
3066     tmp;
3067     memset(&tmp, 0, sizeof(tmp));
3068
3069     tmp.block.nVersion       = pblock->nVersion;
3070     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
3071     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3072     tmp.block.nTime          = pblock->nTime;
3073     tmp.block.nBits          = pblock->nBits;
3074     tmp.block.nNonce         = pblock->nNonce;
3075
3076     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3077     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3078
3079     // Byte swap all the input buffer
3080     for (int i = 0; i < sizeof(tmp)/4; i++)
3081         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3082
3083     // Precalc the first half of the first hash, which stays constant
3084     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3085
3086     memcpy(pdata, &tmp.block, 128);
3087     memcpy(phash1, &tmp.hash1, 64);
3088 }
3089
3090
3091 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3092 {
3093     uint256 hash = pblock->GetHash();
3094     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3095
3096     if (hash > hashTarget)
3097         return false;
3098
3099     //// debug print
3100     printf("BitcoinMiner:\n");
3101     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3102     pblock->print();
3103     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3104     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3105
3106     // Found a solution
3107     CRITICAL_BLOCK(cs_main)
3108     {
3109         if (pblock->hashPrevBlock != hashBestChain)
3110             return error("BitcoinMiner : generated block is stale");
3111
3112         // Remove key from key pool
3113         reservekey.KeepKey();
3114
3115         // Track how many getdata requests this block gets
3116         CRITICAL_BLOCK(wallet.cs_wallet)
3117             wallet.mapRequestCount[pblock->GetHash()] = 0;
3118
3119         // Process this block the same as if we had received it from another node
3120         if (!ProcessBlock(NULL, pblock))
3121             return error("BitcoinMiner : ProcessBlock, block not accepted");
3122     }
3123
3124     return true;
3125 }
3126
3127 void static ThreadBitcoinMiner(void* parg);
3128
3129 void static BitcoinMiner(CWallet *pwallet)
3130 {
3131     printf("BitcoinMiner started\n");
3132     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3133
3134     // Each thread has its own key and counter
3135     CReserveKey reservekey(pwallet);
3136     unsigned int nExtraNonce = 0;
3137
3138     while (fGenerateBitcoins)
3139     {
3140         if (AffinityBugWorkaround(ThreadBitcoinMiner))
3141             return;
3142         if (fShutdown)
3143             return;
3144         while (vNodes.empty() || IsInitialBlockDownload())
3145         {
3146             Sleep(1000);
3147             if (fShutdown)
3148                 return;
3149             if (!fGenerateBitcoins)
3150                 return;
3151         }
3152
3153
3154         //
3155         // Create new block
3156         //
3157         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3158         CBlockIndex* pindexPrev = pindexBest;
3159
3160         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3161         if (!pblock.get())
3162             return;
3163         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3164
3165         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3166
3167
3168         //
3169         // Prebuild hash buffers
3170         //
3171         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3172         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3173         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3174
3175         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3176
3177         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3178         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3179
3180
3181         //
3182         // Search
3183         //
3184         int64 nStart = GetTime();
3185         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3186         uint256 hashbuf[2];
3187         uint256& hash = *alignup<16>(hashbuf);
3188         loop
3189         {
3190             unsigned int nHashesDone = 0;
3191             unsigned int nNonceFound;
3192
3193             // Crypto++ SHA-256
3194             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3195                                             (char*)&hash, nHashesDone);
3196
3197             // Check if something found
3198             if (nNonceFound != -1)
3199             {
3200                 for (int i = 0; i < sizeof(hash)/4; i++)
3201                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3202
3203                 if (hash <= hashTarget)
3204                 {
3205                     // Found a solution
3206                     pblock->nNonce = ByteReverse(nNonceFound);
3207                     assert(hash == pblock->GetHash());
3208
3209                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3210                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3211                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3212                     break;
3213                 }
3214             }
3215
3216             // Meter hashes/sec
3217             static int64 nHashCounter;
3218             if (nHPSTimerStart == 0)
3219             {
3220                 nHPSTimerStart = GetTimeMillis();
3221                 nHashCounter = 0;
3222             }
3223             else
3224                 nHashCounter += nHashesDone;
3225             if (GetTimeMillis() - nHPSTimerStart > 4000)
3226             {
3227                 static CCriticalSection cs;
3228                 CRITICAL_BLOCK(cs)
3229                 {
3230                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3231                     {
3232                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3233                         nHPSTimerStart = GetTimeMillis();
3234                         nHashCounter = 0;
3235                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3236                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3237                         static int64 nLogTime;
3238                         if (GetTime() - nLogTime > 30 * 60)
3239                         {
3240                             nLogTime = GetTime();
3241                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3242                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3243                         }
3244                     }
3245                 }
3246             }
3247
3248             // Check for stop or if block needs to be rebuilt
3249             if (fShutdown)
3250                 return;
3251             if (!fGenerateBitcoins)
3252                 return;
3253             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3254                 return;
3255             if (vNodes.empty())
3256                 break;
3257             if (nBlockNonce >= 0xffff0000)
3258                 break;
3259             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3260                 break;
3261             if (pindexPrev != pindexBest)
3262                 break;
3263
3264             // Update nTime every few seconds
3265             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3266             nBlockTime = ByteReverse(pblock->nTime);
3267         }
3268     }
3269 }
3270
3271 void static ThreadBitcoinMiner(void* parg)
3272 {
3273     CWallet* pwallet = (CWallet*)parg;
3274     try
3275     {
3276         vnThreadsRunning[3]++;
3277         BitcoinMiner(pwallet);
3278         vnThreadsRunning[3]--;
3279     }
3280     catch (std::exception& e) {
3281         vnThreadsRunning[3]--;
3282         PrintException(&e, "ThreadBitcoinMiner()");
3283     } catch (...) {
3284         vnThreadsRunning[3]--;
3285         PrintException(NULL, "ThreadBitcoinMiner()");
3286     }
3287     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3288     nHPSTimerStart = 0;
3289     if (vnThreadsRunning[3] == 0)
3290         dHashesPerSec = 0;
3291     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3292 }
3293
3294
3295 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3296 {
3297     if (fGenerateBitcoins != fGenerate)
3298     {
3299         fGenerateBitcoins = fGenerate;
3300         WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3301         MainFrameRepaint();
3302     }
3303     if (fGenerateBitcoins)
3304     {
3305         int nProcessors = boost::thread::hardware_concurrency();
3306         printf("%d processors\n", nProcessors);
3307         if (nProcessors < 1)
3308             nProcessors = 1;
3309         if (fLimitProcessors && nProcessors > nLimitProcessors)
3310             nProcessors = nLimitProcessors;
3311         int nAddThreads = nProcessors - vnThreadsRunning[3];
3312         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3313         for (int i = 0; i < nAddThreads; i++)
3314         {
3315             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3316                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3317             Sleep(10);
3318         }
3319     }
3320 }