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