Automatically reserialize non-canonical proof-of-stake block signatures.
[novacoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "alert.h"
7 #include "checkpoints.h"
8 #include "db.h"
9 #include "txdb.h"
10 #include "net.h"
11 #include "init.h"
12 #include "ui_interface.h"
13 #include "checkqueue.h"
14 #include "kernel.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
18
19 #include "main.h"
20
21 using namespace std;
22 using namespace boost;
23
24
25
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
28
29 CCriticalSection cs_main;
30
31 CTxMemPool mempool;
32 unsigned int nTransactionsUpdated = 0;
33
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
36
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125  proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44
45 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
46 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
47 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
48 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
49
50 int nCoinbaseMaturity = 500;
51
52 CBlockIndex* pindexGenesisBlock = NULL;
53 int nBestHeight = -1;
54
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
57
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64_t nTimeBestReceived = 0;
61 int nScriptCheckThreads = 0;
62
63 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64
65 map<uint256, CBlock*> mapOrphanBlocks;
66 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
67 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
68 map<uint256, uint256> mapProofOfStake;
69
70 map<uint256, CTransaction> mapOrphanTransactions;
71 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72
73 // Constant stuff for coinbase transactions we create:
74 CScript COINBASE_FLAGS;
75
76 const string strMessageMagic = "NovaCoin Signed Message:\n";
77
78 // Settings
79 int64_t nTransactionFee = MIN_TX_FEE;
80 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
81
82 // Ping and address broadcast intervals
83 int64_t nPingInterval = 30 * 60;
84 int64_t nBroadcastInterval = 24 * 60 * 60;
85
86 extern enum Checkpoints::CPMode CheckpointsMode;
87
88 //////////////////////////////////////////////////////////////////////////////
89 //
90 // dispatching functions
91 //
92
93 // These functions dispatch to one or all registered wallets
94
95
96 void RegisterWallet(CWallet* pwalletIn)
97 {
98     {
99         LOCK(cs_setpwalletRegistered);
100         setpwalletRegistered.insert(pwalletIn);
101     }
102 }
103
104 void UnregisterWallet(CWallet* pwalletIn)
105 {
106     {
107         LOCK(cs_setpwalletRegistered);
108         setpwalletRegistered.erase(pwalletIn);
109     }
110 }
111
112 // check whether the passed transaction is from us
113 bool static IsFromMe(CTransaction& tx)
114 {
115     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116         if (pwallet->IsFromMe(tx))
117             return true;
118     return false;
119 }
120
121 // get the wallet transaction with the given hash (if it exists)
122 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
123 {
124     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125         if (pwallet->GetTransaction(hashTx,wtx))
126             return true;
127     return false;
128 }
129
130 // erases transaction with the given hash from all wallets
131 void static EraseFromWallets(uint256 hash)
132 {
133     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
134         pwallet->EraseFromWallet(hash);
135 }
136
137 // make sure all wallets know about the given transaction, in the given block
138 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
139 {
140     if (!fConnect)
141     {
142         // ppcoin: wallets need to refund inputs when disconnecting coinstake
143         if (tx.IsCoinStake())
144         {
145             BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146                 if (pwallet->IsFromMe(tx))
147                     pwallet->DisableTransaction(tx);
148         }
149         return;
150     }
151
152     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
154 }
155
156 // notify wallets about a new best chain
157 void static SetBestChain(const CBlockLocator& loc)
158 {
159     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160         pwallet->SetBestChain(loc);
161 }
162
163 // notify wallets about an updated transaction
164 void static UpdatedTransaction(const uint256& hashTx)
165 {
166     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167         pwallet->UpdatedTransaction(hashTx);
168 }
169
170 // dump all wallets
171 void static PrintWallets(const CBlock& block)
172 {
173     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
174         pwallet->PrintWallet(block);
175 }
176
177 // notify wallets about an incoming inventory (for request counts)
178 void static Inventory(const uint256& hash)
179 {
180     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
181         pwallet->Inventory(hash);
182 }
183
184 // ask wallets to resend their transactions
185 void ResendWalletTransactions()
186 {
187     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
188         pwallet->ResendWalletTransactions();
189 }
190
191
192
193
194
195
196
197 //////////////////////////////////////////////////////////////////////////////
198 //
199 // mapOrphanTransactions
200 //
201
202 bool AddOrphanTx(const CTransaction& tx)
203 {
204     uint256 hash = tx.GetHash();
205     if (mapOrphanTransactions.count(hash))
206         return false;
207
208     // Ignore big transactions, to avoid a
209     // send-big-orphans memory exhaustion attack. If a peer has a legitimate
210     // large transaction with a missing parent then we assume
211     // it will rebroadcast it later, after the parent transaction(s)
212     // have been mined or received.
213     // 10,000 orphans, each of which is at most 5,000 bytes big is
214     // at most 500 megabytes of orphans:
215
216     size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
217
218     if (nSize > 5000)
219     {
220         printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
221         return false;
222     }
223
224     mapOrphanTransactions[hash] = tx;
225     BOOST_FOREACH(const CTxIn& txin, tx.vin)
226         mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
227
228     printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
229         mapOrphanTransactions.size());
230     return true;
231 }
232
233 void static EraseOrphanTx(uint256 hash)
234 {
235     if (!mapOrphanTransactions.count(hash))
236         return;
237     const CTransaction& tx = mapOrphanTransactions[hash];
238     BOOST_FOREACH(const CTxIn& txin, tx.vin)
239     {
240         mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
241         if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
242             mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
243     }
244     mapOrphanTransactions.erase(hash);
245 }
246
247 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
248 {
249     unsigned int nEvicted = 0;
250     while (mapOrphanTransactions.size() > nMaxOrphans)
251     {
252         // Evict a random orphan:
253         uint256 randomhash = GetRandHash();
254         map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
255         if (it == mapOrphanTransactions.end())
256             it = mapOrphanTransactions.begin();
257         EraseOrphanTx(it->first);
258         ++nEvicted;
259     }
260     return nEvicted;
261 }
262
263
264
265
266
267
268
269 //////////////////////////////////////////////////////////////////////////////
270 //
271 // CTransaction and CTxIndex
272 //
273
274 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
275 {
276     SetNull();
277     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
278         return false;
279     if (!ReadFromDisk(txindexRet.pos))
280         return false;
281     if (prevout.n >= vout.size())
282     {
283         SetNull();
284         return false;
285     }
286     return true;
287 }
288
289 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
290 {
291     CTxIndex txindex;
292     return ReadFromDisk(txdb, prevout, txindex);
293 }
294
295 bool CTransaction::ReadFromDisk(COutPoint prevout)
296 {
297     CTxDB txdb("r");
298     CTxIndex txindex;
299     return ReadFromDisk(txdb, prevout, txindex);
300 }
301
302 bool CTransaction::IsStandard(string& strReason) const
303 {
304     if (nVersion > CTransaction::CURRENT_VERSION)
305     {
306         strReason = "version";
307         return false;
308     }
309
310     unsigned int nDataOut = 0;
311     txnouttype whichType;
312     BOOST_FOREACH(const CTxIn& txin, vin)
313     {
314         // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
315         // keys. (remember the 520 byte limit on redeemScript size) That works
316         // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
317         // bytes of scriptSig, which we round off to 1650 bytes for some minor
318         // future-proofing. That's also enough to spend a 20-of-20
319         // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
320         // considered standard)
321         if (txin.scriptSig.size() > 1650)
322         {
323             strReason = "scriptsig-size";
324             return false;
325         }
326         if (!txin.scriptSig.IsPushOnly())
327         {
328             strReason = "scriptsig-not-pushonly";
329             return false;
330         }
331         if (!txin.scriptSig.HasCanonicalPushes()) {
332             strReason = "txin-scriptsig-not-canonicalpushes";
333             return false;
334         }
335     }
336     BOOST_FOREACH(const CTxOut& txout, vout) {
337         if (!::IsStandard(txout.scriptPubKey, whichType)) {
338             strReason = "scriptpubkey";
339             return false;
340         }
341         if (whichType == TX_NULL_DATA)
342             nDataOut++;
343         else {
344             if (txout.nValue == 0) {
345                 strReason = "txout-value=0";
346                 return false;
347             }
348             if (!txout.scriptPubKey.HasCanonicalPushes()) {
349                 strReason = "txout-scriptsig-not-canonicalpushes";
350                 return false;
351             }
352         }
353     }
354
355     // only one OP_RETURN txout is permitted
356     if (nDataOut > 1) {
357         strReason = "multi-op-return";
358         return false;
359     }
360
361     return true;
362 }
363
364 //
365 // Check transaction inputs, and make sure any
366 // pay-to-script-hash transactions are evaluating IsStandard scripts
367 //
368 // Why bother? To avoid denial-of-service attacks; an attacker
369 // can submit a standard HASH... OP_EQUAL transaction,
370 // which will get accepted into blocks. The redemption
371 // script can be anything; an attacker could use a very
372 // expensive-to-check-upon-redemption script like:
373 //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
374 //
375 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
376 {
377     if (IsCoinBase())
378         return true; // Coinbases don't use vin normally
379
380     for (unsigned int i = 0; i < vin.size(); i++)
381     {
382         const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
383
384         vector<vector<unsigned char> > vSolutions;
385         txnouttype whichType;
386         // get the scriptPubKey corresponding to this input:
387         const CScript& prevScript = prev.scriptPubKey;
388         if (!Solver(prevScript, whichType, vSolutions))
389             return false;
390         int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
391         if (nArgsExpected < 0)
392             return false;
393
394         // Transactions with extra stuff in their scriptSigs are
395         // non-standard. Note that this EvalScript() call will
396         // be quick, because if there are any operations
397         // beside "push data" in the scriptSig the
398         // IsStandard() call returns false
399         vector<vector<unsigned char> > stack;
400         if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
401             return false;
402
403         if (whichType == TX_SCRIPTHASH)
404         {
405             if (stack.empty())
406                 return false;
407             CScript subscript(stack.back().begin(), stack.back().end());
408             vector<vector<unsigned char> > vSolutions2;
409             txnouttype whichType2;
410             if (!Solver(subscript, whichType2, vSolutions2))
411                 return false;
412             if (whichType2 == TX_SCRIPTHASH)
413                 return false;
414
415             int tmpExpected;
416             tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
417             if (tmpExpected < 0)
418                 return false;
419             nArgsExpected += tmpExpected;
420         }
421
422         if (stack.size() != (unsigned int)nArgsExpected)
423             return false;
424     }
425
426     return true;
427 }
428
429 unsigned int
430 CTransaction::GetLegacySigOpCount() const
431 {
432     unsigned int nSigOps = 0;
433     BOOST_FOREACH(const CTxIn& txin, vin)
434     {
435         nSigOps += txin.scriptSig.GetSigOpCount(false);
436     }
437     BOOST_FOREACH(const CTxOut& txout, vout)
438     {
439         nSigOps += txout.scriptPubKey.GetSigOpCount(false);
440     }
441     return nSigOps;
442 }
443
444
445 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
446 {
447     if (fClient)
448     {
449         if (hashBlock == 0)
450             return 0;
451     }
452     else
453     {
454         CBlock blockTmp;
455         if (pblock == NULL)
456         {
457             // Load the block this tx is in
458             CTxIndex txindex;
459             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
460                 return 0;
461             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
462                 return 0;
463             pblock = &blockTmp;
464         }
465
466         // Update the tx's hashBlock
467         hashBlock = pblock->GetHash();
468
469         // Locate the transaction
470         for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
471             if (pblock->vtx[nIndex] == *(CTransaction*)this)
472                 break;
473         if (nIndex == (int)pblock->vtx.size())
474         {
475             vMerkleBranch.clear();
476             nIndex = -1;
477             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
478             return 0;
479         }
480
481         // Fill in merkle branch
482         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
483     }
484
485     // Is the tx in a block that's in the main chain
486     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
487     if (mi == mapBlockIndex.end())
488         return 0;
489     CBlockIndex* pindex = (*mi).second;
490     if (!pindex || !pindex->IsInMainChain())
491         return 0;
492
493     return pindexBest->nHeight - pindex->nHeight + 1;
494 }
495
496
497
498
499
500
501
502 bool CTransaction::CheckTransaction() const
503 {
504     // Basic checks that don't depend on any context
505     if (vin.empty())
506         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
507     if (vout.empty())
508         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
509     // Size limits
510     if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
511         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
512
513     // Check for negative or overflow output values
514     int64_t nValueOut = 0;
515     for (unsigned int i = 0; i < vout.size(); i++)
516     {
517         const CTxOut& txout = vout[i];
518         if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
519             return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
520
521         if (txout.nValue < 0)
522             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
523         if (txout.nValue > MAX_MONEY)
524             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
525         nValueOut += txout.nValue;
526         if (!MoneyRange(nValueOut))
527             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
528     }
529
530     // Check for duplicate inputs
531     set<COutPoint> vInOutPoints;
532     BOOST_FOREACH(const CTxIn& txin, vin)
533     {
534         if (vInOutPoints.count(txin.prevout))
535             return false;
536         vInOutPoints.insert(txin.prevout);
537     }
538
539     if (IsCoinBase())
540     {
541         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
542             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
543     }
544     else
545     {
546         BOOST_FOREACH(const CTxIn& txin, vin)
547             if (txin.prevout.IsNull())
548                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
549     }
550
551     return true;
552 }
553
554 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
555 {
556     int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
557
558     if(IsCoinStake())
559     {
560         // Enforce 0.01 as minimum fee for old approach or coinstake
561         nMinTxFee = CENT;
562         nMinRelayTxFee = CENT;
563     }
564
565     // Base fee is either nMinTxFee or nMinRelayTxFee
566     int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
567
568     unsigned int nNewBlockSize = nBlockSize + nBytes;
569     int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
570
571     if (fAllowFree)
572     {
573         if (nBlockSize == 1)
574         {
575             // Transactions under 1K are free
576             if (nBytes < 1000)
577                 nMinFee = 0;
578         }
579         else
580         {
581             // Free transaction area
582             if (nNewBlockSize < 27000)
583                 nMinFee = 0;
584         }
585     }
586
587     // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
588     //    each non empty output which is less than 0.01
589     //
590     // It's safe to ignore empty outputs here, because these inputs are allowed
591     //     only for coinbase and coinstake transactions.
592     BOOST_FOREACH(const CTxOut& txout, vout)
593         if (txout.nValue < CENT && !txout.IsEmpty())
594             nMinFee += nBaseFee;
595
596     // Raise the price as the block approaches full
597     if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
598     {
599         if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
600             return MAX_MONEY;
601         nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
602     }
603
604     if (!MoneyRange(nMinFee))
605         nMinFee = MAX_MONEY;
606
607     return nMinFee;
608 }
609
610
611 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
612                         bool* pfMissingInputs)
613 {
614     if (pfMissingInputs)
615         *pfMissingInputs = false;
616
617     if (!tx.CheckTransaction())
618         return error("CTxMemPool::accept() : CheckTransaction failed");
619
620     // Coinbase is only valid in a block, not as a loose transaction
621     if (tx.IsCoinBase())
622         return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
623
624     // ppcoin: coinstake is also only valid in a block, not as a loose transaction
625     if (tx.IsCoinStake())
626         return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
627
628     // To help v0.1.5 clients who would see it as a negative number
629     if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
630         return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
631
632     // Rather not work on nonstandard transactions (unless -testnet)
633     string strNonStd;
634     if (!fTestNet && !tx.IsStandard(strNonStd))
635         return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
636
637     // Do we already have it?
638     uint256 hash = tx.GetHash();
639     {
640         LOCK(cs);
641         if (mapTx.count(hash))
642             return false;
643     }
644     if (fCheckInputs)
645         if (txdb.ContainsTx(hash))
646             return false;
647
648     // Check for conflicts with in-memory transactions
649     CTransaction* ptxOld = NULL;
650     for (unsigned int i = 0; i < tx.vin.size(); i++)
651     {
652         COutPoint outpoint = tx.vin[i].prevout;
653         if (mapNextTx.count(outpoint))
654         {
655             // Disable replacement feature for now
656             return false;
657
658             // Allow replacing with a newer version of the same transaction
659             if (i != 0)
660                 return false;
661             ptxOld = mapNextTx[outpoint].ptx;
662             if (ptxOld->IsFinal())
663                 return false;
664             if (!tx.IsNewerThan(*ptxOld))
665                 return false;
666             for (unsigned int i = 0; i < tx.vin.size(); i++)
667             {
668                 COutPoint outpoint = tx.vin[i].prevout;
669                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
670                     return false;
671             }
672             break;
673         }
674     }
675
676     if (fCheckInputs)
677     {
678         MapPrevTx mapInputs;
679         map<uint256, CTxIndex> mapUnused;
680         bool fInvalid = false;
681         if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
682         {
683             if (fInvalid)
684                 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
685             if (pfMissingInputs)
686                 *pfMissingInputs = true;
687             return false;
688         }
689
690         // Check for non-standard pay-to-script-hash in inputs
691         if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
692             return error("CTxMemPool::accept() : nonstandard transaction input");
693
694         // Note: if you modify this code to accept non-standard transactions, then
695         // you should add code here to check that the transaction does a
696         // reasonable number of ECDSA signature verifications.
697
698         int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
699         unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
700
701         // Don't accept it if it can't get into a block
702         int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
703         if (nFees < txMinFee)
704             return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
705                          hash.ToString().c_str(),
706                          nFees, txMinFee);
707
708         // Continuously rate-limit free transactions
709         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
710         // be annoying or make others' transactions take longer to confirm.
711         if (nFees < MIN_RELAY_TX_FEE)
712         {
713             static CCriticalSection cs;
714             static double dFreeCount;
715             static int64_t nLastTime;
716             int64_t nNow = GetTime();
717
718             {
719                 LOCK(cs);
720                 // Use an exponentially decaying ~10-minute window:
721                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
722                 nLastTime = nNow;
723                 // -limitfreerelay unit is thousand-bytes-per-minute
724                 // At default rate it would take over a month to fill 1GB
725                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
726                     return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
727                 if (fDebug)
728                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
729                 dFreeCount += nSize;
730             }
731         }
732
733         // Check against previous transactions
734         // This is done last to help prevent CPU exhaustion denial-of-service attacks.
735         if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
736         {
737             return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
738         }
739     }
740
741     // Store transaction in memory
742     {
743         LOCK(cs);
744         if (ptxOld)
745         {
746             printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
747             remove(*ptxOld);
748         }
749         addUnchecked(hash, tx);
750     }
751
752     ///// are we sure this is ok when loading transactions or restoring block txes
753     // If updated, erase old tx from wallet
754     if (ptxOld)
755         EraseFromWallets(ptxOld->GetHash());
756
757     printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
758            hash.ToString().substr(0,10).c_str(),
759            mapTx.size());
760     return true;
761 }
762
763 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
764 {
765     return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
766 }
767
768 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
769 {
770     // Add to memory pool without checking anything.  Don't call this directly,
771     // call CTxMemPool::accept to properly check the transaction first.
772     {
773         mapTx[hash] = tx;
774         for (unsigned int i = 0; i < tx.vin.size(); i++)
775             mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
776         nTransactionsUpdated++;
777     }
778     return true;
779 }
780
781
782 bool CTxMemPool::remove(CTransaction &tx)
783 {
784     // Remove transaction from memory pool
785     {
786         LOCK(cs);
787         uint256 hash = tx.GetHash();
788         if (mapTx.count(hash))
789         {
790             BOOST_FOREACH(const CTxIn& txin, tx.vin)
791                 mapNextTx.erase(txin.prevout);
792             mapTx.erase(hash);
793             nTransactionsUpdated++;
794         }
795     }
796     return true;
797 }
798
799 void CTxMemPool::clear()
800 {
801     LOCK(cs);
802     mapTx.clear();
803     mapNextTx.clear();
804     ++nTransactionsUpdated;
805 }
806
807 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
808 {
809     vtxid.clear();
810
811     LOCK(cs);
812     vtxid.reserve(mapTx.size());
813     for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
814         vtxid.push_back((*mi).first);
815 }
816
817
818
819
820 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
821 {
822     if (hashBlock == 0 || nIndex == -1)
823         return 0;
824
825     // Find the block it claims to be in
826     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
827     if (mi == mapBlockIndex.end())
828         return 0;
829     CBlockIndex* pindex = (*mi).second;
830     if (!pindex || !pindex->IsInMainChain())
831         return 0;
832
833     // Make sure the merkle branch connects to this block
834     if (!fMerkleVerified)
835     {
836         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
837             return 0;
838         fMerkleVerified = true;
839     }
840
841     pindexRet = pindex;
842     return pindexBest->nHeight - pindex->nHeight + 1;
843 }
844
845
846 int CMerkleTx::GetBlocksToMaturity() const
847 {
848     if (!(IsCoinBase() || IsCoinStake()))
849         return 0;
850     return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
851 }
852
853
854 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
855 {
856     if (fClient)
857     {
858         if (!IsInMainChain() && !ClientConnectInputs())
859             return false;
860         return CTransaction::AcceptToMemoryPool(txdb, false);
861     }
862     else
863     {
864         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
865     }
866 }
867
868 bool CMerkleTx::AcceptToMemoryPool()
869 {
870     CTxDB txdb("r");
871     return AcceptToMemoryPool(txdb);
872 }
873
874
875
876 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
877 {
878
879     {
880         LOCK(mempool.cs);
881         // Add previous supporting transactions first
882         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
883         {
884             if (!(tx.IsCoinBase() || tx.IsCoinStake()))
885             {
886                 uint256 hash = tx.GetHash();
887                 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
888                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
889             }
890         }
891         return AcceptToMemoryPool(txdb, fCheckInputs);
892     }
893     return false;
894 }
895
896 bool CWalletTx::AcceptWalletTransaction()
897 {
898     CTxDB txdb("r");
899     return AcceptWalletTransaction(txdb);
900 }
901
902 int CTxIndex::GetDepthInMainChain() const
903 {
904     // Read block header
905     CBlock block;
906     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
907         return 0;
908     // Find the block in the index
909     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
910     if (mi == mapBlockIndex.end())
911         return 0;
912     CBlockIndex* pindex = (*mi).second;
913     if (!pindex || !pindex->IsInMainChain())
914         return 0;
915     return 1 + nBestHeight - pindex->nHeight;
916 }
917
918 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
919 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
920 {
921     {
922         LOCK(cs_main);
923         {
924             LOCK(mempool.cs);
925             if (mempool.exists(hash))
926             {
927                 tx = mempool.lookup(hash);
928                 return true;
929             }
930         }
931         CTxDB txdb("r");
932         CTxIndex txindex;
933         if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
934         {
935             CBlock block;
936             if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
937                 hashBlock = block.GetHash();
938             return true;
939         }
940     }
941     return false;
942 }
943
944
945
946
947
948
949
950
951 //////////////////////////////////////////////////////////////////////////////
952 //
953 // CBlock and CBlockIndex
954 //
955
956 static CBlockIndex* pblockindexFBBHLast;
957 CBlockIndex* FindBlockByHeight(int nHeight)
958 {
959     CBlockIndex *pblockindex;
960     if (nHeight < nBestHeight / 2)
961         pblockindex = pindexGenesisBlock;
962     else
963         pblockindex = pindexBest;
964     if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
965         pblockindex = pblockindexFBBHLast;
966     while (pblockindex->nHeight > nHeight)
967         pblockindex = pblockindex->pprev;
968     while (pblockindex->nHeight < nHeight)
969         pblockindex = pblockindex->pnext;
970     pblockindexFBBHLast = pblockindex;
971     return pblockindex;
972 }
973
974 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
975 {
976     if (!fReadTransactions)
977     {
978         *this = pindex->GetBlockHeader();
979         return true;
980     }
981     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
982         return false;
983     if (GetHash() != pindex->GetBlockHash())
984         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
985     return true;
986 }
987
988 uint256 static GetOrphanRoot(const CBlock* pblock)
989 {
990     // Work back to the first block in the orphan chain
991     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
992         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
993     return pblock->GetHash();
994 }
995
996 // ppcoin: find block wanted by given orphan block
997 uint256 WantedByOrphan(const CBlock* pblockOrphan)
998 {
999     // Work back to the first block in the orphan chain
1000     while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1001         pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1002     return pblockOrphan->hashPrevBlock;
1003 }
1004
1005 // select stake target limit according to hard-coded conditions
1006 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1007 {
1008     if(fTestNet) // separate proof of stake target limit for testnet
1009         return bnProofOfStakeLimit;
1010     if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1011         return bnProofOfStakeLimit;
1012     if(nHeight + 1 > 15000) // 24 bits since block 15000
1013         return bnProofOfStakeLegacyLimit;
1014     if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1015         return bnProofOfStakeHardLimit;
1016
1017     return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1018 }
1019
1020 // miner's coin base reward based on nBits
1021 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1022 {
1023     CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1024
1025     CBigNum bnTarget;
1026     bnTarget.SetCompact(nBits);
1027     CBigNum bnTargetLimit = bnProofOfWorkLimit;
1028     bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1029
1030     // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1031     // A reasonably continuous curve is used to avoid shock to market
1032     // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1033     //
1034     // Human readable form:
1035     //
1036     // nSubsidy = 100 / (diff ^ 1/6)
1037     //
1038     // Please note that we're using bisection to find an approximate solutuion
1039     CBigNum bnLowerBound = CENT;
1040     CBigNum bnUpperBound = bnSubsidyLimit;
1041     while (bnLowerBound + CENT <= bnUpperBound)
1042     {
1043         CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1044         if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1045             bnUpperBound = bnMidValue;
1046         else
1047             bnLowerBound = bnMidValue;
1048     }
1049
1050     int64_t nSubsidy = bnUpperBound.getuint64();
1051
1052     nSubsidy = (nSubsidy / CENT) * CENT;
1053     if (fDebug && GetBoolArg("-printcreation"))
1054         printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1055
1056     return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1057 }
1058
1059 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1060 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1061 {
1062     int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1063
1064     if(fTestNet || nTime > STAKE_SWITCH_TIME)
1065     {
1066         // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1067
1068         CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1069         CBigNum bnTarget;
1070         bnTarget.SetCompact(nBits);
1071         CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1072         bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1073
1074         // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1075
1076         CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1077             bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1078             bnMidPart, bnRewardPart;
1079
1080         while (bnLowerBound + CENT <= bnUpperBound)
1081         {
1082             CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1083             if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1084             {
1085                 //
1086                 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1087                 //
1088                 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1089                 //
1090                 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1091                 //
1092
1093                 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1094                 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1095             }
1096             else
1097             {
1098                 //
1099                 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1100                 //
1101                 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1102                 //
1103                 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1104                 //
1105
1106                 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1107                 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1108             }
1109
1110             if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1111                 bnUpperBound = bnMidValue;
1112             else
1113                 bnLowerBound = bnMidValue;
1114         }
1115
1116         nRewardCoinYear = bnUpperBound.getuint64();
1117         nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1118     }
1119     else
1120     {
1121         // Old creation amount per coin-year, 5% fixed stake mint rate
1122         nRewardCoinYear = 5 * CENT;
1123     }
1124
1125     if(bCoinYearOnly)
1126         return nRewardCoinYear;
1127
1128     nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1129
1130     // Set reasonable reward limit for large inputs since 20 Oct 2013
1131     //
1132     // This will stimulate large holders to use smaller inputs, that's good for the network protection
1133     if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1134     {
1135         if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1136             printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1137
1138         nSubsidy = min(nSubsidy, nSubsidyLimit);
1139     }
1140
1141     if (fDebug && GetBoolArg("-printcreation"))
1142         printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1143     return nSubsidy;
1144 }
1145
1146 static const int64_t nTargetTimespan = 7 * 24 * 60 * 60;  // one week
1147
1148 // get proof of work blocks max spacing according to hard-coded conditions
1149 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1150 {
1151     if(nTime > TARGETS_SWITCH_TIME)
1152         return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1153
1154     if(fTestNet)
1155         return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1156
1157     return 12 * nStakeTargetSpacing; // 2 hours otherwise
1158 }
1159
1160 //
1161 // maximum nBits value could possible be required nTime after
1162 //
1163 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1164 {
1165     CBigNum bnResult;
1166     bnResult.SetCompact(nBase);
1167     bnResult *= 2;
1168     while (nTime > 0 && bnResult < bnTargetLimit)
1169     {
1170         // Maximum 200% adjustment per day...
1171         bnResult *= 2;
1172         nTime -= 24 * 60 * 60;
1173     }
1174     if (bnResult > bnTargetLimit)
1175         bnResult = bnTargetLimit;
1176     return bnResult.GetCompact();
1177 }
1178
1179 //
1180 // minimum amount of work that could possibly be required nTime after
1181 // minimum proof-of-work required was nBase
1182 //
1183 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1184 {
1185     return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1186 }
1187
1188 //
1189 // minimum amount of stake that could possibly be required nTime after
1190 // minimum proof-of-stake required was nBase
1191 //
1192 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1193 {
1194     return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1195 }
1196
1197
1198 // ppcoin: find last block index up to pindex
1199 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1200 {
1201     while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1202         pindex = pindex->pprev;
1203     return pindex;
1204 }
1205
1206 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1207 {
1208     CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1209
1210     if (pindexLast == NULL)
1211         return bnTargetLimit.GetCompact(); // genesis block
1212
1213     const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1214     if (pindexPrev->pprev == NULL)
1215         return bnTargetLimit.GetCompact(); // first block
1216     const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1217     if (pindexPrevPrev->pprev == NULL)
1218         return bnTargetLimit.GetCompact(); // second block
1219
1220     int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1221
1222     // ppcoin: target change every block
1223     // ppcoin: retarget with exponential moving toward target spacing
1224     CBigNum bnNew;
1225     bnNew.SetCompact(pindexPrev->nBits);
1226     int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1227     int64_t nInterval = nTargetTimespan / nTargetSpacing;
1228     bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1229     bnNew /= ((nInterval + 1) * nTargetSpacing);
1230
1231     if (bnNew > bnTargetLimit)
1232         bnNew = bnTargetLimit;
1233
1234     return bnNew.GetCompact();
1235 }
1236
1237 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1238 {
1239     CBigNum bnTarget;
1240     bnTarget.SetCompact(nBits);
1241
1242     // Check range
1243     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1244         return error("CheckProofOfWork() : nBits below minimum work");
1245
1246     // Check proof of work matches claimed amount
1247     if (hash > bnTarget.getuint256())
1248         return error("CheckProofOfWork() : hash doesn't match nBits");
1249
1250     return true;
1251 }
1252
1253 // Return maximum amount of blocks that other nodes claim to have
1254 int GetNumBlocksOfPeers()
1255 {
1256     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1257 }
1258
1259 bool IsInitialBlockDownload()
1260 {
1261     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1262         return true;
1263     static int64_t nLastUpdate;
1264     static CBlockIndex* pindexLastBest;
1265     int64_t nCurrentTime = GetTime();
1266     if (pindexBest != pindexLastBest)
1267     {
1268         pindexLastBest = pindexBest;
1269         nLastUpdate = nCurrentTime;
1270     }
1271     return (nCurrentTime - nLastUpdate < 10 &&
1272             pindexBest->GetBlockTime() < nCurrentTime - 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     static int8_t counter = 0;
2217     if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2218         uiInterface.NotifyBlocksChanged();
2219     return true;
2220 }
2221
2222
2223
2224
2225 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2226 {
2227     // These are checks that are independent of context
2228     // that can be verified before saving an orphan block.
2229
2230     set<uint256> uniqueTx; // tx hashes
2231     unsigned int nSigOps = 0; // total sigops
2232
2233     // Size limits
2234     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2235         return DoS(100, error("CheckBlock() : size limits failed"));
2236
2237     bool fProofOfStake = IsProofOfStake();
2238
2239     // First transaction must be coinbase, the rest must not be
2240     if (!vtx[0].IsCoinBase())
2241         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2242
2243     if (!vtx[0].CheckTransaction())
2244         return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2245
2246     uniqueTx.insert(vtx[0].GetHash());
2247     nSigOps += vtx[0].GetLegacySigOpCount();
2248
2249     if (fProofOfStake)
2250     {
2251         // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need 
2252         //   check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2253
2254         // nNonce must be zero for proof-of-stake blocks
2255         if (nNonce != 0)
2256             return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2257
2258         // Coinbase output should be empty if proof-of-stake block
2259         if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2260             return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2261
2262         // Check coinstake timestamp
2263         if (GetBlockTime() != (int64_t)vtx[1].nTime)
2264             return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2265
2266         // NovaCoin: check proof-of-stake block signature
2267         if (fCheckSig && !CheckBlockSignature())
2268             return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2269
2270         if (!vtx[1].CheckTransaction())
2271             return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2272
2273         uniqueTx.insert(vtx[1].GetHash());
2274         nSigOps += vtx[1].GetLegacySigOpCount();
2275     }
2276     else
2277     {
2278         // Check proof of work matches claimed amount
2279         if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2280             return DoS(50, error("CheckBlock() : proof of work failed"));
2281
2282         // Check timestamp
2283         if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2284             return error("CheckBlock() : block timestamp too far in the future");
2285
2286         // Check coinbase timestamp
2287         if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2288             return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2289     }
2290
2291     // Iterate all transactions starting from second for proof-of-stake block 
2292     //    or first for proof-of-work block
2293     for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2294     {
2295         const CTransaction& tx = vtx[i];
2296
2297         // Reject coinbase transactions at non-zero index
2298         if (tx.IsCoinBase())
2299             return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2300
2301         // Reject coinstake transactions at index != 1
2302         if (tx.IsCoinStake())
2303             return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2304
2305         // Check transaction timestamp
2306         if (GetBlockTime() < (int64_t)tx.nTime)
2307             return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2308
2309         // Check transaction consistency
2310         if (!tx.CheckTransaction())
2311             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2312
2313         // Add transaction hash into list of unique transaction IDs
2314         uniqueTx.insert(tx.GetHash());
2315
2316         // Calculate sigops count
2317         nSigOps += tx.GetLegacySigOpCount();
2318     }
2319
2320     // Check for duplicate txids. This is caught by ConnectInputs(),
2321     // but catching it earlier avoids a potential DoS attack:
2322     if (uniqueTx.size() != vtx.size())
2323         return DoS(100, error("CheckBlock() : duplicate transaction"));
2324
2325     // Reject block if validation would consume too much resources.
2326     if (nSigOps > MAX_BLOCK_SIGOPS)
2327         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2328
2329     // Check merkle root
2330     if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2331         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2332
2333     return true;
2334 }
2335
2336 bool CBlock::AcceptBlock()
2337 {
2338     // Check for duplicate
2339     uint256 hash = GetHash();
2340     if (mapBlockIndex.count(hash))
2341         return error("AcceptBlock() : block already in mapBlockIndex");
2342
2343     // Get prev block index
2344     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2345     if (mi == mapBlockIndex.end())
2346         return DoS(10, error("AcceptBlock() : prev block not found"));
2347     CBlockIndex* pindexPrev = (*mi).second;
2348     int nHeight = pindexPrev->nHeight+1;
2349
2350     // Check proof-of-work or proof-of-stake
2351     if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2352         return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2353
2354     // Check timestamp against prev
2355     if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2356         return error("AcceptBlock() : block's timestamp is too early");
2357
2358     // Check that all transactions are finalized
2359     BOOST_FOREACH(const CTransaction& tx, vtx)
2360         if (!tx.IsFinal(nHeight, GetBlockTime()))
2361             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2362
2363     // Check that the block chain matches the known block chain up to a checkpoint
2364     if (!Checkpoints::CheckHardened(nHeight, hash))
2365         return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2366
2367     bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2368
2369     // Check that the block satisfies synchronized checkpoint
2370     if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2371         return error("AcceptBlock() : rejected by synchronized checkpoint");
2372
2373     if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2374         strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2375
2376     // Enforce rule that the coinbase starts with serialized block height
2377     CScript expect = CScript() << nHeight;
2378     if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2379         !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2380         return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2381
2382     // Write block to history file
2383     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2384         return error("AcceptBlock() : out of disk space");
2385     unsigned int nFile = std::numeric_limits<unsigned int>::max();
2386     unsigned int nBlockPos = 0;
2387     if (!WriteToDisk(nFile, nBlockPos))
2388         return error("AcceptBlock() : WriteToDisk failed");
2389     if (!AddToBlockIndex(nFile, nBlockPos))
2390         return error("AcceptBlock() : AddToBlockIndex failed");
2391
2392     // Relay inventory, but don't relay old inventory during initial block download
2393     int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2394     if (hashBestChain == hash)
2395     {
2396         LOCK(cs_vNodes);
2397         BOOST_FOREACH(CNode* pnode, vNodes)
2398             if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2399                 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2400     }
2401
2402     // ppcoin: check pending sync-checkpoint
2403     Checkpoints::AcceptPendingSyncCheckpoint();
2404
2405     return true;
2406 }
2407
2408 uint256 CBlockIndex::GetBlockTrust() const
2409 {
2410     CBigNum bnTarget;
2411     bnTarget.SetCompact(nBits);
2412
2413     if (bnTarget <= 0)
2414         return 0;
2415
2416     /* Old protocol */
2417     if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2418         return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2419
2420     /* New protocol */
2421
2422     // Calculate work amount for block
2423     uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2424
2425     // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2426     nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2427
2428     // Return nPoWTrust for the first 12 blocks
2429     if (pprev == NULL || pprev->nHeight < 12)
2430         return nPoWTrust;
2431
2432     const CBlockIndex* currentIndex = pprev;
2433
2434     if(IsProofOfStake())
2435     {
2436         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2437
2438         // Return 1/3 of score if parent block is not the PoW block
2439         if (!pprev->IsProofOfWork())
2440             return (bnNewTrust / 3).getuint256();
2441
2442         int nPoWCount = 0;
2443
2444         // Check last 12 blocks type
2445         while (pprev->nHeight - currentIndex->nHeight < 12)
2446         {
2447             if (currentIndex->IsProofOfWork())
2448                 nPoWCount++;
2449             currentIndex = currentIndex->pprev;
2450         }
2451
2452         // Return 1/3 of score if less than 3 PoW blocks found
2453         if (nPoWCount < 3)
2454             return (bnNewTrust / 3).getuint256();
2455
2456         return bnNewTrust.getuint256();
2457     }
2458     else
2459     {
2460         CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2461
2462         // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2463         if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2464             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2465
2466         int nPoSCount = 0;
2467
2468         // Check last 12 blocks type
2469         while (pprev->nHeight - currentIndex->nHeight < 12)
2470         {
2471             if (currentIndex->IsProofOfStake())
2472                 nPoSCount++;
2473             currentIndex = currentIndex->pprev;
2474         }
2475
2476         // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2477         if (nPoSCount < 7)
2478             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2479
2480         bnTarget.SetCompact(pprev->nBits);
2481
2482         if (bnTarget <= 0)
2483             return 0;
2484
2485         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2486
2487         // Return nPoWTrust + full trust score for previous block nBits
2488         return nPoWTrust + bnNewTrust.getuint256();
2489     }
2490 }
2491
2492 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2493 {
2494     unsigned int nFound = 0;
2495     for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2496     {
2497         if (pstart->nVersion >= minVersion)
2498             ++nFound;
2499         pstart = pstart->pprev;
2500     }
2501     return (nFound >= nRequired);
2502 }
2503
2504 bool static ReserealizeBlockSignature(CBlock* pblock)
2505 {
2506     if (pblock->IsProofOfWork())
2507     {
2508         pblock->vchBlockSig.clear();
2509         return true;
2510     }
2511
2512     return CKey::ReserealizeSignature(pblock->vchBlockSig);
2513 }
2514
2515 bool static IsCanonicalBlockSignature(CBlock* pblock)
2516 {
2517     if (pblock->IsProofOfWork())
2518         return pblock->vchBlockSig.empty();
2519
2520     return IsDERSignature(pblock->vchBlockSig);
2521 }
2522
2523 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2524 {
2525     // Check for duplicate
2526     uint256 hash = pblock->GetHash();
2527     if (mapBlockIndex.count(hash))
2528         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2529     if (mapOrphanBlocks.count(hash))
2530         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2531
2532     // Check proof-of-stake
2533     // Limited duplicity on stake: prevents block flood attack
2534     // Duplicate stake allowed only when there is orphan child block
2535     if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2536         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());
2537
2538     // Strip the garbage from newly received blocks, if we found some
2539     if (!IsCanonicalBlockSignature(pblock)) {
2540         if (!ReserealizeBlockSignature(pblock))
2541             printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2542     }
2543
2544     // Preliminary checks
2545     if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2546         return error("ProcessBlock() : CheckBlock FAILED");
2547
2548     // ppcoin: verify hash target and signature of coinstake tx
2549     if (pblock->IsProofOfStake())
2550     {
2551         uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2552         if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2553         {
2554             printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2555             return false; // do not error here as we expect this during initial block download
2556         }
2557         if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2558             mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2559     }
2560
2561     CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2562     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2563     {
2564         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2565         int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2566         CBigNum bnNewBlock;
2567         bnNewBlock.SetCompact(pblock->nBits);
2568         CBigNum bnRequired;
2569
2570         if (pblock->IsProofOfStake())
2571             bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2572         else
2573             bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2574
2575         if (bnNewBlock > bnRequired)
2576         {
2577             if (pfrom)
2578                 pfrom->Misbehaving(100);
2579             return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2580         }
2581     }
2582
2583     // ppcoin: ask for pending sync-checkpoint if any
2584     if (!IsInitialBlockDownload())
2585         Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2586
2587     // If don't already have its previous block, shunt it off to holding area until we get it
2588     if (!mapBlockIndex.count(pblock->hashPrevBlock))
2589     {
2590         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2591         // ppcoin: check proof-of-stake
2592         if (pblock->IsProofOfStake())
2593         {
2594             // Limited duplicity on stake: prevents block flood attack
2595             // Duplicate stake allowed only when there is orphan child block
2596             if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2597                 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2598             else
2599                 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2600         }
2601         CBlock* pblock2 = new CBlock(*pblock);
2602         mapOrphanBlocks.insert(make_pair(hash, pblock2));
2603         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2604
2605         // Ask this guy to fill in what we're missing
2606         if (pfrom)
2607         {
2608             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2609             // ppcoin: getblocks may not obtain the ancestor block rejected
2610             // earlier by duplicate-stake check so we ask for it again directly
2611             if (!IsInitialBlockDownload())
2612                 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2613         }
2614         return true;
2615     }
2616
2617     // Store to disk
2618     if (!pblock->AcceptBlock())
2619         return error("ProcessBlock() : AcceptBlock FAILED");
2620
2621     // Recursively process any orphan blocks that depended on this one
2622     vector<uint256> vWorkQueue;
2623     vWorkQueue.push_back(hash);
2624     for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2625     {
2626         uint256 hashPrev = vWorkQueue[i];
2627         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2628              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2629              ++mi)
2630         {
2631             CBlock* pblockOrphan = (*mi).second;
2632             if (pblockOrphan->AcceptBlock())
2633                 vWorkQueue.push_back(pblockOrphan->GetHash());
2634             mapOrphanBlocks.erase(pblockOrphan->GetHash());
2635             setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2636             delete pblockOrphan;
2637         }
2638         mapOrphanBlocksByPrev.erase(hashPrev);
2639     }
2640
2641     printf("ProcessBlock: ACCEPTED\n");
2642
2643     // ppcoin: if responsible for sync-checkpoint send it
2644     if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2645         Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2646
2647     return true;
2648 }
2649
2650 // ppcoin: check block signature
2651 bool CBlock::CheckBlockSignature() const
2652 {
2653     if (IsProofOfWork())
2654         return true;
2655
2656     vector<valtype> vSolutions;
2657     txnouttype whichType;
2658
2659     const CTxOut& txout = vtx[1].vout[1];
2660
2661     if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2662         return false;
2663     if (whichType == TX_PUBKEY)
2664     {
2665         valtype& vchPubKey = vSolutions[0];
2666         CKey key;
2667         if (!key.SetPubKey(vchPubKey))
2668             return false;
2669         if (vchBlockSig.empty())
2670             return false;
2671         return key.Verify(GetHash(), vchBlockSig);
2672     }
2673     return false;
2674 }
2675
2676 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2677 {
2678     uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2679
2680     // Check for nMinDiskSpace bytes (currently 50MB)
2681     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2682     {
2683         fShutdown = true;
2684         string strMessage = _("Warning: Disk space is low!");
2685         strMiscWarning = strMessage;
2686         printf("*** %s\n", strMessage.c_str());
2687         uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2688         StartShutdown();
2689         return false;
2690     }
2691     return true;
2692 }
2693
2694 static filesystem::path BlockFilePath(unsigned int nFile)
2695 {
2696     string strBlockFn = strprintf("blk%04u.dat", nFile);
2697     return GetDataDir() / strBlockFn;
2698 }
2699
2700 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2701 {
2702     if ((nFile < 1) || (nFile == (unsigned int) -1))
2703         return NULL;
2704     FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2705     if (!file)
2706         return NULL;
2707     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2708     {
2709         if (fseek(file, nBlockPos, SEEK_SET) != 0)
2710         {
2711             fclose(file);
2712             return NULL;
2713         }
2714     }
2715     return file;
2716 }
2717
2718 static unsigned int nCurrentBlockFile = 1;
2719
2720 FILE* AppendBlockFile(unsigned int& nFileRet)
2721 {
2722     nFileRet = 0;
2723     while (true)
2724     {
2725         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2726         if (!file)
2727             return NULL;
2728         if (fseek(file, 0, SEEK_END) != 0)
2729             return NULL;
2730         // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2731         if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2732         {
2733             nFileRet = nCurrentBlockFile;
2734             return file;
2735         }
2736         fclose(file);
2737         nCurrentBlockFile++;
2738     }
2739 }
2740
2741 void UnloadBlockIndex()
2742 {
2743     mapBlockIndex.clear();
2744     setStakeSeen.clear();
2745     pindexGenesisBlock = NULL;
2746     nBestHeight = 0;
2747     nBestChainTrust = 0;
2748     nBestInvalidTrust = 0;
2749     hashBestChain = 0;
2750     pindexBest = NULL;
2751 }
2752
2753 bool LoadBlockIndex(bool fAllowNew)
2754 {
2755     if (fTestNet)
2756     {
2757         pchMessageStart[0] = 0xcd;
2758         pchMessageStart[1] = 0xf2;
2759         pchMessageStart[2] = 0xc0;
2760         pchMessageStart[3] = 0xef;
2761
2762         bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2763         nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2764         nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2765         nCoinbaseMaturity = 10; // test maturity is 10 blocks
2766         nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2767     }
2768
2769     //
2770     // Load block index
2771     //
2772     CTxDB txdb("cr+");
2773     if (!txdb.LoadBlockIndex())
2774         return false;
2775
2776     //
2777     // Init with genesis block
2778     //
2779     if (mapBlockIndex.empty())
2780     {
2781         if (!fAllowNew)
2782             return false;
2783
2784         // Genesis block
2785
2786         // MainNet:
2787
2788         //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2789         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2790         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2791         //    CTxOut(empty)
2792         //  vMerkleTree: 4cb33b3b6a
2793
2794         // TestNet:
2795
2796         //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2797         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2798         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2799         //    CTxOut(empty)
2800         //  vMerkleTree: 4cb33b3b6a
2801
2802         const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2803         CTransaction txNew;
2804         txNew.nTime = 1360105017;
2805         txNew.vin.resize(1);
2806         txNew.vout.resize(1);
2807         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2808         txNew.vout[0].SetEmpty();
2809         CBlock block;
2810         block.vtx.push_back(txNew);
2811         block.hashPrevBlock = 0;
2812         block.hashMerkleRoot = block.BuildMerkleTree();
2813         block.nVersion = 1;
2814         block.nTime    = 1360105017;
2815         block.nBits    = bnProofOfWorkLimit.GetCompact();
2816         block.nNonce   = !fTestNet ? 1575379 : 46534;
2817
2818         //// debug print
2819         assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2820         block.print();
2821         assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2822         assert(block.CheckBlock());
2823
2824         // Start new block file
2825         unsigned int nFile;
2826         unsigned int nBlockPos;
2827         if (!block.WriteToDisk(nFile, nBlockPos))
2828             return error("LoadBlockIndex() : writing genesis block to disk failed");
2829         if (!block.AddToBlockIndex(nFile, nBlockPos))
2830             return error("LoadBlockIndex() : genesis block not accepted");
2831
2832         // initialize synchronized checkpoint
2833         if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2834             return error("LoadBlockIndex() : failed to init sync checkpoint");
2835
2836         // upgrade time set to zero if txdb initialized
2837         {
2838             if (!txdb.WriteModifierUpgradeTime(0))
2839                 return error("LoadBlockIndex() : failed to init upgrade info");
2840             printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2841         }
2842     }
2843
2844     {
2845         CTxDB txdb("r+");
2846         string strPubKey = "";
2847         if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2848         {
2849             // write checkpoint master key to db
2850             txdb.TxnBegin();
2851             if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2852                 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2853             if (!txdb.TxnCommit())
2854                 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2855             if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2856                 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2857         }
2858
2859         // upgrade time set to zero if blocktreedb initialized
2860         if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2861         {
2862             if (nModifierUpgradeTime)
2863                 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2864             else
2865                 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2866         }
2867         else
2868         {
2869             nModifierUpgradeTime = GetTime();
2870             printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2871             if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2872                 return error("LoadBlockIndex() : failed to write upgrade info");
2873         }
2874
2875 #ifndef USE_LEVELDB
2876         txdb.Close();
2877 #endif
2878     }
2879
2880     return true;
2881 }
2882
2883
2884
2885 void PrintBlockTree()
2886 {
2887     // pre-compute tree structure
2888     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2889     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2890     {
2891         CBlockIndex* pindex = (*mi).second;
2892         mapNext[pindex->pprev].push_back(pindex);
2893         // test
2894         //while (rand() % 3 == 0)
2895         //    mapNext[pindex->pprev].push_back(pindex);
2896     }
2897
2898     vector<pair<int, CBlockIndex*> > vStack;
2899     vStack.push_back(make_pair(0, pindexGenesisBlock));
2900
2901     int nPrevCol = 0;
2902     while (!vStack.empty())
2903     {
2904         int nCol = vStack.back().first;
2905         CBlockIndex* pindex = vStack.back().second;
2906         vStack.pop_back();
2907
2908         // print split or gap
2909         if (nCol > nPrevCol)
2910         {
2911             for (int i = 0; i < nCol-1; i++)
2912                 printf("| ");
2913             printf("|\\\n");
2914         }
2915         else if (nCol < nPrevCol)
2916         {
2917             for (int i = 0; i < nCol; i++)
2918                 printf("| ");
2919             printf("|\n");
2920        }
2921         nPrevCol = nCol;
2922
2923         // print columns
2924         for (int i = 0; i < nCol; i++)
2925             printf("| ");
2926
2927         // print item
2928         CBlock block;
2929         block.ReadFromDisk(pindex);
2930         printf("%d (%u,%u) %s  %08x  %s  mint %7s  tx %" PRIszu "",
2931             pindex->nHeight,
2932             pindex->nFile,
2933             pindex->nBlockPos,
2934             block.GetHash().ToString().c_str(),
2935             block.nBits,
2936             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2937             FormatMoney(pindex->nMint).c_str(),
2938             block.vtx.size());
2939
2940         PrintWallets(block);
2941
2942         // put the main time-chain first
2943         vector<CBlockIndex*>& vNext = mapNext[pindex];
2944         for (unsigned int i = 0; i < vNext.size(); i++)
2945         {
2946             if (vNext[i]->pnext)
2947             {
2948                 swap(vNext[0], vNext[i]);
2949                 break;
2950             }
2951         }
2952
2953         // iterate children
2954         for (unsigned int i = 0; i < vNext.size(); i++)
2955             vStack.push_back(make_pair(nCol+i, vNext[i]));
2956     }
2957 }
2958
2959 bool LoadExternalBlockFile(FILE* fileIn)
2960 {
2961     int64_t nStart = GetTimeMillis();
2962
2963     int nLoaded = 0;
2964     {
2965         LOCK(cs_main);
2966         try {
2967             CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2968             unsigned int nPos = 0;
2969             while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2970             {
2971                 unsigned char pchData[65536];
2972                 do {
2973                     fseek(blkdat, nPos, SEEK_SET);
2974                     int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2975                     if (nRead <= 8)
2976                     {
2977                         nPos = (unsigned int)-1;
2978                         break;
2979                     }
2980                     void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2981                     if (nFind)
2982                     {
2983                         if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2984                         {
2985                             nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2986                             break;
2987                         }
2988                         nPos += ((unsigned char*)nFind - pchData) + 1;
2989                     }
2990                     else
2991                         nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2992                 } while(!fRequestShutdown);
2993                 if (nPos == (unsigned int)-1)
2994                     break;
2995                 fseek(blkdat, nPos, SEEK_SET);
2996                 unsigned int nSize;
2997                 blkdat >> nSize;
2998                 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2999                 {
3000                     CBlock block;
3001                     blkdat >> block;
3002                     if (ProcessBlock(NULL,&block))
3003                     {
3004                         nLoaded++;
3005                         nPos += 4 + nSize;
3006                     }
3007                 }
3008             }
3009         }
3010         catch (std::exception &e) {
3011             printf("%s() : Deserialize or I/O error caught during load\n",
3012                    BOOST_CURRENT_FUNCTION);
3013         }
3014     }
3015     printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3016     return nLoaded > 0;
3017 }
3018
3019 //////////////////////////////////////////////////////////////////////////////
3020 //
3021 // CAlert
3022 //
3023
3024 extern map<uint256, CAlert> mapAlerts;
3025 extern CCriticalSection cs_mapAlerts;
3026
3027 string GetWarnings(string strFor)
3028 {
3029     int nPriority = 0;
3030     string strStatusBar;
3031     string strRPC;
3032
3033     if (GetBoolArg("-testsafemode"))
3034         strRPC = "test";
3035
3036     // Misc warnings like out of disk space and clock is wrong
3037     if (strMiscWarning != "")
3038     {
3039         nPriority = 1000;
3040         strStatusBar = strMiscWarning;
3041     }
3042
3043     // if detected unmet upgrade requirement enter safe mode
3044     // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3045     if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3046     {
3047         nPriority = 5000;
3048         strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3049     }
3050
3051     // if detected invalid checkpoint enter safe mode
3052     if (Checkpoints::hashInvalidCheckpoint != 0)
3053     {
3054         nPriority = 3000;
3055         strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3056     }
3057
3058     // Alerts
3059     {
3060         LOCK(cs_mapAlerts);
3061         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3062         {
3063             const CAlert& alert = item.second;
3064             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3065             {
3066                 nPriority = alert.nPriority;
3067                 strStatusBar = alert.strStatusBar;
3068                 if (nPriority > 1000)
3069                     strRPC = strStatusBar;
3070             }
3071         }
3072     }
3073
3074     if (strFor == "statusbar")
3075         return strStatusBar;
3076     else if (strFor == "rpc")
3077         return strRPC;
3078     assert(!"GetWarnings() : invalid parameter");
3079     return "error";
3080 }
3081
3082
3083
3084
3085
3086
3087
3088
3089 //////////////////////////////////////////////////////////////////////////////
3090 //
3091 // Messages
3092 //
3093
3094
3095 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3096 {
3097     switch (inv.type)
3098     {
3099     case MSG_TX:
3100         {
3101         bool txInMap = false;
3102             {
3103             LOCK(mempool.cs);
3104             txInMap = (mempool.exists(inv.hash));
3105             }
3106         return txInMap ||
3107                mapOrphanTransactions.count(inv.hash) ||
3108                txdb.ContainsTx(inv.hash);
3109         }
3110
3111     case MSG_BLOCK:
3112         return mapBlockIndex.count(inv.hash) ||
3113                mapOrphanBlocks.count(inv.hash);
3114     }
3115     // Don't know what it is, just say we already got one
3116     return true;
3117 }
3118
3119
3120
3121
3122 // The message start string is designed to be unlikely to occur in normal data.
3123 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3124 // a large 4-byte int at any alignment.
3125 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3126
3127 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3128 {
3129     static map<CService, CPubKey> mapReuseKey;
3130     RandAddSeedPerfmon();
3131     if (fDebug)
3132         printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3133     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3134     {
3135         printf("dropmessagestest DROPPING RECV MESSAGE\n");
3136         return true;
3137     }
3138
3139     if (strCommand == "version")
3140     {
3141         // Each connection can only send one version message
3142         if (pfrom->nVersion != 0)
3143         {
3144             pfrom->Misbehaving(1);
3145             return false;
3146         }
3147
3148         int64_t nTime;
3149         CAddress addrMe;
3150         CAddress addrFrom;
3151         uint64_t nNonce = 1;
3152         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3153         if (pfrom->nVersion < MIN_PROTO_VERSION)
3154         {
3155             // Since February 20, 2012, the protocol is initiated at version 209,
3156             // and earlier versions are no longer supported
3157             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3158             pfrom->fDisconnect = true;
3159             return false;
3160         }
3161
3162         if (pfrom->nVersion == 10300)
3163             pfrom->nVersion = 300;
3164         if (!vRecv.empty())
3165             vRecv >> addrFrom >> nNonce;
3166         if (!vRecv.empty())
3167             vRecv >> pfrom->strSubVer;
3168         if (!vRecv.empty())
3169             vRecv >> pfrom->nStartingHeight;
3170
3171         if (pfrom->fInbound && addrMe.IsRoutable())
3172         {
3173             pfrom->addrLocal = addrMe;
3174             SeenLocal(addrMe);
3175         }
3176
3177         // Disconnect if we connected to ourself
3178         if (nNonce == nLocalHostNonce && nNonce > 1)
3179         {
3180             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3181             pfrom->fDisconnect = true;
3182             return true;
3183         }
3184
3185         if (pfrom->nVersion < 60010)
3186         {
3187             printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3188             pfrom->fDisconnect = true;
3189             return true;
3190         }
3191
3192         // record my external IP reported by peer
3193         if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3194             addrSeenByPeer = addrMe;
3195
3196         // Be shy and don't send version until we hear
3197         if (pfrom->fInbound)
3198             pfrom->PushVersion();
3199
3200         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3201
3202         AddTimeData(pfrom->addr, nTime);
3203
3204         // Change version
3205         pfrom->PushMessage("verack");
3206         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3207
3208         if (!pfrom->fInbound)
3209         {
3210             // Advertise our address
3211             if (!fNoListen && !IsInitialBlockDownload())
3212             {
3213                 CAddress addr = GetLocalAddress(&pfrom->addr);
3214                 if (addr.IsRoutable())
3215                     pfrom->PushAddress(addr);
3216             }
3217
3218             // Get recent addresses
3219             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3220             {
3221                 pfrom->PushMessage("getaddr");
3222                 pfrom->fGetAddr = true;
3223             }
3224             addrman.Good(pfrom->addr);
3225         } else {
3226             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3227             {
3228                 addrman.Add(addrFrom, addrFrom);
3229                 addrman.Good(addrFrom);
3230             }
3231         }
3232
3233         // Ask the first connected node for block updates
3234         static int nAskedForBlocks = 0;
3235         if (!pfrom->fClient && !pfrom->fOneShot &&
3236             (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3237             (pfrom->nVersion < NOBLKS_VERSION_START ||
3238              pfrom->nVersion >= NOBLKS_VERSION_END) &&
3239              (nAskedForBlocks < 1 || vNodes.size() <= 1))
3240         {
3241             nAskedForBlocks++;
3242             pfrom->PushGetBlocks(pindexBest, uint256(0));
3243         }
3244
3245         // Relay alerts
3246         {
3247             LOCK(cs_mapAlerts);
3248             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3249                 item.second.RelayTo(pfrom);
3250         }
3251
3252         // Relay sync-checkpoint
3253         {
3254             LOCK(Checkpoints::cs_hashSyncCheckpoint);
3255             if (!Checkpoints::checkpointMessage.IsNull())
3256                 Checkpoints::checkpointMessage.RelayTo(pfrom);
3257         }
3258
3259         pfrom->fSuccessfullyConnected = true;
3260
3261         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());
3262
3263         cPeerBlockCounts.input(pfrom->nStartingHeight);
3264
3265         // ppcoin: ask for pending sync-checkpoint if any
3266         if (!IsInitialBlockDownload())
3267             Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3268     }
3269
3270
3271     else if (pfrom->nVersion == 0)
3272     {
3273         // Must have a version message before anything else
3274         pfrom->Misbehaving(1);
3275         return false;
3276     }
3277
3278
3279     else if (strCommand == "verack")
3280     {
3281         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3282     }
3283
3284
3285     else if (strCommand == "addr")
3286     {
3287         vector<CAddress> vAddr;
3288         vRecv >> vAddr;
3289
3290         // Don't want addr from older versions unless seeding
3291         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3292             return true;
3293         if (vAddr.size() > 1000)
3294         {
3295             pfrom->Misbehaving(20);
3296             return error("message addr size() = %" PRIszu "", vAddr.size());
3297         }
3298
3299         // Store the new addresses
3300         vector<CAddress> vAddrOk;
3301         int64_t nNow = GetAdjustedTime();
3302         int64_t nSince = nNow - 10 * 60;
3303         BOOST_FOREACH(CAddress& addr, vAddr)
3304         {
3305             if (fShutdown)
3306                 return true;
3307             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3308                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3309             pfrom->AddAddressKnown(addr);
3310             bool fReachable = IsReachable(addr);
3311             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3312             {
3313                 // Relay to a limited number of other nodes
3314                 {
3315                     LOCK(cs_vNodes);
3316                     // Use deterministic randomness to send to the same nodes for 24 hours
3317                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3318                     static uint256 hashSalt;
3319                     if (hashSalt == 0)
3320                         hashSalt = GetRandHash();
3321                     uint64_t hashAddr = addr.GetHash();
3322                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3323                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3324                     multimap<uint256, CNode*> mapMix;
3325                     BOOST_FOREACH(CNode* pnode, vNodes)
3326                     {
3327                         if (pnode->nVersion < CADDR_TIME_VERSION)
3328                             continue;
3329                         unsigned int nPointer;
3330                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3331                         uint256 hashKey = hashRand ^ nPointer;
3332                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3333                         mapMix.insert(make_pair(hashKey, pnode));
3334                     }
3335                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3336                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3337                         ((*mi).second)->PushAddress(addr);
3338                 }
3339             }
3340             // Do not store addresses outside our network
3341             if (fReachable)
3342                 vAddrOk.push_back(addr);
3343         }
3344         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3345         if (vAddr.size() < 1000)
3346             pfrom->fGetAddr = false;
3347         if (pfrom->fOneShot)
3348             pfrom->fDisconnect = true;
3349     }
3350
3351     else if (strCommand == "inv")
3352     {
3353         vector<CInv> vInv;
3354         vRecv >> vInv;
3355         if (vInv.size() > MAX_INV_SZ)
3356         {
3357             pfrom->Misbehaving(20);
3358             return error("message inv size() = %" PRIszu "", vInv.size());
3359         }
3360
3361         // find last block in inv vector
3362         unsigned int nLastBlock = (unsigned int)(-1);
3363         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3364             if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3365                 nLastBlock = vInv.size() - 1 - nInv;
3366                 break;
3367             }
3368         }
3369         CTxDB txdb("r");
3370         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3371         {
3372             const CInv &inv = vInv[nInv];
3373
3374             if (fShutdown)
3375                 return true;
3376             pfrom->AddInventoryKnown(inv);
3377
3378             bool fAlreadyHave = AlreadyHave(txdb, inv);
3379             if (fDebug)
3380                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3381
3382             if (!fAlreadyHave)
3383                 pfrom->AskFor(inv);
3384             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3385                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3386             } else if (nInv == nLastBlock) {
3387                 // In case we are on a very long side-chain, it is possible that we already have
3388                 // the last block in an inv bundle sent in response to getblocks. Try to detect
3389                 // this situation and push another getblocks to continue.
3390                 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3391                 if (fDebug)
3392                     printf("force request: %s\n", inv.ToString().c_str());
3393             }
3394
3395             // Track requests for our stuff
3396             Inventory(inv.hash);
3397         }
3398     }
3399
3400
3401     else if (strCommand == "getdata")
3402     {
3403         vector<CInv> vInv;
3404         vRecv >> vInv;
3405         if (vInv.size() > MAX_INV_SZ)
3406         {
3407             pfrom->Misbehaving(20);
3408             return error("message getdata size() = %" PRIszu "", vInv.size());
3409         }
3410
3411         if (fDebugNet || (vInv.size() != 1))
3412             printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3413
3414         BOOST_FOREACH(const CInv& inv, vInv)
3415         {
3416             if (fShutdown)
3417                 return true;
3418             if (fDebugNet || (vInv.size() == 1))
3419                 printf("received getdata for: %s\n", inv.ToString().c_str());
3420
3421             if (inv.type == MSG_BLOCK)
3422             {
3423                 // Send block from disk
3424                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3425                 if (mi != mapBlockIndex.end())
3426                 {
3427                     CBlock block;
3428                     block.ReadFromDisk((*mi).second);
3429                     pfrom->PushMessage("block", block);
3430
3431                     // Trigger them to send a getblocks request for the next batch of inventory
3432                     if (inv.hash == pfrom->hashContinue)
3433                     {
3434                         // ppcoin: send latest proof-of-work block to allow the
3435                         // download node to accept as orphan (proof-of-stake 
3436                         // block might be rejected by stake connection check)
3437                         vector<CInv> vInv;
3438                         vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3439                         pfrom->PushMessage("inv", vInv);
3440                         pfrom->hashContinue = 0;
3441                     }
3442                 }
3443             }
3444             else if (inv.IsKnownType())
3445             {
3446                 // Send stream from relay memory
3447                 bool pushed = false;
3448                 {
3449                     LOCK(cs_mapRelay);
3450                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3451                     if (mi != mapRelay.end()) {
3452                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3453                         pushed = true;
3454                     }
3455                 }
3456                 if (!pushed && inv.type == MSG_TX) {
3457                     LOCK(mempool.cs);
3458                     if (mempool.exists(inv.hash)) {
3459                         CTransaction tx = mempool.lookup(inv.hash);
3460                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3461                         ss.reserve(1000);
3462                         ss << tx;
3463                         pfrom->PushMessage("tx", ss);
3464                     }
3465                 }
3466             }
3467
3468             // Track requests for our stuff
3469             Inventory(inv.hash);
3470         }
3471     }
3472
3473
3474     else if (strCommand == "getblocks")
3475     {
3476         CBlockLocator locator;
3477         uint256 hashStop;
3478         vRecv >> locator >> hashStop;
3479
3480         // Find the last block the caller has in the main chain
3481         CBlockIndex* pindex = locator.GetBlockIndex();
3482
3483         // Send the rest of the chain
3484         if (pindex)
3485             pindex = pindex->pnext;
3486         int nLimit = 500;
3487         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3488         for (; pindex; pindex = pindex->pnext)
3489         {
3490             if (pindex->GetBlockHash() == hashStop)
3491             {
3492                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3493                 // ppcoin: tell downloading node about the latest block if it's
3494                 // without risk being rejected due to stake connection check
3495                 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3496                     pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3497                 break;
3498             }
3499             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3500             if (--nLimit <= 0)
3501             {
3502                 // When this block is requested, we'll send an inv that'll make them
3503                 // getblocks the next batch of inventory.
3504                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3505                 pfrom->hashContinue = pindex->GetBlockHash();
3506                 break;
3507             }
3508         }
3509     }
3510     else if (strCommand == "checkpoint")
3511     {
3512         CSyncCheckpoint checkpoint;
3513         vRecv >> checkpoint;
3514
3515         if (checkpoint.ProcessSyncCheckpoint(pfrom))
3516         {
3517             // Relay
3518             pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3519             LOCK(cs_vNodes);
3520             BOOST_FOREACH(CNode* pnode, vNodes)
3521                 checkpoint.RelayTo(pnode);
3522         }
3523     }
3524
3525     else if (strCommand == "getheaders")
3526     {
3527         CBlockLocator locator;
3528         uint256 hashStop;
3529         vRecv >> locator >> hashStop;
3530
3531         CBlockIndex* pindex = NULL;
3532         if (locator.IsNull())
3533         {
3534             // If locator is null, return the hashStop block
3535             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3536             if (mi == mapBlockIndex.end())
3537                 return true;
3538             pindex = (*mi).second;
3539         }
3540         else
3541         {
3542             // Find the last block the caller has in the main chain
3543             pindex = locator.GetBlockIndex();
3544             if (pindex)
3545                 pindex = pindex->pnext;
3546         }
3547
3548         vector<CBlock> vHeaders;
3549         int nLimit = 2000;
3550         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3551         for (; pindex; pindex = pindex->pnext)
3552         {
3553             vHeaders.push_back(pindex->GetBlockHeader());
3554             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3555                 break;
3556         }
3557         pfrom->PushMessage("headers", vHeaders);
3558     }
3559
3560
3561     else if (strCommand == "tx")
3562     {
3563         vector<uint256> vWorkQueue;
3564         vector<uint256> vEraseQueue;
3565         CDataStream vMsg(vRecv);
3566         CTxDB txdb("r");
3567         CTransaction tx;
3568         vRecv >> tx;
3569
3570         CInv inv(MSG_TX, tx.GetHash());
3571         pfrom->AddInventoryKnown(inv);
3572
3573         bool fMissingInputs = false;
3574         if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3575         {
3576             SyncWithWallets(tx, NULL, true);
3577             RelayTransaction(tx, inv.hash);
3578             mapAlreadyAskedFor.erase(inv);
3579             vWorkQueue.push_back(inv.hash);
3580             vEraseQueue.push_back(inv.hash);
3581
3582             // Recursively process any orphan transactions that depended on this one
3583             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3584             {
3585                 uint256 hashPrev = vWorkQueue[i];
3586                 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3587                      mi != mapOrphanTransactionsByPrev[hashPrev].end();
3588                      ++mi)
3589                 {
3590                     const uint256& orphanTxHash = *mi;
3591                     CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3592                     bool fMissingInputs2 = false;
3593
3594                     if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3595                     {
3596                         printf("   accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3597                         SyncWithWallets(tx, NULL, true);
3598                         RelayTransaction(orphanTx, orphanTxHash);
3599                         mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3600                         vWorkQueue.push_back(orphanTxHash);
3601                         vEraseQueue.push_back(orphanTxHash);
3602                     }
3603                     else if (!fMissingInputs2)
3604                     {
3605                         // invalid orphan
3606                         vEraseQueue.push_back(orphanTxHash);
3607                         printf("   removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3608                     }
3609                 }
3610             }
3611
3612             BOOST_FOREACH(uint256 hash, vEraseQueue)
3613                 EraseOrphanTx(hash);
3614         }
3615         else if (fMissingInputs)
3616         {
3617             AddOrphanTx(tx);
3618
3619             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3620             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3621             if (nEvicted > 0)
3622                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3623         }
3624         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3625     }
3626
3627
3628     else if (strCommand == "block")
3629     {
3630         CBlock block;
3631         vRecv >> block;
3632         uint256 hashBlock = block.GetHash();
3633
3634         printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3635         // block.print();
3636
3637         CInv inv(MSG_BLOCK, hashBlock);
3638         pfrom->AddInventoryKnown(inv);
3639
3640         if (ProcessBlock(pfrom, &block))
3641             mapAlreadyAskedFor.erase(inv);
3642         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3643     }
3644
3645
3646     else if (strCommand == "getaddr")
3647     {
3648         // Don't return addresses older than nCutOff timestamp
3649         int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3650         pfrom->vAddrToSend.clear();
3651         vector<CAddress> vAddr = addrman.GetAddr();
3652         BOOST_FOREACH(const CAddress &addr, vAddr)
3653             if(addr.nTime > nCutOff)
3654                 pfrom->PushAddress(addr);
3655     }
3656
3657
3658     else if (strCommand == "mempool")
3659     {
3660         std::vector<uint256> vtxid;
3661         mempool.queryHashes(vtxid);
3662         vector<CInv> vInv;
3663         for (unsigned int i = 0; i < vtxid.size(); i++) {
3664             CInv inv(MSG_TX, vtxid[i]);
3665             vInv.push_back(inv);
3666             if (i == (MAX_INV_SZ - 1))
3667                     break;
3668         }
3669         if (vInv.size() > 0)
3670             pfrom->PushMessage("inv", vInv);
3671     }
3672
3673
3674     else if (strCommand == "checkorder")
3675     {
3676         uint256 hashReply;
3677         vRecv >> hashReply;
3678
3679         if (!GetBoolArg("-allowreceivebyip"))
3680         {
3681             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3682             return true;
3683         }
3684
3685         CWalletTx order;
3686         vRecv >> order;
3687
3688         /// we have a chance to check the order here
3689
3690         // Keep giving the same key to the same ip until they use it
3691         if (!mapReuseKey.count(pfrom->addr))
3692             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3693
3694         // Send back approval of order and pubkey to use
3695         CScript scriptPubKey;
3696         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3697         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3698     }
3699
3700
3701     else if (strCommand == "reply")
3702     {
3703         uint256 hashReply;
3704         vRecv >> hashReply;
3705
3706         CRequestTracker tracker;
3707         {
3708             LOCK(pfrom->cs_mapRequests);
3709             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3710             if (mi != pfrom->mapRequests.end())
3711             {
3712                 tracker = (*mi).second;
3713                 pfrom->mapRequests.erase(mi);
3714             }
3715         }
3716         if (!tracker.IsNull())
3717             tracker.fn(tracker.param1, vRecv);
3718     }
3719
3720
3721     else if (strCommand == "ping")
3722     {
3723         if (pfrom->nVersion > BIP0031_VERSION)
3724         {
3725             uint64_t nonce = 0;
3726             vRecv >> nonce;
3727             // Echo the message back with the nonce. This allows for two useful features:
3728             //
3729             // 1) A remote node can quickly check if the connection is operational
3730             // 2) Remote nodes can measure the latency of the network thread. If this node
3731             //    is overloaded it won't respond to pings quickly and the remote node can
3732             //    avoid sending us more work, like chain download requests.
3733             //
3734             // The nonce stops the remote getting confused between different pings: without
3735             // it, if the remote node sends a ping once per second and this node takes 5
3736             // seconds to respond to each, the 5th ping the remote sends would appear to
3737             // return very quickly.
3738             pfrom->PushMessage("pong", nonce);
3739         }
3740     }
3741
3742
3743     else if (strCommand == "alert")
3744     {
3745         CAlert alert;
3746         vRecv >> alert;
3747
3748         uint256 alertHash = alert.GetHash();
3749         if (pfrom->setKnown.count(alertHash) == 0)
3750         {
3751             if (alert.ProcessAlert())
3752             {
3753                 // Relay
3754                 pfrom->setKnown.insert(alertHash);
3755                 {
3756                     LOCK(cs_vNodes);
3757                     BOOST_FOREACH(CNode* pnode, vNodes)
3758                         alert.RelayTo(pnode);
3759                 }
3760             }
3761             else {
3762                 // Small DoS penalty so peers that send us lots of
3763                 // duplicate/expired/invalid-signature/whatever alerts
3764                 // eventually get banned.
3765                 // This isn't a Misbehaving(100) (immediate ban) because the
3766                 // peer might be an older or different implementation with
3767                 // a different signature key, etc.
3768                 pfrom->Misbehaving(10);
3769             }
3770         }
3771     }
3772
3773
3774     else
3775     {
3776         // Ignore unknown commands for extensibility
3777     }
3778
3779
3780     // Update the last seen time for this node's address
3781     if (pfrom->fNetworkNode)
3782         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3783             AddressCurrentlyConnected(pfrom->addr);
3784
3785
3786     return true;
3787 }
3788
3789 bool ProcessMessages(CNode* pfrom)
3790 {
3791     CDataStream& vRecv = pfrom->vRecv;
3792     if (vRecv.empty())
3793         return true;
3794     //if (fDebug)
3795     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
3796
3797     //
3798     // Message format
3799     //  (4) message start
3800     //  (12) command
3801     //  (4) size
3802     //  (4) checksum
3803     //  (x) data
3804     //
3805
3806     while (true)
3807     {
3808         // Don't bother if send buffer is too full to respond anyway
3809         if (pfrom->vSend.size() >= SendBufferSize())
3810             break;
3811
3812         // Scan for message start
3813         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3814         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3815         if (vRecv.end() - pstart < nHeaderSize)
3816         {
3817             if ((int)vRecv.size() > nHeaderSize)
3818             {
3819                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3820                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3821             }
3822             break;
3823         }
3824         if (pstart - vRecv.begin() > 0)
3825             printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3826         vRecv.erase(vRecv.begin(), pstart);
3827
3828         // Read header
3829         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3830         CMessageHeader hdr;
3831         vRecv >> hdr;
3832         if (!hdr.IsValid())
3833         {
3834             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3835             continue;
3836         }
3837         string strCommand = hdr.GetCommand();
3838
3839         // Message size
3840         unsigned int nMessageSize = hdr.nMessageSize;
3841         if (nMessageSize > MAX_SIZE)
3842         {
3843             printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3844             continue;
3845         }
3846         if (nMessageSize > vRecv.size())
3847         {
3848             // Rewind and wait for rest of message
3849             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3850             break;
3851         }
3852
3853         // Checksum
3854         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3855         unsigned int nChecksum = 0;
3856         memcpy(&nChecksum, &hash, sizeof(nChecksum));
3857         if (nChecksum != hdr.nChecksum)
3858         {
3859             printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3860                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3861             continue;
3862         }
3863
3864         // Copy message to its own buffer
3865         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3866         vRecv.ignore(nMessageSize);
3867
3868         // Process message
3869         bool fRet = false;
3870         try
3871         {
3872             {
3873                 LOCK(cs_main);
3874                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3875             }
3876             if (fShutdown)
3877                 return true;
3878         }
3879         catch (std::ios_base::failure& e)
3880         {
3881             if (strstr(e.what(), "end of data"))
3882             {
3883                 // Allow exceptions from under-length message on vRecv
3884                 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());
3885             }
3886             else if (strstr(e.what(), "size too large"))
3887             {
3888                 // Allow exceptions from over-long size
3889                 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3890             }
3891             else
3892             {
3893                 PrintExceptionContinue(&e, "ProcessMessages()");
3894             }
3895         }
3896         catch (std::exception& e) {
3897             PrintExceptionContinue(&e, "ProcessMessages()");
3898         } catch (...) {
3899             PrintExceptionContinue(NULL, "ProcessMessages()");
3900         }
3901
3902         if (!fRet)
3903             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3904     }
3905
3906     vRecv.Compact();
3907     return true;
3908 }
3909
3910
3911 bool SendMessages(CNode* pto, bool fSendTrickle)
3912 {
3913     TRY_LOCK(cs_main, lockMain);
3914     if (lockMain) {
3915         // Don't send anything until we get their version message
3916         if (pto->nVersion == 0)
3917             return true;
3918
3919         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3920         // right now.
3921         if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3922             uint64_t nonce = 0;
3923             if (pto->nVersion > BIP0031_VERSION)
3924                 pto->PushMessage("ping", nonce);
3925             else
3926                 pto->PushMessage("ping");
3927         }
3928
3929         // Start block sync
3930         if (pto->fStartSync) {
3931             pto->fStartSync = false;
3932             pto->PushGetBlocks(pindexBest, uint256(0));
3933         }
3934
3935         // Resend wallet transactions that haven't gotten in a block yet
3936         ResendWalletTransactions();
3937
3938         // Address refresh broadcast
3939         static int64_t nLastRebroadcast;
3940         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > nBroadcastInterval))
3941         {
3942             {
3943                 LOCK(cs_vNodes);
3944                 BOOST_FOREACH(CNode* pnode, vNodes)
3945                 {
3946                     // Periodically clear setAddrKnown to allow refresh broadcasts
3947                     if (nLastRebroadcast)
3948                         pnode->setAddrKnown.clear();
3949
3950                     // Rebroadcast our address
3951                     if (!fNoListen)
3952                     {
3953                         CAddress addr = GetLocalAddress(&pnode->addr);
3954                         if (addr.IsRoutable())
3955                             pnode->PushAddress(addr);
3956                     }
3957                 }
3958             }
3959             nLastRebroadcast = GetTime();
3960         }
3961
3962         //
3963         // Message: addr
3964         //
3965         if (fSendTrickle)
3966         {
3967             vector<CAddress> vAddr;
3968             vAddr.reserve(pto->vAddrToSend.size());
3969             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3970             {
3971                 // returns true if wasn't already contained in the set
3972                 if (pto->setAddrKnown.insert(addr).second)
3973                 {
3974                     vAddr.push_back(addr);
3975                     // receiver rejects addr messages larger than 1000
3976                     if (vAddr.size() >= 1000)
3977                     {
3978                         pto->PushMessage("addr", vAddr);
3979                         vAddr.clear();
3980                     }
3981                 }
3982             }
3983             pto->vAddrToSend.clear();
3984             if (!vAddr.empty())
3985                 pto->PushMessage("addr", vAddr);
3986         }
3987
3988
3989         //
3990         // Message: inventory
3991         //
3992         vector<CInv> vInv;
3993         vector<CInv> vInvWait;
3994         {
3995             LOCK(pto->cs_inventory);
3996             vInv.reserve(pto->vInventoryToSend.size());
3997             vInvWait.reserve(pto->vInventoryToSend.size());
3998             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3999             {
4000                 if (pto->setInventoryKnown.count(inv))
4001                     continue;
4002
4003                 // trickle out tx inv to protect privacy
4004                 if (inv.type == MSG_TX && !fSendTrickle)
4005                 {
4006                     // 1/4 of tx invs blast to all immediately
4007                     static uint256 hashSalt;
4008                     if (hashSalt == 0)
4009                         hashSalt = GetRandHash();
4010                     uint256 hashRand = inv.hash ^ hashSalt;
4011                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4012                     bool fTrickleWait = ((hashRand & 3) != 0);
4013
4014                     // always trickle our own transactions
4015                     if (!fTrickleWait)
4016                     {
4017                         CWalletTx wtx;
4018                         if (GetTransaction(inv.hash, wtx))
4019                             if (wtx.fFromMe)
4020                                 fTrickleWait = true;
4021                     }
4022
4023                     if (fTrickleWait)
4024                     {
4025                         vInvWait.push_back(inv);
4026                         continue;
4027                     }
4028                 }
4029
4030                 // returns true if wasn't already contained in the set
4031                 if (pto->setInventoryKnown.insert(inv).second)
4032                 {
4033                     vInv.push_back(inv);
4034                     if (vInv.size() >= 1000)
4035                     {
4036                         pto->PushMessage("inv", vInv);
4037                         vInv.clear();
4038                     }
4039                 }
4040             }
4041             pto->vInventoryToSend = vInvWait;
4042         }
4043         if (!vInv.empty())
4044             pto->PushMessage("inv", vInv);
4045
4046
4047         //
4048         // Message: getdata
4049         //
4050         vector<CInv> vGetData;
4051         int64_t nNow = GetTime() * 1000000;
4052         CTxDB txdb("r");
4053         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4054         {
4055             const CInv& inv = (*pto->mapAskFor.begin()).second;
4056             if (!AlreadyHave(txdb, inv))
4057             {
4058                 if (fDebugNet)
4059                     printf("sending getdata: %s\n", inv.ToString().c_str());
4060                 vGetData.push_back(inv);
4061                 if (vGetData.size() >= 1000)
4062                 {
4063                     pto->PushMessage("getdata", vGetData);
4064                     vGetData.clear();
4065                 }
4066                 mapAlreadyAskedFor[inv] = nNow;
4067             }
4068             pto->mapAskFor.erase(pto->mapAskFor.begin());
4069         }
4070         if (!vGetData.empty())
4071             pto->PushMessage("getdata", vGetData);
4072
4073     }
4074     return true;
4075 }
4076
4077
4078 class CMainCleanup
4079 {
4080 public:
4081     CMainCleanup() {}
4082     ~CMainCleanup() {
4083         // block headers
4084         std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4085         for (; it1 != mapBlockIndex.end(); it1++)
4086             delete (*it1).second;
4087         mapBlockIndex.clear();
4088
4089         // orphan blocks
4090         std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4091         for (; it2 != mapOrphanBlocks.end(); it2++)
4092             delete (*it2).second;
4093         mapOrphanBlocks.clear();
4094
4095         // orphan transactions
4096     }
4097 } instance_of_cmaincleanup;