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