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