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