Remove legacy block schema version checking
[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;
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 * bnTargetLimit;
1036                 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget;
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 * bnTargetLimit;
1049                 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget;
1050             }
1051
1052             if (bnMidPart > bnRewardPart)
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     if (fDebug && GetBoolArg("-printcreation"))
1077         printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1078     return nSubsidy;
1079 }
1080
1081 static const int64 nTargetTimespan = 7 * 24 * 60 * 60;  // one week
1082
1083 // get proof of work blocks max spacing according to hard-coded conditions
1084 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1085 {
1086     if(nTime > TARGETS_SWITCH_TIME)
1087         return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1088
1089     if(fTestNet)
1090         return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1091
1092     return 12 * nStakeTargetSpacing; // 2 hours otherwise
1093 }
1094
1095 //
1096 // minimum amount of work that could possibly be required nTime after
1097 // minimum work required was nBase
1098 //
1099 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1100 {
1101     CBigNum bnTargetLimit = bnProofOfWorkLimit;
1102
1103     CBigNum bnResult;
1104     bnResult.SetCompact(nBase);
1105     bnResult *= 2;
1106     while (nTime > 0 && bnResult < bnTargetLimit)
1107     {
1108         // Maximum 200% adjustment per day...
1109         bnResult *= 2;
1110         nTime -= 24 * 60 * 60;
1111     }
1112     if (bnResult > bnTargetLimit)
1113         bnResult = bnTargetLimit;
1114     return bnResult.GetCompact();
1115 }
1116
1117 // ppcoin: find last block index up to pindex
1118 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1119 {
1120     while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1121         pindex = pindex->pprev;
1122     return pindex;
1123 }
1124
1125 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1126 {
1127     CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1128
1129     if (pindexLast == NULL)
1130         return bnTargetLimit.GetCompact(); // genesis block
1131
1132     const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1133     if (pindexPrev->pprev == NULL)
1134         return bnTargetLimit.GetCompact(); // first block
1135     const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1136     if (pindexPrevPrev->pprev == NULL)
1137         return bnTargetLimit.GetCompact(); // second block
1138
1139     int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1140
1141     // ppcoin: target change every block
1142     // ppcoin: retarget with exponential moving toward target spacing
1143     CBigNum bnNew;
1144     bnNew.SetCompact(pindexPrev->nBits);
1145     int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1146     int64 nInterval = nTargetTimespan / nTargetSpacing;
1147     bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1148     bnNew /= ((nInterval + 1) * nTargetSpacing);
1149
1150     if (bnNew > bnTargetLimit)
1151         bnNew = bnTargetLimit;
1152
1153     return bnNew.GetCompact();
1154 }
1155
1156 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1157 {
1158     CBigNum bnTarget;
1159     bnTarget.SetCompact(nBits);
1160
1161     // Check range
1162     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1163         return error("CheckProofOfWork() : nBits below minimum work");
1164
1165     // Check proof of work matches claimed amount
1166     if (hash > bnTarget.getuint256())
1167         return error("CheckProofOfWork() : hash doesn't match nBits");
1168
1169     return true;
1170 }
1171
1172 // Return maximum amount of blocks that other nodes claim to have
1173 int GetNumBlocksOfPeers()
1174 {
1175     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1176 }
1177
1178 bool IsInitialBlockDownload()
1179 {
1180     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1181         return true;
1182     static int64 nLastUpdate;
1183     static CBlockIndex* pindexLastBest;
1184     if (pindexBest != pindexLastBest)
1185     {
1186         pindexLastBest = pindexBest;
1187         nLastUpdate = GetTime();
1188     }
1189     return (GetTime() - nLastUpdate < 10 &&
1190             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1191 }
1192
1193 void static InvalidChainFound(CBlockIndex* pindexNew)
1194 {
1195     if (pindexNew->nChainTrust > nBestInvalidTrust)
1196     {
1197         nBestInvalidTrust = pindexNew->nChainTrust;
1198         CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1199         uiInterface.NotifyBlocksChanged();
1200     }
1201
1202     uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1203     uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1204
1205     printf("InvalidChainFound: invalid block=%s  height=%d  trust=%s  blocktrust=%"PRI64d"  date=%s\n",
1206       pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1207       CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1208       DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1209     printf("InvalidChainFound:  current best=%s  height=%d  trust=%s  blocktrust=%"PRI64d"  date=%s\n",
1210       hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1211       CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1212       nBestBlockTrust.Get64(),
1213       DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1214 }
1215
1216
1217 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1218 {
1219     nTime = max(GetBlockTime(), GetAdjustedTime());
1220 }
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1233 {
1234     // Relinquish previous transactions' spent pointers
1235     if (!IsCoinBase())
1236     {
1237         BOOST_FOREACH(const CTxIn& txin, vin)
1238         {
1239             COutPoint prevout = txin.prevout;
1240
1241             // Get prev txindex from disk
1242             CTxIndex txindex;
1243             if (!txdb.ReadTxIndex(prevout.hash, txindex))
1244                 return error("DisconnectInputs() : ReadTxIndex failed");
1245
1246             if (prevout.n >= txindex.vSpent.size())
1247                 return error("DisconnectInputs() : prevout.n out of range");
1248
1249             // Mark outpoint as not spent
1250             txindex.vSpent[prevout.n].SetNull();
1251
1252             // Write back
1253             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1254                 return error("DisconnectInputs() : UpdateTxIndex failed");
1255         }
1256     }
1257
1258     // Remove transaction from index
1259     // This can fail if a duplicate of this transaction was in a chain that got
1260     // reorganized away. This is only possible if this transaction was completely
1261     // spent, so erasing it would be a no-op anyway.
1262     txdb.EraseTxIndex(*this);
1263
1264     return true;
1265 }
1266
1267
1268 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1269                                bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1270 {
1271     // FetchInputs can return false either because we just haven't seen some inputs
1272     // (in which case the transaction should be stored as an orphan)
1273     // or because the transaction is malformed (in which case the transaction should
1274     // be dropped).  If tx is definitely invalid, fInvalid will be set to true.
1275     fInvalid = false;
1276
1277     if (IsCoinBase())
1278         return true; // Coinbase transactions have no inputs to fetch.
1279
1280     for (unsigned int i = 0; i < vin.size(); i++)
1281     {
1282         COutPoint prevout = vin[i].prevout;
1283         if (inputsRet.count(prevout.hash))
1284             continue; // Got it already
1285
1286         // Read txindex
1287         CTxIndex& txindex = inputsRet[prevout.hash].first;
1288         bool fFound = true;
1289         if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1290         {
1291             // Get txindex from current proposed changes
1292             txindex = mapTestPool.find(prevout.hash)->second;
1293         }
1294         else
1295         {
1296             // Read txindex from txdb
1297             fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1298         }
1299         if (!fFound && (fBlock || fMiner))
1300             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());
1301
1302         // Read txPrev
1303         CTransaction& txPrev = inputsRet[prevout.hash].second;
1304         if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1305         {
1306             // Get prev tx from single transactions in memory
1307             {
1308                 LOCK(mempool.cs);
1309                 if (!mempool.exists(prevout.hash))
1310                     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());
1311                 txPrev = mempool.lookup(prevout.hash);
1312             }
1313             if (!fFound)
1314                 txindex.vSpent.resize(txPrev.vout.size());
1315         }
1316         else
1317         {
1318             // Get prev tx from disk
1319             if (!txPrev.ReadFromDisk(txindex.pos))
1320                 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
1321         }
1322     }
1323
1324     // Make sure all prevout.n indexes are valid:
1325     for (unsigned int i = 0; i < vin.size(); i++)
1326     {
1327         const COutPoint prevout = vin[i].prevout;
1328         assert(inputsRet.count(prevout.hash) != 0);
1329         const CTxIndex& txindex = inputsRet[prevout.hash].first;
1330         const CTransaction& txPrev = inputsRet[prevout.hash].second;
1331         if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1332         {
1333             // Revisit this if/when transaction replacement is implemented and allows
1334             // adding inputs:
1335             fInvalid = true;
1336             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()));
1337         }
1338     }
1339
1340     return true;
1341 }
1342
1343 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1344 {
1345     MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1346     if (mi == inputs.end())
1347         throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1348
1349     const CTransaction& txPrev = (mi->second).second;
1350     if (input.prevout.n >= txPrev.vout.size())
1351         throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1352
1353     return txPrev.vout[input.prevout.n];
1354 }
1355
1356 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1357 {
1358     if (IsCoinBase())
1359         return 0;
1360
1361     int64 nResult = 0;
1362     for (unsigned int i = 0; i < vin.size(); i++)
1363     {
1364         nResult += GetOutputFor(vin[i], inputs).nValue;
1365     }
1366     return nResult;
1367
1368 }
1369
1370 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1371 {
1372     if (IsCoinBase())
1373         return 0;
1374
1375     unsigned int nSigOps = 0;
1376     for (unsigned int i = 0; i < vin.size(); i++)
1377     {
1378         const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1379         if (prevout.scriptPubKey.IsPayToScriptHash())
1380             nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1381     }
1382     return nSigOps;
1383 }
1384
1385 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1386                                  map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1387                                  const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1388 {
1389     // Take over previous transactions' spent pointers
1390     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1391     // fMiner is true when called from the internal bitcoin miner
1392     // ... both are false when called from CTransaction::AcceptToMemoryPool
1393     if (!IsCoinBase())
1394     {
1395         int64 nValueIn = 0;
1396         int64 nFees = 0;
1397         for (unsigned int i = 0; i < vin.size(); i++)
1398         {
1399             COutPoint prevout = vin[i].prevout;
1400             assert(inputs.count(prevout.hash) > 0);
1401             CTxIndex& txindex = inputs[prevout.hash].first;
1402             CTransaction& txPrev = inputs[prevout.hash].second;
1403
1404             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1405                 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()));
1406
1407             // If prev is coinbase or coinstake, check that it's matured
1408             if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1409                 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1410                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1411                         return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1412
1413             // ppcoin: check transaction timestamp
1414             if (txPrev.nTime > nTime)
1415                 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1416
1417             // Check for negative or overflow input values
1418             nValueIn += txPrev.vout[prevout.n].nValue;
1419             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1420                 return DoS(100, error("ConnectInputs() : txin values out of range"));
1421
1422         }
1423         // The first loop above does all the inexpensive checks.
1424         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1425         // Helps prevent CPU exhaustion attacks.
1426         for (unsigned int i = 0; i < vin.size(); i++)
1427         {
1428             COutPoint prevout = vin[i].prevout;
1429             assert(inputs.count(prevout.hash) > 0);
1430             CTxIndex& txindex = inputs[prevout.hash].first;
1431             CTransaction& txPrev = inputs[prevout.hash].second;
1432
1433             // Check for conflicts (double-spend)
1434             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1435             // for an attacker to attempt to split the network.
1436             if (!txindex.vSpent[prevout.n].IsNull())
1437                 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());
1438
1439             // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1440             // before the last blockchain checkpoint. This is safe because block merkle hashes are
1441             // still computed and checked, and any change will be caught at the next checkpoint.
1442             if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1443             {
1444                 // Verify signature
1445                 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1446                 {
1447                     // only during transition phase for P2SH: do not invoke anti-DoS code for
1448                     // potentially old clients relaying bad P2SH transactions
1449                     if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1450                         return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1451
1452                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1453                 }
1454             }
1455
1456             // Mark outpoints as spent
1457             txindex.vSpent[prevout.n] = posThisTx;
1458
1459             // Write back
1460             if (fBlock || fMiner)
1461             {
1462                 mapTestPool[prevout.hash] = txindex;
1463             }
1464         }
1465
1466         if (IsCoinStake())
1467         {
1468             // ppcoin: coin stake tx earns reward instead of paying fee
1469             uint64 nCoinAge;
1470             if (!GetCoinAge(txdb, nCoinAge))
1471                 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1472
1473             int64 nStakeReward = GetValueOut() - nValueIn;
1474             int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1475
1476             if (nStakeReward > nCalculatedStakeReward)
1477                 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1478         }
1479         else
1480         {
1481             if (nValueIn < GetValueOut())
1482                 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1483
1484             // Tally transaction fees
1485             int64 nTxFee = nValueIn - GetValueOut();
1486             if (nTxFee < 0)
1487                 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1488             // ppcoin: enforce transaction fees for every block
1489             if (nTxFee < GetMinFee())
1490                 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;
1491
1492             nFees += nTxFee;
1493             if (!MoneyRange(nFees))
1494                 return DoS(100, error("ConnectInputs() : nFees out of range"));
1495         }
1496     }
1497
1498     return true;
1499 }
1500
1501
1502 bool CTransaction::ClientConnectInputs()
1503 {
1504     if (IsCoinBase())
1505         return false;
1506
1507     // Take over previous transactions' spent pointers
1508     {
1509         LOCK(mempool.cs);
1510         int64 nValueIn = 0;
1511         for (unsigned int i = 0; i < vin.size(); i++)
1512         {
1513             // Get prev tx from single transactions in memory
1514             COutPoint prevout = vin[i].prevout;
1515             if (!mempool.exists(prevout.hash))
1516                 return false;
1517             CTransaction& txPrev = mempool.lookup(prevout.hash);
1518
1519             if (prevout.n >= txPrev.vout.size())
1520                 return false;
1521
1522             // Verify signature
1523             if (!VerifySignature(txPrev, *this, i, true, 0))
1524                 return error("ConnectInputs() : VerifySignature failed");
1525
1526             ///// this is redundant with the mempool.mapNextTx stuff,
1527             ///// not sure which I want to get rid of
1528             ///// this has to go away now that posNext is gone
1529             // // Check for conflicts
1530             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1531             //     return error("ConnectInputs() : prev tx already used");
1532             //
1533             // // Flag outpoints as used
1534             // txPrev.vout[prevout.n].posNext = posThisTx;
1535
1536             nValueIn += txPrev.vout[prevout.n].nValue;
1537
1538             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1539                 return error("ClientConnectInputs() : txin values out of range");
1540         }
1541         if (GetValueOut() > nValueIn)
1542             return false;
1543     }
1544
1545     return true;
1546 }
1547
1548
1549
1550
1551 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1552 {
1553     // Disconnect in reverse order
1554     for (int i = vtx.size()-1; i >= 0; i--)
1555         if (!vtx[i].DisconnectInputs(txdb))
1556             return false;
1557
1558     // Update block index on disk without changing it in memory.
1559     // The memory index structure will be changed after the db commits.
1560     if (pindex->pprev)
1561     {
1562         CDiskBlockIndex blockindexPrev(pindex->pprev);
1563         blockindexPrev.hashNext = 0;
1564         if (!txdb.WriteBlockIndex(blockindexPrev))
1565             return error("DisconnectBlock() : WriteBlockIndex failed");
1566     }
1567
1568     // ppcoin: clean up wallet after disconnecting coinstake
1569     BOOST_FOREACH(CTransaction& tx, vtx)
1570         SyncWithWallets(tx, this, false, false);
1571
1572     return true;
1573 }
1574
1575 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1576 {
1577     // Check it again in case a previous version let a bad block in
1578     if (!CheckBlock(!fJustCheck, !fJustCheck))
1579         return false;
1580
1581     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1582     // unless those are already completely spent.
1583     // If such overwrites are allowed, coinbases and transactions depending upon those
1584     // can be duplicated to remove the ability to spend the first instance -- even after
1585     // being sent to another address.
1586     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1587     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1588     // already refuses previously-known transaction ids entirely.
1589     // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1590     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1591     // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1592     // initial block download.
1593     bool fEnforceBIP30 = true; // Always active in NovaCoin
1594     bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1595
1596     //// issue here: it doesn't know the version
1597     unsigned int nTxPos;
1598     if (fJustCheck)
1599         // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1600         // 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
1601         nTxPos = 1;
1602     else
1603         nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1604
1605     map<uint256, CTxIndex> mapQueuedChanges;
1606     int64 nFees = 0;
1607     int64 nValueIn = 0;
1608     int64 nValueOut = 0;
1609     unsigned int nSigOps = 0;
1610     BOOST_FOREACH(CTransaction& tx, vtx)
1611     {
1612         uint256 hashTx = tx.GetHash();
1613
1614         if (fEnforceBIP30) {
1615             CTxIndex txindexOld;
1616             if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1617                 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1618                     if (pos.IsNull())
1619                         return false;
1620             }
1621         }
1622
1623         nSigOps += tx.GetLegacySigOpCount();
1624         if (nSigOps > MAX_BLOCK_SIGOPS)
1625             return DoS(100, error("ConnectBlock() : too many sigops"));
1626
1627         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1628         if (!fJustCheck)
1629             nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1630
1631         MapPrevTx mapInputs;
1632         if (tx.IsCoinBase())
1633             nValueOut += tx.GetValueOut();
1634         else
1635         {
1636             bool fInvalid;
1637             if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1638                 return false;
1639
1640             if (fStrictPayToScriptHash)
1641             {
1642                 // Add in sigops done by pay-to-script-hash inputs;
1643                 // this is to prevent a "rogue miner" from creating
1644                 // an incredibly-expensive-to-validate block.
1645                 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1646                 if (nSigOps > MAX_BLOCK_SIGOPS)
1647                     return DoS(100, error("ConnectBlock() : too many sigops"));
1648             }
1649
1650             int64 nTxValueIn = tx.GetValueIn(mapInputs);
1651             int64 nTxValueOut = tx.GetValueOut();
1652             nValueIn += nTxValueIn;
1653             nValueOut += nTxValueOut;
1654             if (!tx.IsCoinStake())
1655                 nFees += nTxValueIn - nTxValueOut;
1656
1657             if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1658                 return false;
1659         }
1660
1661         mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1662     }
1663
1664     // ppcoin: track money supply and mint amount info
1665     pindex->nMint = nValueOut - nValueIn + nFees;
1666     pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1667     if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1668         return error("Connect() : WriteBlockIndex for pindex failed");
1669
1670     // ppcoin: fees are not collected by miners as in bitcoin
1671     // ppcoin: fees are destroyed to compensate the entire network
1672     if (fDebug && GetBoolArg("-printcreation"))
1673         printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1674
1675     if (fJustCheck)
1676         return true;
1677
1678     // Write queued txindex changes
1679     for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1680     {
1681         if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1682             return error("ConnectBlock() : UpdateTxIndex failed");
1683     }
1684
1685     // Update block index on disk without changing it in memory.
1686     // The memory index structure will be changed after the db commits.
1687     if (pindex->pprev)
1688     {
1689         CDiskBlockIndex blockindexPrev(pindex->pprev);
1690         blockindexPrev.hashNext = pindex->GetBlockHash();
1691         if (!txdb.WriteBlockIndex(blockindexPrev))
1692             return error("ConnectBlock() : WriteBlockIndex failed");
1693     }
1694
1695     // Watch for transactions paying to me
1696     BOOST_FOREACH(CTransaction& tx, vtx)
1697         SyncWithWallets(tx, this, true);
1698
1699     return true;
1700 }
1701
1702 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1703 {
1704     printf("REORGANIZE\n");
1705
1706     // Find the fork
1707     CBlockIndex* pfork = pindexBest;
1708     CBlockIndex* plonger = pindexNew;
1709     while (pfork != plonger)
1710     {
1711         while (plonger->nHeight > pfork->nHeight)
1712             if (!(plonger = plonger->pprev))
1713                 return error("Reorganize() : plonger->pprev is null");
1714         if (pfork == plonger)
1715             break;
1716         if (!(pfork = pfork->pprev))
1717             return error("Reorganize() : pfork->pprev is null");
1718     }
1719
1720     // List of what to disconnect
1721     vector<CBlockIndex*> vDisconnect;
1722     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1723         vDisconnect.push_back(pindex);
1724
1725     // List of what to connect
1726     vector<CBlockIndex*> vConnect;
1727     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1728         vConnect.push_back(pindex);
1729     reverse(vConnect.begin(), vConnect.end());
1730
1731     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());
1732     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());
1733
1734     // Disconnect shorter branch
1735     vector<CTransaction> vResurrect;
1736     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1737     {
1738         CBlock block;
1739         if (!block.ReadFromDisk(pindex))
1740             return error("Reorganize() : ReadFromDisk for disconnect failed");
1741         if (!block.DisconnectBlock(txdb, pindex))
1742             return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1743
1744         // Queue memory transactions to resurrect
1745         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1746             if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1747                 vResurrect.push_back(tx);
1748     }
1749
1750     // Connect longer branch
1751     vector<CTransaction> vDelete;
1752     for (unsigned int i = 0; i < vConnect.size(); i++)
1753     {
1754         CBlockIndex* pindex = vConnect[i];
1755         CBlock block;
1756         if (!block.ReadFromDisk(pindex))
1757             return error("Reorganize() : ReadFromDisk for connect failed");
1758         if (!block.ConnectBlock(txdb, pindex))
1759         {
1760             // Invalid block
1761             return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1762         }
1763
1764         // Queue memory transactions to delete
1765         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1766             vDelete.push_back(tx);
1767     }
1768     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1769         return error("Reorganize() : WriteHashBestChain failed");
1770
1771     // Make sure it's successfully written to disk before changing memory structure
1772     if (!txdb.TxnCommit())
1773         return error("Reorganize() : TxnCommit failed");
1774
1775     // Disconnect shorter branch
1776     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1777         if (pindex->pprev)
1778             pindex->pprev->pnext = NULL;
1779
1780     // Connect longer branch
1781     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1782         if (pindex->pprev)
1783             pindex->pprev->pnext = pindex;
1784
1785     // Resurrect memory transactions that were in the disconnected branch
1786     BOOST_FOREACH(CTransaction& tx, vResurrect)
1787         tx.AcceptToMemoryPool(txdb, false);
1788
1789     // Delete redundant memory transactions that are in the connected branch
1790     BOOST_FOREACH(CTransaction& tx, vDelete)
1791         mempool.remove(tx);
1792
1793     printf("REORGANIZE: done\n");
1794
1795     return true;
1796 }
1797
1798
1799 // Called from inside SetBestChain: attaches a block to the new best chain being built
1800 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1801 {
1802     uint256 hash = GetHash();
1803
1804     // Adding to current best branch
1805     if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1806     {
1807         txdb.TxnAbort();
1808         InvalidChainFound(pindexNew);
1809         return false;
1810     }
1811     if (!txdb.TxnCommit())
1812         return error("SetBestChain() : TxnCommit failed");
1813
1814     // Add to current best branch
1815     pindexNew->pprev->pnext = pindexNew;
1816
1817     // Delete redundant memory transactions
1818     BOOST_FOREACH(CTransaction& tx, vtx)
1819         mempool.remove(tx);
1820
1821     return true;
1822 }
1823
1824 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1825 {
1826     uint256 hash = GetHash();
1827
1828     if (!txdb.TxnBegin())
1829         return error("SetBestChain() : TxnBegin failed");
1830
1831     if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1832     {
1833         txdb.WriteHashBestChain(hash);
1834         if (!txdb.TxnCommit())
1835             return error("SetBestChain() : TxnCommit failed");
1836         pindexGenesisBlock = pindexNew;
1837     }
1838     else if (hashPrevBlock == hashBestChain)
1839     {
1840         if (!SetBestChainInner(txdb, pindexNew))
1841             return error("SetBestChain() : SetBestChainInner failed");
1842     }
1843     else
1844     {
1845         // the first block in the new chain that will cause it to become the new best chain
1846         CBlockIndex *pindexIntermediate = pindexNew;
1847
1848         // list of blocks that need to be connected afterwards
1849         std::vector<CBlockIndex*> vpindexSecondary;
1850
1851         // Reorganize is costly in terms of db load, as it works in a single db transaction.
1852         // Try to limit how much needs to be done inside
1853         while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1854         {
1855             vpindexSecondary.push_back(pindexIntermediate);
1856             pindexIntermediate = pindexIntermediate->pprev;
1857         }
1858
1859         if (!vpindexSecondary.empty())
1860             printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1861
1862         // Switch to new best branch
1863         if (!Reorganize(txdb, pindexIntermediate))
1864         {
1865             txdb.TxnAbort();
1866             InvalidChainFound(pindexNew);
1867             return error("SetBestChain() : Reorganize failed");
1868         }
1869
1870         // Connect further blocks
1871         BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1872         {
1873             CBlock block;
1874             if (!block.ReadFromDisk(pindex))
1875             {
1876                 printf("SetBestChain() : ReadFromDisk failed\n");
1877                 break;
1878             }
1879             if (!txdb.TxnBegin()) {
1880                 printf("SetBestChain() : TxnBegin 2 failed\n");
1881                 break;
1882             }
1883             // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1884             if (!block.SetBestChainInner(txdb, pindex))
1885                 break;
1886         }
1887     }
1888
1889     // Update best block in wallet (so we can detect restored wallets)
1890     bool fIsInitialDownload = IsInitialBlockDownload();
1891     if (!fIsInitialDownload)
1892     {
1893         const CBlockLocator locator(pindexNew);
1894         ::SetBestChain(locator);
1895     }
1896
1897     // New best block
1898     hashBestChain = hash;
1899     pindexBest = pindexNew;
1900     pblockindexFBBHLast = NULL;
1901     nBestHeight = pindexBest->nHeight;
1902     nBestChainTrust = pindexNew->nChainTrust;
1903     nTimeBestReceived = GetTime();
1904     nTransactionsUpdated++;
1905
1906     uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1907
1908     printf("SetBestChain: new best=%s  height=%d  trust=%s  blocktrust=%"PRI64d"  date=%s\n",
1909       hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1910       CBigNum(nBestChainTrust).ToString().c_str(),
1911       nBestBlockTrust.Get64(),
1912       DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1913
1914     // Check the version of the last 100 blocks to see if we need to upgrade:
1915     if (!fIsInitialDownload)
1916     {
1917         int nUpgraded = 0;
1918         const CBlockIndex* pindex = pindexBest;
1919         for (int i = 0; i < 100 && pindex != NULL; i++)
1920         {
1921             if (pindex->nVersion > CBlock::CURRENT_VERSION)
1922                 ++nUpgraded;
1923             pindex = pindex->pprev;
1924         }
1925         if (nUpgraded > 0)
1926             printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1927         if (nUpgraded > 100/2)
1928             // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1929             strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1930     }
1931
1932     std::string strCmd = GetArg("-blocknotify", "");
1933
1934     if (!fIsInitialDownload && !strCmd.empty())
1935     {
1936         boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1937         boost::thread t(runCommand, strCmd); // thread runs free
1938     }
1939
1940     return true;
1941 }
1942
1943 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1944 // Only those coins meeting minimum age requirement counts. As those
1945 // transactions not in main chain are not currently indexed so we
1946 // might not find out about their coin age. Older transactions are 
1947 // guaranteed to be in main chain by sync-checkpoint. This rule is
1948 // introduced to help nodes establish a consistent view of the coin
1949 // age (trust score) of competing branches.
1950 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1951 {
1952     CBigNum bnCentSecond = 0;  // coin age in the unit of cent-seconds
1953     nCoinAge = 0;
1954
1955     if (IsCoinBase())
1956         return true;
1957
1958     BOOST_FOREACH(const CTxIn& txin, vin)
1959     {
1960         // First try finding the previous transaction in database
1961         CTransaction txPrev;
1962         CTxIndex txindex;
1963         if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1964             continue;  // previous transaction not in main chain
1965         if (nTime < txPrev.nTime)
1966             return false;  // Transaction timestamp violation
1967
1968         // Read block header
1969         CBlock block;
1970         if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1971             return false; // unable to read block of previous transaction
1972         if (block.GetBlockTime() + nStakeMinAge > nTime)
1973             continue; // only count coins meeting min age requirement
1974
1975         int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1976         bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1977
1978         if (fDebug && GetBoolArg("-printcoinage"))
1979             printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1980     }
1981
1982     CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1983     if (fDebug && GetBoolArg("-printcoinage"))
1984         printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1985     nCoinAge = bnCoinDay.getuint64();
1986     return true;
1987 }
1988
1989 // ppcoin: total coin age spent in block, in the unit of coin-days.
1990 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1991 {
1992     nCoinAge = 0;
1993
1994     CTxDB txdb("r");
1995     BOOST_FOREACH(const CTransaction& tx, vtx)
1996     {
1997         uint64 nTxCoinAge;
1998         if (tx.GetCoinAge(txdb, nTxCoinAge))
1999             nCoinAge += nTxCoinAge;
2000         else
2001             return false;
2002     }
2003
2004     if (nCoinAge == 0) // block coin age minimum 1 coin-day
2005         nCoinAge = 1;
2006     if (fDebug && GetBoolArg("-printcoinage"))
2007         printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2008     return true;
2009 }
2010
2011 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2012 {
2013     // Check for duplicate
2014     uint256 hash = GetHash();
2015     if (mapBlockIndex.count(hash))
2016         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2017
2018     // Construct new block index object
2019     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2020     if (!pindexNew)
2021         return error("AddToBlockIndex() : new CBlockIndex failed");
2022     pindexNew->phashBlock = &hash;
2023     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2024     if (miPrev != mapBlockIndex.end())
2025     {
2026         pindexNew->pprev = (*miPrev).second;
2027         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2028     }
2029
2030     // ppcoin: compute chain trust score
2031     pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2032
2033     // ppcoin: compute stake entropy bit for stake modifier
2034     if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2035         return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2036
2037     // ppcoin: record proof-of-stake hash value
2038     if (pindexNew->IsProofOfStake())
2039     {
2040         if (!mapProofOfStake.count(hash))
2041             return error("AddToBlockIndex() : hashProofOfStake not found in map");
2042         pindexNew->hashProofOfStake = mapProofOfStake[hash];
2043     }
2044
2045     // ppcoin: compute stake modifier
2046     uint64 nStakeModifier = 0;
2047     bool fGeneratedStakeModifier = false;
2048     if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2049         return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2050     pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2051     pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2052     if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2053         return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2054
2055     // Add to mapBlockIndex
2056     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2057     if (pindexNew->IsProofOfStake())
2058         setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2059     pindexNew->phashBlock = &((*mi).first);
2060
2061     // Write to disk block index
2062     CTxDB txdb;
2063     if (!txdb.TxnBegin())
2064         return false;
2065     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2066     if (!txdb.TxnCommit())
2067         return false;
2068
2069     // New best
2070     if (pindexNew->nChainTrust > nBestChainTrust)
2071         if (!SetBestChain(txdb, pindexNew))
2072             return false;
2073
2074     txdb.Close();
2075
2076     if (pindexNew == pindexBest)
2077     {
2078         // Notify UI to display prev block's coinbase if it was ours
2079         static uint256 hashPrevBestCoinBase;
2080         UpdatedTransaction(hashPrevBestCoinBase);
2081         hashPrevBestCoinBase = vtx[0].GetHash();
2082     }
2083
2084     uiInterface.NotifyBlocksChanged();
2085     return true;
2086 }
2087
2088
2089
2090
2091 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2092 {
2093     // These are checks that are independent of context
2094     // that can be verified before saving an orphan block.
2095
2096     // Size limits
2097     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2098         return DoS(100, error("CheckBlock() : size limits failed"));
2099
2100     // Special short-term limits to avoid 10,000 BDB lock limit:
2101     if (GetBlockTime() < LOCKS_SWITCH_TIME)
2102     {
2103         // Rule is: #unique txids referenced <= 4,500
2104         // ... to prevent 10,000 BDB lock exhaustion on old clients
2105         set<uint256> setTxIn;
2106         for (size_t i = 0; i < vtx.size(); i++)
2107         {
2108             setTxIn.insert(vtx[i].GetHash());
2109             if (i == 0) continue; // skip coinbase txin
2110             BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
2111                     setTxIn.insert(txin.prevout.hash);
2112         }
2113         size_t nTxids = setTxIn.size();
2114         if (nTxids > 4500)
2115             return error("CheckBlock() : maxlocks violation");
2116     }
2117
2118     // Check proof of work matches claimed amount
2119     if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2120         return DoS(50, error("CheckBlock() : proof of work failed"));
2121
2122     // Check timestamp
2123     if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2124         return error("CheckBlock() : block timestamp too far in the future");
2125
2126     // First transaction must be coinbase, the rest must not be
2127     if (vtx.empty() || !vtx[0].IsCoinBase())
2128         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2129     for (unsigned int i = 1; i < vtx.size(); i++)
2130         if (vtx[i].IsCoinBase())
2131             return DoS(100, error("CheckBlock() : more than one coinbase"));
2132
2133     // Check coinbase timestamp
2134     if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2135         return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2136
2137     if (IsProofOfStake())
2138     {
2139         // Coinbase output should be empty if proof-of-stake block
2140         if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2141             return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2142
2143         // Second transaction must be coinstake, the rest must not be
2144         if (vtx.empty() || !vtx[1].IsCoinStake())
2145             return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2146         for (unsigned int i = 2; i < vtx.size(); i++)
2147             if (vtx[i].IsCoinStake())
2148                 return DoS(100, error("CheckBlock() : more than one coinstake"));
2149
2150         // Check coinstake timestamp
2151         if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2152             return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2153     }
2154     else
2155     {
2156         // Coinbase fee paid until 20 Sep 2013
2157         int64 nFee = GetBlockTime() < CHAINCHECKS_SWITCH_TIME ? vtx[0].GetMinFee() - MIN_TX_FEE : 0;
2158
2159         // Check coinbase reward
2160         if (vtx[0].GetValueOut() > (GetProofOfWorkReward(nBits) - nFee))
2161             return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2162                    vtx[0].GetValueOut(),
2163                    GetProofOfWorkReward(nBits) - nFee));
2164     }
2165
2166     // Check transactions
2167     BOOST_FOREACH(const CTransaction& tx, vtx)
2168     {
2169         if (!tx.CheckTransaction())
2170             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2171
2172         // ppcoin: check transaction timestamp
2173         if (GetBlockTime() < (int64)tx.nTime)
2174             return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2175     }
2176
2177     // Check for duplicate txids. This is caught by ConnectInputs(),
2178     // but catching it earlier avoids a potential DoS attack:
2179     set<uint256> uniqueTx;
2180     BOOST_FOREACH(const CTransaction& tx, vtx)
2181     {
2182         uniqueTx.insert(tx.GetHash());
2183     }
2184     if (uniqueTx.size() != vtx.size())
2185         return DoS(100, error("CheckBlock() : duplicate transaction"));
2186
2187     unsigned int nSigOps = 0;
2188     BOOST_FOREACH(const CTransaction& tx, vtx)
2189     {
2190         nSigOps += tx.GetLegacySigOpCount();
2191     }
2192     if (nSigOps > MAX_BLOCK_SIGOPS)
2193         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2194
2195     // Check merkle root
2196     if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2197         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2198
2199     // NovaCoin: check proof-of-stake block signature
2200     if (IsProofOfStake() || (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME))
2201     {
2202         if (!CheckBlockSignature())
2203             return DoS(100, error("CheckBlock() : bad block signature"));
2204     }
2205
2206     return true;
2207 }
2208
2209 bool CBlock::AcceptBlock()
2210 {
2211     // Check for duplicate
2212     uint256 hash = GetHash();
2213     if (mapBlockIndex.count(hash))
2214         return error("AcceptBlock() : block already in mapBlockIndex");
2215
2216     // Get prev block index
2217     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2218     if (mi == mapBlockIndex.end())
2219         return DoS(10, error("AcceptBlock() : prev block not found"));
2220     CBlockIndex* pindexPrev = (*mi).second;
2221     int nHeight = pindexPrev->nHeight+1;
2222
2223     // Check proof-of-work or proof-of-stake
2224     if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2225         return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2226
2227     // Check timestamp against prev
2228     if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2229         return error("AcceptBlock() : block's timestamp is too early");
2230
2231     // Check that all transactions are finalized
2232     BOOST_FOREACH(const CTransaction& tx, vtx)
2233         if (!tx.IsFinal(nHeight, GetBlockTime()))
2234             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2235
2236     // Check that the block chain matches the known block chain up to a checkpoint
2237     if (!Checkpoints::CheckHardened(nHeight, hash))
2238         return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2239
2240     // ppcoin: check that the block satisfies synchronized checkpoint
2241     if (!Checkpoints::CheckSync(hash, pindexPrev))
2242     {
2243         if(!GetBoolArg("-nosynccheckpoints", false))
2244         {
2245             return error("AcceptBlock() : rejected by synchronized checkpoint");
2246         }
2247         else
2248         {
2249             strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2250         }
2251     }
2252
2253     // Enforce rule that the coinbase starts with serialized block height
2254     CScript expect = CScript() << nHeight;
2255     if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2256         return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2257
2258     // Write block to history file
2259     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2260         return error("AcceptBlock() : out of disk space");
2261     unsigned int nFile = -1;
2262     unsigned int nBlockPos = 0;
2263     if (!WriteToDisk(nFile, nBlockPos))
2264         return error("AcceptBlock() : WriteToDisk failed");
2265     if (!AddToBlockIndex(nFile, nBlockPos))
2266         return error("AcceptBlock() : AddToBlockIndex failed");
2267
2268     // Relay inventory, but don't relay old inventory during initial block download
2269     int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2270     if (hashBestChain == hash)
2271     {
2272         LOCK(cs_vNodes);
2273         BOOST_FOREACH(CNode* pnode, vNodes)
2274             if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2275                 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2276     }
2277
2278     // ppcoin: check pending sync-checkpoint
2279     Checkpoints::AcceptPendingSyncCheckpoint();
2280
2281     return true;
2282 }
2283
2284 uint256 CBlockIndex::GetBlockTrust() const
2285 {
2286     CBigNum bnTarget;
2287     bnTarget.SetCompact(nBits);
2288
2289     if (bnTarget <= 0)
2290         return 0;
2291
2292     /* Old protocol, will be removed later */
2293     if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2294         return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2295
2296     /* New protocol */
2297
2298     // Calculate work amount for block
2299     uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2300
2301     // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2302     nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2303
2304     // Return nPoWTrust for the first 12 blocks
2305     if (pprev == NULL || pprev->nHeight < 12)
2306         return nPoWTrust;
2307
2308     const CBlockIndex* currentIndex = pprev;
2309
2310     if(IsProofOfStake())
2311     {
2312         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2313
2314         // Return 1/3 of score if parent block is not the PoW block
2315         if (!pprev->IsProofOfWork())
2316             return (bnNewTrust / 3).getuint256();
2317
2318         int nPoWCount = 0;
2319
2320         // Check last 12 blocks type
2321         while (pprev->nHeight - currentIndex->nHeight < 12)
2322         {
2323             if (currentIndex->IsProofOfWork())
2324                 nPoWCount++;
2325             currentIndex = currentIndex->pprev;
2326         }
2327
2328         // Return 1/3 of score if less than 3 PoW blocks found
2329         if (nPoWCount < 3)
2330             return (bnNewTrust / 3).getuint256();
2331
2332         return bnNewTrust.getuint256();
2333     }
2334     else
2335     {
2336         CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2337
2338         // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2339         if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2340             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2341
2342         int nPoSCount = 0;
2343
2344         // Check last 12 blocks type
2345         while (pprev->nHeight - currentIndex->nHeight < 12)
2346         {
2347             if (currentIndex->IsProofOfStake())
2348                 nPoSCount++;
2349             currentIndex = currentIndex->pprev;
2350         }
2351
2352         // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2353         if (nPoSCount < 7)
2354             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2355
2356         bnTarget.SetCompact(pprev->nBits);
2357
2358         if (bnTarget <= 0)
2359             return 0;
2360
2361         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2362
2363         // Return nPoWTrust + full trust score for previous block nBits
2364         return nPoWTrust + bnNewTrust.getuint256();
2365     }
2366 }
2367
2368 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2369 {
2370     unsigned int nFound = 0;
2371     for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2372     {
2373         if (pstart->nVersion >= minVersion)
2374             ++nFound;
2375         pstart = pstart->pprev;
2376     }
2377     return (nFound >= nRequired);
2378 }
2379
2380 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2381 {
2382     // Check for duplicate
2383     uint256 hash = pblock->GetHash();
2384     if (mapBlockIndex.count(hash))
2385         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2386     if (mapOrphanBlocks.count(hash))
2387         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2388
2389     // ppcoin: check proof-of-stake
2390     // Limited duplicity on stake: prevents block flood attack
2391     // Duplicate stake allowed only when there is orphan child block
2392     if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2393         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());
2394
2395     // Preliminary checks
2396     if (!pblock->CheckBlock())
2397         return error("ProcessBlock() : CheckBlock FAILED");
2398
2399     // ppcoin: verify hash target and signature of coinstake tx
2400     if (pblock->IsProofOfStake())
2401     {
2402         uint256 hashProofOfStake = 0;
2403         if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2404         {
2405             printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2406             return false; // do not error here as we expect this during initial block download
2407         }
2408         if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2409             mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2410     }
2411
2412     CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2413     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2414     {
2415         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2416         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2417         CBigNum bnNewBlock;
2418         bnNewBlock.SetCompact(pblock->nBits);
2419         CBigNum bnRequired;
2420         bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2421         if (bnNewBlock > bnRequired)
2422         {
2423             if (pfrom)
2424                 pfrom->Misbehaving(100);
2425             return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2426         }
2427     }
2428
2429     // ppcoin: ask for pending sync-checkpoint if any
2430     if (!IsInitialBlockDownload())
2431         Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2432
2433     // If don't already have its previous block, shunt it off to holding area until we get it
2434     if (!mapBlockIndex.count(pblock->hashPrevBlock))
2435     {
2436         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2437         CBlock* pblock2 = new CBlock(*pblock);
2438         // ppcoin: check proof-of-stake
2439         if (pblock2->IsProofOfStake())
2440         {
2441             // Limited duplicity on stake: prevents block flood attack
2442             // Duplicate stake allowed only when there is orphan child block
2443             if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2444                 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());
2445             else
2446                 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2447         }
2448         mapOrphanBlocks.insert(make_pair(hash, pblock2));
2449         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2450
2451         // Ask this guy to fill in what we're missing
2452         if (pfrom)
2453         {
2454             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2455             // ppcoin: getblocks may not obtain the ancestor block rejected
2456             // earlier by duplicate-stake check so we ask for it again directly
2457             if (!IsInitialBlockDownload())
2458                 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2459         }
2460         return true;
2461     }
2462
2463     // Store to disk
2464     if (!pblock->AcceptBlock())
2465         return error("ProcessBlock() : AcceptBlock FAILED");
2466
2467     // Recursively process any orphan blocks that depended on this one
2468     vector<uint256> vWorkQueue;
2469     vWorkQueue.push_back(hash);
2470     for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2471     {
2472         uint256 hashPrev = vWorkQueue[i];
2473         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2474              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2475              ++mi)
2476         {
2477             CBlock* pblockOrphan = (*mi).second;
2478             if (pblockOrphan->AcceptBlock())
2479                 vWorkQueue.push_back(pblockOrphan->GetHash());
2480             mapOrphanBlocks.erase(pblockOrphan->GetHash());
2481             setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2482             delete pblockOrphan;
2483         }
2484         mapOrphanBlocksByPrev.erase(hashPrev);
2485     }
2486
2487     printf("ProcessBlock: ACCEPTED\n");
2488
2489     // ppcoin: if responsible for sync-checkpoint send it
2490     if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2491         Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2492
2493     return true;
2494 }
2495
2496 // ppcoin: sign block
2497 bool CBlock::SignBlock(const CKeyStore& keystore)
2498 {
2499     vector<valtype> vSolutions;
2500     txnouttype whichType;
2501
2502     if(!IsProofOfStake())
2503     {
2504         for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2505         {
2506             const CTxOut& txout = vtx[0].vout[i];
2507
2508             if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2509                 continue;
2510
2511             if (whichType == TX_PUBKEY)
2512             {
2513                 // Sign
2514                 valtype& vchPubKey = vSolutions[0];
2515                 CKey key;
2516
2517                 if (!keystore.GetKey(Hash160(vchPubKey), key))
2518                     continue;
2519                 if (key.GetPubKey() != vchPubKey)
2520                     continue;
2521                 if(!key.Sign(GetHash(), vchBlockSig))
2522                     continue;
2523
2524                 return true;
2525             }
2526         }
2527     }
2528     else
2529     {
2530         const CTxOut& txout = vtx[1].vout[1];
2531
2532         if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2533             return false;
2534
2535         if (whichType == TX_PUBKEY)
2536         {
2537             // Sign
2538             valtype& vchPubKey = vSolutions[0];
2539             CKey key;
2540
2541             if (!keystore.GetKey(Hash160(vchPubKey), key))
2542                 return false;
2543             if (key.GetPubKey() != vchPubKey)
2544                 return false;
2545
2546             return key.Sign(GetHash(), vchBlockSig);
2547         }
2548     }
2549
2550     printf("Sign failed\n");
2551     return false;
2552 }
2553
2554 // ppcoin: check block signature
2555 bool CBlock::CheckBlockSignature() const
2556 {
2557     if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2558         return vchBlockSig.empty();
2559
2560     vector<valtype> vSolutions;
2561     txnouttype whichType;
2562
2563     if(IsProofOfStake())
2564     {
2565         const CTxOut& txout = vtx[1].vout[1];
2566
2567         if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2568             return false;
2569         if (whichType == TX_PUBKEY)
2570         {
2571             valtype& vchPubKey = vSolutions[0];
2572             CKey key;
2573             if (!key.SetPubKey(vchPubKey))
2574                 return false;
2575             if (vchBlockSig.empty())
2576                 return false;
2577             return key.Verify(GetHash(), vchBlockSig);
2578         }
2579     }
2580     else
2581     {
2582         for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2583         {
2584             const CTxOut& txout = vtx[0].vout[i];
2585
2586             if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2587                 return false;
2588
2589             if (whichType == TX_PUBKEY)
2590             {
2591                 // Verify
2592                 valtype& vchPubKey = vSolutions[0];
2593                 CKey key;
2594                 if (!key.SetPubKey(vchPubKey))
2595                     continue;
2596                 if (vchBlockSig.empty())
2597                     continue;
2598                 if(!key.Verify(GetHash(), vchBlockSig))
2599                     continue;
2600
2601                 return true;
2602             }
2603         }
2604     }
2605     return false;
2606 }
2607
2608 bool CheckDiskSpace(uint64 nAdditionalBytes)
2609 {
2610     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2611
2612     // Check for nMinDiskSpace bytes (currently 50MB)
2613     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2614     {
2615         fShutdown = true;
2616         string strMessage = _("Warning: Disk space is low!");
2617         strMiscWarning = strMessage;
2618         printf("*** %s\n", strMessage.c_str());
2619         uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2620         StartShutdown();
2621         return false;
2622     }
2623     return true;
2624 }
2625
2626 static filesystem::path BlockFilePath(unsigned int nFile)
2627 {
2628     string strBlockFn = strprintf("blk%04u.dat", nFile);
2629     return GetDataDir() / strBlockFn;
2630 }
2631
2632 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2633 {
2634     if ((nFile < 1) || (nFile == (unsigned int) -1))
2635         return NULL;
2636     FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2637     if (!file)
2638         return NULL;
2639     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2640     {
2641         if (fseek(file, nBlockPos, SEEK_SET) != 0)
2642         {
2643             fclose(file);
2644             return NULL;
2645         }
2646     }
2647     return file;
2648 }
2649
2650 static unsigned int nCurrentBlockFile = 1;
2651
2652 FILE* AppendBlockFile(unsigned int& nFileRet)
2653 {
2654     nFileRet = 0;
2655     loop
2656     {
2657         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2658         if (!file)
2659             return NULL;
2660         if (fseek(file, 0, SEEK_END) != 0)
2661             return NULL;
2662         // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2663         if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2664         {
2665             nFileRet = nCurrentBlockFile;
2666             return file;
2667         }
2668         fclose(file);
2669         nCurrentBlockFile++;
2670     }
2671 }
2672
2673 bool LoadBlockIndex(bool fAllowNew)
2674 {
2675     if (fTestNet)
2676     {
2677         pchMessageStart[0] = 0xcd;
2678         pchMessageStart[1] = 0xf2;
2679         pchMessageStart[2] = 0xc0;
2680         pchMessageStart[3] = 0xef;
2681
2682         bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2683         nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2684         nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2685         nCoinbaseMaturity = 10; // test maturity is 10 blocks
2686         nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2687     }
2688
2689     //
2690     // Load block index
2691     //
2692     CTxDB txdb("cr");
2693     if (!txdb.LoadBlockIndex())
2694         return false;
2695     txdb.Close();
2696
2697     //
2698     // Init with genesis block
2699     //
2700     if (mapBlockIndex.empty())
2701     {
2702         if (!fAllowNew)
2703             return false;
2704
2705         // Genesis block
2706
2707         // MainNet:
2708
2709         //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2710         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2711         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2712         //    CTxOut(empty)
2713         //  vMerkleTree: 4cb33b3b6a
2714
2715         // TestNet:
2716
2717         //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2718         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2719         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2720         //    CTxOut(empty)
2721         //  vMerkleTree: 4cb33b3b6a
2722
2723         const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2724         CTransaction txNew;
2725         txNew.nTime = 1360105017;
2726         txNew.vin.resize(1);
2727         txNew.vout.resize(1);
2728         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2729         txNew.vout[0].SetEmpty();
2730         CBlock block;
2731         block.vtx.push_back(txNew);
2732         block.hashPrevBlock = 0;
2733         block.hashMerkleRoot = block.BuildMerkleTree();
2734         block.nVersion = 1;
2735         block.nTime    = 1360105017;
2736         block.nBits    = bnProofOfWorkLimit.GetCompact();
2737         block.nNonce   = !fTestNet ? 1575379 : 46534;
2738
2739         //// debug print
2740         assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2741         block.print();
2742         assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2743         assert(block.CheckBlock());
2744
2745         // Start new block file
2746         unsigned int nFile;
2747         unsigned int nBlockPos;
2748         if (!block.WriteToDisk(nFile, nBlockPos))
2749             return error("LoadBlockIndex() : writing genesis block to disk failed");
2750         if (!block.AddToBlockIndex(nFile, nBlockPos))
2751             return error("LoadBlockIndex() : genesis block not accepted");
2752
2753         // ppcoin: initialize synchronized checkpoint
2754         if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2755             return error("LoadBlockIndex() : failed to init sync checkpoint");
2756     }
2757
2758     // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2759     {
2760         CTxDB txdb;
2761         string strPubKey = "";
2762         if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2763         {
2764             // write checkpoint master key to db
2765             txdb.TxnBegin();
2766             if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2767                 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2768             if (!txdb.TxnCommit())
2769                 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2770             if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2771                 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2772         }
2773         txdb.Close();
2774     }
2775
2776     return true;
2777 }
2778
2779
2780
2781 void PrintBlockTree()
2782 {
2783     // pre-compute tree structure
2784     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2785     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2786     {
2787         CBlockIndex* pindex = (*mi).second;
2788         mapNext[pindex->pprev].push_back(pindex);
2789         // test
2790         //while (rand() % 3 == 0)
2791         //    mapNext[pindex->pprev].push_back(pindex);
2792     }
2793
2794     vector<pair<int, CBlockIndex*> > vStack;
2795     vStack.push_back(make_pair(0, pindexGenesisBlock));
2796
2797     int nPrevCol = 0;
2798     while (!vStack.empty())
2799     {
2800         int nCol = vStack.back().first;
2801         CBlockIndex* pindex = vStack.back().second;
2802         vStack.pop_back();
2803
2804         // print split or gap
2805         if (nCol > nPrevCol)
2806         {
2807             for (int i = 0; i < nCol-1; i++)
2808                 printf("| ");
2809             printf("|\\\n");
2810         }
2811         else if (nCol < nPrevCol)
2812         {
2813             for (int i = 0; i < nCol; i++)
2814                 printf("| ");
2815             printf("|\n");
2816        }
2817         nPrevCol = nCol;
2818
2819         // print columns
2820         for (int i = 0; i < nCol; i++)
2821             printf("| ");
2822
2823         // print item
2824         CBlock block;
2825         block.ReadFromDisk(pindex);
2826         printf("%d (%u,%u) %s  %08x  %s  mint %7s  tx %"PRIszu"",
2827             pindex->nHeight,
2828             pindex->nFile,
2829             pindex->nBlockPos,
2830             block.GetHash().ToString().c_str(),
2831             block.nBits,
2832             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2833             FormatMoney(pindex->nMint).c_str(),
2834             block.vtx.size());
2835
2836         PrintWallets(block);
2837
2838         // put the main time-chain first
2839         vector<CBlockIndex*>& vNext = mapNext[pindex];
2840         for (unsigned int i = 0; i < vNext.size(); i++)
2841         {
2842             if (vNext[i]->pnext)
2843             {
2844                 swap(vNext[0], vNext[i]);
2845                 break;
2846             }
2847         }
2848
2849         // iterate children
2850         for (unsigned int i = 0; i < vNext.size(); i++)
2851             vStack.push_back(make_pair(nCol+i, vNext[i]));
2852     }
2853 }
2854
2855 bool LoadExternalBlockFile(FILE* fileIn)
2856 {
2857     int64 nStart = GetTimeMillis();
2858
2859     int nLoaded = 0;
2860     {
2861         LOCK(cs_main);
2862         try {
2863             CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2864             unsigned int nPos = 0;
2865             while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2866             {
2867                 unsigned char pchData[65536];
2868                 do {
2869                     fseek(blkdat, nPos, SEEK_SET);
2870                     int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2871                     if (nRead <= 8)
2872                     {
2873                         nPos = (unsigned int)-1;
2874                         break;
2875                     }
2876                     void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2877                     if (nFind)
2878                     {
2879                         if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2880                         {
2881                             nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2882                             break;
2883                         }
2884                         nPos += ((unsigned char*)nFind - pchData) + 1;
2885                     }
2886                     else
2887                         nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2888                 } while(!fRequestShutdown);
2889                 if (nPos == (unsigned int)-1)
2890                     break;
2891                 fseek(blkdat, nPos, SEEK_SET);
2892                 unsigned int nSize;
2893                 blkdat >> nSize;
2894                 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2895                 {
2896                     CBlock block;
2897                     blkdat >> block;
2898                     if (ProcessBlock(NULL,&block))
2899                     {
2900                         nLoaded++;
2901                         nPos += 4 + nSize;
2902                     }
2903                 }
2904             }
2905         }
2906         catch (std::exception &e) {
2907             printf("%s() : Deserialize or I/O error caught during load\n",
2908                    __PRETTY_FUNCTION__);
2909         }
2910     }
2911     printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2912     return nLoaded > 0;
2913 }
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923 //////////////////////////////////////////////////////////////////////////////
2924 //
2925 // CAlert
2926 //
2927
2928 extern map<uint256, CAlert> mapAlerts;
2929 extern CCriticalSection cs_mapAlerts;
2930
2931 static string strMintMessage = "Info: Minting suspended due to locked wallet.";
2932 static string strMintWarning;
2933
2934 string GetWarnings(string strFor)
2935 {
2936     int nPriority = 0;
2937     string strStatusBar;
2938     string strRPC;
2939
2940     if (GetBoolArg("-testsafemode"))
2941         strRPC = "test";
2942
2943     // ppcoin: wallet lock warning for minting
2944     if (strMintWarning != "")
2945     {
2946         nPriority = 0;
2947         strStatusBar = strMintWarning;
2948     }
2949
2950     // Misc warnings like out of disk space and clock is wrong
2951     if (strMiscWarning != "")
2952     {
2953         nPriority = 1000;
2954         strStatusBar = strMiscWarning;
2955     }
2956
2957     // ppcoin: should not enter safe mode for longer invalid chain
2958     // ppcoin: if sync-checkpoint is too old do not enter safe mode
2959     if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2960     {
2961         nPriority = 100;
2962         strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2963     }
2964
2965     // ppcoin: if detected invalid checkpoint enter safe mode
2966     if (Checkpoints::hashInvalidCheckpoint != 0)
2967     {
2968         nPriority = 3000;
2969         strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2970     }
2971
2972     // Alerts
2973     {
2974         LOCK(cs_mapAlerts);
2975         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2976         {
2977             const CAlert& alert = item.second;
2978             if (alert.AppliesToMe() && alert.nPriority > nPriority)
2979             {
2980                 nPriority = alert.nPriority;
2981                 strStatusBar = alert.strStatusBar;
2982                 if (nPriority > 1000)
2983                     strRPC = strStatusBar;  // ppcoin: safe mode for high alert
2984             }
2985         }
2986     }
2987
2988     if (strFor == "statusbar")
2989         return strStatusBar;
2990     else if (strFor == "rpc")
2991         return strRPC;
2992     assert(!"GetWarnings() : invalid parameter");
2993     return "error";
2994 }
2995
2996
2997
2998
2999
3000
3001
3002
3003 //////////////////////////////////////////////////////////////////////////////
3004 //
3005 // Messages
3006 //
3007
3008
3009 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3010 {
3011     switch (inv.type)
3012     {
3013     case MSG_TX:
3014         {
3015         bool txInMap = false;
3016             {
3017             LOCK(mempool.cs);
3018             txInMap = (mempool.exists(inv.hash));
3019             }
3020         return txInMap ||
3021                mapOrphanTransactions.count(inv.hash) ||
3022                txdb.ContainsTx(inv.hash);
3023         }
3024
3025     case MSG_BLOCK:
3026         return mapBlockIndex.count(inv.hash) ||
3027                mapOrphanBlocks.count(inv.hash);
3028     }
3029     // Don't know what it is, just say we already got one
3030     return true;
3031 }
3032
3033
3034
3035
3036 // The message start string is designed to be unlikely to occur in normal data.
3037 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3038 // a large 4-byte int at any alignment.
3039 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3040
3041 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3042 {
3043     static map<CService, CPubKey> mapReuseKey;
3044     RandAddSeedPerfmon();
3045     if (fDebug)
3046         printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3047     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3048     {
3049         printf("dropmessagestest DROPPING RECV MESSAGE\n");
3050         return true;
3051     }
3052
3053
3054
3055
3056
3057     if (strCommand == "version")
3058     {
3059         // Each connection can only send one version message
3060         if (pfrom->nVersion != 0)
3061         {
3062             pfrom->Misbehaving(1);
3063             return false;
3064         }
3065
3066         int64 nTime;
3067         CAddress addrMe;
3068         CAddress addrFrom;
3069         uint64 nNonce = 1;
3070         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3071         if (pfrom->nVersion < MIN_PROTO_VERSION)
3072         {
3073             // Since February 20, 2012, the protocol is initiated at version 209,
3074             // and earlier versions are no longer supported
3075             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3076             pfrom->fDisconnect = true;
3077             return false;
3078         }
3079
3080         if (pfrom->nVersion == 10300)
3081             pfrom->nVersion = 300;
3082         if (!vRecv.empty())
3083             vRecv >> addrFrom >> nNonce;
3084         if (!vRecv.empty())
3085             vRecv >> pfrom->strSubVer;
3086         if (!vRecv.empty())
3087             vRecv >> pfrom->nStartingHeight;
3088
3089         if (pfrom->fInbound && addrMe.IsRoutable())
3090         {
3091             pfrom->addrLocal = addrMe;
3092             SeenLocal(addrMe);
3093         }
3094
3095         // Disconnect if we connected to ourself
3096         if (nNonce == nLocalHostNonce && nNonce > 1)
3097         {
3098             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3099             pfrom->fDisconnect = true;
3100             return true;
3101         }
3102
3103         // ppcoin: record my external IP reported by peer
3104         if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3105             addrSeenByPeer = addrMe;
3106
3107         // Be shy and don't send version until we hear
3108         if (pfrom->fInbound)
3109             pfrom->PushVersion();
3110
3111         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3112
3113         AddTimeData(pfrom->addr, nTime);
3114
3115         // Change version
3116         pfrom->PushMessage("verack");
3117         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3118
3119         if (!pfrom->fInbound)
3120         {
3121             // Advertise our address
3122             if (!fNoListen && !IsInitialBlockDownload())
3123             {
3124                 CAddress addr = GetLocalAddress(&pfrom->addr);
3125                 if (addr.IsRoutable())
3126                     pfrom->PushAddress(addr);
3127             }
3128
3129             // Get recent addresses
3130             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3131             {
3132                 pfrom->PushMessage("getaddr");
3133                 pfrom->fGetAddr = true;
3134             }
3135             addrman.Good(pfrom->addr);
3136         } else {
3137             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3138             {
3139                 addrman.Add(addrFrom, addrFrom);
3140                 addrman.Good(addrFrom);
3141             }
3142         }
3143
3144         // Ask the first connected node for block updates
3145         static int nAskedForBlocks = 0;
3146         if (!pfrom->fClient && !pfrom->fOneShot &&
3147             (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3148             (pfrom->nVersion < NOBLKS_VERSION_START ||
3149              pfrom->nVersion >= NOBLKS_VERSION_END) &&
3150              (nAskedForBlocks < 1 || vNodes.size() <= 1))
3151         {
3152             nAskedForBlocks++;
3153             pfrom->PushGetBlocks(pindexBest, uint256(0));
3154         }
3155
3156         // Relay alerts
3157         {
3158             LOCK(cs_mapAlerts);
3159             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3160                 item.second.RelayTo(pfrom);
3161         }
3162
3163         // ppcoin: relay sync-checkpoint
3164         {
3165             LOCK(Checkpoints::cs_hashSyncCheckpoint);
3166             if (!Checkpoints::checkpointMessage.IsNull())
3167                 Checkpoints::checkpointMessage.RelayTo(pfrom);
3168         }
3169
3170         pfrom->fSuccessfullyConnected = true;
3171
3172         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());
3173
3174         cPeerBlockCounts.input(pfrom->nStartingHeight);
3175
3176         // ppcoin: ask for pending sync-checkpoint if any
3177         if (!IsInitialBlockDownload())
3178             Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3179     }
3180
3181
3182     else if (pfrom->nVersion == 0)
3183     {
3184         // Must have a version message before anything else
3185         pfrom->Misbehaving(1);
3186         return false;
3187     }
3188
3189
3190     else if (strCommand == "verack")
3191     {
3192         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3193     }
3194
3195
3196     else if (strCommand == "addr")
3197     {
3198         vector<CAddress> vAddr;
3199         vRecv >> vAddr;
3200
3201         // Don't want addr from older versions unless seeding
3202         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3203             return true;
3204         if (vAddr.size() > 1000)
3205         {
3206             pfrom->Misbehaving(20);
3207             return error("message addr size() = %"PRIszu"", vAddr.size());
3208         }
3209
3210         // Store the new addresses
3211         vector<CAddress> vAddrOk;
3212         int64 nNow = GetAdjustedTime();
3213         int64 nSince = nNow - 10 * 60;
3214         BOOST_FOREACH(CAddress& addr, vAddr)
3215         {
3216             if (fShutdown)
3217                 return true;
3218             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3219                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3220             pfrom->AddAddressKnown(addr);
3221             bool fReachable = IsReachable(addr);
3222             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3223             {
3224                 // Relay to a limited number of other nodes
3225                 {
3226                     LOCK(cs_vNodes);
3227                     // Use deterministic randomness to send to the same nodes for 24 hours
3228                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3229                     static uint256 hashSalt;
3230                     if (hashSalt == 0)
3231                         hashSalt = GetRandHash();
3232                     uint64 hashAddr = addr.GetHash();
3233                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3234                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3235                     multimap<uint256, CNode*> mapMix;
3236                     BOOST_FOREACH(CNode* pnode, vNodes)
3237                     {
3238                         if (pnode->nVersion < CADDR_TIME_VERSION)
3239                             continue;
3240                         unsigned int nPointer;
3241                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3242                         uint256 hashKey = hashRand ^ nPointer;
3243                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3244                         mapMix.insert(make_pair(hashKey, pnode));
3245                     }
3246                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3247                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3248                         ((*mi).second)->PushAddress(addr);
3249                 }
3250             }
3251             // Do not store addresses outside our network
3252             if (fReachable)
3253                 vAddrOk.push_back(addr);
3254         }
3255         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3256         if (vAddr.size() < 1000)
3257             pfrom->fGetAddr = false;
3258         if (pfrom->fOneShot)
3259             pfrom->fDisconnect = true;
3260     }
3261
3262
3263     else if (strCommand == "inv")
3264     {
3265         vector<CInv> vInv;
3266         vRecv >> vInv;
3267         if (vInv.size() > MAX_INV_SZ)
3268         {
3269             pfrom->Misbehaving(20);
3270             return error("message inv size() = %"PRIszu"", vInv.size());
3271         }
3272
3273         // find last block in inv vector
3274         unsigned int nLastBlock = (unsigned int)(-1);
3275         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3276             if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3277                 nLastBlock = vInv.size() - 1 - nInv;
3278                 break;
3279             }
3280         }
3281         CTxDB txdb("r");
3282         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3283         {
3284             const CInv &inv = vInv[nInv];
3285
3286             if (fShutdown)
3287                 return true;
3288             pfrom->AddInventoryKnown(inv);
3289
3290             bool fAlreadyHave = AlreadyHave(txdb, inv);
3291             if (fDebug)
3292                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3293
3294             if (!fAlreadyHave)
3295                 pfrom->AskFor(inv);
3296             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3297                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3298             } else if (nInv == nLastBlock) {
3299                 // In case we are on a very long side-chain, it is possible that we already have
3300                 // the last block in an inv bundle sent in response to getblocks. Try to detect
3301                 // this situation and push another getblocks to continue.
3302                 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3303                 if (fDebug)
3304                     printf("force request: %s\n", inv.ToString().c_str());
3305             }
3306
3307             // Track requests for our stuff
3308             Inventory(inv.hash);
3309         }
3310     }
3311
3312
3313     else if (strCommand == "getdata")
3314     {
3315         vector<CInv> vInv;
3316         vRecv >> vInv;
3317         if (vInv.size() > MAX_INV_SZ)
3318         {
3319             pfrom->Misbehaving(20);
3320             return error("message getdata size() = %"PRIszu"", vInv.size());
3321         }
3322
3323         if (fDebugNet || (vInv.size() != 1))
3324             printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3325
3326         BOOST_FOREACH(const CInv& inv, vInv)
3327         {
3328             if (fShutdown)
3329                 return true;
3330             if (fDebugNet || (vInv.size() == 1))
3331                 printf("received getdata for: %s\n", inv.ToString().c_str());
3332
3333             if (inv.type == MSG_BLOCK)
3334             {
3335                 // Send block from disk
3336                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3337                 if (mi != mapBlockIndex.end())
3338                 {
3339                     CBlock block;
3340                     block.ReadFromDisk((*mi).second);
3341                     pfrom->PushMessage("block", block);
3342
3343                     // Trigger them to send a getblocks request for the next batch of inventory
3344                     if (inv.hash == pfrom->hashContinue)
3345                     {
3346                         // ppcoin: send latest proof-of-work block to allow the
3347                         // download node to accept as orphan (proof-of-stake 
3348                         // block might be rejected by stake connection check)
3349                         vector<CInv> vInv;
3350                         vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3351                         pfrom->PushMessage("inv", vInv);
3352                         pfrom->hashContinue = 0;
3353                     }
3354                 }
3355             }
3356             else if (inv.IsKnownType())
3357             {
3358                 // Send stream from relay memory
3359                 bool pushed = false;
3360                 {
3361                     LOCK(cs_mapRelay);
3362                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3363                     if (mi != mapRelay.end()) {
3364                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3365                         pushed = true;
3366                     }
3367                 }
3368                 if (!pushed && inv.type == MSG_TX) {
3369                     LOCK(mempool.cs);
3370                     if (mempool.exists(inv.hash)) {
3371                         CTransaction tx = mempool.lookup(inv.hash);
3372                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3373                         ss.reserve(1000);
3374                         ss << tx;
3375                         pfrom->PushMessage("tx", ss);
3376                     }
3377                 }
3378             }
3379
3380             // Track requests for our stuff
3381             Inventory(inv.hash);
3382         }
3383     }
3384
3385
3386     else if (strCommand == "getblocks")
3387     {
3388         CBlockLocator locator;
3389         uint256 hashStop;
3390         vRecv >> locator >> hashStop;
3391
3392         // Find the last block the caller has in the main chain
3393         CBlockIndex* pindex = locator.GetBlockIndex();
3394
3395         // Send the rest of the chain
3396         if (pindex)
3397             pindex = pindex->pnext;
3398         int nLimit = 500;
3399         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3400         for (; pindex; pindex = pindex->pnext)
3401         {
3402             if (pindex->GetBlockHash() == hashStop)
3403             {
3404                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3405                 // ppcoin: tell downloading node about the latest block if it's
3406                 // without risk being rejected due to stake connection check
3407                 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3408                     pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3409                 break;
3410             }
3411             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3412             if (--nLimit <= 0)
3413             {
3414                 // When this block is requested, we'll send an inv that'll make them
3415                 // getblocks the next batch of inventory.
3416                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3417                 pfrom->hashContinue = pindex->GetBlockHash();
3418                 break;
3419             }
3420         }
3421     }
3422     else if (strCommand == "checkpoint")
3423     {
3424         CSyncCheckpoint checkpoint;
3425         vRecv >> checkpoint;
3426
3427         if (checkpoint.ProcessSyncCheckpoint(pfrom))
3428         {
3429             // Relay
3430             pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3431             LOCK(cs_vNodes);
3432             BOOST_FOREACH(CNode* pnode, vNodes)
3433                 checkpoint.RelayTo(pnode);
3434         }
3435     }
3436
3437     else if (strCommand == "getheaders")
3438     {
3439         CBlockLocator locator;
3440         uint256 hashStop;
3441         vRecv >> locator >> hashStop;
3442
3443         CBlockIndex* pindex = NULL;
3444         if (locator.IsNull())
3445         {
3446             // If locator is null, return the hashStop block
3447             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3448             if (mi == mapBlockIndex.end())
3449                 return true;
3450             pindex = (*mi).second;
3451         }
3452         else
3453         {
3454             // Find the last block the caller has in the main chain
3455             pindex = locator.GetBlockIndex();
3456             if (pindex)
3457                 pindex = pindex->pnext;
3458         }
3459
3460         vector<CBlock> vHeaders;
3461         int nLimit = 2000;
3462         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3463         for (; pindex; pindex = pindex->pnext)
3464         {
3465             vHeaders.push_back(pindex->GetBlockHeader());
3466             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3467                 break;
3468         }
3469         pfrom->PushMessage("headers", vHeaders);
3470     }
3471
3472
3473     else if (strCommand == "tx")
3474     {
3475         vector<uint256> vWorkQueue;
3476         vector<uint256> vEraseQueue;
3477         CDataStream vMsg(vRecv);
3478         CTxDB txdb("r");
3479         CTransaction tx;
3480         vRecv >> tx;
3481
3482         CInv inv(MSG_TX, tx.GetHash());
3483         pfrom->AddInventoryKnown(inv);
3484
3485         // Truncate messages to the size of the tx in them
3486         unsigned int nSize = ::GetSerializeSize(tx,SER_NETWORK, PROTOCOL_VERSION);
3487         if (nSize < vMsg.size()){
3488             vMsg.resize(nSize);
3489         }
3490
3491         bool fMissingInputs = false;
3492         if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3493         {
3494             SyncWithWallets(tx, NULL, true);
3495             RelayMessage(inv, vMsg);
3496             mapAlreadyAskedFor.erase(inv);
3497             vWorkQueue.push_back(inv.hash);
3498             vEraseQueue.push_back(inv.hash);
3499
3500             // Recursively process any orphan transactions that depended on this one
3501             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3502             {
3503                 uint256 hashPrev = vWorkQueue[i];
3504                 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3505                      mi != mapOrphanTransactionsByPrev[hashPrev].end();
3506                      ++mi)
3507                 {
3508                     const CDataStream& vMsg = *((*mi).second);
3509                     CTransaction tx;
3510                     CDataStream(vMsg) >> tx;
3511                     CInv inv(MSG_TX, tx.GetHash());
3512                     bool fMissingInputs2 = false;
3513
3514                     if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3515                     {
3516                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3517                         SyncWithWallets(tx, NULL, true);
3518                         RelayMessage(inv, vMsg);
3519                         mapAlreadyAskedFor.erase(inv);
3520                         vWorkQueue.push_back(inv.hash);
3521                         vEraseQueue.push_back(inv.hash);
3522                     }
3523                     else if (!fMissingInputs2)
3524                     {
3525                         // invalid orphan
3526                         vEraseQueue.push_back(inv.hash);
3527                         printf("   removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3528                     }
3529                 }
3530             }
3531
3532             BOOST_FOREACH(uint256 hash, vEraseQueue)
3533                 EraseOrphanTx(hash);
3534         }
3535         else if (fMissingInputs)
3536         {
3537             AddOrphanTx(vMsg);
3538
3539             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3540             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3541             if (nEvicted > 0)
3542                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3543         }
3544         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3545     }
3546
3547
3548     else if (strCommand == "block")
3549     {
3550         CBlock block;
3551         vRecv >> block;
3552
3553         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3554         // block.print();
3555
3556         CInv inv(MSG_BLOCK, block.GetHash());
3557         pfrom->AddInventoryKnown(inv);
3558
3559         if (ProcessBlock(pfrom, &block))
3560             mapAlreadyAskedFor.erase(inv);
3561         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3562     }
3563
3564
3565     else if (strCommand == "getaddr")
3566     {
3567         pfrom->vAddrToSend.clear();
3568         vector<CAddress> vAddr = addrman.GetAddr();
3569         BOOST_FOREACH(const CAddress &addr, vAddr)
3570             pfrom->PushAddress(addr);
3571     }
3572
3573
3574     else if (strCommand == "mempool")
3575     {
3576         std::vector<uint256> vtxid;
3577         mempool.queryHashes(vtxid);
3578         vector<CInv> vInv;
3579         for (unsigned int i = 0; i < vtxid.size(); i++) {
3580             CInv inv(MSG_TX, vtxid[i]);
3581             vInv.push_back(inv);
3582             if (i == (MAX_INV_SZ - 1))
3583                     break;
3584         }
3585         if (vInv.size() > 0)
3586             pfrom->PushMessage("inv", vInv);
3587     }
3588
3589
3590     else if (strCommand == "checkorder")
3591     {
3592         uint256 hashReply;
3593         vRecv >> hashReply;
3594
3595         if (!GetBoolArg("-allowreceivebyip"))
3596         {
3597             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3598             return true;
3599         }
3600
3601         CWalletTx order;
3602         vRecv >> order;
3603
3604         /// we have a chance to check the order here
3605
3606         // Keep giving the same key to the same ip until they use it
3607         if (!mapReuseKey.count(pfrom->addr))
3608             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3609
3610         // Send back approval of order and pubkey to use
3611         CScript scriptPubKey;
3612         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3613         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3614     }
3615
3616
3617     else if (strCommand == "reply")
3618     {
3619         uint256 hashReply;
3620         vRecv >> hashReply;
3621
3622         CRequestTracker tracker;
3623         {
3624             LOCK(pfrom->cs_mapRequests);
3625             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3626             if (mi != pfrom->mapRequests.end())
3627             {
3628                 tracker = (*mi).second;
3629                 pfrom->mapRequests.erase(mi);
3630             }
3631         }
3632         if (!tracker.IsNull())
3633             tracker.fn(tracker.param1, vRecv);
3634     }
3635
3636
3637     else if (strCommand == "ping")
3638     {
3639         if (pfrom->nVersion > BIP0031_VERSION)
3640         {
3641             uint64 nonce = 0;
3642             vRecv >> nonce;
3643             // Echo the message back with the nonce. This allows for two useful features:
3644             //
3645             // 1) A remote node can quickly check if the connection is operational
3646             // 2) Remote nodes can measure the latency of the network thread. If this node
3647             //    is overloaded it won't respond to pings quickly and the remote node can
3648             //    avoid sending us more work, like chain download requests.
3649             //
3650             // The nonce stops the remote getting confused between different pings: without
3651             // it, if the remote node sends a ping once per second and this node takes 5
3652             // seconds to respond to each, the 5th ping the remote sends would appear to
3653             // return very quickly.
3654             pfrom->PushMessage("pong", nonce);
3655         }
3656     }
3657
3658
3659     else if (strCommand == "alert")
3660     {
3661         CAlert alert;
3662         vRecv >> alert;
3663
3664         uint256 alertHash = alert.GetHash();
3665         if (pfrom->setKnown.count(alertHash) == 0)
3666         {
3667             if (alert.ProcessAlert())
3668             {
3669                 // Relay
3670                 pfrom->setKnown.insert(alertHash);
3671                 {
3672                     LOCK(cs_vNodes);
3673                     BOOST_FOREACH(CNode* pnode, vNodes)
3674                         alert.RelayTo(pnode);
3675                 }
3676             }
3677             else {
3678                 // Small DoS penalty so peers that send us lots of
3679                 // duplicate/expired/invalid-signature/whatever alerts
3680                 // eventually get banned.
3681                 // This isn't a Misbehaving(100) (immediate ban) because the
3682                 // peer might be an older or different implementation with
3683                 // a different signature key, etc.
3684                 pfrom->Misbehaving(10);
3685             }
3686         }
3687     }
3688
3689
3690     else
3691     {
3692         // Ignore unknown commands for extensibility
3693     }
3694
3695
3696     // Update the last seen time for this node's address
3697     if (pfrom->fNetworkNode)
3698         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3699             AddressCurrentlyConnected(pfrom->addr);
3700
3701
3702     return true;
3703 }
3704
3705 bool ProcessMessages(CNode* pfrom)
3706 {
3707     CDataStream& vRecv = pfrom->vRecv;
3708     if (vRecv.empty())
3709         return true;
3710     //if (fDebug)
3711     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
3712
3713     //
3714     // Message format
3715     //  (4) message start
3716     //  (12) command
3717     //  (4) size
3718     //  (4) checksum
3719     //  (x) data
3720     //
3721
3722     loop
3723     {
3724         // Don't bother if send buffer is too full to respond anyway
3725         if (pfrom->vSend.size() >= SendBufferSize())
3726             break;
3727
3728         // Scan for message start
3729         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3730         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3731         if (vRecv.end() - pstart < nHeaderSize)
3732         {
3733             if ((int)vRecv.size() > nHeaderSize)
3734             {
3735                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3736                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3737             }
3738             break;
3739         }
3740         if (pstart - vRecv.begin() > 0)
3741             printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3742         vRecv.erase(vRecv.begin(), pstart);
3743
3744         // Read header
3745         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3746         CMessageHeader hdr;
3747         vRecv >> hdr;
3748         if (!hdr.IsValid())
3749         {
3750             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3751             continue;
3752         }
3753         string strCommand = hdr.GetCommand();
3754
3755         // Message size
3756         unsigned int nMessageSize = hdr.nMessageSize;
3757         if (nMessageSize > MAX_SIZE)
3758         {
3759             printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3760             continue;
3761         }
3762         if (nMessageSize > vRecv.size())
3763         {
3764             // Rewind and wait for rest of message
3765             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3766             break;
3767         }
3768
3769         // Checksum
3770         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3771         unsigned int nChecksum = 0;
3772         memcpy(&nChecksum, &hash, sizeof(nChecksum));
3773         if (nChecksum != hdr.nChecksum)
3774         {
3775             printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3776                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3777             continue;
3778         }
3779
3780         // Copy message to its own buffer
3781         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3782         vRecv.ignore(nMessageSize);
3783
3784         // Process message
3785         bool fRet = false;
3786         try
3787         {
3788             {
3789                 LOCK(cs_main);
3790                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3791             }
3792             if (fShutdown)
3793                 return true;
3794         }
3795         catch (std::ios_base::failure& e)
3796         {
3797             if (strstr(e.what(), "end of data"))
3798             {
3799                 // Allow exceptions from under-length message on vRecv
3800                 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());
3801             }
3802             else if (strstr(e.what(), "size too large"))
3803             {
3804                 // Allow exceptions from over-long size
3805                 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3806             }
3807             else
3808             {
3809                 PrintExceptionContinue(&e, "ProcessMessages()");
3810             }
3811         }
3812         catch (std::exception& e) {
3813             PrintExceptionContinue(&e, "ProcessMessages()");
3814         } catch (...) {
3815             PrintExceptionContinue(NULL, "ProcessMessages()");
3816         }
3817
3818         if (!fRet)
3819             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3820     }
3821
3822     vRecv.Compact();
3823     return true;
3824 }
3825
3826
3827 bool SendMessages(CNode* pto, bool fSendTrickle)
3828 {
3829     TRY_LOCK(cs_main, lockMain);
3830     if (lockMain) {
3831         // Don't send anything until we get their version message
3832         if (pto->nVersion == 0)
3833             return true;
3834
3835         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3836         // right now.
3837         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3838             uint64 nonce = 0;
3839             if (pto->nVersion > BIP0031_VERSION)
3840                 pto->PushMessage("ping", nonce);
3841             else
3842                 pto->PushMessage("ping");
3843         }
3844
3845         // Resend wallet transactions that haven't gotten in a block yet
3846         ResendWalletTransactions();
3847
3848         // Address refresh broadcast
3849         static int64 nLastRebroadcast;
3850         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3851         {
3852             {
3853                 LOCK(cs_vNodes);
3854                 BOOST_FOREACH(CNode* pnode, vNodes)
3855                 {
3856                     // Periodically clear setAddrKnown to allow refresh broadcasts
3857                     if (nLastRebroadcast)
3858                         pnode->setAddrKnown.clear();
3859
3860                     // Rebroadcast our address
3861                     if (!fNoListen)
3862                     {
3863                         CAddress addr = GetLocalAddress(&pnode->addr);
3864                         if (addr.IsRoutable())
3865                             pnode->PushAddress(addr);
3866                     }
3867                 }
3868             }
3869             nLastRebroadcast = GetTime();
3870         }
3871
3872         //
3873         // Message: addr
3874         //
3875         if (fSendTrickle)
3876         {
3877             vector<CAddress> vAddr;
3878             vAddr.reserve(pto->vAddrToSend.size());
3879             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3880             {
3881                 // returns true if wasn't already contained in the set
3882                 if (pto->setAddrKnown.insert(addr).second)
3883                 {
3884                     vAddr.push_back(addr);
3885                     // receiver rejects addr messages larger than 1000
3886                     if (vAddr.size() >= 1000)
3887                     {
3888                         pto->PushMessage("addr", vAddr);
3889                         vAddr.clear();
3890                     }
3891                 }
3892             }
3893             pto->vAddrToSend.clear();
3894             if (!vAddr.empty())
3895                 pto->PushMessage("addr", vAddr);
3896         }
3897
3898
3899         //
3900         // Message: inventory
3901         //
3902         vector<CInv> vInv;
3903         vector<CInv> vInvWait;
3904         {
3905             LOCK(pto->cs_inventory);
3906             vInv.reserve(pto->vInventoryToSend.size());
3907             vInvWait.reserve(pto->vInventoryToSend.size());
3908             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3909             {
3910                 if (pto->setInventoryKnown.count(inv))
3911                     continue;
3912
3913                 // trickle out tx inv to protect privacy
3914                 if (inv.type == MSG_TX && !fSendTrickle)
3915                 {
3916                     // 1/4 of tx invs blast to all immediately
3917                     static uint256 hashSalt;
3918                     if (hashSalt == 0)
3919                         hashSalt = GetRandHash();
3920                     uint256 hashRand = inv.hash ^ hashSalt;
3921                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3922                     bool fTrickleWait = ((hashRand & 3) != 0);
3923
3924                     // always trickle our own transactions
3925                     if (!fTrickleWait)
3926                     {
3927                         CWalletTx wtx;
3928                         if (GetTransaction(inv.hash, wtx))
3929                             if (wtx.fFromMe)
3930                                 fTrickleWait = true;
3931                     }
3932
3933                     if (fTrickleWait)
3934                     {
3935                         vInvWait.push_back(inv);
3936                         continue;
3937                     }
3938                 }
3939
3940                 // returns true if wasn't already contained in the set
3941                 if (pto->setInventoryKnown.insert(inv).second)
3942                 {
3943                     vInv.push_back(inv);
3944                     if (vInv.size() >= 1000)
3945                     {
3946                         pto->PushMessage("inv", vInv);
3947                         vInv.clear();
3948                     }
3949                 }
3950             }
3951             pto->vInventoryToSend = vInvWait;
3952         }
3953         if (!vInv.empty())
3954             pto->PushMessage("inv", vInv);
3955
3956
3957         //
3958         // Message: getdata
3959         //
3960         vector<CInv> vGetData;
3961         int64 nNow = GetTime() * 1000000;
3962         CTxDB txdb("r");
3963         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3964         {
3965             const CInv& inv = (*pto->mapAskFor.begin()).second;
3966             if (!AlreadyHave(txdb, inv))
3967             {
3968                 if (fDebugNet)
3969                     printf("sending getdata: %s\n", inv.ToString().c_str());
3970                 vGetData.push_back(inv);
3971                 if (vGetData.size() >= 1000)
3972                 {
3973                     pto->PushMessage("getdata", vGetData);
3974                     vGetData.clear();
3975                 }
3976                 mapAlreadyAskedFor[inv] = nNow;
3977             }
3978             pto->mapAskFor.erase(pto->mapAskFor.begin());
3979         }
3980         if (!vGetData.empty())
3981             pto->PushMessage("getdata", vGetData);
3982
3983     }
3984     return true;
3985 }
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000 //////////////////////////////////////////////////////////////////////////////
4001 //
4002 // BitcoinMiner
4003 //
4004
4005 int static FormatHashBlocks(void* pbuffer, unsigned int len)
4006 {
4007     unsigned char* pdata = (unsigned char*)pbuffer;
4008     unsigned int blocks = 1 + ((len + 8) / 64);
4009     unsigned char* pend = pdata + 64 * blocks;
4010     memset(pdata + len, 0, 64 * blocks - len);
4011     pdata[len] = 0x80;
4012     unsigned int bits = len * 8;
4013     pend[-1] = (bits >> 0) & 0xff;
4014     pend[-2] = (bits >> 8) & 0xff;
4015     pend[-3] = (bits >> 16) & 0xff;
4016     pend[-4] = (bits >> 24) & 0xff;
4017     return blocks;
4018 }
4019
4020 static const unsigned int pSHA256InitState[8] =
4021 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
4022
4023 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
4024 {
4025     SHA256_CTX ctx;
4026     unsigned char data[64];
4027
4028     SHA256_Init(&ctx);
4029
4030     for (int i = 0; i < 16; i++)
4031         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
4032
4033     for (int i = 0; i < 8; i++)
4034         ctx.h[i] = ((uint32_t*)pinit)[i];
4035
4036     SHA256_Update(&ctx, data, sizeof(data));
4037     for (int i = 0; i < 8; i++)
4038         ((uint32_t*)pstate)[i] = ctx.h[i];
4039 }
4040
4041 // Some explaining would be appreciated
4042 class COrphan
4043 {
4044 public:
4045     CTransaction* ptx;
4046     set<uint256> setDependsOn;
4047     double dPriority;
4048     double dFeePerKb;
4049
4050     COrphan(CTransaction* ptxIn)
4051     {
4052         ptx = ptxIn;
4053         dPriority = dFeePerKb = 0;
4054     }
4055
4056     void print() const
4057     {
4058         printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4059                ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4060         BOOST_FOREACH(uint256 hash, setDependsOn)
4061             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4062     }
4063 };
4064
4065
4066 uint64 nLastBlockTx = 0;
4067 uint64 nLastBlockSize = 0;
4068 int64 nLastCoinStakeSearchInterval = 0;
4069  
4070 // We want to sort transactions by priority and fee, so:
4071 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4072 class TxPriorityCompare
4073 {
4074     bool byFee;
4075 public:
4076     TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4077     bool operator()(const TxPriority& a, const TxPriority& b)
4078     {
4079         if (byFee)
4080         {
4081             if (a.get<1>() == b.get<1>())
4082                 return a.get<0>() < b.get<0>();
4083             return a.get<1>() < b.get<1>();
4084         }
4085         else
4086         {
4087             if (a.get<0>() == b.get<0>())
4088                 return a.get<1>() < b.get<1>();
4089             return a.get<0>() < b.get<0>();
4090         }
4091     }
4092 };
4093
4094 // CreateNewBlock:
4095 //   fProofOfStake: try (best effort) to make a proof-of-stake block
4096 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
4097 {
4098     CReserveKey reservekey(pwallet);
4099
4100     // Create new block
4101     auto_ptr<CBlock> pblock(new CBlock());
4102     if (!pblock.get())
4103         return NULL;
4104
4105     // Create coinbase tx
4106     CTransaction txNew;
4107     txNew.vin.resize(1);
4108     txNew.vin[0].prevout.SetNull();
4109     txNew.vout.resize(1);
4110     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4111
4112     // Add our coinbase tx as first transaction
4113     pblock->vtx.push_back(txNew);
4114
4115     // Largest block you're willing to create:
4116     unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4117     // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4118     nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4119
4120     // Special compatibility rule before 20 Aug: limit size to 500,000 bytes:
4121     if (GetAdjustedTime() < LOCKS_SWITCH_TIME)
4122         nBlockMaxSize = std::min(nBlockMaxSize, (unsigned int)(MAX_BLOCK_SIZE_GEN));
4123
4124     // How much of the block should be dedicated to high-priority transactions,
4125     // included regardless of the fees they pay
4126     unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4127     nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4128
4129     // Minimum block size you want to create; block will be filled with free transactions
4130     // until there are no more or the block reaches this size:
4131     unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4132     nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4133
4134     // Fee-per-kilobyte amount considered the same as "free"
4135     // Be careful setting this: if you set it to zero then
4136     // a transaction spammer can cheaply fill blocks using
4137     // 1-satoshi-fee transactions. It should be set above the real
4138     // cost to you of processing a transaction.
4139     int64 nMinTxFee = MIN_TX_FEE;
4140     if (mapArgs.count("-mintxfee"))
4141         ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4142
4143     // ppcoin: if coinstake available add coinstake tx
4144     static int64 nLastCoinStakeSearchTime = GetAdjustedTime();  // only initialized at startup
4145     CBlockIndex* pindexPrev = pindexBest;
4146
4147     if (fProofOfStake)  // attempt to find a coinstake
4148     {
4149         pblock->nBits = GetNextTargetRequired(pindexPrev, true);
4150         CTransaction txCoinStake;
4151         int64 nSearchTime = txCoinStake.nTime; // search to current time
4152         if (nSearchTime > nLastCoinStakeSearchTime)
4153         {
4154             if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
4155             {
4156                 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
4157                 {   // make sure coinstake would meet timestamp protocol
4158                     // as it would be the same as the block timestamp
4159                     pblock->vtx[0].vout[0].SetEmpty();
4160                     pblock->vtx[0].nTime = txCoinStake.nTime;
4161                     pblock->vtx.push_back(txCoinStake);
4162                 }
4163             }
4164             nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
4165             nLastCoinStakeSearchTime = nSearchTime;
4166         }
4167     }
4168
4169     pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
4170
4171     // Collect memory pool transactions into the block
4172     int64 nFees = 0;
4173     {
4174         LOCK2(cs_main, mempool.cs);
4175         CBlockIndex* pindexPrev = pindexBest;
4176         CTxDB txdb("r");
4177
4178         // Priority order to process transactions
4179         list<COrphan> vOrphan; // list memory doesn't move
4180         map<uint256, vector<COrphan*> > mapDependers;
4181
4182         // This vector will be sorted into a priority queue:
4183         vector<TxPriority> vecPriority;
4184         vecPriority.reserve(mempool.mapTx.size());
4185         for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4186         {
4187             CTransaction& tx = (*mi).second;
4188             if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
4189                 continue;
4190
4191             COrphan* porphan = NULL;
4192             double dPriority = 0;
4193             int64 nTotalIn = 0;
4194             bool fMissingInputs = false;
4195             BOOST_FOREACH(const CTxIn& txin, tx.vin)
4196             {
4197                 // Read prev transaction
4198                 CTransaction txPrev;
4199                 CTxIndex txindex;
4200                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
4201                 {
4202                     // This should never happen; all transactions in the memory
4203                     // pool should connect to either transactions in the chain
4204                     // or other transactions in the memory pool.
4205                     if (!mempool.mapTx.count(txin.prevout.hash))
4206                     {
4207                         printf("ERROR: mempool transaction missing input\n");
4208                         if (fDebug) assert("mempool transaction missing input" == 0);
4209                         fMissingInputs = true;
4210                         if (porphan)
4211                             vOrphan.pop_back();
4212                         break;
4213                     }
4214
4215                     // Has to wait for dependencies
4216                     if (!porphan)
4217                     {
4218                         // Use list for automatic deletion
4219                         vOrphan.push_back(COrphan(&tx));
4220                         porphan = &vOrphan.back();
4221                     }
4222                     mapDependers[txin.prevout.hash].push_back(porphan);
4223                     porphan->setDependsOn.insert(txin.prevout.hash);
4224                     nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4225                     continue;
4226                 }
4227                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
4228                 nTotalIn += nValueIn;
4229
4230                 int nConf = txindex.GetDepthInMainChain();
4231                 dPriority += (double)nValueIn * nConf;
4232             }
4233             if (fMissingInputs) continue;
4234
4235             // Priority is sum(valuein * age) / txsize
4236             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4237             dPriority /= nTxSize;
4238
4239             // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4240             // client code rounds up the size to the nearest 1K. That's good, because it gives an
4241             // incentive to create smaller transactions.
4242             double dFeePerKb =  double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4243
4244             if (porphan)
4245             {
4246                 porphan->dPriority = dPriority;
4247                 porphan->dFeePerKb = dFeePerKb;
4248             }
4249             else
4250                 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4251         }
4252
4253         // Collect transactions into block
4254         map<uint256, CTxIndex> mapTestPool;
4255         uint64 nBlockSize = 1000;
4256         uint64 nBlockTx = 0;
4257         int nBlockSigOps = 100;
4258         bool fSortedByFee = (nBlockPrioritySize <= 0);
4259
4260         TxPriorityCompare comparer(fSortedByFee);
4261         std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4262
4263         while (!vecPriority.empty())
4264         {
4265             // Take highest priority transaction off the priority queue:
4266             double dPriority = vecPriority.front().get<0>();
4267             double dFeePerKb = vecPriority.front().get<1>();
4268             CTransaction& tx = *(vecPriority.front().get<2>());
4269
4270             std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4271             vecPriority.pop_back();
4272
4273             // Size limits
4274             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4275             if (nBlockSize + nTxSize >= nBlockMaxSize)
4276                 continue;
4277
4278             // Legacy limits on sigOps:
4279             unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4280             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4281                 continue;
4282
4283             // Timestamp limit
4284             if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
4285                 continue;
4286
4287             // ppcoin: simplify transaction fee - allow free = false
4288             int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
4289
4290             // Skip free transactions if we're past the minimum block size:
4291             if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4292                 continue;
4293
4294             // Prioritize by fee once past the priority size or we run out of high-priority
4295             // transactions:
4296             if (!fSortedByFee &&
4297                 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4298             {
4299                 fSortedByFee = true;
4300                 comparer = TxPriorityCompare(fSortedByFee);
4301                 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4302             }
4303
4304             // Connecting shouldn't fail due to dependency on other memory pool transactions
4305             // because we're already processing them in order of dependency
4306             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
4307             MapPrevTx mapInputs;
4308             bool fInvalid;
4309             if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
4310                 continue;
4311
4312             int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
4313             if (nTxFees < nMinFee)
4314                 continue;
4315
4316             nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
4317             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4318                 continue;
4319
4320             if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
4321                 continue;
4322             mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
4323             swap(mapTestPool, mapTestPoolTmp);
4324
4325             // Added
4326             pblock->vtx.push_back(tx);
4327             nBlockSize += nTxSize;
4328             ++nBlockTx;
4329             nBlockSigOps += nTxSigOps;
4330             nFees += nTxFees;
4331
4332             if (fDebug && GetBoolArg("-printpriority"))
4333             {
4334                 printf("priority %.1f feeperkb %.1f txid %s\n",
4335                        dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4336             }
4337
4338             // Add transactions that depend on this one to the priority queue
4339             uint256 hash = tx.GetHash();
4340             if (mapDependers.count(hash))
4341             {
4342                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4343                 {
4344                     if (!porphan->setDependsOn.empty())
4345                     {
4346                         porphan->setDependsOn.erase(hash);
4347                         if (porphan->setDependsOn.empty())
4348                         {
4349                             vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4350                             std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4351                         }
4352                     }
4353                 }
4354             }
4355         }
4356
4357         nLastBlockTx = nBlockTx;
4358         nLastBlockSize = nBlockSize;
4359
4360         if (fDebug && GetBoolArg("-printpriority"))
4361             printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4362
4363         if (pblock->IsProofOfWork())
4364             pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
4365
4366         // Fill in header
4367         pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
4368         if (pblock->IsProofOfStake())
4369             pblock->nTime      = pblock->vtx[1].nTime; //same as coinstake timestamp
4370         pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4371         pblock->nTime          = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4372         if (pblock->IsProofOfWork())
4373             pblock->UpdateTime(pindexPrev);
4374         pblock->nNonce         = 0;
4375     }
4376
4377     return pblock.release();
4378 }
4379
4380
4381 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4382 {
4383     // Update nExtraNonce
4384     static uint256 hashPrevBlock;
4385     if (hashPrevBlock != pblock->hashPrevBlock)
4386     {
4387         nExtraNonce = 0;
4388         hashPrevBlock = pblock->hashPrevBlock;
4389     }
4390     ++nExtraNonce;
4391     unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4392     pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4393     assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4394
4395     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4396 }
4397
4398
4399 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4400 {
4401     //
4402     // Pre-build hash buffers
4403     //
4404     struct
4405     {
4406         struct unnamed2
4407         {
4408             int nVersion;
4409             uint256 hashPrevBlock;
4410             uint256 hashMerkleRoot;
4411             unsigned int nTime;
4412             unsigned int nBits;
4413             unsigned int nNonce;
4414         }
4415         block;
4416         unsigned char pchPadding0[64];
4417         uint256 hash1;
4418         unsigned char pchPadding1[64];
4419     }
4420     tmp;
4421     memset(&tmp, 0, sizeof(tmp));
4422
4423     tmp.block.nVersion       = pblock->nVersion;
4424     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
4425     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4426     tmp.block.nTime          = pblock->nTime;
4427     tmp.block.nBits          = pblock->nBits;
4428     tmp.block.nNonce         = pblock->nNonce;
4429
4430     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4431     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4432
4433     // Byte swap all the input buffer
4434     for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4435         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4436
4437     // Precalc the first half of the first hash, which stays constant
4438     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4439
4440     memcpy(pdata, &tmp.block, 128);
4441     memcpy(phash1, &tmp.hash1, 64);
4442 }
4443
4444
4445 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4446 {
4447     uint256 hash = pblock->GetHash();
4448     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4449
4450     if (hash > hashTarget && pblock->IsProofOfWork())
4451         return error("BitcoinMiner : proof-of-work not meeting target");
4452
4453     //// debug print
4454     printf("BitcoinMiner:\n");
4455     printf("new block found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4456     pblock->print();
4457     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4458
4459     // Found a solution
4460     {
4461         LOCK(cs_main);
4462         if (pblock->hashPrevBlock != hashBestChain)
4463             return error("BitcoinMiner : generated block is stale");
4464
4465         // Remove key from key pool
4466         reservekey.KeepKey();
4467
4468         // Track how many getdata requests this block gets
4469         {
4470             LOCK(wallet.cs_wallet);
4471             wallet.mapRequestCount[pblock->GetHash()] = 0;
4472         }
4473
4474         // Process this block the same as if we had received it from another node
4475         if (!ProcessBlock(NULL, pblock))
4476             return error("BitcoinMiner : ProcessBlock, block not accepted");
4477     }
4478
4479     return true;
4480 }
4481
4482 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
4483 {
4484     SetThreadPriority(THREAD_PRIORITY_LOWEST);
4485
4486     // Make this thread recognisable as the mining thread
4487     RenameThread("bitcoin-miner");
4488
4489     // Each thread has its own key and counter
4490     CReserveKey reservekey(pwallet);
4491     unsigned int nExtraNonce = 0;
4492
4493     while (fProofOfStake)
4494     {
4495         if (fShutdown)
4496             return;
4497         while (vNodes.empty() || IsInitialBlockDownload())
4498         {
4499             Sleep(1000);
4500             if (fShutdown)
4501                 return;
4502             if (!fProofOfStake)
4503                 return;
4504         }
4505
4506         while (pwallet->IsLocked())
4507         {
4508             strMintWarning = strMintMessage;
4509             Sleep(1000);
4510         }
4511         strMintWarning = "";
4512
4513         //
4514         // Create new block
4515         //
4516         CBlockIndex* pindexPrev = pindexBest;
4517
4518         auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
4519         if (!pblock.get())
4520             return;
4521         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4522
4523         if (fProofOfStake)
4524         {
4525             // ppcoin: if proof-of-stake block found then process block
4526             if (pblock->IsProofOfStake())
4527             {
4528                 if (!pblock->SignBlock(*pwalletMain))
4529                 {
4530                     strMintWarning = strMintMessage;
4531                     continue;
4532                 }
4533                 strMintWarning = "";
4534                 printf("StakeMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str()); 
4535                 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4536                 CheckWork(pblock.get(), *pwalletMain, reservekey);
4537                 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4538             }
4539             Sleep(500);
4540             continue;
4541         }
4542     }
4543 }
4544