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