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