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