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