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