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