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