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