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