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