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