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