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