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