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