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