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