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