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