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