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