Merge branch 'master' of https://github.com/bitcoin/bitcoin
[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 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         if(pfrom->nStartingHeight > nTotalBlocksEstimate)
1879         {
1880             nTotalBlocksEstimate = pfrom->nStartingHeight;
1881         }
1882     }
1883
1884
1885     else if (pfrom->nVersion == 0)
1886     {
1887         // Must have a version message before anything else
1888         return false;
1889     }
1890
1891
1892     else if (strCommand == "verack")
1893     {
1894         pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1895     }
1896
1897
1898     else if (strCommand == "addr")
1899     {
1900         vector<CAddress> vAddr;
1901         vRecv >> vAddr;
1902
1903         // Don't want addr from older versions unless seeding
1904         if (pfrom->nVersion < 209)
1905             return true;
1906         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1907             return true;
1908         if (vAddr.size() > 1000)
1909             return error("message addr size() = %d", vAddr.size());
1910
1911         // Store the new addresses
1912         CAddrDB addrDB;
1913         addrDB.TxnBegin();
1914         int64 nNow = GetAdjustedTime();
1915         int64 nSince = nNow - 10 * 60;
1916         BOOST_FOREACH(CAddress& addr, vAddr)
1917         {
1918             if (fShutdown)
1919                 return true;
1920             // ignore IPv6 for now, since it isn't implemented anyway
1921             if (!addr.IsIPv4())
1922                 continue;
1923             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1924                 addr.nTime = nNow - 5 * 24 * 60 * 60;
1925             AddAddress(addr, 2 * 60 * 60, &addrDB);
1926             pfrom->AddAddressKnown(addr);
1927             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1928             {
1929                 // Relay to a limited number of other nodes
1930                 CRITICAL_BLOCK(cs_vNodes)
1931                 {
1932                     // Use deterministic randomness to send to the same nodes for 24 hours
1933                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1934                     static uint256 hashSalt;
1935                     if (hashSalt == 0)
1936                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1937                     uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1938                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
1939                     multimap<uint256, CNode*> mapMix;
1940                     BOOST_FOREACH(CNode* pnode, vNodes)
1941                     {
1942                         if (pnode->nVersion < 31402)
1943                             continue;
1944                         unsigned int nPointer;
1945                         memcpy(&nPointer, &pnode, sizeof(nPointer));
1946                         uint256 hashKey = hashRand ^ nPointer;
1947                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
1948                         mapMix.insert(make_pair(hashKey, pnode));
1949                     }
1950                     int nRelayNodes = 2;
1951                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1952                         ((*mi).second)->PushAddress(addr);
1953                 }
1954             }
1955         }
1956         addrDB.TxnCommit();  // Save addresses (it's ok if this fails)
1957         if (vAddr.size() < 1000)
1958             pfrom->fGetAddr = false;
1959     }
1960
1961
1962     else if (strCommand == "inv")
1963     {
1964         vector<CInv> vInv;
1965         vRecv >> vInv;
1966         if (vInv.size() > 50000)
1967             return error("message inv size() = %d", vInv.size());
1968
1969         CTxDB txdb("r");
1970         BOOST_FOREACH(const CInv& inv, vInv)
1971         {
1972             if (fShutdown)
1973                 return true;
1974             pfrom->AddInventoryKnown(inv);
1975
1976             bool fAlreadyHave = AlreadyHave(txdb, inv);
1977             printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1978
1979             if (!fAlreadyHave)
1980                 pfrom->AskFor(inv);
1981             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1982                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1983
1984             // Track requests for our stuff
1985             Inventory(inv.hash);
1986         }
1987     }
1988
1989
1990     else if (strCommand == "getdata")
1991     {
1992         vector<CInv> vInv;
1993         vRecv >> vInv;
1994         if (vInv.size() > 50000)
1995             return error("message getdata size() = %d", vInv.size());
1996
1997         BOOST_FOREACH(const CInv& inv, vInv)
1998         {
1999             if (fShutdown)
2000                 return true;
2001             printf("received getdata for: %s\n", inv.ToString().c_str());
2002
2003             if (inv.type == MSG_BLOCK)
2004             {
2005                 // Send block from disk
2006                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2007                 if (mi != mapBlockIndex.end())
2008                 {
2009                     CBlock block;
2010                     block.ReadFromDisk((*mi).second);
2011                     pfrom->PushMessage("block", block);
2012
2013                     // Trigger them to send a getblocks request for the next batch of inventory
2014                     if (inv.hash == pfrom->hashContinue)
2015                     {
2016                         // Bypass PushInventory, this must send even if redundant,
2017                         // and we want it right after the last block so they don't
2018                         // wait for other stuff first.
2019                         vector<CInv> vInv;
2020                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2021                         pfrom->PushMessage("inv", vInv);
2022                         pfrom->hashContinue = 0;
2023                     }
2024                 }
2025             }
2026             else if (inv.IsKnownType())
2027             {
2028                 // Send stream from relay memory
2029                 CRITICAL_BLOCK(cs_mapRelay)
2030                 {
2031                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2032                     if (mi != mapRelay.end())
2033                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2034                 }
2035             }
2036
2037             // Track requests for our stuff
2038             Inventory(inv.hash);
2039         }
2040     }
2041
2042
2043     else if (strCommand == "getblocks")
2044     {
2045         CBlockLocator locator;
2046         uint256 hashStop;
2047         vRecv >> locator >> hashStop;
2048
2049         // Find the last block the caller has in the main chain
2050         CBlockIndex* pindex = locator.GetBlockIndex();
2051
2052         // Send the rest of the chain
2053         if (pindex)
2054             pindex = pindex->pnext;
2055         int nLimit = 500 + locator.GetDistanceBack();
2056         unsigned int nBytes = 0;
2057         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2058         for (; pindex; pindex = pindex->pnext)
2059         {
2060             if (pindex->GetBlockHash() == hashStop)
2061             {
2062                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2063                 break;
2064             }
2065             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2066             CBlock block;
2067             block.ReadFromDisk(pindex, true);
2068             nBytes += block.GetSerializeSize(SER_NETWORK);
2069             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2070             {
2071                 // When this block is requested, we'll send an inv that'll make them
2072                 // getblocks the next batch of inventory.
2073                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2074                 pfrom->hashContinue = pindex->GetBlockHash();
2075                 break;
2076             }
2077         }
2078     }
2079
2080
2081     else if (strCommand == "getheaders")
2082     {
2083         CBlockLocator locator;
2084         uint256 hashStop;
2085         vRecv >> locator >> hashStop;
2086
2087         CBlockIndex* pindex = NULL;
2088         if (locator.IsNull())
2089         {
2090             // If locator is null, return the hashStop block
2091             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2092             if (mi == mapBlockIndex.end())
2093                 return true;
2094             pindex = (*mi).second;
2095         }
2096         else
2097         {
2098             // Find the last block the caller has in the main chain
2099             pindex = locator.GetBlockIndex();
2100             if (pindex)
2101                 pindex = pindex->pnext;
2102         }
2103
2104         vector<CBlock> vHeaders;
2105         int nLimit = 2000 + locator.GetDistanceBack();
2106         printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2107         for (; pindex; pindex = pindex->pnext)
2108         {
2109             vHeaders.push_back(pindex->GetBlockHeader());
2110             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2111                 break;
2112         }
2113         pfrom->PushMessage("headers", vHeaders);
2114     }
2115
2116
2117     else if (strCommand == "tx")
2118     {
2119         vector<uint256> vWorkQueue;
2120         CDataStream vMsg(vRecv);
2121         CTransaction tx;
2122         vRecv >> tx;
2123
2124         CInv inv(MSG_TX, tx.GetHash());
2125         pfrom->AddInventoryKnown(inv);
2126
2127         bool fMissingInputs = false;
2128         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2129         {
2130             SyncWithWallets(tx, NULL, true);
2131             RelayMessage(inv, vMsg);
2132             mapAlreadyAskedFor.erase(inv);
2133             vWorkQueue.push_back(inv.hash);
2134
2135             // Recursively process any orphan transactions that depended on this one
2136             for (int i = 0; i < vWorkQueue.size(); i++)
2137             {
2138                 uint256 hashPrev = vWorkQueue[i];
2139                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2140                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2141                      ++mi)
2142                 {
2143                     const CDataStream& vMsg = *((*mi).second);
2144                     CTransaction tx;
2145                     CDataStream(vMsg) >> tx;
2146                     CInv inv(MSG_TX, tx.GetHash());
2147
2148                     if (tx.AcceptToMemoryPool(true))
2149                     {
2150                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2151                         SyncWithWallets(tx, NULL, true);
2152                         RelayMessage(inv, vMsg);
2153                         mapAlreadyAskedFor.erase(inv);
2154                         vWorkQueue.push_back(inv.hash);
2155                     }
2156                 }
2157             }
2158
2159             BOOST_FOREACH(uint256 hash, vWorkQueue)
2160                 EraseOrphanTx(hash);
2161         }
2162         else if (fMissingInputs)
2163         {
2164             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2165             AddOrphanTx(vMsg);
2166         }
2167     }
2168
2169
2170     else if (strCommand == "block")
2171     {
2172         CBlock block;
2173         vRecv >> block;
2174
2175         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2176         // block.print();
2177
2178         CInv inv(MSG_BLOCK, block.GetHash());
2179         pfrom->AddInventoryKnown(inv);
2180
2181         if (ProcessBlock(pfrom, &block))
2182             mapAlreadyAskedFor.erase(inv);
2183     }
2184
2185
2186     else if (strCommand == "getaddr")
2187     {
2188         // Nodes rebroadcast an addr every 24 hours
2189         pfrom->vAddrToSend.clear();
2190         int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2191         CRITICAL_BLOCK(cs_mapAddresses)
2192         {
2193             unsigned int nCount = 0;
2194             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2195             {
2196                 const CAddress& addr = item.second;
2197                 if (addr.nTime > nSince)
2198                     nCount++;
2199             }
2200             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2201             {
2202                 const CAddress& addr = item.second;
2203                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2204                     pfrom->PushAddress(addr);
2205             }
2206         }
2207     }
2208
2209
2210     else if (strCommand == "checkorder")
2211     {
2212         uint256 hashReply;
2213         vRecv >> hashReply;
2214
2215         if (!GetBoolArg("-allowreceivebyip"))
2216         {
2217             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2218             return true;
2219         }
2220
2221         CWalletTx order;
2222         vRecv >> order;
2223
2224         /// we have a chance to check the order here
2225
2226         // Keep giving the same key to the same ip until they use it
2227         if (!mapReuseKey.count(pfrom->addr.ip))
2228             mapReuseKey[pfrom->addr.ip] = pwalletMain->GetOrReuseKeyFromPool();
2229
2230         // Send back approval of order and pubkey to use
2231         CScript scriptPubKey;
2232         scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2233         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2234     }
2235
2236
2237     else if (strCommand == "reply")
2238     {
2239         uint256 hashReply;
2240         vRecv >> hashReply;
2241
2242         CRequestTracker tracker;
2243         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2244         {
2245             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2246             if (mi != pfrom->mapRequests.end())
2247             {
2248                 tracker = (*mi).second;
2249                 pfrom->mapRequests.erase(mi);
2250             }
2251         }
2252         if (!tracker.IsNull())
2253             tracker.fn(tracker.param1, vRecv);
2254     }
2255
2256
2257     else if (strCommand == "ping")
2258     {
2259     }
2260
2261
2262     else if (strCommand == "alert")
2263     {
2264         CAlert alert;
2265         vRecv >> alert;
2266
2267         if (alert.ProcessAlert())
2268         {
2269             // Relay
2270             pfrom->setKnown.insert(alert.GetHash());
2271             CRITICAL_BLOCK(cs_vNodes)
2272                 BOOST_FOREACH(CNode* pnode, vNodes)
2273                     alert.RelayTo(pnode);
2274         }
2275     }
2276
2277
2278     else
2279     {
2280         // Ignore unknown commands for extensibility
2281     }
2282
2283
2284     // Update the last seen time for this node's address
2285     if (pfrom->fNetworkNode)
2286         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2287             AddressCurrentlyConnected(pfrom->addr);
2288
2289
2290     return true;
2291 }
2292
2293 bool ProcessMessages(CNode* pfrom)
2294 {
2295     CDataStream& vRecv = pfrom->vRecv;
2296     if (vRecv.empty())
2297         return true;
2298     //if (fDebug)
2299     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2300
2301     //
2302     // Message format
2303     //  (4) message start
2304     //  (12) command
2305     //  (4) size
2306     //  (4) checksum
2307     //  (x) data
2308     //
2309
2310     loop
2311     {
2312         // Scan for message start
2313         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2314         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2315         if (vRecv.end() - pstart < nHeaderSize)
2316         {
2317             if (vRecv.size() > nHeaderSize)
2318             {
2319                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2320                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2321             }
2322             break;
2323         }
2324         if (pstart - vRecv.begin() > 0)
2325             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2326         vRecv.erase(vRecv.begin(), pstart);
2327
2328         // Read header
2329         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2330         CMessageHeader hdr;
2331         vRecv >> hdr;
2332         if (!hdr.IsValid())
2333         {
2334             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2335             continue;
2336         }
2337         string strCommand = hdr.GetCommand();
2338
2339         // Message size
2340         unsigned int nMessageSize = hdr.nMessageSize;
2341         if (nMessageSize > MAX_SIZE)
2342         {
2343             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2344             continue;
2345         }
2346         if (nMessageSize > vRecv.size())
2347         {
2348             // Rewind and wait for rest of message
2349             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2350             break;
2351         }
2352
2353         // Checksum
2354         if (vRecv.GetVersion() >= 209)
2355         {
2356             uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2357             unsigned int nChecksum = 0;
2358             memcpy(&nChecksum, &hash, sizeof(nChecksum));
2359             if (nChecksum != hdr.nChecksum)
2360             {
2361                 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2362                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2363                 continue;
2364             }
2365         }
2366
2367         // Copy message to its own buffer
2368         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2369         vRecv.ignore(nMessageSize);
2370
2371         // Process message
2372         bool fRet = false;
2373         try
2374         {
2375             CRITICAL_BLOCK(cs_main)
2376                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2377             if (fShutdown)
2378                 return true;
2379         }
2380         catch (std::ios_base::failure& e)
2381         {
2382             if (strstr(e.what(), "end of data"))
2383             {
2384                 // Allow exceptions from underlength message on vRecv
2385                 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());
2386             }
2387             else if (strstr(e.what(), "size too large"))
2388             {
2389                 // Allow exceptions from overlong size
2390                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2391             }
2392             else
2393             {
2394                 PrintExceptionContinue(&e, "ProcessMessage()");
2395             }
2396         }
2397         catch (std::exception& e) {
2398             PrintExceptionContinue(&e, "ProcessMessage()");
2399         } catch (...) {
2400             PrintExceptionContinue(NULL, "ProcessMessage()");
2401         }
2402
2403         if (!fRet)
2404             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2405     }
2406
2407     vRecv.Compact();
2408     return true;
2409 }
2410
2411
2412 bool SendMessages(CNode* pto, bool fSendTrickle)
2413 {
2414     CRITICAL_BLOCK(cs_main)
2415     {
2416         // Don't send anything until we get their version message
2417         if (pto->nVersion == 0)
2418             return true;
2419
2420         // Keep-alive ping
2421         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2422             pto->PushMessage("ping");
2423
2424         // Resend wallet transactions that haven't gotten in a block yet
2425         ResendWalletTransactions();
2426
2427         // Address refresh broadcast
2428         static int64 nLastRebroadcast;
2429         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2430         {
2431             nLastRebroadcast = GetTime();
2432             CRITICAL_BLOCK(cs_vNodes)
2433             {
2434                 BOOST_FOREACH(CNode* pnode, vNodes)
2435                 {
2436                     // Periodically clear setAddrKnown to allow refresh broadcasts
2437                     pnode->setAddrKnown.clear();
2438
2439                     // Rebroadcast our address
2440                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2441                     {
2442                         CAddress addr(addrLocalHost);
2443                         addr.nTime = GetAdjustedTime();
2444                         pnode->PushAddress(addr);
2445                     }
2446                 }
2447             }
2448         }
2449
2450         // Clear out old addresses periodically so it's not too much work at once
2451         static int64 nLastClear;
2452         if (nLastClear == 0)
2453             nLastClear = GetTime();
2454         if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2455         {
2456             nLastClear = GetTime();
2457             CRITICAL_BLOCK(cs_mapAddresses)
2458             {
2459                 CAddrDB addrdb;
2460                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2461                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2462                      mi != mapAddresses.end();)
2463                 {
2464                     const CAddress& addr = (*mi).second;
2465                     if (addr.nTime < nSince)
2466                     {
2467                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2468                             break;
2469                         addrdb.EraseAddress(addr);
2470                         mapAddresses.erase(mi++);
2471                     }
2472                     else
2473                         mi++;
2474                 }
2475             }
2476         }
2477
2478
2479         //
2480         // Message: addr
2481         //
2482         if (fSendTrickle)
2483         {
2484             vector<CAddress> vAddr;
2485             vAddr.reserve(pto->vAddrToSend.size());
2486             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2487             {
2488                 // returns true if wasn't already contained in the set
2489                 if (pto->setAddrKnown.insert(addr).second)
2490                 {
2491                     vAddr.push_back(addr);
2492                     // receiver rejects addr messages larger than 1000
2493                     if (vAddr.size() >= 1000)
2494                     {
2495                         pto->PushMessage("addr", vAddr);
2496                         vAddr.clear();
2497                     }
2498                 }
2499             }
2500             pto->vAddrToSend.clear();
2501             if (!vAddr.empty())
2502                 pto->PushMessage("addr", vAddr);
2503         }
2504
2505
2506         //
2507         // Message: inventory
2508         //
2509         vector<CInv> vInv;
2510         vector<CInv> vInvWait;
2511         CRITICAL_BLOCK(pto->cs_inventory)
2512         {
2513             vInv.reserve(pto->vInventoryToSend.size());
2514             vInvWait.reserve(pto->vInventoryToSend.size());
2515             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2516             {
2517                 if (pto->setInventoryKnown.count(inv))
2518                     continue;
2519
2520                 // trickle out tx inv to protect privacy
2521                 if (inv.type == MSG_TX && !fSendTrickle)
2522                 {
2523                     // 1/4 of tx invs blast to all immediately
2524                     static uint256 hashSalt;
2525                     if (hashSalt == 0)
2526                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2527                     uint256 hashRand = inv.hash ^ hashSalt;
2528                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2529                     bool fTrickleWait = ((hashRand & 3) != 0);
2530
2531                     // always trickle our own transactions
2532                     if (!fTrickleWait)
2533                     {
2534                         CWalletTx wtx;
2535                         if (GetTransaction(inv.hash, wtx))
2536                             if (wtx.fFromMe)
2537                                 fTrickleWait = true;
2538                     }
2539
2540                     if (fTrickleWait)
2541                     {
2542                         vInvWait.push_back(inv);
2543                         continue;
2544                     }
2545                 }
2546
2547                 // returns true if wasn't already contained in the set
2548                 if (pto->setInventoryKnown.insert(inv).second)
2549                 {
2550                     vInv.push_back(inv);
2551                     if (vInv.size() >= 1000)
2552                     {
2553                         pto->PushMessage("inv", vInv);
2554                         vInv.clear();
2555                     }
2556                 }
2557             }
2558             pto->vInventoryToSend = vInvWait;
2559         }
2560         if (!vInv.empty())
2561             pto->PushMessage("inv", vInv);
2562
2563
2564         //
2565         // Message: getdata
2566         //
2567         vector<CInv> vGetData;
2568         int64 nNow = GetTime() * 1000000;
2569         CTxDB txdb("r");
2570         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2571         {
2572             const CInv& inv = (*pto->mapAskFor.begin()).second;
2573             if (!AlreadyHave(txdb, inv))
2574             {
2575                 printf("sending getdata: %s\n", inv.ToString().c_str());
2576                 vGetData.push_back(inv);
2577                 if (vGetData.size() >= 1000)
2578                 {
2579                     pto->PushMessage("getdata", vGetData);
2580                     vGetData.clear();
2581                 }
2582             }
2583             mapAlreadyAskedFor[inv] = nNow;
2584             pto->mapAskFor.erase(pto->mapAskFor.begin());
2585         }
2586         if (!vGetData.empty())
2587             pto->PushMessage("getdata", vGetData);
2588
2589     }
2590     return true;
2591 }
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606 //////////////////////////////////////////////////////////////////////////////
2607 //
2608 // BitcoinMiner
2609 //
2610
2611 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2612 {
2613     unsigned char* pdata = (unsigned char*)pbuffer;
2614     unsigned int blocks = 1 + ((len + 8) / 64);
2615     unsigned char* pend = pdata + 64 * blocks;
2616     memset(pdata + len, 0, 64 * blocks - len);
2617     pdata[len] = 0x80;
2618     unsigned int bits = len * 8;
2619     pend[-1] = (bits >> 0) & 0xff;
2620     pend[-2] = (bits >> 8) & 0xff;
2621     pend[-3] = (bits >> 16) & 0xff;
2622     pend[-4] = (bits >> 24) & 0xff;
2623     return blocks;
2624 }
2625
2626 using CryptoPP::ByteReverse;
2627
2628 static const unsigned int pSHA256InitState[8] =
2629 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2630
2631 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2632 {
2633     memcpy(pstate, pinit, 32);
2634     CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
2635 }
2636
2637 //
2638 // ScanHash scans nonces looking for a hash with at least some zero bits.
2639 // It operates on big endian data.  Caller does the byte reversing.
2640 // All input buffers are 16-byte aligned.  nNonce is usually preserved
2641 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2642 // the block is rebuilt and nNonce starts over at zero.
2643 //
2644 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2645 {
2646     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2647     for (;;)
2648     {
2649         // Crypto++ SHA-256
2650         // Hash pdata using pmidstate as the starting state into
2651         // preformatted buffer phash1, then hash phash1 into phash
2652         nNonce++;
2653         SHA256Transform(phash1, pdata, pmidstate);
2654         SHA256Transform(phash, phash1, pSHA256InitState);
2655
2656         // Return the nonce if the hash has at least some zero bits,
2657         // caller will check if it has enough to reach the target
2658         if (((unsigned short*)phash)[14] == 0)
2659             return nNonce;
2660
2661         // If nothing found after trying for a while, return -1
2662         if ((nNonce & 0xffff) == 0)
2663         {
2664             nHashesDone = 0xffff+1;
2665             return -1;
2666         }
2667     }
2668 }
2669
2670
2671 class COrphan
2672 {
2673 public:
2674     CTransaction* ptx;
2675     set<uint256> setDependsOn;
2676     double dPriority;
2677
2678     COrphan(CTransaction* ptxIn)
2679     {
2680         ptx = ptxIn;
2681         dPriority = 0;
2682     }
2683
2684     void print() const
2685     {
2686         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2687         BOOST_FOREACH(uint256 hash, setDependsOn)
2688             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2689     }
2690 };
2691
2692
2693 CBlock* CreateNewBlock(CReserveKey& reservekey)
2694 {
2695     CBlockIndex* pindexPrev = pindexBest;
2696
2697     // Create new block
2698     auto_ptr<CBlock> pblock(new CBlock());
2699     if (!pblock.get())
2700         return NULL;
2701
2702     // Create coinbase tx
2703     CTransaction txNew;
2704     txNew.vin.resize(1);
2705     txNew.vin[0].prevout.SetNull();
2706     txNew.vout.resize(1);
2707     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2708
2709     // Add our coinbase tx as first transaction
2710     pblock->vtx.push_back(txNew);
2711
2712     // Collect memory pool transactions into the block
2713     int64 nFees = 0;
2714     CRITICAL_BLOCK(cs_main)
2715     CRITICAL_BLOCK(cs_mapTransactions)
2716     {
2717         CTxDB txdb("r");
2718
2719         // Priority order to process transactions
2720         list<COrphan> vOrphan; // list memory doesn't move
2721         map<uint256, vector<COrphan*> > mapDependers;
2722         multimap<double, CTransaction*> mapPriority;
2723         for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2724         {
2725             CTransaction& tx = (*mi).second;
2726             if (tx.IsCoinBase() || !tx.IsFinal())
2727                 continue;
2728
2729             COrphan* porphan = NULL;
2730             double dPriority = 0;
2731             BOOST_FOREACH(const CTxIn& txin, tx.vin)
2732             {
2733                 // Read prev transaction
2734                 CTransaction txPrev;
2735                 CTxIndex txindex;
2736                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2737                 {
2738                     // Has to wait for dependencies
2739                     if (!porphan)
2740                     {
2741                         // Use list for automatic deletion
2742                         vOrphan.push_back(COrphan(&tx));
2743                         porphan = &vOrphan.back();
2744                     }
2745                     mapDependers[txin.prevout.hash].push_back(porphan);
2746                     porphan->setDependsOn.insert(txin.prevout.hash);
2747                     continue;
2748                 }
2749                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2750
2751                 // Read block header
2752                 int nConf = txindex.GetDepthInMainChain();
2753
2754                 dPriority += (double)nValueIn * nConf;
2755
2756                 if (fDebug && GetBoolArg("-printpriority"))
2757                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2758             }
2759
2760             // Priority is sum(valuein * age) / txsize
2761             dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2762
2763             if (porphan)
2764                 porphan->dPriority = dPriority;
2765             else
2766                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2767
2768             if (fDebug && GetBoolArg("-printpriority"))
2769             {
2770                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2771                 if (porphan)
2772                     porphan->print();
2773                 printf("\n");
2774             }
2775         }
2776
2777         // Collect transactions into block
2778         map<uint256, CTxIndex> mapTestPool;
2779         uint64 nBlockSize = 1000;
2780         int nBlockSigOps = 100;
2781         while (!mapPriority.empty())
2782         {
2783             // Take highest priority transaction off priority queue
2784             double dPriority = -(*mapPriority.begin()).first;
2785             CTransaction& tx = *(*mapPriority.begin()).second;
2786             mapPriority.erase(mapPriority.begin());
2787
2788             // Size limits
2789             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2790             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2791                 continue;
2792             int nTxSigOps = tx.GetSigOpCount();
2793             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2794                 continue;
2795
2796             // Transaction fee required depends on block size
2797             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2798             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2799
2800             // Connecting shouldn't fail due to dependency on other memory pool transactions
2801             // because we're already processing them in order of dependency
2802             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2803             if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
2804                 continue;
2805             swap(mapTestPool, mapTestPoolTmp);
2806
2807             // Added
2808             pblock->vtx.push_back(tx);
2809             nBlockSize += nTxSize;
2810             nBlockSigOps += nTxSigOps;
2811
2812             // Add transactions that depend on this one to the priority queue
2813             uint256 hash = tx.GetHash();
2814             if (mapDependers.count(hash))
2815             {
2816                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2817                 {
2818                     if (!porphan->setDependsOn.empty())
2819                     {
2820                         porphan->setDependsOn.erase(hash);
2821                         if (porphan->setDependsOn.empty())
2822                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2823                     }
2824                 }
2825             }
2826         }
2827     }
2828     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2829
2830     // Fill in header
2831     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
2832     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2833     pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2834     pblock->nBits          = GetNextWorkRequired(pindexPrev);
2835     pblock->nNonce         = 0;
2836
2837     return pblock.release();
2838 }
2839
2840
2841 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
2842 {
2843     // Update nExtraNonce
2844     int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2845     if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
2846     {
2847         nExtraNonce = 1;
2848         nPrevTime = nNow;
2849     }
2850     pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
2851     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2852 }
2853
2854
2855 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2856 {
2857     //
2858     // Prebuild hash buffers
2859     //
2860     struct
2861     {
2862         struct unnamed2
2863         {
2864             int nVersion;
2865             uint256 hashPrevBlock;
2866             uint256 hashMerkleRoot;
2867             unsigned int nTime;
2868             unsigned int nBits;
2869             unsigned int nNonce;
2870         }
2871         block;
2872         unsigned char pchPadding0[64];
2873         uint256 hash1;
2874         unsigned char pchPadding1[64];
2875     }
2876     tmp;
2877     memset(&tmp, 0, sizeof(tmp));
2878
2879     tmp.block.nVersion       = pblock->nVersion;
2880     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
2881     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2882     tmp.block.nTime          = pblock->nTime;
2883     tmp.block.nBits          = pblock->nBits;
2884     tmp.block.nNonce         = pblock->nNonce;
2885
2886     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2887     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2888
2889     // Byte swap all the input buffer
2890     for (int i = 0; i < sizeof(tmp)/4; i++)
2891         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2892
2893     // Precalc the first half of the first hash, which stays constant
2894     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2895
2896     memcpy(pdata, &tmp.block, 128);
2897     memcpy(phash1, &tmp.hash1, 64);
2898 }
2899
2900
2901 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2902 {
2903     uint256 hash = pblock->GetHash();
2904     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2905
2906     if (hash > hashTarget)
2907         return false;
2908
2909     //// debug print
2910     printf("BitcoinMiner:\n");
2911     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2912     pblock->print();
2913     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2914     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2915
2916     // Found a solution
2917     CRITICAL_BLOCK(cs_main)
2918     {
2919         if (pblock->hashPrevBlock != hashBestChain)
2920             return error("BitcoinMiner : generated block is stale");
2921
2922         // Remove key from key pool
2923         reservekey.KeepKey();
2924
2925         // Track how many getdata requests this block gets
2926         CRITICAL_BLOCK(wallet.cs_mapRequestCount)
2927             wallet.mapRequestCount[pblock->GetHash()] = 0;
2928
2929         // Process this block the same as if we had received it from another node
2930         if (!ProcessBlock(NULL, pblock))
2931             return error("BitcoinMiner : ProcessBlock, block not accepted");
2932     }
2933
2934     Sleep(2000);
2935     return true;
2936 }
2937
2938 void static ThreadBitcoinMiner(void* parg);
2939
2940 void static BitcoinMiner(CWallet *pwallet)
2941 {
2942     printf("BitcoinMiner started\n");
2943     SetThreadPriority(THREAD_PRIORITY_LOWEST);
2944
2945     // Each thread has its own key and counter
2946     CReserveKey reservekey(pwallet);
2947     unsigned int nExtraNonce = 0;
2948     int64 nPrevTime = 0;
2949
2950     while (fGenerateBitcoins)
2951     {
2952         if (AffinityBugWorkaround(ThreadBitcoinMiner))
2953             return;
2954         if (fShutdown)
2955             return;
2956         while (vNodes.empty() || IsInitialBlockDownload())
2957         {
2958             Sleep(1000);
2959             if (fShutdown)
2960                 return;
2961             if (!fGenerateBitcoins)
2962                 return;
2963         }
2964
2965
2966         //
2967         // Create new block
2968         //
2969         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2970         CBlockIndex* pindexPrev = pindexBest;
2971
2972         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2973         if (!pblock.get())
2974             return;
2975         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
2976
2977         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2978
2979
2980         //
2981         // Prebuild hash buffers
2982         //
2983         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2984         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
2985         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
2986
2987         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
2988
2989         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
2990         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
2991
2992
2993         //
2994         // Search
2995         //
2996         int64 nStart = GetTime();
2997         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2998         uint256 hashbuf[2];
2999         uint256& hash = *alignup<16>(hashbuf);
3000         loop
3001         {
3002             unsigned int nHashesDone = 0;
3003             unsigned int nNonceFound;
3004
3005             // Crypto++ SHA-256
3006             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3007                                             (char*)&hash, nHashesDone);
3008
3009             // Check if something found
3010             if (nNonceFound != -1)
3011             {
3012                 for (int i = 0; i < sizeof(hash)/4; i++)
3013                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3014
3015                 if (hash <= hashTarget)
3016                 {
3017                     // Found a solution
3018                     pblock->nNonce = ByteReverse(nNonceFound);
3019                     assert(hash == pblock->GetHash());
3020
3021                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3022                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3023                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3024                     break;
3025                 }
3026             }
3027
3028             // Meter hashes/sec
3029             static int64 nHashCounter;
3030             if (nHPSTimerStart == 0)
3031             {
3032                 nHPSTimerStart = GetTimeMillis();
3033                 nHashCounter = 0;
3034             }
3035             else
3036                 nHashCounter += nHashesDone;
3037             if (GetTimeMillis() - nHPSTimerStart > 4000)
3038             {
3039                 static CCriticalSection cs;
3040                 CRITICAL_BLOCK(cs)
3041                 {
3042                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3043                     {
3044                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3045                         nHPSTimerStart = GetTimeMillis();
3046                         nHashCounter = 0;
3047                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3048                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3049                         static int64 nLogTime;
3050                         if (GetTime() - nLogTime > 30 * 60)
3051                         {
3052                             nLogTime = GetTime();
3053                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3054                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3055                         }
3056                     }
3057                 }
3058             }
3059
3060             // Check for stop or if block needs to be rebuilt
3061             if (fShutdown)
3062                 return;
3063             if (!fGenerateBitcoins)
3064                 return;
3065             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3066                 return;
3067             if (vNodes.empty())
3068                 break;
3069             if (nBlockNonce >= 0xffff0000)
3070                 break;
3071             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3072                 break;
3073             if (pindexPrev != pindexBest)
3074                 break;
3075
3076             // Update nTime every few seconds
3077             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3078             nBlockTime = ByteReverse(pblock->nTime);
3079         }
3080     }
3081 }
3082
3083 void static ThreadBitcoinMiner(void* parg)
3084 {
3085     CWallet* pwallet = (CWallet*)parg;
3086     try
3087     {
3088         vnThreadsRunning[3]++;
3089         BitcoinMiner(pwallet);
3090         vnThreadsRunning[3]--;
3091     }
3092     catch (std::exception& e) {
3093         vnThreadsRunning[3]--;
3094         PrintException(&e, "ThreadBitcoinMiner()");
3095     } catch (...) {
3096         vnThreadsRunning[3]--;
3097         PrintException(NULL, "ThreadBitcoinMiner()");
3098     }
3099     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3100     nHPSTimerStart = 0;
3101     if (vnThreadsRunning[3] == 0)
3102         dHashesPerSec = 0;
3103     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3104 }
3105
3106
3107 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3108 {
3109     if (fGenerateBitcoins != fGenerate)
3110     {
3111         fGenerateBitcoins = fGenerate;
3112         WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3113         MainFrameRepaint();
3114     }
3115     if (fGenerateBitcoins)
3116     {
3117         int nProcessors = boost::thread::hardware_concurrency();
3118         printf("%d processors\n", nProcessors);
3119         if (nProcessors < 1)
3120             nProcessors = 1;
3121         if (fLimitProcessors && nProcessors > nLimitProcessors)
3122             nProcessors = nLimitProcessors;
3123         int nAddThreads = nProcessors - vnThreadsRunning[3];
3124         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3125         for (int i = 0; i < nAddThreads; i++)
3126         {
3127             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3128                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3129             Sleep(10);
3130         }
3131     }
3132 }