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