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