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