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