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