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