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