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