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