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