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