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