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