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