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