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