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