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