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