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