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