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