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