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