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