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