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