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