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