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