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