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