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