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