1271c1aa62d618b44effc1b9b8a68c07b8b67928
[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     if (fTestNet)
2800     {
2801         pchMessageStart[0] = 0xcd;
2802         pchMessageStart[1] = 0xf2;
2803         pchMessageStart[2] = 0xc0;
2804         pchMessageStart[3] = 0xef;
2805
2806         bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2807         nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2808         nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2809         nCoinbaseMaturity = 10; // test maturity is 10 blocks
2810         nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2811     }
2812
2813     //
2814     // Load block index
2815     //
2816     CTxDB txdb("cr+");
2817     if (!txdb.LoadBlockIndex())
2818         return false;
2819
2820     //
2821     // Init with genesis block
2822     //
2823     if (mapBlockIndex.empty())
2824     {
2825         if (!fAllowNew)
2826             return false;
2827
2828         // Genesis block
2829
2830         // MainNet:
2831
2832         //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2833         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2834         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2835         //    CTxOut(empty)
2836         //  vMerkleTree: 4cb33b3b6a
2837
2838         // TestNet:
2839
2840         //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2841         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2842         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2843         //    CTxOut(empty)
2844         //  vMerkleTree: 4cb33b3b6a
2845
2846         const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2847         CTransaction txNew;
2848         txNew.nTime = 1360105017;
2849         txNew.vin.resize(1);
2850         txNew.vout.resize(1);
2851         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2852         txNew.vout[0].SetEmpty();
2853         CBlock block;
2854         block.vtx.push_back(txNew);
2855         block.hashPrevBlock = 0;
2856         block.hashMerkleRoot = block.BuildMerkleTree();
2857         block.nVersion = 1;
2858         block.nTime    = 1360105017;
2859         block.nBits    = bnProofOfWorkLimit.GetCompact();
2860         block.nNonce   = !fTestNet ? 1575379 : 46534;
2861
2862         //// debug print
2863         assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2864         block.print();
2865         assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2866         assert(block.CheckBlock());
2867
2868         // Start new block file
2869         unsigned int nFile;
2870         unsigned int nBlockPos;
2871         if (!block.WriteToDisk(nFile, nBlockPos))
2872             return error("LoadBlockIndex() : writing genesis block to disk failed");
2873         if (!block.AddToBlockIndex(nFile, nBlockPos))
2874             return error("LoadBlockIndex() : genesis block not accepted");
2875
2876         // initialize synchronized checkpoint
2877         if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2878             return error("LoadBlockIndex() : failed to init sync checkpoint");
2879
2880         // upgrade time set to zero if txdb initialized
2881         {
2882             if (!txdb.WriteModifierUpgradeTime(0))
2883                 return error("LoadBlockIndex() : failed to init upgrade info");
2884             printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2885         }
2886     }
2887
2888     {
2889         CTxDB txdb("r+");
2890         string strPubKey = "";
2891         if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2892         {
2893             // write checkpoint master key to db
2894             txdb.TxnBegin();
2895             if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2896                 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2897             if (!txdb.TxnCommit())
2898                 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2899             if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2900                 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2901         }
2902
2903         // upgrade time set to zero if blocktreedb initialized
2904         if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2905         {
2906             if (nModifierUpgradeTime)
2907                 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2908             else
2909                 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2910         }
2911         else
2912         {
2913             nModifierUpgradeTime = GetTime();
2914             printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2915             if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2916                 return error("LoadBlockIndex() : failed to write upgrade info");
2917         }
2918
2919 #ifndef USE_LEVELDB
2920         txdb.Close();
2921 #endif
2922     }
2923
2924     return true;
2925 }
2926
2927
2928
2929 void PrintBlockTree()
2930 {
2931     // pre-compute tree structure
2932     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2933     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2934     {
2935         CBlockIndex* pindex = (*mi).second;
2936         mapNext[pindex->pprev].push_back(pindex);
2937         // test
2938         //while (rand() % 3 == 0)
2939         //    mapNext[pindex->pprev].push_back(pindex);
2940     }
2941
2942     vector<pair<int, CBlockIndex*> > vStack;
2943     vStack.push_back(make_pair(0, pindexGenesisBlock));
2944
2945     int nPrevCol = 0;
2946     while (!vStack.empty())
2947     {
2948         int nCol = vStack.back().first;
2949         CBlockIndex* pindex = vStack.back().second;
2950         vStack.pop_back();
2951
2952         // print split or gap
2953         if (nCol > nPrevCol)
2954         {
2955             for (int i = 0; i < nCol-1; i++)
2956                 printf("| ");
2957             printf("|\\\n");
2958         }
2959         else if (nCol < nPrevCol)
2960         {
2961             for (int i = 0; i < nCol; i++)
2962                 printf("| ");
2963             printf("|\n");
2964        }
2965         nPrevCol = nCol;
2966
2967         // print columns
2968         for (int i = 0; i < nCol; i++)
2969             printf("| ");
2970
2971         // print item
2972         CBlock block;
2973         block.ReadFromDisk(pindex);
2974         printf("%d (%u,%u) %s  %08x  %s  mint %7s  tx %"PRIszu"",
2975             pindex->nHeight,
2976             pindex->nFile,
2977             pindex->nBlockPos,
2978             block.GetHash().ToString().c_str(),
2979             block.nBits,
2980             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2981             FormatMoney(pindex->nMint).c_str(),
2982             block.vtx.size());
2983
2984         PrintWallets(block);
2985
2986         // put the main time-chain first
2987         vector<CBlockIndex*>& vNext = mapNext[pindex];
2988         for (unsigned int i = 0; i < vNext.size(); i++)
2989         {
2990             if (vNext[i]->pnext)
2991             {
2992                 swap(vNext[0], vNext[i]);
2993                 break;
2994             }
2995         }
2996
2997         // iterate children
2998         for (unsigned int i = 0; i < vNext.size(); i++)
2999             vStack.push_back(make_pair(nCol+i, vNext[i]));
3000     }
3001 }
3002
3003 bool LoadExternalBlockFile(FILE* fileIn)
3004 {
3005     int64 nStart = GetTimeMillis();
3006
3007     int nLoaded = 0;
3008     {
3009         LOCK(cs_main);
3010         try {
3011             CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3012             unsigned int nPos = 0;
3013             while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
3014             {
3015                 unsigned char pchData[65536];
3016                 do {
3017                     fseek(blkdat, nPos, SEEK_SET);
3018                     int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
3019                     if (nRead <= 8)
3020                     {
3021                         nPos = (unsigned int)-1;
3022                         break;
3023                     }
3024                     void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
3025                     if (nFind)
3026                     {
3027                         if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3028                         {
3029                             nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3030                             break;
3031                         }
3032                         nPos += ((unsigned char*)nFind - pchData) + 1;
3033                     }
3034                     else
3035                         nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3036                 } while(!fRequestShutdown);
3037                 if (nPos == (unsigned int)-1)
3038                     break;
3039                 fseek(blkdat, nPos, SEEK_SET);
3040                 unsigned int nSize;
3041                 blkdat >> nSize;
3042                 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3043                 {
3044                     CBlock block;
3045                     blkdat >> block;
3046                     if (ProcessBlock(NULL,&block))
3047                     {
3048                         nLoaded++;
3049                         nPos += 4 + nSize;
3050                     }
3051                 }
3052             }
3053         }
3054         catch (std::exception &e) {
3055             printf("%s() : Deserialize or I/O error caught during load\n",
3056                    BOOST_CURRENT_FUNCTION);
3057         }
3058     }
3059     printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3060     return nLoaded > 0;
3061 }
3062
3063 //////////////////////////////////////////////////////////////////////////////
3064 //
3065 // CAlert
3066 //
3067
3068 extern map<uint256, CAlert> mapAlerts;
3069 extern CCriticalSection cs_mapAlerts;
3070
3071 string GetWarnings(string strFor)
3072 {
3073     int nPriority = 0;
3074     string strStatusBar;
3075     string strRPC;
3076
3077     if (GetBoolArg("-testsafemode"))
3078         strRPC = "test";
3079
3080     // Misc warnings like out of disk space and clock is wrong
3081     if (strMiscWarning != "")
3082     {
3083         nPriority = 1000;
3084         strStatusBar = strMiscWarning;
3085     }
3086
3087     // if detected unmet upgrade requirement enter safe mode
3088     // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3089     if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3090     {
3091         nPriority = 5000;
3092         strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3093     }
3094
3095     // if detected invalid checkpoint enter safe mode
3096     if (Checkpoints::hashInvalidCheckpoint != 0)
3097     {
3098         nPriority = 3000;
3099         strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3100     }
3101
3102     // Alerts
3103     {
3104         LOCK(cs_mapAlerts);
3105         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3106         {
3107             const CAlert& alert = item.second;
3108             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3109             {
3110                 nPriority = alert.nPriority;
3111                 strStatusBar = alert.strStatusBar;
3112                 if (nPriority > 1000)
3113                     strRPC = strStatusBar;
3114             }
3115         }
3116     }
3117
3118     if (strFor == "statusbar")
3119         return strStatusBar;
3120     else if (strFor == "rpc")
3121         return strRPC;
3122     assert(!"GetWarnings() : invalid parameter");
3123     return "error";
3124 }
3125
3126
3127
3128
3129
3130
3131
3132
3133 //////////////////////////////////////////////////////////////////////////////
3134 //
3135 // Messages
3136 //
3137
3138
3139 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3140 {
3141     switch (inv.type)
3142     {
3143     case MSG_TX:
3144         {
3145         bool txInMap = false;
3146             {
3147             LOCK(mempool.cs);
3148             txInMap = (mempool.exists(inv.hash));
3149             }
3150         return txInMap ||
3151                mapOrphanTransactions.count(inv.hash) ||
3152                txdb.ContainsTx(inv.hash);
3153         }
3154
3155     case MSG_BLOCK:
3156         return mapBlockIndex.count(inv.hash) ||
3157                mapOrphanBlocks.count(inv.hash);
3158     }
3159     // Don't know what it is, just say we already got one
3160     return true;
3161 }
3162
3163
3164
3165
3166 // The message start string is designed to be unlikely to occur in normal data.
3167 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3168 // a large 4-byte int at any alignment.
3169 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3170
3171 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3172 {
3173     static map<CService, CPubKey> mapReuseKey;
3174     RandAddSeedPerfmon();
3175     if (fDebug)
3176         printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3177     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3178     {
3179         printf("dropmessagestest DROPPING RECV MESSAGE\n");
3180         return true;
3181     }
3182
3183     if (strCommand == "version")
3184     {
3185         // Each connection can only send one version message
3186         if (pfrom->nVersion != 0)
3187         {
3188             pfrom->Misbehaving(1);
3189             return false;
3190         }
3191
3192         int64 nTime;
3193         CAddress addrMe;
3194         CAddress addrFrom;
3195         uint64 nNonce = 1;
3196         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3197         if (pfrom->nVersion < MIN_PROTO_VERSION)
3198         {
3199             // Since February 20, 2012, the protocol is initiated at version 209,
3200             // and earlier versions are no longer supported
3201             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3202             pfrom->fDisconnect = true;
3203             return false;
3204         }
3205
3206         if (pfrom->nVersion == 10300)
3207             pfrom->nVersion = 300;
3208         if (!vRecv.empty())
3209             vRecv >> addrFrom >> nNonce;
3210         if (!vRecv.empty())
3211             vRecv >> pfrom->strSubVer;
3212         if (!vRecv.empty())
3213             vRecv >> pfrom->nStartingHeight;
3214
3215         if (pfrom->fInbound && addrMe.IsRoutable())
3216         {
3217             pfrom->addrLocal = addrMe;
3218             SeenLocal(addrMe);
3219         }
3220
3221         // Disconnect if we connected to ourself
3222         if (nNonce == nLocalHostNonce && nNonce > 1)
3223         {
3224             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3225             pfrom->fDisconnect = true;
3226             return true;
3227         }
3228
3229         if (pfrom->nVersion < 60010)
3230         {
3231             printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3232             pfrom->fDisconnect = true;
3233             return true;
3234         }
3235
3236         // record my external IP reported by peer
3237         if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3238             addrSeenByPeer = addrMe;
3239
3240         // Be shy and don't send version until we hear
3241         if (pfrom->fInbound)
3242             pfrom->PushVersion();
3243
3244         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3245
3246         AddTimeData(pfrom->addr, nTime);
3247
3248         // Change version
3249         pfrom->PushMessage("verack");
3250         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3251
3252         if (!pfrom->fInbound)
3253         {
3254             // Advertise our address
3255             if (!fNoListen && !IsInitialBlockDownload())
3256             {
3257                 CAddress addr = GetLocalAddress(&pfrom->addr);
3258                 if (addr.IsRoutable())
3259                     pfrom->PushAddress(addr);
3260             }
3261
3262             // Get recent addresses
3263             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3264             {
3265                 pfrom->PushMessage("getaddr");
3266                 pfrom->fGetAddr = true;
3267             }
3268             addrman.Good(pfrom->addr);
3269         } else {
3270             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3271             {
3272                 addrman.Add(addrFrom, addrFrom);
3273                 addrman.Good(addrFrom);
3274             }
3275         }
3276
3277         // Ask the first connected node for block updates
3278         static int nAskedForBlocks = 0;
3279         if (!pfrom->fClient && !pfrom->fOneShot &&
3280             (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3281             (pfrom->nVersion < NOBLKS_VERSION_START ||
3282              pfrom->nVersion >= NOBLKS_VERSION_END) &&
3283              (nAskedForBlocks < 1 || vNodes.size() <= 1))
3284         {
3285             nAskedForBlocks++;
3286             pfrom->PushGetBlocks(pindexBest, uint256(0));
3287         }
3288
3289         // Relay alerts
3290         {
3291             LOCK(cs_mapAlerts);
3292             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3293                 item.second.RelayTo(pfrom);
3294         }
3295
3296         // Relay sync-checkpoint
3297         {
3298             LOCK(Checkpoints::cs_hashSyncCheckpoint);
3299             if (!Checkpoints::checkpointMessage.IsNull())
3300                 Checkpoints::checkpointMessage.RelayTo(pfrom);
3301         }
3302
3303         pfrom->fSuccessfullyConnected = true;
3304
3305         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());
3306
3307         cPeerBlockCounts.input(pfrom->nStartingHeight);
3308
3309         // ppcoin: ask for pending sync-checkpoint if any
3310         if (!IsInitialBlockDownload())
3311             Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3312     }
3313
3314
3315     else if (pfrom->nVersion == 0)
3316     {
3317         // Must have a version message before anything else
3318         pfrom->Misbehaving(1);
3319         return false;
3320     }
3321
3322
3323     else if (strCommand == "verack")
3324     {
3325         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3326     }
3327
3328
3329     else if (strCommand == "addr")
3330     {
3331         vector<CAddress> vAddr;
3332         vRecv >> vAddr;
3333
3334         // Don't want addr from older versions unless seeding
3335         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3336             return true;
3337         if (vAddr.size() > 1000)
3338         {
3339             pfrom->Misbehaving(20);
3340             return error("message addr size() = %"PRIszu"", vAddr.size());
3341         }
3342
3343         // Store the new addresses
3344         vector<CAddress> vAddrOk;
3345         int64 nNow = GetAdjustedTime();
3346         int64 nSince = nNow - 10 * 60;
3347         BOOST_FOREACH(CAddress& addr, vAddr)
3348         {
3349             if (fShutdown)
3350                 return true;
3351             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3352                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3353             pfrom->AddAddressKnown(addr);
3354             bool fReachable = IsReachable(addr);
3355             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3356             {
3357                 // Relay to a limited number of other nodes
3358                 {
3359                     LOCK(cs_vNodes);
3360                     // Use deterministic randomness to send to the same nodes for 24 hours
3361                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3362                     static uint256 hashSalt;
3363                     if (hashSalt == 0)
3364                         hashSalt = GetRandHash();
3365                     uint64 hashAddr = addr.GetHash();
3366                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3367                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3368                     multimap<uint256, CNode*> mapMix;
3369                     BOOST_FOREACH(CNode* pnode, vNodes)
3370                     {
3371                         if (pnode->nVersion < CADDR_TIME_VERSION)
3372                             continue;
3373                         unsigned int nPointer;
3374                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3375                         uint256 hashKey = hashRand ^ nPointer;
3376                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3377                         mapMix.insert(make_pair(hashKey, pnode));
3378                     }
3379                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3380                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3381                         ((*mi).second)->PushAddress(addr);
3382                 }
3383             }
3384             // Do not store addresses outside our network
3385             if (fReachable)
3386                 vAddrOk.push_back(addr);
3387         }
3388         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3389         if (vAddr.size() < 1000)
3390             pfrom->fGetAddr = false;
3391         if (pfrom->fOneShot)
3392             pfrom->fDisconnect = true;
3393     }
3394
3395     else if (strCommand == "inv")
3396     {
3397         vector<CInv> vInv;
3398         vRecv >> vInv;
3399         if (vInv.size() > MAX_INV_SZ)
3400         {
3401             pfrom->Misbehaving(20);
3402             return error("message inv size() = %"PRIszu"", vInv.size());
3403         }
3404
3405         // find last block in inv vector
3406         unsigned int nLastBlock = (unsigned int)(-1);
3407         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3408             if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3409                 nLastBlock = vInv.size() - 1 - nInv;
3410                 break;
3411             }
3412         }
3413         CTxDB txdb("r");
3414         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3415         {
3416             const CInv &inv = vInv[nInv];
3417
3418             if (fShutdown)
3419                 return true;
3420             pfrom->AddInventoryKnown(inv);
3421
3422             bool fAlreadyHave = AlreadyHave(txdb, inv);
3423             if (fDebug)
3424                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3425
3426             if (!fAlreadyHave)
3427                 pfrom->AskFor(inv);
3428             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3429                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3430             } else if (nInv == nLastBlock) {
3431                 // In case we are on a very long side-chain, it is possible that we already have
3432                 // the last block in an inv bundle sent in response to getblocks. Try to detect
3433                 // this situation and push another getblocks to continue.
3434                 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3435                 if (fDebug)
3436                     printf("force request: %s\n", inv.ToString().c_str());
3437             }
3438
3439             // Track requests for our stuff
3440             Inventory(inv.hash);
3441         }
3442     }
3443
3444
3445     else if (strCommand == "getdata")
3446     {
3447         vector<CInv> vInv;
3448         vRecv >> vInv;
3449         if (vInv.size() > MAX_INV_SZ)
3450         {
3451             pfrom->Misbehaving(20);
3452             return error("message getdata size() = %"PRIszu"", vInv.size());
3453         }
3454
3455         if (fDebugNet || (vInv.size() != 1))
3456             printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3457
3458         BOOST_FOREACH(const CInv& inv, vInv)
3459         {
3460             if (fShutdown)
3461                 return true;
3462             if (fDebugNet || (vInv.size() == 1))
3463                 printf("received getdata for: %s\n", inv.ToString().c_str());
3464
3465             if (inv.type == MSG_BLOCK)
3466             {
3467                 // Send block from disk
3468                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3469                 if (mi != mapBlockIndex.end())
3470                 {
3471                     CBlock block;
3472                     block.ReadFromDisk((*mi).second);
3473                     pfrom->PushMessage("block", block);
3474
3475                     // Trigger them to send a getblocks request for the next batch of inventory
3476                     if (inv.hash == pfrom->hashContinue)
3477                     {
3478                         // ppcoin: send latest proof-of-work block to allow the
3479                         // download node to accept as orphan (proof-of-stake 
3480                         // block might be rejected by stake connection check)
3481                         vector<CInv> vInv;
3482                         vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3483                         pfrom->PushMessage("inv", vInv);
3484                         pfrom->hashContinue = 0;
3485                     }
3486                 }
3487             }
3488             else if (inv.IsKnownType())
3489             {
3490                 // Send stream from relay memory
3491                 bool pushed = false;
3492                 {
3493                     LOCK(cs_mapRelay);
3494                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3495                     if (mi != mapRelay.end()) {
3496                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3497                         pushed = true;
3498                     }
3499                 }
3500                 if (!pushed && inv.type == MSG_TX) {
3501                     LOCK(mempool.cs);
3502                     if (mempool.exists(inv.hash)) {
3503                         CTransaction tx = mempool.lookup(inv.hash);
3504                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3505                         ss.reserve(1000);
3506                         ss << tx;
3507                         pfrom->PushMessage("tx", ss);
3508                     }
3509                 }
3510             }
3511
3512             // Track requests for our stuff
3513             Inventory(inv.hash);
3514         }
3515     }
3516
3517
3518     else if (strCommand == "getblocks")
3519     {
3520         CBlockLocator locator;
3521         uint256 hashStop;
3522         vRecv >> locator >> hashStop;
3523
3524         // Find the last block the caller has in the main chain
3525         CBlockIndex* pindex = locator.GetBlockIndex();
3526
3527         // Send the rest of the chain
3528         if (pindex)
3529             pindex = pindex->pnext;
3530         int nLimit = 500;
3531         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3532         for (; pindex; pindex = pindex->pnext)
3533         {
3534             if (pindex->GetBlockHash() == hashStop)
3535             {
3536                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3537                 // ppcoin: tell downloading node about the latest block if it's
3538                 // without risk being rejected due to stake connection check
3539                 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3540                     pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3541                 break;
3542             }
3543             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3544             if (--nLimit <= 0)
3545             {
3546                 // When this block is requested, we'll send an inv that'll make them
3547                 // getblocks the next batch of inventory.
3548                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3549                 pfrom->hashContinue = pindex->GetBlockHash();
3550                 break;
3551             }
3552         }
3553     }
3554     else if (strCommand == "checkpoint")
3555     {
3556         CSyncCheckpoint checkpoint;
3557         vRecv >> checkpoint;
3558
3559         if (checkpoint.ProcessSyncCheckpoint(pfrom))
3560         {
3561             // Relay
3562             pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3563             LOCK(cs_vNodes);
3564             BOOST_FOREACH(CNode* pnode, vNodes)
3565                 checkpoint.RelayTo(pnode);
3566         }
3567     }
3568
3569     else if (strCommand == "getheaders")
3570     {
3571         CBlockLocator locator;
3572         uint256 hashStop;
3573         vRecv >> locator >> hashStop;
3574
3575         CBlockIndex* pindex = NULL;
3576         if (locator.IsNull())
3577         {
3578             // If locator is null, return the hashStop block
3579             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3580             if (mi == mapBlockIndex.end())
3581                 return true;
3582             pindex = (*mi).second;
3583         }
3584         else
3585         {
3586             // Find the last block the caller has in the main chain
3587             pindex = locator.GetBlockIndex();
3588             if (pindex)
3589                 pindex = pindex->pnext;
3590         }
3591
3592         vector<CBlock> vHeaders;
3593         int nLimit = 2000;
3594         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3595         for (; pindex; pindex = pindex->pnext)
3596         {
3597             vHeaders.push_back(pindex->GetBlockHeader());
3598             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3599                 break;
3600         }
3601         pfrom->PushMessage("headers", vHeaders);
3602     }
3603
3604
3605     else if (strCommand == "tx")
3606     {
3607         vector<uint256> vWorkQueue;
3608         vector<uint256> vEraseQueue;
3609         CDataStream vMsg(vRecv);
3610         CTxDB txdb("r");
3611         CTransaction tx;
3612         vRecv >> tx;
3613
3614         CInv inv(MSG_TX, tx.GetHash());
3615         pfrom->AddInventoryKnown(inv);
3616
3617         bool fMissingInputs = false;
3618         if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3619         {
3620             SyncWithWallets(tx, NULL, true);
3621             RelayTransaction(tx, inv.hash);
3622             mapAlreadyAskedFor.erase(inv);
3623             vWorkQueue.push_back(inv.hash);
3624             vEraseQueue.push_back(inv.hash);
3625
3626             // Recursively process any orphan transactions that depended on this one
3627             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3628             {
3629                 uint256 hashPrev = vWorkQueue[i];
3630                 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3631                      mi != mapOrphanTransactionsByPrev[hashPrev].end();
3632                      ++mi)
3633                 {
3634                     const uint256& orphanTxHash = *mi;
3635                     CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3636                     bool fMissingInputs2 = false;
3637
3638                     if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3639                     {
3640                         printf("   accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3641                         SyncWithWallets(tx, NULL, true);
3642                         RelayTransaction(orphanTx, orphanTxHash);
3643                         mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3644                         vWorkQueue.push_back(orphanTxHash);
3645                         vEraseQueue.push_back(orphanTxHash);
3646                     }
3647                     else if (!fMissingInputs2)
3648                     {
3649                         // invalid orphan
3650                         vEraseQueue.push_back(orphanTxHash);
3651                         printf("   removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3652                     }
3653                 }
3654             }
3655
3656             BOOST_FOREACH(uint256 hash, vEraseQueue)
3657                 EraseOrphanTx(hash);
3658         }
3659         else if (fMissingInputs)
3660         {
3661             AddOrphanTx(tx);
3662
3663             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3664             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3665             if (nEvicted > 0)
3666                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3667         }
3668         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3669     }
3670
3671
3672     else if (strCommand == "block")
3673     {
3674         CBlock block;
3675         vRecv >> block;
3676         uint256 hashBlock = block.GetHash();
3677
3678         printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3679         // block.print();
3680
3681         CInv inv(MSG_BLOCK, hashBlock);
3682         pfrom->AddInventoryKnown(inv);
3683
3684         if (ProcessBlock(pfrom, &block))
3685             mapAlreadyAskedFor.erase(inv);
3686         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3687     }
3688
3689
3690     else if (strCommand == "getaddr")
3691     {
3692         // Don't return addresses older than nCutOff timestamp
3693         int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3694         pfrom->vAddrToSend.clear();
3695         vector<CAddress> vAddr = addrman.GetAddr();
3696         BOOST_FOREACH(const CAddress &addr, vAddr)
3697             if(addr.nTime > nCutOff)
3698                 pfrom->PushAddress(addr);
3699     }
3700
3701
3702     else if (strCommand == "mempool")
3703     {
3704         std::vector<uint256> vtxid;
3705         mempool.queryHashes(vtxid);
3706         vector<CInv> vInv;
3707         for (unsigned int i = 0; i < vtxid.size(); i++) {
3708             CInv inv(MSG_TX, vtxid[i]);
3709             vInv.push_back(inv);
3710             if (i == (MAX_INV_SZ - 1))
3711                     break;
3712         }
3713         if (vInv.size() > 0)
3714             pfrom->PushMessage("inv", vInv);
3715     }
3716
3717
3718     else if (strCommand == "checkorder")
3719     {
3720         uint256 hashReply;
3721         vRecv >> hashReply;
3722
3723         if (!GetBoolArg("-allowreceivebyip"))
3724         {
3725             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3726             return true;
3727         }
3728
3729         CWalletTx order;
3730         vRecv >> order;
3731
3732         /// we have a chance to check the order here
3733
3734         // Keep giving the same key to the same ip until they use it
3735         if (!mapReuseKey.count(pfrom->addr))
3736             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3737
3738         // Send back approval of order and pubkey to use
3739         CScript scriptPubKey;
3740         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3741         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3742     }
3743
3744
3745     else if (strCommand == "reply")
3746     {
3747         uint256 hashReply;
3748         vRecv >> hashReply;
3749
3750         CRequestTracker tracker;
3751         {
3752             LOCK(pfrom->cs_mapRequests);
3753             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3754             if (mi != pfrom->mapRequests.end())
3755             {
3756                 tracker = (*mi).second;
3757                 pfrom->mapRequests.erase(mi);
3758             }
3759         }
3760         if (!tracker.IsNull())
3761             tracker.fn(tracker.param1, vRecv);
3762     }
3763
3764
3765     else if (strCommand == "ping")
3766     {
3767         if (pfrom->nVersion > BIP0031_VERSION)
3768         {
3769             uint64 nonce = 0;
3770             vRecv >> nonce;
3771             // Echo the message back with the nonce. This allows for two useful features:
3772             //
3773             // 1) A remote node can quickly check if the connection is operational
3774             // 2) Remote nodes can measure the latency of the network thread. If this node
3775             //    is overloaded it won't respond to pings quickly and the remote node can
3776             //    avoid sending us more work, like chain download requests.
3777             //
3778             // The nonce stops the remote getting confused between different pings: without
3779             // it, if the remote node sends a ping once per second and this node takes 5
3780             // seconds to respond to each, the 5th ping the remote sends would appear to
3781             // return very quickly.
3782             pfrom->PushMessage("pong", nonce);
3783         }
3784     }
3785
3786
3787     else if (strCommand == "alert")
3788     {
3789         CAlert alert;
3790         vRecv >> alert;
3791
3792         uint256 alertHash = alert.GetHash();
3793         if (pfrom->setKnown.count(alertHash) == 0)
3794         {
3795             if (alert.ProcessAlert())
3796             {
3797                 // Relay
3798                 pfrom->setKnown.insert(alertHash);
3799                 {
3800                     LOCK(cs_vNodes);
3801                     BOOST_FOREACH(CNode* pnode, vNodes)
3802                         alert.RelayTo(pnode);
3803                 }
3804             }
3805             else {
3806                 // Small DoS penalty so peers that send us lots of
3807                 // duplicate/expired/invalid-signature/whatever alerts
3808                 // eventually get banned.
3809                 // This isn't a Misbehaving(100) (immediate ban) because the
3810                 // peer might be an older or different implementation with
3811                 // a different signature key, etc.
3812                 pfrom->Misbehaving(10);
3813             }
3814         }
3815     }
3816
3817
3818     else
3819     {
3820         // Ignore unknown commands for extensibility
3821     }
3822
3823
3824     // Update the last seen time for this node's address
3825     if (pfrom->fNetworkNode)
3826         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3827             AddressCurrentlyConnected(pfrom->addr);
3828
3829
3830     return true;
3831 }
3832
3833 bool ProcessMessages(CNode* pfrom)
3834 {
3835     CDataStream& vRecv = pfrom->vRecv;
3836     if (vRecv.empty())
3837         return true;
3838     //if (fDebug)
3839     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
3840
3841     //
3842     // Message format
3843     //  (4) message start
3844     //  (12) command
3845     //  (4) size
3846     //  (4) checksum
3847     //  (x) data
3848     //
3849
3850     while (true)
3851     {
3852         // Don't bother if send buffer is too full to respond anyway
3853         if (pfrom->vSend.size() >= SendBufferSize())
3854             break;
3855
3856         // Scan for message start
3857         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3858         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3859         if (vRecv.end() - pstart < nHeaderSize)
3860         {
3861             if ((int)vRecv.size() > nHeaderSize)
3862             {
3863                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3864                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3865             }
3866             break;
3867         }
3868         if (pstart - vRecv.begin() > 0)
3869             printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3870         vRecv.erase(vRecv.begin(), pstart);
3871
3872         // Read header
3873         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3874         CMessageHeader hdr;
3875         vRecv >> hdr;
3876         if (!hdr.IsValid())
3877         {
3878             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3879             continue;
3880         }
3881         string strCommand = hdr.GetCommand();
3882
3883         // Message size
3884         unsigned int nMessageSize = hdr.nMessageSize;
3885         if (nMessageSize > MAX_SIZE)
3886         {
3887             printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3888             continue;
3889         }
3890         if (nMessageSize > vRecv.size())
3891         {
3892             // Rewind and wait for rest of message
3893             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3894             break;
3895         }
3896
3897         // Checksum
3898         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3899         unsigned int nChecksum = 0;
3900         memcpy(&nChecksum, &hash, sizeof(nChecksum));
3901         if (nChecksum != hdr.nChecksum)
3902         {
3903             printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3904                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3905             continue;
3906         }
3907
3908         // Copy message to its own buffer
3909         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3910         vRecv.ignore(nMessageSize);
3911
3912         // Process message
3913         bool fRet = false;
3914         try
3915         {
3916             {
3917                 LOCK(cs_main);
3918                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3919             }
3920             if (fShutdown)
3921                 return true;
3922         }
3923         catch (std::ios_base::failure& e)
3924         {
3925             if (strstr(e.what(), "end of data"))
3926             {
3927                 // Allow exceptions from under-length message on vRecv
3928                 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());
3929             }
3930             else if (strstr(e.what(), "size too large"))
3931             {
3932                 // Allow exceptions from over-long size
3933                 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3934             }
3935             else
3936             {
3937                 PrintExceptionContinue(&e, "ProcessMessages()");
3938             }
3939         }
3940         catch (std::exception& e) {
3941             PrintExceptionContinue(&e, "ProcessMessages()");
3942         } catch (...) {
3943             PrintExceptionContinue(NULL, "ProcessMessages()");
3944         }
3945
3946         if (!fRet)
3947             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3948     }
3949
3950     vRecv.Compact();
3951     return true;
3952 }
3953
3954
3955 bool SendMessages(CNode* pto, bool fSendTrickle)
3956 {
3957     TRY_LOCK(cs_main, lockMain);
3958     if (lockMain) {
3959         // Don't send anything until we get their version message
3960         if (pto->nVersion == 0)
3961             return true;
3962
3963         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3964         // right now.
3965         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3966             uint64 nonce = 0;
3967             if (pto->nVersion > BIP0031_VERSION)
3968                 pto->PushMessage("ping", nonce);
3969             else
3970                 pto->PushMessage("ping");
3971         }
3972
3973         // Start block sync
3974         if (pto->fStartSync) {
3975             pto->fStartSync = false;
3976             pto->PushGetBlocks(pindexBest, uint256(0));
3977         }
3978
3979         // Resend wallet transactions that haven't gotten in a block yet
3980         ResendWalletTransactions();
3981
3982         // Address refresh broadcast
3983         static int64 nLastRebroadcast;
3984         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3985         {
3986             {
3987                 LOCK(cs_vNodes);
3988                 BOOST_FOREACH(CNode* pnode, vNodes)
3989                 {
3990                     // Periodically clear setAddrKnown to allow refresh broadcasts
3991                     if (nLastRebroadcast)
3992                         pnode->setAddrKnown.clear();
3993
3994                     // Rebroadcast our address
3995                     if (!fNoListen)
3996                     {
3997                         CAddress addr = GetLocalAddress(&pnode->addr);
3998                         if (addr.IsRoutable())
3999                             pnode->PushAddress(addr);
4000                     }
4001                 }
4002             }
4003             nLastRebroadcast = GetTime();
4004         }
4005
4006         //
4007         // Message: addr
4008         //
4009         if (fSendTrickle)
4010         {
4011             vector<CAddress> vAddr;
4012             vAddr.reserve(pto->vAddrToSend.size());
4013             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4014             {
4015                 // returns true if wasn't already contained in the set
4016                 if (pto->setAddrKnown.insert(addr).second)
4017                 {
4018                     vAddr.push_back(addr);
4019                     // receiver rejects addr messages larger than 1000
4020                     if (vAddr.size() >= 1000)
4021                     {
4022                         pto->PushMessage("addr", vAddr);
4023                         vAddr.clear();
4024                     }
4025                 }
4026             }
4027             pto->vAddrToSend.clear();
4028             if (!vAddr.empty())
4029                 pto->PushMessage("addr", vAddr);
4030         }
4031
4032
4033         //
4034         // Message: inventory
4035         //
4036         vector<CInv> vInv;
4037         vector<CInv> vInvWait;
4038         {
4039             LOCK(pto->cs_inventory);
4040             vInv.reserve(pto->vInventoryToSend.size());
4041             vInvWait.reserve(pto->vInventoryToSend.size());
4042             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4043             {
4044                 if (pto->setInventoryKnown.count(inv))
4045                     continue;
4046
4047                 // trickle out tx inv to protect privacy
4048                 if (inv.type == MSG_TX && !fSendTrickle)
4049                 {
4050                     // 1/4 of tx invs blast to all immediately
4051                     static uint256 hashSalt;
4052                     if (hashSalt == 0)
4053                         hashSalt = GetRandHash();
4054                     uint256 hashRand = inv.hash ^ hashSalt;
4055                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
4056                     bool fTrickleWait = ((hashRand & 3) != 0);
4057
4058                     // always trickle our own transactions
4059                     if (!fTrickleWait)
4060                     {
4061                         CWalletTx wtx;
4062                         if (GetTransaction(inv.hash, wtx))
4063                             if (wtx.fFromMe)
4064                                 fTrickleWait = true;
4065                     }
4066
4067                     if (fTrickleWait)
4068                     {
4069                         vInvWait.push_back(inv);
4070                         continue;
4071                     }
4072                 }
4073
4074                 // returns true if wasn't already contained in the set
4075                 if (pto->setInventoryKnown.insert(inv).second)
4076                 {
4077                     vInv.push_back(inv);
4078                     if (vInv.size() >= 1000)
4079                     {
4080                         pto->PushMessage("inv", vInv);
4081                         vInv.clear();
4082                     }
4083                 }
4084             }
4085             pto->vInventoryToSend = vInvWait;
4086         }
4087         if (!vInv.empty())
4088             pto->PushMessage("inv", vInv);
4089
4090
4091         //
4092         // Message: getdata
4093         //
4094         vector<CInv> vGetData;
4095         int64 nNow = GetTime() * 1000000;
4096         CTxDB txdb("r");
4097         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4098         {
4099             const CInv& inv = (*pto->mapAskFor.begin()).second;
4100             if (!AlreadyHave(txdb, inv))
4101             {
4102                 if (fDebugNet)
4103                     printf("sending getdata: %s\n", inv.ToString().c_str());
4104                 vGetData.push_back(inv);
4105                 if (vGetData.size() >= 1000)
4106                 {
4107                     pto->PushMessage("getdata", vGetData);
4108                     vGetData.clear();
4109                 }
4110                 mapAlreadyAskedFor[inv] = nNow;
4111             }
4112             pto->mapAskFor.erase(pto->mapAskFor.begin());
4113         }
4114         if (!vGetData.empty())
4115             pto->PushMessage("getdata", vGetData);
4116
4117     }
4118     return true;
4119 }