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