Replace VerifyScript with CScriptCheck
[novacoin.git] / src / main.h
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 #ifndef BITCOIN_MAIN_H
6 #define BITCOIN_MAIN_H
7
8 #include "timestamps.h"
9 #include "bignum.h"
10 #include "sync.h"
11 #include "net.h"
12 #include "script.h"
13 #include "scrypt.h"
14 #include "zerocoin/Zerocoin.h"
15
16 #include <list>
17
18 class CWallet;
19 class CBlock;
20 class CBlockIndex;
21 class CKeyItem;
22 class CReserveKey;
23 class COutPoint;
24
25 class CAddress;
26 class CInv;
27 class CRequestTracker;
28 class CNode;
29
30 static const unsigned int MAX_BLOCK_SIZE = 1000000;
31 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
34 static const unsigned int MAX_INV_SZ = 50000;
35
36 static const int64 MIN_TX_FEE = CENT/10;
37 static const int64 MIN_RELAY_TX_FEE = CENT/50;
38
39 static const int64 MAX_MONEY = 2000000000 * COIN;
40 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
41 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
42 static const int64 MIN_TXOUT_AMOUNT = CENT/100;
43
44 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
45 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
46 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
47
48 #ifdef USE_UPNP
49 static const int fHaveUPnP = true;
50 #else
51 static const int fHaveUPnP = false;
52 #endif
53
54 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
55 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
56
57 inline int64 PastDrift(int64 nTime)   { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
58 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
59
60 extern libzerocoin::Params* ZCParams;
61 extern CScript COINBASE_FLAGS;
62 extern CCriticalSection cs_main;
63 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
64 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
65 extern CBlockIndex* pindexGenesisBlock;
66 extern unsigned int nStakeMinAge;
67 extern unsigned int nNodeLifespan;
68 extern int nCoinbaseMaturity;
69 extern int nBestHeight;
70 extern uint256 nBestChainTrust;
71 extern uint256 nBestInvalidTrust;
72 extern uint256 hashBestChain;
73 extern CBlockIndex* pindexBest;
74 extern unsigned int nTransactionsUpdated;
75 extern uint64 nLastBlockTx;
76 extern uint64 nLastBlockSize;
77 extern int64 nLastCoinStakeSearchInterval;
78 extern const std::string strMessageMagic;
79 extern int64 nTimeBestReceived;
80 extern CCriticalSection cs_setpwalletRegistered;
81 extern std::set<CWallet*> setpwalletRegistered;
82 extern unsigned char pchMessageStart[4];
83 extern std::map<uint256, CBlock*> mapOrphanBlocks;
84
85 // Settings
86 extern int64 nTransactionFee;
87 extern int64 nMinimumInputValue;
88 extern bool fUseFastIndex;
89 extern unsigned int nDerivationMethodIndex;
90
91 // Minimum disk space required - used in CheckDiskSpace()
92 static const uint64 nMinDiskSpace = 52428800;
93
94 class CReserveKey;
95 class CTxDB;
96 class CTxIndex;
97
98 void RegisterWallet(CWallet* pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn);
100 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
101 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
102 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
103 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
104 FILE* AppendBlockFile(unsigned int& nFileRet);
105 bool LoadBlockIndex(bool fAllowNew=true);
106 void PrintBlockTree();
107 CBlockIndex* FindBlockByHeight(int nHeight);
108 bool ProcessMessages(CNode* pfrom);
109 bool SendMessages(CNode* pto, bool fSendTrickle);
110 bool LoadExternalBlockFile(FILE* fileIn);
111
112 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
113 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
114 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees=0);
115 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
116 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
117 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
118 int GetNumBlocksOfPeers();
119 bool IsInitialBlockDownload();
120 std::string GetWarnings(std::string strFor);
121 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
122 uint256 WantedByOrphan(const CBlock* pblockOrphan);
123 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
124 void StakeMiner(CWallet *pwallet);
125 void ResendWalletTransactions();
126
127 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
128
129
130
131
132
133
134
135 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
136
137 /** Position on disk for a particular transaction. */
138 class CDiskTxPos
139 {
140 public:
141     unsigned int nFile;
142     unsigned int nBlockPos;
143     unsigned int nTxPos;
144
145     CDiskTxPos()
146     {
147         SetNull();
148     }
149
150     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
151     {
152         nFile = nFileIn;
153         nBlockPos = nBlockPosIn;
154         nTxPos = nTxPosIn;
155     }
156
157     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
158     void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
159     bool IsNull() const { return (nFile == (unsigned int) -1); }
160
161     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
162     {
163         return (a.nFile     == b.nFile &&
164                 a.nBlockPos == b.nBlockPos &&
165                 a.nTxPos    == b.nTxPos);
166     }
167
168     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
169     {
170         return !(a == b);
171     }
172
173
174     std::string ToString() const
175     {
176         if (IsNull())
177             return "null";
178         else
179             return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
180     }
181
182     void print() const
183     {
184         printf("%s", ToString().c_str());
185     }
186 };
187
188
189
190 /** An inpoint - a combination of a transaction and an index n into its vin */
191 class CInPoint
192 {
193 public:
194     CTransaction* ptx;
195     unsigned int n;
196
197     CInPoint() { SetNull(); }
198     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
199     void SetNull() { ptx = NULL; n = (unsigned int) -1; }
200     bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
201 };
202
203
204
205 /** An outpoint - a combination of a transaction hash and an index n into its vout */
206 class COutPoint
207 {
208 public:
209     uint256 hash;
210     unsigned int n;
211
212     COutPoint() { SetNull(); }
213     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
214     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
215     void SetNull() { hash = 0; n = (unsigned int) -1; }
216     bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
217
218     friend bool operator<(const COutPoint& a, const COutPoint& b)
219     {
220         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
221     }
222
223     friend bool operator==(const COutPoint& a, const COutPoint& b)
224     {
225         return (a.hash == b.hash && a.n == b.n);
226     }
227
228     friend bool operator!=(const COutPoint& a, const COutPoint& b)
229     {
230         return !(a == b);
231     }
232
233     std::string ToString() const
234     {
235         return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
236     }
237
238     void print() const
239     {
240         printf("%s\n", ToString().c_str());
241     }
242 };
243
244
245
246
247 /** An input of a transaction.  It contains the location of the previous
248  * transaction's output that it claims and a signature that matches the
249  * output's public key.
250  */
251 class CTxIn
252 {
253 public:
254     COutPoint prevout;
255     CScript scriptSig;
256     unsigned int nSequence;
257
258     CTxIn()
259     {
260         nSequence = std::numeric_limits<unsigned int>::max();
261     }
262
263     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
264     {
265         prevout = prevoutIn;
266         scriptSig = scriptSigIn;
267         nSequence = nSequenceIn;
268     }
269
270     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
271     {
272         prevout = COutPoint(hashPrevTx, nOut);
273         scriptSig = scriptSigIn;
274         nSequence = nSequenceIn;
275     }
276
277     IMPLEMENT_SERIALIZE
278     (
279         READWRITE(prevout);
280         READWRITE(scriptSig);
281         READWRITE(nSequence);
282     )
283
284     bool IsFinal() const
285     {
286         return (nSequence == std::numeric_limits<unsigned int>::max());
287     }
288
289     friend bool operator==(const CTxIn& a, const CTxIn& b)
290     {
291         return (a.prevout   == b.prevout &&
292                 a.scriptSig == b.scriptSig &&
293                 a.nSequence == b.nSequence);
294     }
295
296     friend bool operator!=(const CTxIn& a, const CTxIn& b)
297     {
298         return !(a == b);
299     }
300
301     std::string ToStringShort() const
302     {
303         return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
304     }
305
306     std::string ToString() const
307     {
308         std::string str;
309         str += "CTxIn(";
310         str += prevout.ToString();
311         if (prevout.IsNull())
312             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
313         else
314             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
315         if (nSequence != std::numeric_limits<unsigned int>::max())
316             str += strprintf(", nSequence=%u", nSequence);
317         str += ")";
318         return str;
319     }
320
321     void print() const
322     {
323         printf("%s\n", ToString().c_str());
324     }
325 };
326
327
328
329
330 /** An output of a transaction.  It contains the public key that the next input
331  * must be able to sign with to claim it.
332  */
333 class CTxOut
334 {
335 public:
336     int64 nValue;
337     CScript scriptPubKey;
338
339     CTxOut()
340     {
341         SetNull();
342     }
343
344     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
345     {
346         nValue = nValueIn;
347         scriptPubKey = scriptPubKeyIn;
348     }
349
350     IMPLEMENT_SERIALIZE
351     (
352         READWRITE(nValue);
353         READWRITE(scriptPubKey);
354     )
355
356     void SetNull()
357     {
358         nValue = -1;
359         scriptPubKey.clear();
360     }
361
362     bool IsNull()
363     {
364         return (nValue == -1);
365     }
366
367     void SetEmpty()
368     {
369         nValue = 0;
370         scriptPubKey.clear();
371     }
372
373     bool IsEmpty() const
374     {
375         return (nValue == 0 && scriptPubKey.empty());
376     }
377
378     uint256 GetHash() const
379     {
380         return SerializeHash(*this);
381     }
382
383     friend bool operator==(const CTxOut& a, const CTxOut& b)
384     {
385         return (a.nValue       == b.nValue &&
386                 a.scriptPubKey == b.scriptPubKey);
387     }
388
389     friend bool operator!=(const CTxOut& a, const CTxOut& b)
390     {
391         return !(a == b);
392     }
393
394     std::string ToStringShort() const
395     {
396         return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
397     }
398
399     std::string ToString() const
400     {
401         if (IsEmpty()) return "CTxOut(empty)";
402         if (scriptPubKey.size() < 6)
403             return "CTxOut(error)";
404         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
405     }
406
407     void print() const
408     {
409         printf("%s\n", ToString().c_str());
410     }
411 };
412
413
414
415
416 enum GetMinFee_mode
417 {
418     GMF_BLOCK,
419     GMF_RELAY,
420     GMF_SEND,
421 };
422
423 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
424
425 /** The basic transaction that is broadcasted on the network and contained in
426  * blocks.  A transaction can contain multiple inputs and outputs.
427  */
428 class CTransaction
429 {
430 public:
431     static const int CURRENT_VERSION=1;
432     int nVersion;
433     unsigned int nTime;
434     std::vector<CTxIn> vin;
435     std::vector<CTxOut> vout;
436     unsigned int nLockTime;
437
438     // Denial-of-service detection:
439     mutable int nDoS;
440     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
441
442     CTransaction()
443     {
444         SetNull();
445     }
446
447     IMPLEMENT_SERIALIZE
448     (
449         READWRITE(this->nVersion);
450         nVersion = this->nVersion;
451         READWRITE(nTime);
452         READWRITE(vin);
453         READWRITE(vout);
454         READWRITE(nLockTime);
455     )
456
457     void SetNull()
458     {
459         nVersion = CTransaction::CURRENT_VERSION;
460         nTime = GetAdjustedTime();
461         vin.clear();
462         vout.clear();
463         nLockTime = 0;
464         nDoS = 0;  // Denial-of-service prevention
465     }
466
467     bool IsNull() const
468     {
469         return (vin.empty() && vout.empty());
470     }
471
472     uint256 GetHash() const
473     {
474         return SerializeHash(*this);
475     }
476
477     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
478     {
479         // Time based nLockTime implemented in 0.1.6
480         if (nLockTime == 0)
481             return true;
482         if (nBlockHeight == 0)
483             nBlockHeight = nBestHeight;
484         if (nBlockTime == 0)
485             nBlockTime = GetAdjustedTime();
486         if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
487             return true;
488         BOOST_FOREACH(const CTxIn& txin, vin)
489             if (!txin.IsFinal())
490                 return false;
491         return true;
492     }
493
494     bool IsNewerThan(const CTransaction& old) const
495     {
496         if (vin.size() != old.vin.size())
497             return false;
498         for (unsigned int i = 0; i < vin.size(); i++)
499             if (vin[i].prevout != old.vin[i].prevout)
500                 return false;
501
502         bool fNewer = false;
503         unsigned int nLowest = std::numeric_limits<unsigned int>::max();
504         for (unsigned int i = 0; i < vin.size(); i++)
505         {
506             if (vin[i].nSequence != old.vin[i].nSequence)
507             {
508                 if (vin[i].nSequence <= nLowest)
509                 {
510                     fNewer = false;
511                     nLowest = vin[i].nSequence;
512                 }
513                 if (old.vin[i].nSequence < nLowest)
514                 {
515                     fNewer = true;
516                     nLowest = old.vin[i].nSequence;
517                 }
518             }
519         }
520         return fNewer;
521     }
522
523     bool IsCoinBase() const
524     {
525         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
526     }
527
528     bool IsCoinStake() const
529     {
530         // ppcoin: the coin stake transaction is marked with the first output empty
531         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
532     }
533
534     /** Check for standard transaction types
535         @return True if all outputs (scriptPubKeys) use only standard transaction forms
536     */
537     bool IsStandard() const;
538
539     /** Check for standard transaction types
540         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
541         @return True if all inputs (scriptSigs) use only standard transaction forms
542         @see CTransaction::FetchInputs
543     */
544     bool AreInputsStandard(const MapPrevTx& mapInputs) const;
545
546     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
547         @return number of sigops this transaction's outputs will produce when spent
548         @see CTransaction::FetchInputs
549     */
550     unsigned int GetLegacySigOpCount() const;
551
552     /** Count ECDSA signature operations in pay-to-script-hash inputs.
553
554         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
555         @return maximum number of sigops required to validate this transaction's inputs
556         @see CTransaction::FetchInputs
557      */
558     unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
559
560     /** Amount of bitcoins spent by this transaction.
561         @return sum of all outputs (note: does not include fees)
562      */
563     int64 GetValueOut() const
564     {
565         int64 nValueOut = 0;
566         BOOST_FOREACH(const CTxOut& txout, vout)
567         {
568             nValueOut += txout.nValue;
569             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
570                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
571         }
572         return nValueOut;
573     }
574
575     /** Amount of bitcoins coming in to this transaction
576         Note that lightweight clients may not know anything besides the hash of previous transactions,
577         so may not be able to calculate this.
578
579         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
580         @return Sum of value of all inputs (scriptSigs)
581         @see CTransaction::FetchInputs
582      */
583     int64 GetValueIn(const MapPrevTx& mapInputs) const;
584
585     static bool AllowFree(double dPriority)
586     {
587         // Large (in bytes) low-priority (new, small-coin) transactions
588         // need a fee.
589         return dPriority > COIN * 144 / 250;
590     }
591
592     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
593
594     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
595     {
596         CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
597         if (!filein)
598             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
599
600         // Read transaction
601         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
602             return error("CTransaction::ReadFromDisk() : fseek failed");
603
604         try {
605             filein >> *this;
606         }
607         catch (std::exception &e) {
608             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
609         }
610
611         // Return file pointer
612         if (pfileRet)
613         {
614             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
615                 return error("CTransaction::ReadFromDisk() : second fseek failed");
616             *pfileRet = filein.release();
617         }
618         return true;
619     }
620
621     friend bool operator==(const CTransaction& a, const CTransaction& b)
622     {
623         return (a.nVersion  == b.nVersion &&
624                 a.nTime     == b.nTime &&
625                 a.vin       == b.vin &&
626                 a.vout      == b.vout &&
627                 a.nLockTime == b.nLockTime);
628     }
629
630     friend bool operator!=(const CTransaction& a, const CTransaction& b)
631     {
632         return !(a == b);
633     }
634
635     std::string ToStringShort() const
636     {
637         std::string str;
638         str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
639         return str;
640     }
641
642     std::string ToString() const
643     {
644         std::string str;
645         str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
646         str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
647             GetHash().ToString().substr(0,10).c_str(),
648             nTime,
649             nVersion,
650             vin.size(),
651             vout.size(),
652             nLockTime);
653         for (unsigned int i = 0; i < vin.size(); i++)
654             str += "    " + vin[i].ToString() + "\n";
655         for (unsigned int i = 0; i < vout.size(); i++)
656             str += "    " + vout[i].ToString() + "\n";
657         return str;
658     }
659
660     void print() const
661     {
662         printf("%s", ToString().c_str());
663     }
664
665
666     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
667     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
668     bool ReadFromDisk(COutPoint prevout);
669     bool DisconnectInputs(CTxDB& txdb);
670
671     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
672
673      @param[in] txdb    Transaction database
674      @param[in] mapTestPool     List of pending changes to the transaction index database
675      @param[in] fBlock  True if being called to add a new best-block to the chain
676      @param[in] fMiner  True if being called by CreateNewBlock
677      @param[out] inputsRet      Pointers to this transaction's inputs
678      @param[out] fInvalid       returns true if transaction is invalid
679      @return    Returns true if all inputs are in txdb or mapTestPool
680      */
681     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
682                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
683
684     /** Sanity check previous transactions, then, if all checks succeed,
685         mark them as spent by this transaction.
686
687         @param[in] inputs       Previous transactions (from FetchInputs)
688         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
689         @param[in] posThisTx    Position of this transaction on disk
690         @param[in] pindexBlock
691         @param[in] fBlock       true if called from ConnectBlock
692         @param[in] fMiner       true if called from CreateNewBlock
693         @param[in] fStrictPayToScriptHash       true if fully validating p2sh transactions
694         @return Returns true if all checks succeed
695      */
696     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
697                        std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
698                        const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags=STANDARD_SCRIPT_VERIFY_FLAGS);
699     bool ClientConnectInputs();
700     bool CheckTransaction() const;
701     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
702     bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const;  // ppcoin: get transaction coin age
703
704 protected:
705     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
706 };
707
708 /** Closure representing one script verification
709  *  Note that this stores references to the spending transaction */
710 class CScriptCheck
711 {
712 private:
713     CScript scriptPubKey;
714     const CTransaction *ptxTo;
715     unsigned int nIn;
716     unsigned int nFlags;
717     int nHashType;
718
719 public:
720     CScriptCheck() {}
721     CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
722         scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
723         ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
724
725     bool operator()() const;
726
727     void swap(CScriptCheck &check) {
728         scriptPubKey.swap(check.scriptPubKey);
729         std::swap(ptxTo, check.ptxTo);
730         std::swap(nIn, check.nIn);
731         std::swap(nFlags, check.nFlags);
732         std::swap(nHashType, check.nHashType);
733     }
734 };
735
736
737
738
739 /** A transaction with a merkle branch linking it to the block chain. */
740 class CMerkleTx : public CTransaction
741 {
742 public:
743     uint256 hashBlock;
744     std::vector<uint256> vMerkleBranch;
745     int nIndex;
746
747     // memory only
748     mutable bool fMerkleVerified;
749
750
751     CMerkleTx()
752     {
753         Init();
754     }
755
756     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
757     {
758         Init();
759     }
760
761     void Init()
762     {
763         hashBlock = 0;
764         nIndex = -1;
765         fMerkleVerified = false;
766     }
767
768
769     IMPLEMENT_SERIALIZE
770     (
771         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
772         nVersion = this->nVersion;
773         READWRITE(hashBlock);
774         READWRITE(vMerkleBranch);
775         READWRITE(nIndex);
776     )
777
778
779     int SetMerkleBranch(const CBlock* pblock=NULL);
780     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
781     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
782     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
783     int GetBlocksToMaturity() const;
784     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
785     bool AcceptToMemoryPool();
786 };
787
788
789
790
791 /**  A txdb record that contains the disk location of a transaction and the
792  * locations of transactions that spend its outputs.  vSpent is really only
793  * used as a flag, but having the location is very helpful for debugging.
794  */
795 class CTxIndex
796 {
797 public:
798     CDiskTxPos pos;
799     std::vector<CDiskTxPos> vSpent;
800
801     CTxIndex()
802     {
803         SetNull();
804     }
805
806     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
807     {
808         pos = posIn;
809         vSpent.resize(nOutputs);
810     }
811
812     IMPLEMENT_SERIALIZE
813     (
814         if (!(nType & SER_GETHASH))
815             READWRITE(nVersion);
816         READWRITE(pos);
817         READWRITE(vSpent);
818     )
819
820     void SetNull()
821     {
822         pos.SetNull();
823         vSpent.clear();
824     }
825
826     bool IsNull()
827     {
828         return pos.IsNull();
829     }
830
831     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
832     {
833         return (a.pos    == b.pos &&
834                 a.vSpent == b.vSpent);
835     }
836
837     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
838     {
839         return !(a == b);
840     }
841     int GetDepthInMainChain() const;
842
843 };
844
845
846
847
848
849 /** Nodes collect new transactions into a block, hash them into a hash tree,
850  * and scan through nonce values to make the block's hash satisfy proof-of-work
851  * requirements.  When they solve the proof-of-work, they broadcast the block
852  * to everyone and the block is added to the block chain.  The first transaction
853  * in the block is a special one that creates a new coin owned by the creator
854  * of the block.
855  *
856  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
857  * is indexed by CBlockIndex objects in memory.
858  */
859 class CBlock
860 {
861 public:
862     // header
863     static const int CURRENT_VERSION=6;
864     int nVersion;
865     uint256 hashPrevBlock;
866     uint256 hashMerkleRoot;
867     unsigned int nTime;
868     unsigned int nBits;
869     unsigned int nNonce;
870
871     // network and disk
872     std::vector<CTransaction> vtx;
873
874     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
875     std::vector<unsigned char> vchBlockSig;
876
877     // memory only
878     mutable std::vector<uint256> vMerkleTree;
879
880     // Denial-of-service detection:
881     mutable int nDoS;
882     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
883
884     CBlock()
885     {
886         SetNull();
887     }
888
889     IMPLEMENT_SERIALIZE
890     (
891         READWRITE(this->nVersion);
892         nVersion = this->nVersion;
893         READWRITE(hashPrevBlock);
894         READWRITE(hashMerkleRoot);
895         READWRITE(nTime);
896         READWRITE(nBits);
897         READWRITE(nNonce);
898
899         // ConnectBlock depends on vtx following header to generate CDiskTxPos
900         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
901         {
902             READWRITE(vtx);
903             READWRITE(vchBlockSig);
904         }
905         else if (fRead)
906         {
907             const_cast<CBlock*>(this)->vtx.clear();
908             const_cast<CBlock*>(this)->vchBlockSig.clear();
909         }
910     )
911
912     void SetNull()
913     {
914         nVersion = CBlock::CURRENT_VERSION;
915         hashPrevBlock = 0;
916         hashMerkleRoot = 0;
917         nTime = 0;
918         nBits = 0;
919         nNonce = 0;
920         vtx.clear();
921         vchBlockSig.clear();
922         vMerkleTree.clear();
923         nDoS = 0;
924     }
925
926     bool IsNull() const
927     {
928         return (nBits == 0);
929     }
930
931     uint256 GetHash() const
932     {
933         return scrypt_blockhash(CVOIDBEGIN(nVersion));
934     }
935
936     int64 GetBlockTime() const
937     {
938         return (int64)nTime;
939     }
940
941     void UpdateTime(const CBlockIndex* pindexPrev);
942
943     // ppcoin: entropy bit for stake modifier if chosen by modifier
944     unsigned int GetStakeEntropyBit(unsigned int nTime) const
945     {
946         // Protocol switch to support p2pool at novacoin block #9689
947         if (nTime >= ENTROPY_SWITCH_TIME || fTestNet)
948         {
949             // Take last bit of block hash as entropy bit
950             unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
951             if (fDebug && GetBoolArg("-printstakemodifier"))
952                 printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
953             return nEntropyBit;
954         }
955         // Before novacoin block #9689 - old protocol
956         uint160 hashSig = Hash160(vchBlockSig);
957         if (fDebug && GetBoolArg("-printstakemodifier"))
958             printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
959         hashSig >>= 159; // take the first bit of the hash
960         if (fDebug && GetBoolArg("-printstakemodifier"))
961             printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
962         return hashSig.Get64();
963     }
964
965     // ppcoin: two types of block: proof-of-work or proof-of-stake
966     bool IsProofOfStake() const
967     {
968         return (vtx.size() > 1 && vtx[1].IsCoinStake());
969     }
970
971     bool IsProofOfWork() const
972     {
973         return !IsProofOfStake();
974     }
975
976     std::pair<COutPoint, unsigned int> GetProofOfStake() const
977     {
978         return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
979     }
980
981     // ppcoin: get max transaction timestamp
982     int64 GetMaxTransactionTime() const
983     {
984         int64 maxTransactionTime = 0;
985         BOOST_FOREACH(const CTransaction& tx, vtx)
986             maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
987         return maxTransactionTime;
988     }
989
990     uint256 BuildMerkleTree() const
991     {
992         vMerkleTree.clear();
993         BOOST_FOREACH(const CTransaction& tx, vtx)
994             vMerkleTree.push_back(tx.GetHash());
995         int j = 0;
996         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
997         {
998             for (int i = 0; i < nSize; i += 2)
999             {
1000                 int i2 = std::min(i+1, nSize-1);
1001                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1002                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1003             }
1004             j += nSize;
1005         }
1006         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1007     }
1008
1009     std::vector<uint256> GetMerkleBranch(int nIndex) const
1010     {
1011         if (vMerkleTree.empty())
1012             BuildMerkleTree();
1013         std::vector<uint256> vMerkleBranch;
1014         int j = 0;
1015         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1016         {
1017             int i = std::min(nIndex^1, nSize-1);
1018             vMerkleBranch.push_back(vMerkleTree[j+i]);
1019             nIndex >>= 1;
1020             j += nSize;
1021         }
1022         return vMerkleBranch;
1023     }
1024
1025     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1026     {
1027         if (nIndex == -1)
1028             return 0;
1029         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1030         {
1031             if (nIndex & 1)
1032                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1033             else
1034                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1035             nIndex >>= 1;
1036         }
1037         return hash;
1038     }
1039
1040
1041     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1042     {
1043         // Open history file to append
1044         CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1045         if (!fileout)
1046             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1047
1048         // Write index header
1049         unsigned int nSize = fileout.GetSerializeSize(*this);
1050         fileout << FLATDATA(pchMessageStart) << nSize;
1051
1052         // Write block
1053         long fileOutPos = ftell(fileout);
1054         if (fileOutPos < 0)
1055             return error("CBlock::WriteToDisk() : ftell failed");
1056         nBlockPosRet = fileOutPos;
1057         fileout << *this;
1058
1059         // Flush stdio buffers and commit to disk before returning
1060         fflush(fileout);
1061         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1062             FileCommit(fileout);
1063
1064         return true;
1065     }
1066
1067     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1068     {
1069         SetNull();
1070
1071         // Open history file to read
1072         CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1073         if (!filein)
1074             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1075         if (!fReadTransactions)
1076             filein.nType |= SER_BLOCKHEADERONLY;
1077
1078         // Read block
1079         try {
1080             filein >> *this;
1081         }
1082         catch (std::exception &e) {
1083             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1084         }
1085
1086         // Check the header
1087         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1088             return error("CBlock::ReadFromDisk() : errors in block header");
1089
1090         return true;
1091     }
1092
1093
1094
1095     void print() const
1096     {
1097         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1098             GetHash().ToString().c_str(),
1099             nVersion,
1100             hashPrevBlock.ToString().c_str(),
1101             hashMerkleRoot.ToString().c_str(),
1102             nTime, nBits, nNonce,
1103             vtx.size(),
1104             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1105         for (unsigned int i = 0; i < vtx.size(); i++)
1106         {
1107             printf("  ");
1108             vtx[i].print();
1109         }
1110         printf("  vMerkleTree: ");
1111         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1112             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1113         printf("\n");
1114     }
1115
1116
1117     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1118     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1119     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1120     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1121     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1122     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
1123     bool AcceptBlock();
1124     bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1125     bool SignBlock(CWallet& keystore);
1126     bool CheckBlockSignature(bool fProofOfStake) const;
1127
1128 private:
1129     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1130 };
1131
1132
1133
1134
1135
1136
1137 /** The block chain is a tree shaped structure starting with the
1138  * genesis block at the root, with each block potentially having multiple
1139  * candidates to be the next block.  pprev and pnext link a path through the
1140  * main/longest chain.  A blockindex may have multiple pprev pointing back
1141  * to it, but pnext will only point forward to the longest branch, or will
1142  * be null if the block is not part of the longest chain.
1143  */
1144 class CBlockIndex
1145 {
1146 public:
1147     const uint256* phashBlock;
1148     CBlockIndex* pprev;
1149     CBlockIndex* pnext;
1150     unsigned int nFile;
1151     unsigned int nBlockPos;
1152     uint256 nChainTrust; // ppcoin: trust score of block chain
1153     int nHeight;
1154
1155     int64 nMint;
1156     int64 nMoneySupply;
1157
1158     unsigned int nFlags;  // ppcoin: block index flags
1159     enum  
1160     {
1161         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1162         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
1163         BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1164     };
1165
1166     uint64 nStakeModifier; // hash modifier for proof-of-stake
1167     unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1168
1169     // proof-of-stake specific fields
1170     COutPoint prevoutStake;
1171     unsigned int nStakeTime;
1172     uint256 hashProofOfStake;
1173
1174     // block header
1175     int nVersion;
1176     uint256 hashMerkleRoot;
1177     unsigned int nTime;
1178     unsigned int nBits;
1179     unsigned int nNonce;
1180
1181     CBlockIndex()
1182     {
1183         phashBlock = NULL;
1184         pprev = NULL;
1185         pnext = NULL;
1186         nFile = 0;
1187         nBlockPos = 0;
1188         nHeight = 0;
1189         nChainTrust = 0;
1190         nMint = 0;
1191         nMoneySupply = 0;
1192         nFlags = 0;
1193         nStakeModifier = 0;
1194         nStakeModifierChecksum = 0;
1195         hashProofOfStake = 0;
1196         prevoutStake.SetNull();
1197         nStakeTime = 0;
1198
1199         nVersion       = 0;
1200         hashMerkleRoot = 0;
1201         nTime          = 0;
1202         nBits          = 0;
1203         nNonce         = 0;
1204     }
1205
1206     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1207     {
1208         phashBlock = NULL;
1209         pprev = NULL;
1210         pnext = NULL;
1211         nFile = nFileIn;
1212         nBlockPos = nBlockPosIn;
1213         nHeight = 0;
1214         nChainTrust = 0;
1215         nMint = 0;
1216         nMoneySupply = 0;
1217         nFlags = 0;
1218         nStakeModifier = 0;
1219         nStakeModifierChecksum = 0;
1220         hashProofOfStake = 0;
1221         if (block.IsProofOfStake())
1222         {
1223             SetProofOfStake();
1224             prevoutStake = block.vtx[1].vin[0].prevout;
1225             nStakeTime = block.vtx[1].nTime;
1226         }
1227         else
1228         {
1229             prevoutStake.SetNull();
1230             nStakeTime = 0;
1231         }
1232
1233         nVersion       = block.nVersion;
1234         hashMerkleRoot = block.hashMerkleRoot;
1235         nTime          = block.nTime;
1236         nBits          = block.nBits;
1237         nNonce         = block.nNonce;
1238     }
1239
1240     CBlock GetBlockHeader() const
1241     {
1242         CBlock block;
1243         block.nVersion       = nVersion;
1244         if (pprev)
1245             block.hashPrevBlock = pprev->GetBlockHash();
1246         block.hashMerkleRoot = hashMerkleRoot;
1247         block.nTime          = nTime;
1248         block.nBits          = nBits;
1249         block.nNonce         = nNonce;
1250         return block;
1251     }
1252
1253     uint256 GetBlockHash() const
1254     {
1255         return *phashBlock;
1256     }
1257
1258     int64 GetBlockTime() const
1259     {
1260         return (int64)nTime;
1261     }
1262
1263     uint256 GetBlockTrust() const;
1264
1265     bool IsInMainChain() const
1266     {
1267         return (pnext || this == pindexBest);
1268     }
1269
1270     bool CheckIndex() const
1271     {
1272         return true;
1273     }
1274
1275     enum { nMedianTimeSpan=11 };
1276
1277     int64 GetMedianTimePast() const
1278     {
1279         int64 pmedian[nMedianTimeSpan];
1280         int64* pbegin = &pmedian[nMedianTimeSpan];
1281         int64* pend = &pmedian[nMedianTimeSpan];
1282
1283         const CBlockIndex* pindex = this;
1284         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1285             *(--pbegin) = pindex->GetBlockTime();
1286
1287         std::sort(pbegin, pend);
1288         return pbegin[(pend - pbegin)/2];
1289     }
1290
1291     int64 GetMedianTime() const
1292     {
1293         const CBlockIndex* pindex = this;
1294         for (int i = 0; i < nMedianTimeSpan/2; i++)
1295         {
1296             if (!pindex->pnext)
1297                 return GetBlockTime();
1298             pindex = pindex->pnext;
1299         }
1300         return pindex->GetMedianTimePast();
1301     }
1302
1303     /**
1304      * Returns true if there are nRequired or more blocks of minVersion or above
1305      * in the last nToCheck blocks, starting at pstart and going backwards.
1306      */
1307     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1308                                 unsigned int nRequired, unsigned int nToCheck);
1309
1310
1311     bool IsProofOfWork() const
1312     {
1313         return !(nFlags & BLOCK_PROOF_OF_STAKE);
1314     }
1315
1316     bool IsProofOfStake() const
1317     {
1318         return (nFlags & BLOCK_PROOF_OF_STAKE);
1319     }
1320
1321     void SetProofOfStake()
1322     {
1323         nFlags |= BLOCK_PROOF_OF_STAKE;
1324     }
1325
1326     unsigned int GetStakeEntropyBit() const
1327     {
1328         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1329     }
1330
1331     bool SetStakeEntropyBit(unsigned int nEntropyBit)
1332     {
1333         if (nEntropyBit > 1)
1334             return false;
1335         nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1336         return true;
1337     }
1338
1339     bool GeneratedStakeModifier() const
1340     {
1341         return (nFlags & BLOCK_STAKE_MODIFIER);
1342     }
1343
1344     void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1345     {
1346         nStakeModifier = nModifier;
1347         if (fGeneratedStakeModifier)
1348             nFlags |= BLOCK_STAKE_MODIFIER;
1349     }
1350
1351     std::string ToString() const
1352     {
1353         return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
1354             pprev, pnext, nFile, nBlockPos, nHeight,
1355             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1356             GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1357             nStakeModifier, nStakeModifierChecksum, 
1358             hashProofOfStake.ToString().c_str(),
1359             prevoutStake.ToString().c_str(), nStakeTime,
1360             hashMerkleRoot.ToString().c_str(),
1361             GetBlockHash().ToString().c_str());
1362     }
1363
1364     void print() const
1365     {
1366         printf("%s\n", ToString().c_str());
1367     }
1368 };
1369
1370
1371
1372 /** Used to marshal pointers into hashes for db storage. */
1373 class CDiskBlockIndex : public CBlockIndex
1374 {
1375 private:
1376     uint256 blockHash;
1377
1378 public:
1379     uint256 hashPrev;
1380     uint256 hashNext;
1381
1382     CDiskBlockIndex()
1383     {
1384         hashPrev = 0;
1385         hashNext = 0;
1386         blockHash = 0;
1387     }
1388
1389     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1390     {
1391         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1392         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1393     }
1394
1395     IMPLEMENT_SERIALIZE
1396     (
1397         if (!(nType & SER_GETHASH))
1398             READWRITE(nVersion);
1399
1400         READWRITE(hashNext);
1401         READWRITE(nFile);
1402         READWRITE(nBlockPos);
1403         READWRITE(nHeight);
1404         READWRITE(nMint);
1405         READWRITE(nMoneySupply);
1406         READWRITE(nFlags);
1407         READWRITE(nStakeModifier);
1408         if (IsProofOfStake())
1409         {
1410             READWRITE(prevoutStake);
1411             READWRITE(nStakeTime);
1412             READWRITE(hashProofOfStake);
1413         }
1414         else if (fRead)
1415         {
1416             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1417             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1418             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1419         }
1420
1421         // block header
1422         READWRITE(this->nVersion);
1423         READWRITE(hashPrev);
1424         READWRITE(hashMerkleRoot);
1425         READWRITE(nTime);
1426         READWRITE(nBits);
1427         READWRITE(nNonce);
1428         READWRITE(blockHash);
1429     )
1430
1431     uint256 GetBlockHash() const
1432     {
1433         if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1434             return blockHash;
1435
1436         CBlock block;
1437         block.nVersion        = nVersion;
1438         block.hashPrevBlock   = hashPrev;
1439         block.hashMerkleRoot  = hashMerkleRoot;
1440         block.nTime           = nTime;
1441         block.nBits           = nBits;
1442         block.nNonce          = nNonce;
1443
1444         const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1445
1446         return blockHash;
1447     }
1448
1449     std::string ToString() const
1450     {
1451         std::string str = "CDiskBlockIndex(";
1452         str += CBlockIndex::ToString();
1453         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1454             GetBlockHash().ToString().c_str(),
1455             hashPrev.ToString().c_str(),
1456             hashNext.ToString().c_str());
1457         return str;
1458     }
1459
1460     void print() const
1461     {
1462         printf("%s\n", ToString().c_str());
1463     }
1464 };
1465
1466
1467
1468
1469
1470
1471
1472
1473 /** Describes a place in the block chain to another node such that if the
1474  * other node doesn't have the same branch, it can find a recent common trunk.
1475  * The further back it is, the further before the fork it may be.
1476  */
1477 class CBlockLocator
1478 {
1479 protected:
1480     std::vector<uint256> vHave;
1481 public:
1482
1483     CBlockLocator()
1484     {
1485     }
1486
1487     explicit CBlockLocator(const CBlockIndex* pindex)
1488     {
1489         Set(pindex);
1490     }
1491
1492     explicit CBlockLocator(uint256 hashBlock)
1493     {
1494         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1495         if (mi != mapBlockIndex.end())
1496             Set((*mi).second);
1497     }
1498
1499     CBlockLocator(const std::vector<uint256>& vHaveIn)
1500     {
1501         vHave = vHaveIn;
1502     }
1503
1504     IMPLEMENT_SERIALIZE
1505     (
1506         if (!(nType & SER_GETHASH))
1507             READWRITE(nVersion);
1508         READWRITE(vHave);
1509     )
1510
1511     void SetNull()
1512     {
1513         vHave.clear();
1514     }
1515
1516     bool IsNull()
1517     {
1518         return vHave.empty();
1519     }
1520
1521     void Set(const CBlockIndex* pindex)
1522     {
1523         vHave.clear();
1524         int nStep = 1;
1525         while (pindex)
1526         {
1527             vHave.push_back(pindex->GetBlockHash());
1528
1529             // Exponentially larger steps back
1530             for (int i = 0; pindex && i < nStep; i++)
1531                 pindex = pindex->pprev;
1532             if (vHave.size() > 10)
1533                 nStep *= 2;
1534         }
1535         vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1536     }
1537
1538     int GetDistanceBack()
1539     {
1540         // Retrace how far back it was in the sender's branch
1541         int nDistance = 0;
1542         int nStep = 1;
1543         BOOST_FOREACH(const uint256& hash, vHave)
1544         {
1545             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1546             if (mi != mapBlockIndex.end())
1547             {
1548                 CBlockIndex* pindex = (*mi).second;
1549                 if (pindex->IsInMainChain())
1550                     return nDistance;
1551             }
1552             nDistance += nStep;
1553             if (nDistance > 10)
1554                 nStep *= 2;
1555         }
1556         return nDistance;
1557     }
1558
1559     CBlockIndex* GetBlockIndex()
1560     {
1561         // Find the first block the caller has in the main chain
1562         BOOST_FOREACH(const uint256& hash, vHave)
1563         {
1564             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1565             if (mi != mapBlockIndex.end())
1566             {
1567                 CBlockIndex* pindex = (*mi).second;
1568                 if (pindex->IsInMainChain())
1569                     return pindex;
1570             }
1571         }
1572         return pindexGenesisBlock;
1573     }
1574
1575     uint256 GetBlockHash()
1576     {
1577         // Find the first block the caller has in the main chain
1578         BOOST_FOREACH(const uint256& hash, vHave)
1579         {
1580             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1581             if (mi != mapBlockIndex.end())
1582             {
1583                 CBlockIndex* pindex = (*mi).second;
1584                 if (pindex->IsInMainChain())
1585                     return hash;
1586             }
1587         }
1588         return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1589     }
1590
1591     int GetHeight()
1592     {
1593         CBlockIndex* pindex = GetBlockIndex();
1594         if (!pindex)
1595             return 0;
1596         return pindex->nHeight;
1597     }
1598 };
1599
1600
1601
1602
1603
1604
1605
1606
1607 class CTxMemPool
1608 {
1609 public:
1610     mutable CCriticalSection cs;
1611     std::map<uint256, CTransaction> mapTx;
1612     std::map<COutPoint, CInPoint> mapNextTx;
1613
1614     bool accept(CTxDB& txdb, CTransaction &tx,
1615                 bool fCheckInputs, bool* pfMissingInputs);
1616     bool addUnchecked(const uint256& hash, CTransaction &tx);
1617     bool remove(CTransaction &tx);
1618     void clear();
1619     void queryHashes(std::vector<uint256>& vtxid);
1620
1621     unsigned long size()
1622     {
1623         LOCK(cs);
1624         return mapTx.size();
1625     }
1626
1627     bool exists(uint256 hash)
1628     {
1629         return (mapTx.count(hash) != 0);
1630     }
1631
1632     CTransaction& lookup(uint256 hash)
1633     {
1634         return mapTx[hash];
1635     }
1636 };
1637
1638 extern CTxMemPool mempool;
1639
1640 #endif