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