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