Transaction hash caching
[novacoin.git] / src / main.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "alert.h"
7 #include "checkpoints.h"
8 #include "db.h"
9 #include "net.h"
10 #include "init.h"
11 #include "ui_interface.h"
12 #include "kernel.h"
13 #include "zerocoin/Zerocoin.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
17
18
19 using namespace std;
20 using namespace boost;
21
22 //
23 // Global state
24 //
25
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
28
29 CCriticalSection cs_main;
30
31 CTxMemPool mempool;
32 unsigned int nTransactionsUpdated = 0;
33
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 libzerocoin::Params* ZCParams;
37
38 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
39 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
40 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125  proof of stake difficulty
41 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
42 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43
44 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
45
46 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
47 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
48 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
49 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
50
51 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
53 int nBestHeight = -1;
54
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
57
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64 nTimeBestReceived = 0;
61
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
63
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
68
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
71
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
74
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
76
77 // Settings
78 int64 nTransactionFee = MIN_TX_FEE;
79 int64 nMinimumInputValue = MIN_TX_FEE;
80
81 extern enum Checkpoints::CPMode CheckpointsMode;
82
83 //////////////////////////////////////////////////////////////////////////////
84 //
85 // dispatching functions
86 //
87
88 // These functions dispatch to one or all registered wallets
89
90
91 void RegisterWallet(CWallet* pwalletIn)
92 {
93     {
94         LOCK(cs_setpwalletRegistered);
95         setpwalletRegistered.insert(pwalletIn);
96     }
97 }
98
99 void UnregisterWallet(CWallet* pwalletIn)
100 {
101     {
102         LOCK(cs_setpwalletRegistered);
103         setpwalletRegistered.erase(pwalletIn);
104     }
105 }
106
107 // check whether the passed transaction is from us
108 bool static IsFromMe(CTransaction& tx)
109 {
110     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111         if (pwallet->IsFromMe(tx))
112             return true;
113     return false;
114 }
115
116 // get the wallet transaction with the given hash (if it exists)
117 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
118 {
119     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120         if (pwallet->GetTransaction(hashTx,wtx))
121             return true;
122     return false;
123 }
124
125 // erases transaction with the given hash from all wallets
126 void static EraseFromWallets(uint256 hash)
127 {
128     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129         pwallet->EraseFromWallet(hash);
130 }
131
132 // make sure all wallets know about the given transaction, in the given block
133 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
134 {
135     if (!fConnect)
136     {
137         // ppcoin: wallets need to refund inputs when disconnecting coinstake
138         if (tx.IsCoinStake())
139         {
140             BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141                 if (pwallet->IsFromMe(tx))
142                     pwallet->DisableTransaction(tx);
143         }
144         return;
145     }
146
147     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148         pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
149 }
150
151 // notify wallets about a new best chain
152 void static SetBestChain(const CBlockLocator& loc)
153 {
154     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155         pwallet->SetBestChain(loc);
156 }
157
158 // notify wallets about an updated transaction
159 void static UpdatedTransaction(const uint256& hashTx)
160 {
161     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162         pwallet->UpdatedTransaction(hashTx);
163 }
164
165 // dump all wallets
166 void static PrintWallets(const CBlock& block)
167 {
168     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169         pwallet->PrintWallet(block);
170 }
171
172 // notify wallets about an incoming inventory (for request counts)
173 void static Inventory(const uint256& hash)
174 {
175     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176         pwallet->Inventory(hash);
177 }
178
179 // ask wallets to resend their transactions
180 void ResendWalletTransactions()
181 {
182     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183         pwallet->ResendWalletTransactions();
184 }
185
186
187 //////////////////////////////////////////////////////////////////////////////
188 //
189 // CCoinsView implementations
190 //
191
192 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
193 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
194 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
195 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
196 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
197 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
198
199 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
200 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
201 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
202 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
203 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
204 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
205 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
206
207 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
208
209 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
210
211 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
212     if (cacheCoins.count(txid)) {
213         coins = cacheCoins[txid];
214         return true;
215     }
216     if (base->GetCoins(txid, coins)) {
217         cacheCoins[txid] = coins;
218         return true;
219     }
220     return false;
221 }
222
223 // Select coins from read-only cache or database
224 bool CCoinsViewCache::GetCoinsReadOnly(uint256 txid, CCoins &coins) {
225     if (cacheCoins.count(txid)) {
226         coins = cacheCoins[txid]; // get from cache
227         return true;
228     }
229     if (cacheCoinsReadOnly.count(txid)) {
230         coins = cacheCoinsReadOnly[txid]; // get from read-only cache
231         return true;
232     }
233     if (base->GetCoins(txid, coins)) {
234         cacheCoinsReadOnly[txid] = coins; // save to read-only cache
235         return true;
236     }
237     return false;
238 }
239
240 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 uint256 &txhash) const
1355 {
1356     // mark inputs spent
1357     if (!IsCoinBase()) {
1358         BOOST_FOREACH(const CTxIn &txin, vin) {
1359             CCoins coins;
1360             if (!inputs.GetCoins(txin.prevout.hash, coins))
1361                 return error("UpdateCoins() : cannot find prevtx");
1362             if (coins.nTime > nTimeStamp)
1363                 return error("UpdateCoins() : timestamp violation");
1364             CTxInUndo undo;
1365             if (!coins.Spend(txin.prevout, undo))
1366                 return error("UpdateCoins() : cannot spend input");
1367             txundo.vprevout.push_back(undo);
1368             if (!inputs.SetCoins(txin.prevout.hash, coins))
1369                 return error("UpdateCoins() : cannot update input");
1370         }
1371     }
1372
1373     // add outputs
1374     if (!inputs.SetCoins(txhash, CCoins(*this, nHeight, nTimeStamp)))
1375         return error("UpdateCoins() : cannot update output");
1376
1377     return true;
1378 }
1379
1380 bool CTransaction::HaveInputs(CCoinsView &inputs) const
1381 {
1382     if (!IsCoinBase()) {
1383         // first check whether information about the prevout hash is available
1384         for (unsigned int i = 0; i < vin.size(); i++) {
1385             const COutPoint &prevout = vin[i].prevout;
1386             if (!inputs.HaveCoins(prevout.hash))
1387                 return false;
1388         }
1389
1390         // then check whether the actual outputs are available
1391         for (unsigned int i = 0; i < vin.size(); i++) {
1392             const COutPoint &prevout = vin[i].prevout;
1393             CCoins coins;
1394             inputs.GetCoins(prevout.hash, coins);
1395             if (!coins.IsAvailable(prevout.n))
1396                 return false;
1397         }
1398     }
1399     return true;
1400 }
1401
1402 bool CTransaction::CheckInputs(CCoinsView &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1403 {
1404     if (!IsCoinBase())
1405     {
1406         int64 nValueIn = 0;
1407         int64 nFees = 0;
1408         for (unsigned int i = 0; i < vin.size(); i++)
1409         {
1410             const COutPoint &prevout = vin[i].prevout;
1411             CCoins coins;
1412             if (!inputs.GetCoins(prevout.hash, coins))
1413                 return error("CheckInputs() : cannot find prevout tx");
1414
1415             // Check for conflicts (double-spend)
1416             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1417             // for an attacker to attempt to split the network.
1418             if (!coins.IsAvailable(prevout.n))
1419                 return error("CheckInputs() : %s prev tx already used", GetHash().ToString().substr(0,10).c_str());
1420
1421             // If prev is coinbase or coinstake, check that it's matured
1422             if (coins.IsCoinBase() || coins.IsCoinStake()) {
1423                 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1424                 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1425                     return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1426             }
1427
1428             // Check transaction timestamp
1429             if (coins.nTime > nTime)
1430                 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1431
1432             // Check for negative or overflow input values
1433             nValueIn += coins.vout[prevout.n].nValue;
1434             if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1435                 return DoS(100, error("CheckInputs() : txin values out of range"));
1436         }
1437
1438         if (IsCoinStake())
1439         {
1440             if (!pblock)
1441                 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1442
1443             // Coin stake tx earns reward instead of paying fee
1444             uint64 nCoinAge;
1445             if (!GetCoinAge(nCoinAge))
1446                 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1447
1448             int64 nStakeReward = GetValueOut() - nValueIn;
1449             int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1450
1451             if (nStakeReward > nCalculatedStakeReward)
1452                 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1453         }
1454         else
1455         {
1456             if (nValueIn < GetValueOut())
1457                 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1458
1459             // Tally transaction fees
1460             int64 nTxFee = nValueIn - GetValueOut();
1461             if (nTxFee < 0)
1462                 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1463             nFees += nTxFee;
1464             if (!MoneyRange(nFees))
1465                 return DoS(100, error("CheckInputs() : nFees out of range"));
1466
1467             // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1468             if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1469                 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;
1470         }
1471
1472         // The first loop above does all the inexpensive checks.
1473         // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1474         // Helps prevent CPU exhaustion attacks.
1475
1476         // Skip ECDSA signature verification when connecting blocks
1477         // before the last blockchain checkpoint. This is safe because block merkle hashes are
1478         // still computed and checked, and any change will be caught at the next checkpoint.
1479         if (csmode == CS_ALWAYS || 
1480             (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1481             for (unsigned int i = 0; i < vin.size(); i++) {
1482                 const COutPoint &prevout = vin[i].prevout;
1483                 CCoins coins;
1484                 inputs.GetCoins(prevout.hash, coins);
1485
1486                 // Verify signature
1487                 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1488                     // only during transition phase for P2SH: do not invoke anti-DoS code for
1489                     // potentially old clients relaying bad P2SH transactions
1490                     if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1491                         return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1492
1493                     return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1494                 }
1495             }
1496         }
1497     }
1498
1499     return true;
1500 }
1501
1502
1503 bool CTransaction::ClientCheckInputs() const
1504 {
1505     if (IsCoinBase())
1506         return false;
1507
1508     // Take over previous transactions' spent pointers
1509     {
1510         LOCK(mempool.cs);
1511         int64 nValueIn = 0;
1512         for (unsigned int i = 0; i < vin.size(); i++)
1513         {
1514             // Get prev tx from single transactions in memory
1515             COutPoint prevout = vin[i].prevout;
1516             if (!mempool.exists(prevout.hash))
1517                 return false;
1518             CTransaction& txPrev = mempool.lookup(prevout.hash);
1519
1520             if (prevout.n >= txPrev.vout.size())
1521                 return false;
1522
1523             // Verify signature
1524             if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1525                 return error("ConnectInputs() : VerifySignature failed");
1526
1527             ///// this is redundant with the mempool.mapNextTx stuff,
1528             ///// not sure which I want to get rid of
1529             ///// this has to go away now that posNext is gone
1530             // // Check for conflicts
1531             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1532             //     return error("ConnectInputs() : prev tx already used");
1533             //
1534             // // Flag outpoints as used
1535             // txPrev.vout[prevout.n].posNext = posThisTx;
1536
1537             nValueIn += txPrev.vout[prevout.n].nValue;
1538
1539             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1540                 return error("ClientConnectInputs() : txin values out of range");
1541         }
1542         if (GetValueOut() > nValueIn)
1543             return false;
1544     }
1545
1546     return true;
1547 }
1548
1549 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsView &view)
1550 {
1551     assert(pindex == view.GetBestBlock());
1552
1553     CBlockUndo blockUndo;
1554     {
1555         CDiskBlockPos pos = pindex->GetUndoPos();
1556         if (pos.IsNull())
1557             return error("DisconnectBlock() : no undo data available");
1558         FILE *file = OpenUndoFile(pos, true);
1559         if (file == NULL)
1560             return error("DisconnectBlock() : undo file not available");
1561         CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1562         fileUndo >> blockUndo;
1563     }
1564
1565     assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1566
1567     // undo transactions in reverse order
1568     for (int i = vtx.size() - 1; i >= 0; i--) {
1569         const CTransaction &tx = vtx[i];
1570         uint256 hash = tx.GetHash();
1571
1572         // don't check coinbase coins for proof-of-stake block
1573         if(IsProofOfStake() && tx.IsCoinBase())
1574             continue;
1575
1576         // check that all outputs are available
1577         CCoins outs;
1578         if (!view.GetCoins(hash, outs))
1579             return error("DisconnectBlock() : outputs still spent? database corrupted");
1580
1581         CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1582         if (outs != outsBlock)
1583             return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1584
1585         // remove outputs
1586         if (!view.SetCoins(hash, CCoins()))
1587             return error("DisconnectBlock() : cannot delete coin outputs");
1588
1589         // restore inputs
1590         if (i > 0) { // not coinbases
1591             const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1592             assert(txundo.vprevout.size() == tx.vin.size());
1593             for (unsigned int j = tx.vin.size(); j-- > 0;) {
1594                 const COutPoint &out = tx.vin[j].prevout;
1595                 const CTxInUndo &undo = txundo.vprevout[j];
1596                 CCoins coins;
1597                 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1598                 if (coins.IsPruned()) {
1599                     if (undo.nHeight == 0)
1600                         return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1601                     coins.fCoinBase = undo.fCoinBase;
1602                     coins.fCoinStake = undo.fCoinStake;
1603                     coins.nHeight = undo.nHeight;
1604                     coins.nTime = undo.nTime;
1605                     coins.nBlockTime = undo.nBlockTime;
1606                     coins.nVersion = undo.nVersion;
1607                 } else {
1608                     if (undo.nHeight != 0)
1609                         return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1610                 }
1611                 if (coins.IsAvailable(out.n))
1612                     return error("DisconnectBlock() : prevout output not spent? database corrupted");
1613                 if (coins.vout.size() < out.n+1)
1614                     coins.vout.resize(out.n+1);
1615                 coins.vout[out.n] = undo.txout;
1616                 if (!view.SetCoins(out.hash, coins))
1617                     return error("DisconnectBlock() : cannot restore coin inputs");
1618             }
1619         }
1620     }
1621
1622     // move best block pointer to prevout block
1623     view.SetBestBlock(pindex->pprev);
1624
1625     return true;
1626 }
1627
1628 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1629
1630 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsView &view, bool fJustCheck)
1631 {
1632     // Check it again in case a previous version let a bad block in
1633     if (!CheckBlock(!fJustCheck, !fJustCheck))
1634         return false;
1635
1636     // verify that the view's current state corresponds to the previous block
1637     assert(pindex->pprev == view.GetBestBlock());
1638
1639     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1640     // unless those are already completely spent.
1641     // If such overwrites are allowed, coinbases and transactions depending upon those
1642     // can be duplicated to remove the ability to spend the first instance -- even after
1643     // being sent to another address.
1644     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1645     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1646     // already refuses previously-known transaction ids entirely.
1647     // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1648     // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1649     // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1650     // initial block download.
1651     bool fEnforceBIP30 = true;
1652
1653     if (fEnforceBIP30) {
1654         for (unsigned int i=0; i<vtx.size(); i++) {
1655             uint256 hash = GetTxHash(i);
1656             CCoins coins;
1657             if (view.GetCoins(hash, coins) && !coins.IsPruned())
1658                 return error("ConnectBlock() : tried to overwrite transaction");
1659         }
1660     }
1661
1662     // BIP16 always active
1663     bool fStrictPayToScriptHash = true;
1664
1665     CBlockUndo blockundo;
1666
1667     int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1668     unsigned int nSigOps = 0;
1669     for (unsigned int i=0; i<vtx.size(); i++)
1670     {
1671         const CTransaction &tx = vtx[i];
1672         nSigOps += tx.GetLegacySigOpCount();
1673         if (nSigOps > MAX_BLOCK_SIGOPS)
1674             return DoS(100, error("ConnectBlock() : too many sigops"));
1675
1676         if (!tx.IsCoinBase())
1677         {
1678             if (!tx.HaveInputs(view))
1679                 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1680
1681             if (fStrictPayToScriptHash)
1682             {
1683                 // Add in sigops done by pay-to-script-hash inputs;
1684                 // this is to prevent a "rogue miner" from creating
1685                 // an incredibly-expensive-to-validate block.
1686                 nSigOps += tx.GetP2SHSigOpCount(view);
1687                 if (nSigOps > MAX_BLOCK_SIGOPS)
1688                      return DoS(100, error("ConnectBlock() : too many sigops"));
1689             }
1690
1691             int64 nTxValueOut = tx.GetValueOut();
1692             int64 nTxValueIn  = tx.GetValueIn(view);
1693
1694             nValueIn += nTxValueIn;
1695             nValueOut += nTxValueOut;
1696
1697             if (!tx.IsCoinStake())
1698                 nFees += nTxValueIn - nTxValueOut;
1699
1700             if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1701                 return false;
1702         }
1703         else
1704         {
1705             nValueOut += tx.GetValueOut();
1706         }
1707
1708         // don't create coinbase coins for proof-of-stake block
1709         if(IsProofOfStake() && tx.IsCoinBase())
1710             continue;
1711
1712         CTxUndo txundo;
1713         if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime, GetTxHash(i)))
1714             return error("ConnectBlock() : UpdateInputs failed");
1715         if (!tx.IsCoinBase())
1716             blockundo.vtxundo.push_back(txundo);
1717     }
1718
1719     pindex->nMint = nValueOut - nValueIn + nFees;
1720     pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1721
1722     if (fJustCheck)
1723         return true;
1724
1725     CChainDB chaindb;
1726     CDiskBlockPos pos;
1727
1728     // Write undo information to disk
1729     if (pindex->GetUndoPos().IsNull())
1730     {
1731         if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1732             return error("ConnectBlock() : FindUndoPos failed");
1733         if (!blockundo.WriteToDisk(pos))
1734             return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1735
1736         // update nUndoPos in block index
1737         pindex->nUndoPos = pos.nPos + 1;
1738     }
1739
1740     CDiskBlockIndex blockindex(pindex);
1741     if (!chaindb.WriteBlockIndex(blockindex))
1742         return error("ConnectBlock() : WriteBlockIndex failed");
1743
1744     // add this block to the view's blockchain
1745     if (!view.SetBestBlock(pindex))
1746         return false;
1747
1748     // fees are destroyed to compensate the entire network
1749     if (fDebug && GetBoolArg("-printcreation"))
1750         printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1751
1752     // Watch for transactions paying to me
1753     for (unsigned int i=0; i<vtx.size(); i++)
1754         SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1755
1756     return true;
1757 }
1758
1759 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1760 {
1761     CCoinsViewCache &view = *pcoinsTip;
1762
1763     // special case for attaching the genesis block
1764     // note that no ConnectBlock is called, so its coinbase output is non-spendable
1765     if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1766     {
1767         view.SetBestBlock(pindexNew);
1768         if (!view.Flush())
1769             return false;
1770         pindexGenesisBlock = pindexNew;
1771         pindexBest = pindexNew;
1772         hashBestChain = pindexNew->GetBlockHash();
1773         nBestHeight = pindexBest->nHeight;
1774         nBestChainTrust = pindexNew->nChainTrust;
1775         return true;
1776     }
1777
1778     // Find the fork (typically, there is none)
1779     CBlockIndex* pfork = view.GetBestBlock();
1780     CBlockIndex* plonger = pindexNew;
1781     while (pfork != plonger)
1782     {
1783         while (plonger->nHeight > pfork->nHeight)
1784             if (!(plonger = plonger->pprev))
1785                 return error("SetBestChain() : plonger->pprev is null");
1786         if (pfork == plonger)
1787             break;
1788         if (!(pfork = pfork->pprev))
1789             return error("SetBestChain() : pfork->pprev is null");
1790     }
1791
1792     // List of what to disconnect (typically nothing)
1793     vector<CBlockIndex*> vDisconnect;
1794     for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1795         vDisconnect.push_back(pindex);
1796
1797     // List of what to connect (typically only pindexNew)
1798     vector<CBlockIndex*> vConnect;
1799     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1800         vConnect.push_back(pindex);
1801     reverse(vConnect.begin(), vConnect.end());
1802
1803     if (vDisconnect.size() > 0) {
1804         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());
1805         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());
1806     }
1807
1808     // Disconnect shorter branch
1809     vector<CTransaction> vResurrect;
1810     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1811         CBlock block;
1812         if (!block.ReadFromDisk(pindex))
1813             return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1814         CCoinsViewCache viewTemp(view, true);
1815         if (!block.DisconnectBlock(pindex, viewTemp))
1816             return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1817         if (!viewTemp.Flush())
1818             return error("SetBestBlock() : Cache flush failed after disconnect");
1819
1820         // Queue memory transactions to resurrect
1821         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1822             if (!tx.IsCoinBase() && !tx.IsCoinStake())
1823                 vResurrect.push_back(tx);
1824     }
1825
1826     // Connect longer branch
1827     vector<CTransaction> vDelete;
1828     BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1829         CBlock block;
1830         CBlock *pblock;
1831         if (pindex == pindexNew) // connecting *this block
1832             pblock = this;
1833         else { // other block; read it from disk
1834             if (!block.ReadFromDisk(pindex))
1835                 return error("SetBestBlock() : ReadFromDisk for connect failed");
1836             pblock = &block;
1837         }
1838         CCoinsViewCache viewTemp(view, true);
1839         if (!pblock->ConnectBlock(pindex, viewTemp)) {
1840             InvalidChainFound(pindexNew);
1841             return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1842         }
1843         if (!viewTemp.Flush())
1844             return error("SetBestBlock() : Cache flush failed after connect");
1845
1846         // Queue memory transactions to delete
1847         BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1848             vDelete.push_back(tx);
1849     }
1850
1851     // Make sure it's successfully written to disk before changing memory structure
1852     bool fIsInitialDownload = IsInitialBlockDownload();
1853     if (!fIsInitialDownload || view.GetCacheSize()>5000)
1854         if (!view.Flush())
1855             return false;
1856
1857     // At this point, all changes have been done to the database.
1858     // Proceed by updating the memory structures.
1859
1860     // Disconnect shorter branch
1861     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1862         if (pindex->pprev)
1863             pindex->pprev->pnext = NULL;
1864
1865     // Connect longer branch
1866     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1867         if (pindex->pprev)
1868             pindex->pprev->pnext = pindex;
1869
1870     // Resurrect memory transactions that were in the disconnected branch
1871     BOOST_FOREACH(CTransaction& tx, vResurrect)
1872         tx.AcceptToMemoryPool(false);
1873
1874     // Delete redundant memory transactions that are in the connected branch
1875     BOOST_FOREACH(CTransaction& tx, vDelete)
1876         mempool.remove(tx);
1877
1878     // Update best block in wallet (so we can detect restored wallets)
1879     if (!fIsInitialDownload)
1880     {
1881         const CBlockLocator locator(pindexNew);
1882         ::SetBestChain(locator);
1883     }
1884
1885     // New best block
1886     hashBestChain = pindexNew->GetBlockHash();
1887     pindexBest = pindexNew;
1888     pblockindexFBBHLast = NULL;
1889     nBestHeight = pindexBest->nHeight;
1890     nBestChainTrust = pindexNew->nChainTrust;
1891     nTimeBestReceived = GetTime();
1892     nTransactionsUpdated++;
1893
1894     uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1895
1896     printf("SetBestChain: new best=%s  height=%d  trust=%s  blocktrust=%"PRI64d"  date=%s\n",
1897       hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1898       CBigNum(nBestChainTrust).ToString().c_str(),
1899       nBestBlockTrust.Get64(),
1900       DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1901
1902     // Check the version of the last 100 blocks to see if we need to upgrade:
1903     if (!fIsInitialDownload)
1904     {
1905         int nUpgraded = 0;
1906         const CBlockIndex* pindex = pindexBest;
1907         for (int i = 0; i < 100 && pindex != NULL; i++)
1908         {
1909             if (pindex->nVersion > CBlock::CURRENT_VERSION)
1910                 ++nUpgraded;
1911             pindex = pindex->pprev;
1912         }
1913         if (nUpgraded > 0)
1914             printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1915         if (nUpgraded > 100/2)
1916             // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1917             strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1918     }
1919
1920     std::string strCmd = GetArg("-blocknotify", "");
1921
1922     if (!fIsInitialDownload && !strCmd.empty())
1923     {
1924         boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1925         boost::thread t(runCommand, strCmd); // thread runs free
1926     }
1927
1928     return true;
1929 }
1930
1931 // Total coin age spent in transaction, in the unit of coin-days.
1932 // Only those coins meeting minimum age requirement counts. As those
1933 // transactions not in main chain are not currently indexed so we
1934 // might not find out about their coin age. Older transactions are 
1935 // guaranteed to be in main chain by sync-checkpoint. This rule is
1936 // introduced to help nodes establish a consistent view of the coin
1937 // age (trust score) of competing branches.
1938 bool CTransaction::GetCoinAge(uint64& nCoinAge) const
1939 {
1940     CCoinsViewCache &inputs = *pcoinsTip;
1941
1942     CBigNum bnCentSecond = 0;  // coin age in the unit of cent-seconds
1943     nCoinAge = 0;
1944
1945     if (IsCoinBase())
1946         return true;
1947
1948     for (unsigned int i = 0; i < vin.size(); i++)
1949     {
1950         const COutPoint &prevout = vin[i].prevout;
1951         CCoins coins;
1952         if (!inputs.GetCoins(prevout.hash, coins))
1953             continue;
1954
1955         if (nTime < coins.nTime)
1956             return false;  // Transaction timestamp violation
1957
1958         // only count coins meeting min age requirement
1959         if (coins.nBlockTime + nStakeMinAge > nTime)
1960             continue;
1961
1962         int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1963         bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1964     }
1965
1966     CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1967     if (fDebug && GetBoolArg("-printcoinage"))
1968         printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1969     nCoinAge = bnCoinDay.getuint64();
1970     return true;
1971 }
1972
1973 // Total coin age spent in block, in the unit of coin-days.
1974 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1975 {
1976     nCoinAge = 0;
1977
1978     BOOST_FOREACH(const CTransaction& tx, vtx)
1979     {
1980         uint64 nTxCoinAge;
1981         if (tx.GetCoinAge(nTxCoinAge))
1982             nCoinAge += nTxCoinAge;
1983         else
1984             return false;
1985     }
1986
1987     if (nCoinAge == 0) // block coin age minimum 1 coin-day
1988         nCoinAge = 1;
1989     if (fDebug && GetBoolArg("-printcoinage"))
1990         printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1991     return true;
1992 }
1993
1994 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1995 {
1996     // Check for duplicate
1997     uint256 hash = GetHash();
1998     if (mapBlockIndex.count(hash))
1999         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2000
2001     // Construct new block index object
2002     CBlockIndex* pindexNew = new CBlockIndex(*this);
2003     if (!pindexNew)
2004         return error("AddToBlockIndex() : new CBlockIndex failed");
2005     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2006     pindexNew->phashBlock = &((*mi).first);
2007     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2008     if (miPrev != mapBlockIndex.end())
2009     {
2010         pindexNew->pprev = (*miPrev).second;
2011         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2012     }
2013     pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2014     pindexNew->pos = pos;
2015     pindexNew->nUndoPos = 0;
2016
2017     // Compute stake entropy bit for stake modifier
2018     if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2019         return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2020
2021     // Record proof-of-stake hash value
2022     if (pindexNew->IsProofOfStake())
2023     {
2024         if (!mapProofOfStake.count(hash))
2025             return error("AddToBlockIndex() : hashProofOfStake not found in map");
2026         pindexNew->hashProofOfStake = mapProofOfStake[hash];
2027     }
2028
2029     // Compute stake modifier
2030     uint64 nStakeModifier = 0;
2031     bool fGeneratedStakeModifier = false;
2032     if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2033         return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2034     pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2035     pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2036     if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2037         return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2038
2039     CChainDB chaindb;
2040     if (!chaindb.TxnBegin())
2041         return false;
2042     chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2043     if (!chaindb.TxnCommit())
2044         return false;
2045
2046     // New best
2047     if (!SetBestChain(pindexNew))
2048         return false;
2049
2050     if (pindexNew == pindexBest)
2051     {
2052         // Notify UI to display prev block's coinbase if it was ours
2053         static uint256 hashPrevBestCoinBase;
2054         UpdatedTransaction(hashPrevBestCoinBase);
2055         hashPrevBestCoinBase = GetTxHash(0);
2056     }
2057
2058     uiInterface.NotifyBlocksChanged();
2059     return true;
2060 }
2061
2062 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2063 {
2064     bool fUpdatedLast = false;
2065
2066     LOCK(cs_LastBlockFile);
2067
2068     while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2069         printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2070         FILE *file = OpenBlockFile(pos);
2071         FileCommit(file);
2072         fclose(file);
2073         file = OpenUndoFile(pos);
2074         FileCommit(file);
2075         fclose(file);
2076         nLastBlockFile++;
2077         infoLastBlockFile.SetNull();
2078         chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2079         fUpdatedLast = true;
2080     }
2081
2082     pos.nFile = nLastBlockFile;
2083     pos.nPos = infoLastBlockFile.nSize;
2084     infoLastBlockFile.nSize += nAddSize;
2085     infoLastBlockFile.AddBlock(nHeight, nTime);
2086
2087     unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2088     unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2089     if (nNewChunks > nOldChunks) {
2090         FILE *file = OpenBlockFile(pos);
2091         if (file) {
2092             printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2093             AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2094         }
2095         fclose(file);
2096     }
2097
2098     if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2099         return error("FindBlockPos() : cannot write updated block info");
2100     if (fUpdatedLast)
2101         chaindb.WriteLastBlockFile(nLastBlockFile);
2102
2103     return true;
2104 }
2105
2106 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2107 {
2108     pos.nFile = nFile;
2109
2110     LOCK(cs_LastBlockFile);
2111
2112     unsigned int nNewSize;
2113     if (nFile == nLastBlockFile) {
2114         pos.nPos = infoLastBlockFile.nUndoSize;
2115         nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2116         if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2117             return error("FindUndoPos() : cannot write updated block info");
2118     } else {
2119         CBlockFileInfo info;
2120         if (!chaindb.ReadBlockFileInfo(nFile, info))
2121             return error("FindUndoPos() : cannot read block info");
2122         pos.nPos = info.nUndoSize;
2123         nNewSize = (info.nUndoSize += nAddSize);
2124         if (!chaindb.WriteBlockFileInfo(nFile, info))
2125             return error("FindUndoPos() : cannot write updated block info");
2126     }
2127
2128     unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2129     unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2130     if (nNewChunks > nOldChunks) {
2131         FILE *file = OpenUndoFile(pos);
2132         if (file) {
2133             printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2134             AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2135         }
2136         fclose(file);
2137     }
2138
2139     return true;
2140 }
2141
2142 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2143 {
2144     // These are checks that are independent of context
2145     // that can be verified before saving an orphan block.
2146
2147     // Size limits
2148     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2149         return DoS(100, error("CheckBlock() : size limits failed"));
2150
2151     // Check proof of work matches claimed amount
2152     if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2153         return DoS(50, error("CheckBlock() : proof of work failed"));
2154
2155     // Check timestamp
2156     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2157         return error("CheckBlock() : block timestamp too far in the future");
2158
2159     // First transaction must be coinbase, the rest must not be
2160     if (vtx.empty() || !vtx[0].IsCoinBase())
2161         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2162     for (unsigned int i = 1; i < vtx.size(); i++)
2163         if (vtx[i].IsCoinBase())
2164             return DoS(100, error("CheckBlock() : more than one coinbase"));
2165
2166     // Check coinbase timestamp
2167     if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2168         return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2169
2170     if (IsProofOfStake())
2171     {
2172         // Coinbase output should be empty if proof-of-stake block
2173         if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2174             return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2175
2176         // Second transaction must be coinstake, the rest must not be
2177         if (vtx.empty() || !vtx[1].IsCoinStake())
2178             return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2179         for (unsigned int i = 2; i < vtx.size(); i++)
2180             if (vtx[i].IsCoinStake())
2181                 return DoS(100, error("CheckBlock() : more than one coinstake"));
2182
2183         // Check coinstake timestamp
2184         if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2185             return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2186     }
2187     else
2188     {
2189         int64 nReward = GetProofOfWorkReward(nBits);
2190         // Check coinbase reward
2191         if (vtx[0].GetValueOut() > nReward)
2192             return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2193                    vtx[0].GetValueOut(),
2194                    nReward));
2195
2196         // Should we check proof-of-work block signature or not?
2197         //
2198         // * Always skip on TestNet
2199         // * Perform checking for the first 9689 blocks
2200         // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2201
2202         if(!fTestNet && fCheckSig)
2203         {
2204             bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2205
2206             // check legacy proof-of-work block signature
2207             if (checkEntropySig && !CheckLegacySignature())
2208                 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2209         }
2210     }
2211
2212
2213     // Check transactions
2214     BOOST_FOREACH(const CTransaction& tx, vtx)
2215     {
2216         if (!tx.CheckTransaction())
2217             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2218
2219         // check transaction timestamp
2220         if (GetBlockTime() < (int64)tx.nTime)
2221             return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2222     }
2223
2224     // Check for duplicate txids. This is caught by ConnectInputs(),
2225     // but catching it earlier avoids a potential DoS attack:
2226     BuildMerkleTree();
2227     set<uint256> uniqueTx;
2228     for (unsigned int i=0; i<vtx.size(); i++) {
2229         uniqueTx.insert(GetTxHash(i));
2230     }
2231     if (uniqueTx.size() != vtx.size())
2232         return DoS(100, error("CheckBlock() : duplicate transaction"));
2233
2234     unsigned int nSigOps = 0;
2235     BOOST_FOREACH(const CTransaction& tx, vtx)
2236     {
2237         nSigOps += tx.GetLegacySigOpCount();
2238     }
2239     if (nSigOps > MAX_BLOCK_SIGOPS)
2240         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2241
2242     // Check merkle root
2243     if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2244         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2245
2246     return true;
2247 }
2248
2249
2250 bool CBlock::AcceptBlock()
2251 {
2252     // Check for duplicate
2253     uint256 hash = GetHash();
2254     if (mapBlockIndex.count(hash))
2255         return error("AcceptBlock() : block already in mapBlockIndex");
2256
2257     // Get prev block index
2258     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2259     if (mi == mapBlockIndex.end())
2260         return DoS(10, error("AcceptBlock() : prev block not found"));
2261     CBlockIndex* pindexPrev = (*mi).second;
2262     int nHeight = pindexPrev->nHeight+1;
2263
2264     // Check proof-of-work or proof-of-stake
2265     if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2266         return DoS(100, error("AcceptBlock() : incorrect proof-of-%s amount", IsProofOfWork() ? "work" : "stake"));
2267
2268     // Check timestamp against prev
2269     if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2270         return error("AcceptBlock() : block's timestamp is too early");
2271
2272     // Check that all transactions are finalized
2273     BOOST_FOREACH(const CTransaction& tx, vtx)
2274         if (!tx.IsFinal(nHeight, GetBlockTime()))
2275             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2276
2277     // Check that the block chain matches the known block chain up to a checkpoint
2278     if (!Checkpoints::CheckHardened(nHeight, hash))
2279         return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2280
2281     bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2282
2283     // Check that the block satisfies synchronized checkpoint
2284     if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2285         return error("AcceptBlock() : rejected by synchronized checkpoint");
2286
2287     if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2288         strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2289
2290     // Enforce rule that the coinbase starts with serialized block height
2291     CScript expect = CScript() << nHeight;
2292     if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2293         !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2294         return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2295
2296     // Write block to history file
2297     unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2298     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2299         return error("AcceptBlock() : out of disk space");
2300     CDiskBlockPos blockPos;
2301     {
2302         CChainDB chaindb;
2303         if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2304             return error("AcceptBlock() : FindBlockPos failed");
2305     }
2306     if (!WriteToDisk(blockPos))
2307         return error("AcceptBlock() : WriteToDisk failed");
2308     if (!AddToBlockIndex(blockPos))
2309         return error("AcceptBlock() : AddToBlockIndex failed");
2310
2311     // Relay inventory, but don't relay old inventory during initial block download
2312     int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2313     if (hashBestChain == hash)
2314     {
2315         LOCK(cs_vNodes);
2316         BOOST_FOREACH(CNode* pnode, vNodes)
2317             if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2318                 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2319     }
2320
2321     // Check pending sync-checkpoint
2322     Checkpoints::AcceptPendingSyncCheckpoint();
2323
2324     return true;
2325 }
2326
2327 uint256 CBlockIndex::GetBlockTrust() const
2328 {
2329     CBigNum bnTarget;
2330     bnTarget.SetCompact(nBits);
2331
2332     if (bnTarget <= 0)
2333         return 0;
2334
2335     /* Old protocol */
2336     if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2337         return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2338
2339     /* New protocol */
2340
2341     // Calculate work amount for block
2342     uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2343
2344     // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2345     nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2346
2347     // Return nPoWTrust for the first 12 blocks
2348     if (pprev == NULL || pprev->nHeight < 12)
2349         return nPoWTrust;
2350
2351     const CBlockIndex* currentIndex = pprev;
2352
2353     if(IsProofOfStake())
2354     {
2355         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2356
2357         // Return 1/3 of score if parent block is not the PoW block
2358         if (!pprev->IsProofOfWork())
2359             return (bnNewTrust / 3).getuint256();
2360
2361         int nPoWCount = 0;
2362
2363         // Check last 12 blocks type
2364         while (pprev->nHeight - currentIndex->nHeight < 12)
2365         {
2366             if (currentIndex->IsProofOfWork())
2367                 nPoWCount++;
2368             currentIndex = currentIndex->pprev;
2369         }
2370
2371         // Return 1/3 of score if less than 3 PoW blocks found
2372         if (nPoWCount < 3)
2373             return (bnNewTrust / 3).getuint256();
2374
2375         return bnNewTrust.getuint256();
2376     }
2377     else
2378     {
2379         CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2380
2381         // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2382         if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2383             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2384
2385         int nPoSCount = 0;
2386
2387         // Check last 12 blocks type
2388         while (pprev->nHeight - currentIndex->nHeight < 12)
2389         {
2390             if (currentIndex->IsProofOfStake())
2391                 nPoSCount++;
2392             currentIndex = currentIndex->pprev;
2393         }
2394
2395         // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2396         if (nPoSCount < 7)
2397             return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2398
2399         bnTarget.SetCompact(pprev->nBits);
2400
2401         if (bnTarget <= 0)
2402             return 0;
2403
2404         CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2405
2406         // Return nPoWTrust + full trust score for previous block nBits
2407         return nPoWTrust + bnNewTrust.getuint256();
2408     }
2409 }
2410
2411 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2412 {
2413     unsigned int nFound = 0;
2414     for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2415     {
2416         if (pstart->nVersion >= minVersion)
2417             ++nFound;
2418         pstart = pstart->pprev;
2419     }
2420     return (nFound >= nRequired);
2421 }
2422
2423 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2424 {
2425     // Check for duplicate
2426     uint256 hash = pblock->GetHash();
2427     if (mapBlockIndex.count(hash))
2428         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2429     if (mapOrphanBlocks.count(hash))
2430         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2431
2432     // Preliminary checks
2433     if (!pblock->CheckBlock())
2434         return error("ProcessBlock() : CheckBlock FAILED");
2435
2436     if (pblock->IsProofOfStake())
2437     {
2438         // Limited duplicity on stake: prevents block flood attack
2439         // Duplicate stake allowed only when there is orphan child block
2440         if (setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2441             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());
2442
2443         bool fFatal = false;
2444         uint256 hashProofOfStake;
2445
2446         // Verify proof-of-stake hash target and signatures
2447         if (!pblock->CheckSignature(fFatal, hashProofOfStake))
2448         {
2449             if (fFatal)
2450             {
2451                 // Invalid blockhash/coinstake signature or no generator defined, nothing to do here
2452                 // This also may occur when supplied proof-of-stake doesn't satisfy required target
2453                 if (pfrom)
2454                     pfrom->Misbehaving(100);
2455                 return error("ProcessBlock() : invalid signature in proof-of-stake block %s", hash.ToString().c_str());
2456             }
2457             else
2458             {
2459                 // Blockhash and coinstake signatures are OK but target checkings failed
2460                 // This may occur during initial block download
2461
2462                 if (pfrom)
2463                     pfrom->Misbehaving(1); // Small DoS penalty
2464
2465                 printf("WARNING: ProcessBlock(): proof-of-stake target checkings failed for block %s, we'll try again later\n", hash.ToString().c_str());
2466                 return false;
2467             }
2468         }
2469
2470         if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2471             mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2472     }
2473
2474     CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2475     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2476     {
2477         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2478         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2479         CBigNum bnNewBlock;
2480         bnNewBlock.SetCompact(pblock->nBits);
2481         CBigNum bnRequired;
2482
2483         if (pblock->IsProofOfStake())
2484             bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2485         else
2486             bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2487
2488         if (bnNewBlock > bnRequired)
2489         {
2490             if (pfrom)
2491                 pfrom->Misbehaving(100);
2492             return error("ProcessBlock() : block with too little proof-of-%s", pblock->IsProofOfStake() ? "stake" : "work");
2493         }
2494     }
2495
2496     // Ask for pending sync-checkpoint if any
2497     if (!IsInitialBlockDownload())
2498         Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2499
2500     // If don't already have its previous block, shunt it off to holding area until we get it
2501     if (!mapBlockIndex.count(pblock->hashPrevBlock))
2502     {
2503         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2504         CBlock* pblock2 = new CBlock(*pblock);
2505
2506         if (pblock2->IsProofOfStake())
2507         {
2508             // Limited duplicity on stake: prevents block flood attack
2509             // Duplicate stake allowed only when there is orphan child block
2510             if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2511                 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());
2512             else
2513                 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2514         }
2515
2516         mapOrphanBlocks.insert(make_pair(hash, pblock2));
2517         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2518
2519         // Ask this guy to fill in what we're missing
2520         if (pfrom)
2521         {
2522             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2523             // ppcoin: getblocks may not obtain the ancestor block rejected
2524             // earlier by duplicate-stake check so we ask for it again directly
2525             if (!IsInitialBlockDownload())
2526                 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2527         }
2528         return true;
2529     }
2530
2531     // Store to disk
2532     if (!pblock->AcceptBlock())
2533         return error("ProcessBlock() : AcceptBlock FAILED");
2534
2535     // Recursively process any orphan blocks that depended on this one
2536     vector<uint256> vWorkQueue;
2537     vWorkQueue.push_back(hash);
2538     for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2539     {
2540         uint256 hashPrev = vWorkQueue[i];
2541         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2542              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2543              ++mi)
2544         {
2545             CBlock* pblockOrphan = (*mi).second;
2546             if (pblockOrphan->AcceptBlock())
2547                 vWorkQueue.push_back(pblockOrphan->GetHash());
2548             mapOrphanBlocks.erase(pblockOrphan->GetHash());
2549             setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2550             delete pblockOrphan;
2551         }
2552         mapOrphanBlocksByPrev.erase(hashPrev);
2553     }
2554
2555     printf("ProcessBlock: ACCEPTED\n");
2556
2557     // ppcoin: if responsible for sync-checkpoint send it
2558     if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2559         Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2560
2561     return true;
2562 }
2563
2564 // attempt to generate suitable proof-of-stake
2565 bool CBlock::SignBlock(CWallet& wallet)
2566 {
2567     // if we are trying to sign
2568     //    something except proof-of-stake block template
2569     if (!vtx[0].vout[0].IsEmpty())
2570         return false;
2571
2572     // if we are trying to sign
2573     //    a complete proof-of-stake block
2574     if (IsProofOfStake())
2575         return true;
2576
2577     static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2578
2579     CKey key;
2580     CTransaction txCoinStake;
2581     int64 nSearchTime = txCoinStake.nTime; // search to current time
2582
2583     if (nSearchTime > nLastCoinStakeSearchTime)
2584     {
2585         if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2586         {
2587             if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2588             {
2589                 // make sure coinstake would meet timestamp protocol
2590                 //    as it would be the same as the block timestamp
2591                 vtx[0].nTime = nTime = txCoinStake.nTime;
2592                 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2593                 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2594
2595                 // we have to make sure that we have no future timestamps in
2596                 //    our transactions set
2597                 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2598                     if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2599
2600                 vtx.insert(vtx.begin() + 1, txCoinStake);
2601                 hashMerkleRoot = BuildMerkleTree();
2602
2603                 // append a signature to our block
2604                 return key.Sign(GetHash(), vchBlockSig);
2605             }
2606         }
2607         nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2608         nLastCoinStakeSearchTime = nSearchTime;
2609     }
2610
2611     return false;
2612 }
2613
2614 // get generation key
2615 bool CBlock::GetGenerator(CKey& GeneratorKey) const
2616 {
2617     if(!IsProofOfStake())
2618         return false;
2619
2620     vector<valtype> vSolutions;
2621     txnouttype whichType;
2622
2623     const CTxOut& txout = vtx[1].vout[1];
2624
2625     if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2626         return false;
2627     if (whichType == TX_PUBKEY)
2628     {
2629         valtype& vchPubKey = vSolutions[0];
2630         CKey key;
2631         return GeneratorKey.SetPubKey(vchPubKey);
2632     }
2633
2634     return false;
2635 }
2636
2637 // verify proof-of-stake signatures
2638 bool CBlock::CheckSignature(bool& fFatal, uint256& hashProofOfStake) const
2639 {
2640     CKey key;
2641
2642     // no generator or invalid hash signature means fatal error
2643     fFatal = !GetGenerator(key) || !key.Verify(GetHash(), vchBlockSig);
2644
2645     if (fFatal)
2646         return false;
2647
2648     uint256 hashTarget = 0;
2649     if (!CheckProofOfStake(vtx[1], nBits, hashProofOfStake, hashTarget, fFatal))
2650         return false; // hash target mismatch or invalid coinstake signature
2651
2652     return true;
2653 }
2654
2655 // verify legacy proof-of-work signature
2656 bool CBlock::CheckLegacySignature() const
2657 {
2658     if (IsProofOfStake())
2659         return false;
2660
2661     vector<valtype> vSolutions;
2662     txnouttype whichType;
2663
2664     for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2665     {
2666         const CTxOut& txout = vtx[0].vout[i];
2667
2668         if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2669             return false;
2670
2671         if (whichType == TX_PUBKEY)
2672         {
2673             // Verify
2674             valtype& vchPubKey = vSolutions[0];
2675             CKey key;
2676             if (!key.SetPubKey(vchPubKey))
2677                 continue;
2678             if (vchBlockSig.empty())
2679                 continue;
2680             if(!key.Verify(GetHash(), vchBlockSig))
2681                 continue;
2682             return true;
2683         }
2684     }
2685
2686     return false;
2687 }
2688
2689 bool CheckDiskSpace(uint64 nAdditionalBytes)
2690 {
2691     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2692
2693     // Check for nMinDiskSpace bytes (currently 50MB)
2694     if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2695     {
2696         fShutdown = true;
2697         string strMessage = _("Warning: Disk space is low!");
2698         strMiscWarning = strMessage;
2699         printf("*** %s\n", strMessage.c_str());
2700         uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2701         StartShutdown();
2702         return false;
2703     }
2704     return true;
2705 }
2706
2707
2708 CCriticalSection cs_LastBlockFile;
2709 CBlockFileInfo infoLastBlockFile;
2710 int nLastBlockFile = 0;
2711
2712 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2713 {
2714     if (pos.IsNull())
2715         return NULL;
2716     boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2717     boost::filesystem::create_directories(path.parent_path());
2718     FILE* file = fopen(path.string().c_str(), "rb+");
2719     if (!file && !fReadOnly)
2720         file = fopen(path.string().c_str(), "wb+");
2721     if (!file) {
2722         printf("Unable to open file %s\n", path.string().c_str());
2723         return NULL;
2724     }
2725     if (pos.nPos) {
2726         if (fseek(file, pos.nPos, SEEK_SET)) {
2727             printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2728             fclose(file);
2729             return NULL;
2730         }
2731     }
2732     return file;
2733 }
2734
2735 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2736     return OpenDiskFile(pos, "blk", fReadOnly);
2737 }
2738
2739 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2740     return OpenDiskFile(pos, "rev", fReadOnly);
2741 }
2742
2743 bool LoadBlockIndex(bool fAllowNew)
2744 {
2745     CBigNum bnTrustedModulus;
2746
2747     if (fTestNet)
2748     {
2749         pchMessageStart[0] = 0xcd;
2750         pchMessageStart[1] = 0xf2;
2751         pchMessageStart[2] = 0xc0;
2752         pchMessageStart[3] = 0xef;
2753
2754         bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2755         bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2756         nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2757         nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2758         nCoinbaseMaturity = 10; // test maturity is 10 blocks
2759         nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2760     }
2761     else
2762     {
2763         bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2764     }
2765
2766     // Set up the Zerocoin Params object
2767     ZCParams = new libzerocoin::Params(bnTrustedModulus);
2768
2769     //
2770     // Load block index
2771     //
2772     CChainDB chaindb("cr");
2773     if (!LoadBlockIndex(chaindb))
2774         return false;
2775     chaindb.Close();
2776
2777     //
2778     // Init with genesis block
2779     //
2780     if (mapBlockIndex.empty())
2781     {
2782         if (!fAllowNew)
2783             return false;
2784
2785         // Genesis block
2786
2787         // MainNet:
2788
2789         //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2790         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2791         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2792         //    CTxOut(empty)
2793         //  vMerkleTree: 4cb33b3b6a
2794
2795         // TestNet:
2796
2797         //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2798         //  Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2799         //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2800         //    CTxOut(empty)
2801         //  vMerkleTree: 4cb33b3b6a
2802
2803         const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2804         CTransaction txNew;
2805         txNew.nTime = 1360105017;
2806         txNew.vin.resize(1);
2807         txNew.vout.resize(1);
2808         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2809         txNew.vout[0].SetEmpty();
2810         CBlock block;
2811         block.vtx.push_back(txNew);
2812         block.hashPrevBlock = 0;
2813         block.hashMerkleRoot = block.BuildMerkleTree();
2814         block.nVersion = 1;
2815         block.nTime    = 1360105017;
2816         block.nBits    = bnProofOfWorkLimit.GetCompact();
2817         block.nNonce   = !fTestNet ? 1575379 : 46534;
2818
2819         //// debug print
2820         uint256 hash = block.GetHash();
2821         printf("%s\n", hash.ToString().c_str());
2822         assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2823         block.print();
2824         assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2825         assert(block.CheckBlock());
2826
2827         // Start new block file
2828         unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2829         CDiskBlockPos blockPos;
2830         {
2831             CChainDB chaindb;
2832             if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2833                 return error("AcceptBlock() : FindBlockPos failed");
2834         }
2835         if (!block.WriteToDisk(blockPos))
2836             return error("LoadBlockIndex() : writing genesis block to disk failed");
2837         if (!block.AddToBlockIndex(blockPos))
2838             return error("LoadBlockIndex() : genesis block not accepted");
2839
2840         // initialize synchronized checkpoint
2841         if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2842             return error("LoadBlockIndex() : failed to init sync checkpoint");
2843     }
2844
2845     string strPubKey = "";
2846     {
2847         CChainDB chaindb;
2848         // if checkpoint master key changed must reset sync-checkpoint
2849         if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2850         {
2851             // write checkpoint master key to db
2852             chaindb.TxnBegin();
2853             if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2854                 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2855             if (!chaindb.TxnCommit())
2856                 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2857             if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2858                 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2859         }
2860     }
2861
2862     return true;
2863 }
2864
2865 void PrintBlockTree()
2866 {
2867     // pre-compute tree structure
2868     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2869     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2870     {
2871         CBlockIndex* pindex = (*mi).second;
2872         mapNext[pindex->pprev].push_back(pindex);
2873         // test
2874         //while (rand() % 3 == 0)
2875         //    mapNext[pindex->pprev].push_back(pindex);
2876     }
2877
2878     vector<pair<int, CBlockIndex*> > vStack;
2879     vStack.push_back(make_pair(0, pindexGenesisBlock));
2880
2881     int nPrevCol = 0;
2882     while (!vStack.empty())
2883     {
2884         int nCol = vStack.back().first;
2885         CBlockIndex* pindex = vStack.back().second;
2886         vStack.pop_back();
2887
2888         // print split or gap
2889         if (nCol > nPrevCol)
2890         {
2891             for (int i = 0; i < nCol-1; i++)
2892                 printf("| ");
2893             printf("|\\\n");
2894         }
2895         else if (nCol < nPrevCol)
2896         {
2897             for (int i = 0; i < nCol; i++)
2898                 printf("| ");
2899             printf("|\n");
2900        }
2901         nPrevCol = nCol;
2902
2903         // print columns
2904         for (int i = 0; i < nCol; i++)
2905             printf("| ");
2906
2907         // print item
2908         CBlock block;
2909         block.ReadFromDisk(pindex);
2910         printf("%d (blk%05u.dat:0x%x)  %s  tx %"PRIszu"",
2911             pindex->nHeight,
2912             pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2913             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2914             block.vtx.size());
2915
2916         PrintWallets(block);
2917
2918         // put the main time-chain first
2919         vector<CBlockIndex*>& vNext = mapNext[pindex];
2920         for (unsigned int i = 0; i < vNext.size(); i++)
2921         {
2922             if (vNext[i]->pnext)
2923             {
2924                 swap(vNext[0], vNext[i]);
2925                 break;
2926             }
2927         }
2928
2929         // iterate children
2930         for (unsigned int i = 0; i < vNext.size(); i++)
2931             vStack.push_back(make_pair(nCol+i, vNext[i]));
2932     }
2933 }
2934
2935 bool LoadExternalBlockFile(FILE* fileIn)
2936 {
2937     int64 nStart = GetTimeMillis();
2938
2939     int nLoaded = 0;
2940     {
2941         LOCK(cs_main);
2942         try {
2943             CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2944             unsigned int nPos = 0;
2945             while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2946             {
2947                 unsigned char pchData[65536];
2948                 do {
2949                     fseek(blkdat, nPos, SEEK_SET);
2950                     int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2951                     if (nRead <= 8)
2952                     {
2953                         nPos = (unsigned int)-1;
2954                         break;
2955                     }
2956                     void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2957                     if (nFind)
2958                     {
2959                         if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2960                         {
2961                             nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2962                             break;
2963                         }
2964                         nPos += ((unsigned char*)nFind - pchData) + 1;
2965                     }
2966                     else
2967                         nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2968                 } while(!fRequestShutdown);
2969                 if (nPos == (unsigned int)-1)
2970                     break;
2971                 fseek(blkdat, nPos, SEEK_SET);
2972                 unsigned int nSize;
2973                 blkdat >> nSize;
2974                 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2975                 {
2976                     CBlock block;
2977                     blkdat >> block;
2978                     if (ProcessBlock(NULL,&block))
2979                     {
2980                         nLoaded++;
2981                         nPos += 4 + nSize;
2982                     }
2983                 }
2984             }
2985         }
2986         catch (std::exception &e) {
2987             printf("%s() : Deserialize or I/O error caught during load\n",
2988                    __PRETTY_FUNCTION__);
2989         }
2990     }
2991     printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2992     return nLoaded > 0;
2993 }
2994
2995 //////////////////////////////////////////////////////////////////////////////
2996 //
2997 // CAlert
2998 //
2999
3000 extern map<uint256, CAlert> mapAlerts;
3001 extern CCriticalSection cs_mapAlerts;
3002
3003 extern string strMintMessage;
3004 extern string strMintWarning;
3005
3006 string GetWarnings(string strFor)
3007 {
3008     int nPriority = 0;
3009     string strStatusBar;
3010     string strRPC;
3011
3012     if (GetBoolArg("-testsafemode"))
3013         strRPC = "test";
3014
3015     // ppcoin: wallet lock warning for minting
3016     if (strMintWarning != "")
3017     {
3018         nPriority = 0;
3019         strStatusBar = strMintWarning;
3020     }
3021
3022     // Misc warnings like out of disk space and clock is wrong
3023     if (strMiscWarning != "")
3024     {
3025         nPriority = 1000;
3026         strStatusBar = strMiscWarning;
3027     }
3028
3029     // * Should not enter safe mode for longer invalid chain
3030     // * If sync-checkpoint is too old do not enter safe mode
3031     // * Display warning only in the STRICT mode
3032     if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
3033         !fTestNet && !IsInitialBlockDownload())
3034     {
3035         nPriority = 100;
3036         strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
3037     }
3038
3039     // ppcoin: if detected invalid checkpoint enter safe mode
3040     if (Checkpoints::hashInvalidCheckpoint != 0)
3041     {
3042         nPriority = 3000;
3043         strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3044     }
3045
3046     // Alerts
3047     {
3048         LOCK(cs_mapAlerts);
3049         BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3050         {
3051             const CAlert& alert = item.second;
3052             if (alert.AppliesToMe() && alert.nPriority > nPriority)
3053             {
3054                 nPriority = alert.nPriority;
3055                 strStatusBar = alert.strStatusBar;
3056                 if (nPriority > 1000)
3057                     strRPC = strStatusBar;
3058             }
3059         }
3060     }
3061
3062     if (strFor == "statusbar")
3063         return strStatusBar;
3064     else if (strFor == "rpc")
3065         return strRPC;
3066     assert(!"GetWarnings() : invalid parameter");
3067     return "error";
3068 }
3069
3070
3071
3072
3073
3074
3075
3076
3077 //////////////////////////////////////////////////////////////////////////////
3078 //
3079 // Messages
3080 //
3081
3082
3083 bool static AlreadyHave(const CInv& inv)
3084 {
3085     switch (inv.type)
3086     {
3087     case MSG_TX:
3088         {
3089             bool txInMap = false;
3090             {
3091                 LOCK(mempool.cs);
3092                 txInMap = mempool.exists(inv.hash);
3093             }
3094             return txInMap || mapOrphanTransactions.count(inv.hash) ||
3095                 pcoinsTip->HaveCoins(inv.hash);
3096         }
3097     case MSG_BLOCK:
3098         return mapBlockIndex.count(inv.hash) ||
3099                mapOrphanBlocks.count(inv.hash);
3100     }
3101     // Don't know what it is, just say we already got one
3102     return true;
3103 }
3104
3105
3106
3107
3108 // The message start string is designed to be unlikely to occur in normal data.
3109 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3110 // a large 4-byte int at any alignment.
3111 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3112
3113 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3114 {
3115     static map<CService, CPubKey> mapReuseKey;
3116     RandAddSeedPerfmon();
3117     if (fDebug)
3118         printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3119     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3120     {
3121         printf("dropmessagestest DROPPING RECV MESSAGE\n");
3122         return true;
3123     }
3124
3125     if (strCommand == "version")
3126     {
3127         // Each connection can only send one version message
3128         if (pfrom->nVersion != 0)
3129         {
3130             pfrom->Misbehaving(1);
3131             return false;
3132         }
3133
3134         int64 nTime;
3135         CAddress addrMe;
3136         CAddress addrFrom;
3137         uint64 nNonce = 1;
3138         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3139         if (pfrom->nVersion < MIN_PROTO_VERSION)
3140         {
3141             // Since February 20, 2012, the protocol is initiated at version 209,
3142             // and earlier versions are no longer supported
3143             printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3144             pfrom->fDisconnect = true;
3145             return false;
3146         }
3147
3148         if (pfrom->nVersion == 10300)
3149             pfrom->nVersion = 300;
3150         if (!vRecv.empty())
3151             vRecv >> addrFrom >> nNonce;
3152         if (!vRecv.empty())
3153             vRecv >> pfrom->strSubVer;
3154         if (!vRecv.empty())
3155             vRecv >> pfrom->nStartingHeight;
3156
3157         if (pfrom->fInbound && addrMe.IsRoutable())
3158         {
3159             pfrom->addrLocal = addrMe;
3160             SeenLocal(addrMe);
3161         }
3162
3163         // Disconnect if we connected to ourself
3164         if (nNonce == nLocalHostNonce && nNonce > 1)
3165         {
3166             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3167             pfrom->fDisconnect = true;
3168             return true;
3169         }
3170
3171         // record my external IP reported by peer
3172         if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3173             addrSeenByPeer = addrMe;
3174
3175         // Be shy and don't send version until we hear
3176         if (pfrom->fInbound)
3177             pfrom->PushVersion();
3178
3179         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3180
3181         AddTimeData(pfrom->addr, nTime);
3182
3183         // Change version
3184         pfrom->PushMessage("verack");
3185         pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3186
3187         if (!pfrom->fInbound)
3188         {
3189             // Advertise our address
3190             if (!fNoListen && !IsInitialBlockDownload())
3191             {
3192                 CAddress addr = GetLocalAddress(&pfrom->addr);
3193                 if (addr.IsRoutable())
3194                     pfrom->PushAddress(addr);
3195             }
3196
3197             // Get recent addresses
3198             if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3199             {
3200                 pfrom->PushMessage("getaddr");
3201                 pfrom->fGetAddr = true;
3202             }
3203             addrman.Good(pfrom->addr);
3204         } else {
3205             if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3206             {
3207                 addrman.Add(addrFrom, addrFrom);
3208                 addrman.Good(addrFrom);
3209             }
3210         }
3211
3212         // Ask the first connected node for block updates
3213         static int nAskedForBlocks = 0;
3214         if (!pfrom->fClient && !pfrom->fOneShot &&
3215             (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3216             (pfrom->nVersion < NOBLKS_VERSION_START ||
3217              pfrom->nVersion >= NOBLKS_VERSION_END) &&
3218              (nAskedForBlocks < 1 || vNodes.size() <= 1))
3219         {
3220             nAskedForBlocks++;
3221             pfrom->PushGetBlocks(pindexBest, uint256(0));
3222         }
3223
3224         // Relay alerts
3225         {
3226             LOCK(cs_mapAlerts);
3227             BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3228                 item.second.RelayTo(pfrom);
3229         }
3230
3231         // Relay sync-checkpoint
3232         {
3233             LOCK(Checkpoints::cs_hashSyncCheckpoint);
3234             if (!Checkpoints::checkpointMessage.IsNull())
3235                 Checkpoints::checkpointMessage.RelayTo(pfrom);
3236         }
3237
3238         pfrom->fSuccessfullyConnected = true;
3239
3240         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());
3241
3242         cPeerBlockCounts.input(pfrom->nStartingHeight);
3243
3244         // ppcoin: ask for pending sync-checkpoint if any
3245         if (!IsInitialBlockDownload())
3246             Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3247     }
3248
3249
3250     else if (pfrom->nVersion == 0)
3251     {
3252         // Must have a version message before anything else
3253         pfrom->Misbehaving(1);
3254         return false;
3255     }
3256
3257
3258     else if (strCommand == "verack")
3259     {
3260         pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3261     }
3262
3263
3264     else if (strCommand == "addr")
3265     {
3266         vector<CAddress> vAddr;
3267         vRecv >> vAddr;
3268
3269         // Don't want addr from older versions unless seeding
3270         if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3271             return true;
3272         if (vAddr.size() > 1000)
3273         {
3274             pfrom->Misbehaving(20);
3275             return error("message addr size() = %"PRIszu"", vAddr.size());
3276         }
3277
3278         // Store the new addresses
3279         vector<CAddress> vAddrOk;
3280         int64 nNow = GetAdjustedTime();
3281         int64 nSince = nNow - 10 * 60;
3282         BOOST_FOREACH(CAddress& addr, vAddr)
3283         {
3284             if (fShutdown)
3285                 return true;
3286             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3287                 addr.nTime = nNow - 5 * 24 * 60 * 60;
3288             pfrom->AddAddressKnown(addr);
3289             bool fReachable = IsReachable(addr);
3290             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3291             {
3292                 // Relay to a limited number of other nodes
3293                 {
3294                     LOCK(cs_vNodes);
3295                     // Use deterministic randomness to send to the same nodes for 24 hours
3296                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3297                     static uint256 hashSalt;
3298                     if (hashSalt == 0)
3299                         hashSalt = GetRandHash();
3300                     uint64 hashAddr = addr.GetHash();
3301                     uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3302                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3303                     multimap<uint256, CNode*> mapMix;
3304                     BOOST_FOREACH(CNode* pnode, vNodes)
3305                     {
3306                         if (pnode->nVersion < CADDR_TIME_VERSION)
3307                             continue;
3308                         unsigned int nPointer;
3309                         memcpy(&nPointer, &pnode, sizeof(nPointer));
3310                         uint256 hashKey = hashRand ^ nPointer;
3311                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
3312                         mapMix.insert(make_pair(hashKey, pnode));
3313                     }
3314                     int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3315                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3316                         ((*mi).second)->PushAddress(addr);
3317                 }
3318             }
3319             // Do not store addresses outside our network
3320             if (fReachable)
3321                 vAddrOk.push_back(addr);
3322         }
3323         addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3324         if (vAddr.size() < 1000)
3325             pfrom->fGetAddr = false;
3326         if (pfrom->fOneShot)
3327             pfrom->fDisconnect = true;
3328     }
3329
3330     else if (strCommand == "inv")
3331     {
3332         vector<CInv> vInv;
3333         vRecv >> vInv;
3334         if (vInv.size() > MAX_INV_SZ)
3335         {
3336             pfrom->Misbehaving(20);
3337             return error("message inv size() = %"PRIszu"", vInv.size());
3338         }
3339
3340         // find last block in inv vector
3341         unsigned int nLastBlock = (unsigned int)(-1);
3342         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3343             if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3344                 nLastBlock = vInv.size() - 1 - nInv;
3345                 break;
3346             }
3347         }
3348         for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3349         {
3350             const CInv &inv = vInv[nInv];
3351
3352             if (fShutdown)
3353                 return true;
3354             pfrom->AddInventoryKnown(inv);
3355
3356             bool fAlreadyHave = AlreadyHave(inv);
3357             if (fDebug)
3358                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3359
3360             if (!fAlreadyHave)
3361                 pfrom->AskFor(inv);
3362             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3363                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3364             } else if (nInv == nLastBlock) {
3365                 // In case we are on a very long side-chain, it is possible that we already have
3366                 // the last block in an inv bundle sent in response to getblocks. Try to detect
3367                 // this situation and push another getblocks to continue.
3368                 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3369                 if (fDebug)
3370                     printf("force request: %s\n", inv.ToString().c_str());
3371             }
3372
3373             // Track requests for our stuff
3374             Inventory(inv.hash);
3375         }
3376     }
3377
3378
3379     else if (strCommand == "getdata")
3380     {
3381         vector<CInv> vInv;
3382         vRecv >> vInv;
3383         if (vInv.size() > MAX_INV_SZ)
3384         {
3385             pfrom->Misbehaving(20);
3386             return error("message getdata size() = %"PRIszu"", vInv.size());
3387         }
3388
3389         if (fDebugNet || (vInv.size() != 1))
3390             printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3391
3392         BOOST_FOREACH(const CInv& inv, vInv)
3393         {
3394             if (fShutdown)
3395                 return true;
3396             if (fDebugNet || (vInv.size() == 1))
3397                 printf("received getdata for: %s\n", inv.ToString().c_str());
3398
3399             if (inv.type == MSG_BLOCK)
3400             {
3401                 // Send block from disk
3402                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3403                 if (mi != mapBlockIndex.end())
3404                 {
3405                     CBlock block;
3406                     block.ReadFromDisk((*mi).second);
3407                     pfrom->PushMessage("block", block);
3408
3409                     // Trigger them to send a getblocks request for the next batch of inventory
3410                     if (inv.hash == pfrom->hashContinue)
3411                     {
3412                         // ppcoin: send latest proof-of-work block to allow the
3413                         // download node to accept as orphan (proof-of-stake 
3414                         // block might be rejected by stake connection check)
3415                         vector<CInv> vInv;
3416                         vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3417                         pfrom->PushMessage("inv", vInv);
3418                         pfrom->hashContinue = 0;
3419                     }
3420                 }
3421             }
3422             else if (inv.IsKnownType())
3423             {
3424                 // Send stream from relay memory
3425                 bool pushed = false;
3426                 {
3427                     LOCK(cs_mapRelay);
3428                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3429                     if (mi != mapRelay.end()) {
3430                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3431                         pushed = true;
3432                     }
3433                 }
3434                 if (!pushed && inv.type == MSG_TX) {
3435                     LOCK(mempool.cs);
3436                     if (mempool.exists(inv.hash)) {
3437                         CTransaction tx = mempool.lookup(inv.hash);
3438                         CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3439                         ss.reserve(1000);
3440                         ss << tx;
3441                         pfrom->PushMessage("tx", ss);
3442                     }
3443                 }
3444             }
3445
3446             // Track requests for our stuff
3447             Inventory(inv.hash);
3448         }
3449     }
3450
3451
3452     else if (strCommand == "getblocks")
3453     {
3454         CBlockLocator locator;
3455         uint256 hashStop;
3456         vRecv >> locator >> hashStop;
3457
3458         // Find the last block the caller has in the main chain
3459         CBlockIndex* pindex = locator.GetBlockIndex();
3460
3461         // Send the rest of the chain
3462         if (pindex)
3463             pindex = pindex->pnext;
3464         int nLimit = 500;
3465         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3466         for (; pindex; pindex = pindex->pnext)
3467         {
3468             if (pindex->GetBlockHash() == hashStop)
3469             {
3470                 printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3471                 // ppcoin: tell downloading node about the latest block if it's
3472                 // without risk being rejected due to stake connection check
3473                 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3474                     pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3475                 break;
3476             }
3477             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3478             if (--nLimit <= 0)
3479             {
3480                 // When this block is requested, we'll send an inv that'll make them
3481                 // getblocks the next batch of inventory.
3482                 printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3483                 pfrom->hashContinue = pindex->GetBlockHash();
3484                 break;
3485             }
3486         }
3487     }
3488     else if (strCommand == "checkpoint")
3489     {
3490         CSyncCheckpoint checkpoint;
3491         vRecv >> checkpoint;
3492
3493         if (checkpoint.ProcessSyncCheckpoint(pfrom))
3494         {
3495             // Relay
3496             pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3497             LOCK(cs_vNodes);
3498             BOOST_FOREACH(CNode* pnode, vNodes)
3499                 checkpoint.RelayTo(pnode);
3500         }
3501     }
3502
3503     else if (strCommand == "getheaders")
3504     {
3505         CBlockLocator locator;
3506         uint256 hashStop;
3507         vRecv >> locator >> hashStop;
3508
3509         CBlockIndex* pindex = NULL;
3510         if (locator.IsNull())
3511         {
3512             // If locator is null, return the hashStop block
3513             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3514             if (mi == mapBlockIndex.end())
3515                 return true;
3516             pindex = (*mi).second;
3517         }
3518         else
3519         {
3520             // Find the last block the caller has in the main chain
3521             pindex = locator.GetBlockIndex();
3522             if (pindex)
3523                 pindex = pindex->pnext;
3524         }
3525
3526         vector<CBlock> vHeaders;
3527         int nLimit = 2000;
3528         printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3529         for (; pindex; pindex = pindex->pnext)
3530         {
3531             vHeaders.push_back(pindex->GetBlockHeader());
3532             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3533                 break;
3534         }
3535         pfrom->PushMessage("headers", vHeaders);
3536     }
3537
3538
3539     else if (strCommand == "tx")
3540     {
3541         vector<uint256> vWorkQueue;
3542         vector<uint256> vEraseQueue;
3543         CDataStream vMsg(vRecv);
3544         CTransaction tx;
3545         vRecv >> tx;
3546
3547         CInv inv(MSG_TX, tx.GetHash());
3548         pfrom->AddInventoryKnown(inv);
3549
3550         bool fMissingInputs = false;
3551         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3552         {
3553             SyncWithWallets(inv.hash, tx, NULL, true);
3554             RelayTransaction(tx, inv.hash);
3555             mapAlreadyAskedFor.erase(inv);
3556             vWorkQueue.push_back(inv.hash);
3557             vEraseQueue.push_back(inv.hash);
3558
3559             // Recursively process any orphan transactions that depended on this one
3560             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3561             {
3562                 uint256 hashPrev = vWorkQueue[i];
3563                 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3564                      mi != mapOrphanTransactionsByPrev[hashPrev].end();
3565                      ++mi)
3566                 {
3567                     const uint256& orphanTxHash = *mi;
3568                     CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3569                     bool fMissingInputs2 = false;
3570
3571                     if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
3572                     {
3573                         printf("   accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3574                         SyncWithWallets(inv.hash, tx, NULL, true);
3575                         RelayTransaction(orphanTx, orphanTxHash);
3576                         mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3577                         vWorkQueue.push_back(orphanTxHash);
3578                         vEraseQueue.push_back(orphanTxHash);
3579                     }
3580                     else if (!fMissingInputs2)
3581                     {
3582                         // invalid orphan
3583                         vEraseQueue.push_back(orphanTxHash);
3584                         printf("   removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3585                     }
3586                 }
3587             }
3588
3589             BOOST_FOREACH(uint256 hash, vEraseQueue)
3590                 EraseOrphanTx(hash);
3591         }
3592         else if (fMissingInputs)
3593         {
3594             AddOrphanTx(tx);
3595
3596             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3597             unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3598             if (nEvicted > 0)
3599                 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3600         }
3601         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3602     }
3603
3604
3605     else if (strCommand == "block")
3606     {
3607         CBlock block;
3608         vRecv >> block;
3609         uint256 hashBlock = block.GetHash();
3610
3611         printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3612         // block.print();
3613
3614         CInv inv(MSG_BLOCK, hashBlock);
3615         pfrom->AddInventoryKnown(inv);
3616
3617         if (ProcessBlock(pfrom, &block))
3618             mapAlreadyAskedFor.erase(inv);
3619         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3620     }
3621
3622
3623     else if (strCommand == "getaddr")
3624     {
3625         // Don't return addresses older than nCutOff timestamp
3626         int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3627         pfrom->vAddrToSend.clear();
3628         vector<CAddress> vAddr = addrman.GetAddr();
3629         BOOST_FOREACH(const CAddress &addr, vAddr)
3630             if(addr.nTime > nCutOff)
3631                 pfrom->PushAddress(addr);
3632     }
3633
3634
3635     else if (strCommand == "mempool")
3636     {
3637         std::vector<uint256> vtxid;
3638         mempool.queryHashes(vtxid);
3639         vector<CInv> vInv;
3640         for (unsigned int i = 0; i < vtxid.size(); i++) {
3641             CInv inv(MSG_TX, vtxid[i]);
3642             vInv.push_back(inv);
3643             if (i == (MAX_INV_SZ - 1))
3644                     break;
3645         }
3646         if (vInv.size() > 0)
3647             pfrom->PushMessage("inv", vInv);
3648     }
3649
3650
3651     else if (strCommand == "checkorder")
3652     {
3653         uint256 hashReply;
3654         vRecv >> hashReply;
3655
3656         if (!GetBoolArg("-allowreceivebyip"))
3657         {
3658             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3659             return true;
3660         }
3661
3662         CWalletTx order;
3663         vRecv >> order;
3664
3665         /// we have a chance to check the order here
3666
3667         // Keep giving the same key to the same ip until they use it
3668         if (!mapReuseKey.count(pfrom->addr))
3669             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3670
3671         // Send back approval of order and pubkey to use
3672         CScript scriptPubKey;
3673         scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3674         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3675     }
3676
3677
3678     else if (strCommand == "reply")
3679     {
3680         uint256 hashReply;
3681         vRecv >> hashReply;
3682
3683         CRequestTracker tracker;
3684         {
3685             LOCK(pfrom->cs_mapRequests);
3686             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3687             if (mi != pfrom->mapRequests.end())
3688             {
3689                 tracker = (*mi).second;
3690                 pfrom->mapRequests.erase(mi);
3691             }
3692         }
3693         if (!tracker.IsNull())
3694             tracker.fn(tracker.param1, vRecv);
3695     }
3696
3697
3698     else if (strCommand == "ping")
3699     {
3700         if (pfrom->nVersion > BIP0031_VERSION)
3701         {
3702             uint64 nonce = 0;
3703             vRecv >> nonce;
3704             // Echo the message back with the nonce. This allows for two useful features:
3705             //
3706             // 1) A remote node can quickly check if the connection is operational
3707             // 2) Remote nodes can measure the latency of the network thread. If this node
3708             //    is overloaded it won't respond to pings quickly and the remote node can
3709             //    avoid sending us more work, like chain download requests.
3710             //
3711             // The nonce stops the remote getting confused between different pings: without
3712             // it, if the remote node sends a ping once per second and this node takes 5
3713             // seconds to respond to each, the 5th ping the remote sends would appear to
3714             // return very quickly.
3715             pfrom->PushMessage("pong", nonce);
3716         }
3717     }
3718
3719
3720     else if (strCommand == "alert")
3721     {
3722         CAlert alert;
3723         vRecv >> alert;
3724
3725         uint256 alertHash = alert.GetHash();
3726         if (pfrom->setKnown.count(alertHash) == 0)
3727         {
3728             if (alert.ProcessAlert())
3729             {
3730                 // Relay
3731                 pfrom->setKnown.insert(alertHash);
3732                 {
3733                     LOCK(cs_vNodes);
3734                     BOOST_FOREACH(CNode* pnode, vNodes)
3735                         alert.RelayTo(pnode);
3736                 }
3737             }
3738             else {
3739                 // Small DoS penalty so peers that send us lots of
3740                 // duplicate/expired/invalid-signature/whatever alerts
3741                 // eventually get banned.
3742                 // This isn't a Misbehaving(100) (immediate ban) because the
3743                 // peer might be an older or different implementation with
3744                 // a different signature key, etc.
3745                 pfrom->Misbehaving(10);
3746             }
3747         }
3748     }
3749
3750
3751     else
3752     {
3753         // Ignore unknown commands for extensibility
3754     }
3755
3756
3757     // Update the last seen time for this node's address
3758     if (pfrom->fNetworkNode)
3759         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3760             AddressCurrentlyConnected(pfrom->addr);
3761
3762
3763     return true;
3764 }
3765
3766 bool ProcessMessages(CNode* pfrom)
3767 {
3768     CDataStream& vRecv = pfrom->vRecv;
3769     if (vRecv.empty())
3770         return true;
3771     //if (fDebug)
3772     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
3773
3774     //
3775     // Message format
3776     //  (4) message start
3777     //  (12) command
3778     //  (4) size
3779     //  (4) checksum
3780     //  (x) data
3781     //
3782
3783     while (true)
3784     {
3785         // Don't bother if send buffer is too full to respond anyway
3786         if (pfrom->vSend.size() >= SendBufferSize())
3787             break;
3788
3789         // Scan for message start
3790         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3791         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3792         if (vRecv.end() - pstart < nHeaderSize)
3793         {
3794             if ((int)vRecv.size() > nHeaderSize)
3795             {
3796                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3797                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3798             }
3799             break;
3800         }
3801         if (pstart - vRecv.begin() > 0)
3802             printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3803         vRecv.erase(vRecv.begin(), pstart);
3804
3805         // Read header
3806         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3807         CMessageHeader hdr;
3808         vRecv >> hdr;
3809         if (!hdr.IsValid())
3810         {
3811             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3812             continue;
3813         }
3814         string strCommand = hdr.GetCommand();
3815
3816         // Message size
3817         unsigned int nMessageSize = hdr.nMessageSize;
3818         if (nMessageSize > MAX_SIZE)
3819         {
3820             printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3821             continue;
3822         }
3823         if (nMessageSize > vRecv.size())
3824         {
3825             // Rewind and wait for rest of message
3826             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3827             break;
3828         }
3829
3830         // Checksum
3831         uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3832         unsigned int nChecksum = 0;
3833         memcpy(&nChecksum, &hash, sizeof(nChecksum));
3834         if (nChecksum != hdr.nChecksum)
3835         {
3836             printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3837                strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3838             continue;
3839         }
3840
3841         // Copy message to its own buffer
3842         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3843         vRecv.ignore(nMessageSize);
3844
3845         // Process message
3846         bool fRet = false;
3847         try
3848         {
3849             {
3850                 LOCK(cs_main);
3851                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3852             }
3853             if (fShutdown)
3854                 return true;
3855         }
3856         catch (std::ios_base::failure& e)
3857         {
3858             if (strstr(e.what(), "end of data"))
3859             {
3860                 // Allow exceptions from under-length message on vRecv
3861                 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());
3862             }
3863             else if (strstr(e.what(), "size too large"))
3864             {
3865                 // Allow exceptions from over-long size
3866                 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3867             }
3868             else
3869             {
3870                 PrintExceptionContinue(&e, "ProcessMessages()");
3871             }
3872         }
3873         catch (std::exception& e) {
3874             PrintExceptionContinue(&e, "ProcessMessages()");
3875         } catch (...) {
3876             PrintExceptionContinue(NULL, "ProcessMessages()");
3877         }
3878
3879         if (!fRet)
3880             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3881     }
3882
3883     vRecv.Compact();
3884     return true;
3885 }
3886
3887
3888 bool SendMessages(CNode* pto, bool fSendTrickle)
3889 {
3890     TRY_LOCK(cs_main, lockMain);
3891     if (lockMain) {
3892         // Don't send anything until we get their version message
3893         if (pto->nVersion == 0)
3894             return true;
3895
3896         // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3897         // right now.
3898         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3899             uint64 nonce = 0;
3900             if (pto->nVersion > BIP0031_VERSION)
3901                 pto->PushMessage("ping", nonce);
3902             else
3903                 pto->PushMessage("ping");
3904         }
3905
3906         // Resend wallet transactions that haven't gotten in a block yet
3907         ResendWalletTransactions();
3908
3909         // Address refresh broadcast
3910         static int64 nLastRebroadcast;
3911         if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3912         {
3913             {
3914                 LOCK(cs_vNodes);
3915                 BOOST_FOREACH(CNode* pnode, vNodes)
3916                 {
3917                     // Periodically clear setAddrKnown to allow refresh broadcasts
3918                     if (nLastRebroadcast)
3919                         pnode->setAddrKnown.clear();
3920
3921                     // Rebroadcast our address
3922                     if (!fNoListen)
3923                     {
3924                         CAddress addr = GetLocalAddress(&pnode->addr);
3925                         if (addr.IsRoutable())
3926                             pnode->PushAddress(addr);
3927                     }
3928                 }
3929             }
3930             nLastRebroadcast = GetTime();
3931         }
3932
3933         //
3934         // Message: addr
3935         //
3936         if (fSendTrickle)
3937         {
3938             vector<CAddress> vAddr;
3939             vAddr.reserve(pto->vAddrToSend.size());
3940             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3941             {
3942                 // returns true if wasn't already contained in the set
3943                 if (pto->setAddrKnown.insert(addr).second)
3944                 {
3945                     vAddr.push_back(addr);
3946                     // receiver rejects addr messages larger than 1000
3947                     if (vAddr.size() >= 1000)
3948                     {
3949                         pto->PushMessage("addr", vAddr);
3950                         vAddr.clear();
3951                     }
3952                 }
3953             }
3954             pto->vAddrToSend.clear();
3955             if (!vAddr.empty())
3956                 pto->PushMessage("addr", vAddr);
3957         }
3958
3959
3960         //
3961         // Message: inventory
3962         //
3963         vector<CInv> vInv;
3964         vector<CInv> vInvWait;
3965         {
3966             LOCK(pto->cs_inventory);
3967             vInv.reserve(pto->vInventoryToSend.size());
3968             vInvWait.reserve(pto->vInventoryToSend.size());
3969             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3970             {
3971                 if (pto->setInventoryKnown.count(inv))
3972                     continue;
3973
3974                 // trickle out tx inv to protect privacy
3975                 if (inv.type == MSG_TX && !fSendTrickle)
3976                 {
3977                     // 1/4 of tx invs blast to all immediately
3978                     static uint256 hashSalt;
3979                     if (hashSalt == 0)
3980                         hashSalt = GetRandHash();
3981                     uint256 hashRand = inv.hash ^ hashSalt;
3982                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
3983                     bool fTrickleWait = ((hashRand & 3) != 0);
3984
3985                     // always trickle our own transactions
3986                     if (!fTrickleWait)
3987                     {
3988                         CWalletTx wtx;
3989                         if (GetTransaction(inv.hash, wtx))
3990                             if (wtx.fFromMe)
3991                                 fTrickleWait = true;
3992                     }
3993
3994                     if (fTrickleWait)
3995                     {
3996                         vInvWait.push_back(inv);
3997                         continue;
3998                     }
3999                 }
4000
4001                 // returns true if wasn't already contained in the set
4002                 if (pto->setInventoryKnown.insert(inv).second)
4003                 {
4004                     vInv.push_back(inv);
4005                     if (vInv.size() >= 1000)
4006                     {
4007                         pto->PushMessage("inv", vInv);
4008                         vInv.clear();
4009                     }
4010                 }
4011             }
4012             pto->vInventoryToSend = vInvWait;
4013         }
4014         if (!vInv.empty())
4015             pto->PushMessage("inv", vInv);
4016
4017
4018         //
4019         // Message: getdata
4020         //
4021         vector<CInv> vGetData;
4022         int64 nNow = GetTime() * 1000000;
4023         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4024         {
4025             const CInv& inv = (*pto->mapAskFor.begin()).second;
4026             if (!AlreadyHave(inv))
4027             {
4028                 if (fDebugNet)
4029                     printf("sending getdata: %s\n", inv.ToString().c_str());
4030                 vGetData.push_back(inv);
4031                 if (vGetData.size() >= 1000)
4032                 {
4033                     pto->PushMessage("getdata", vGetData);
4034                     vGetData.clear();
4035                 }
4036                 mapAlreadyAskedFor[inv] = nNow;
4037             }
4038             pto->mapAskFor.erase(pto->mapAskFor.begin());
4039         }
4040         if (!vGetData.empty())
4041             pto->PushMessage("getdata", vGetData);
4042
4043     }
4044     return true;
4045 }
4046
4047 // Amount compression:
4048 // * If the amount is 0, output 0
4049 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4050 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4051 //   * call the result n
4052 //   * output 1 + 10*(9*n + d - 1) + e
4053 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4054 // (this is decodable, as d is in [1-9] and e is in [0-9])
4055
4056 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4057 {
4058     if (n == 0)
4059         return 0;
4060     int e = 0;
4061     while (((n % 10) == 0) && e < 9) {
4062         n /= 10;
4063         e++;
4064     }
4065     if (e < 9) {
4066         int d = (n % 10);
4067         assert(d >= 1 && d <= 9);
4068         n /= 10;
4069         return 1 + (n*9 + d - 1)*10 + e;
4070     } else {
4071         return 1 + (n - 1)*10 + 9;
4072     }
4073 }
4074
4075 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4076 {
4077     // x = 0  OR  x = 1+10*(9*n + d - 1) + e  OR  x = 1+10*(n - 1) + 9
4078     if (x == 0)
4079         return 0;
4080     x--;
4081     // x = 10*(9*n + d - 1) + e
4082     int e = x % 10;
4083     x /= 10;
4084     uint64 n = 0;
4085     if (e < 9) {
4086         // x = 9*n + d - 1
4087         int d = (x % 9) + 1;
4088         x /= 9;
4089         // x = n
4090         n = x*10 + d;
4091     } else {
4092         n = x+1;
4093     }
4094     while (e) {
4095         n *= 10;
4096         e--;
4097     }
4098     return n;
4099 }