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