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