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