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