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