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