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