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