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