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