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