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