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