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