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