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