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