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