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