Update transaction verification protocol
[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 "bignum.h"
10 #include "sync.h"
11 #include "net.h"
12 #include "script.h"
13 #include "scrypt.h"
14 #include "zerocoin/Zerocoin.h"
15
16 #include <list>
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 CRequestTracker;
28 class CNode;
29 class CBlockIndexTrustComparator;
30
31 static const unsigned int MAX_BLOCK_SIZE = 1000000;
32 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
33 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
34 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
35 static const unsigned int MAX_INV_SZ = 50000;
36
37 static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
38 static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
39 static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
40 static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
41
42 static const int64 MIN_TX_FEE = CENT / 10;
43 static const int64 MIN_RELAY_TX_FEE = CENT / 50;
44
45 static const int64 MAX_MONEY = 2000000000 * COIN;
46 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
47 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
48 static const int64 MIN_TXOUT_AMOUNT = CENT / 100;
49
50 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
51 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
52 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
53
54 #ifdef USE_UPNP
55 static const int fHaveUPnP = true;
56 #else
57 static const int fHaveUPnP = false;
58 #endif
59
60 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
61 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
62
63 inline int64 PastDrift(int64 nTime)   { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
64 inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
65
66 extern libzerocoin::Params* ZCParams;
67 extern CScript COINBASE_FLAGS;
68 extern CCriticalSection cs_main;
69 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
70 extern std::set<CBlockIndex*, CBlockIndexTrustComparator> setBlockIndexValid;
71 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
72 extern CBlockIndex* pindexGenesisBlock;
73 extern unsigned int nStakeMinAge;
74 extern unsigned int nNodeLifespan;
75 extern int nCoinbaseMaturity;
76 extern int nBestHeight;
77 extern uint256 nBestChainTrust;
78 extern uint256 nBestInvalidTrust;
79 extern uint256 hashBestChain;
80 extern CBlockIndex* pindexBest;
81 extern unsigned int nTransactionsUpdated;
82 extern uint64 nLastBlockTx;
83 extern uint64 nLastBlockSize;
84 extern int64 nLastCoinStakeSearchInterval;
85 extern const std::string strMessageMagic;
86 extern int64 nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern std::set<CWallet*> setpwalletRegistered;
89 extern unsigned char pchMessageStart[4];
90 extern std::map<uint256, CBlock*> mapOrphanBlocks;
91
92 // Settings
93 extern int64 nTransactionFee;
94 extern int64 nMinimumInputValue;
95 extern bool fUseFastIndex;
96 extern unsigned int nDerivationMethodIndex;
97 extern bool fEnforceCanonical;
98
99 // Minimum disk space required - used in CheckDiskSpace()
100 static const uint64 nMinDiskSpace = 52428800;
101
102 class CReserveKey;
103 class CCoinsDB;
104 class CBlockTreeDB;
105 class CDiskBlockPos;
106 class CCoins;
107 class CTxUndo;
108 class CCoinsView;
109 class CCoinsViewCache;
110
111 void RegisterWallet(CWallet* pwalletIn);
112 void UnregisterWallet(CWallet* pwalletIn);
113 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
114 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
115 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
116 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
117 FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
118 bool LoadBlockIndex(bool fAllowNew=true);
119 void PrintBlockTree();
120 CBlockIndex* FindBlockByHeight(int nHeight);
121 bool ProcessMessages(CNode* pfrom);
122 bool SendMessages(CNode* pto, bool fSendTrickle);
123 bool LoadExternalBlockFile(FILE* fileIn);
124
125 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
126 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
127 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees=0);
128 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
129 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
130 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
131 int GetNumBlocksOfPeers();
132 bool IsInitialBlockDownload();
133 std::string GetWarnings(std::string strFor);
134 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow);
135 bool SetBestChain(CBlockIndex* pindexNew);
136 bool ConnectBestBlock();
137 CBlockIndex * InsertBlockIndex(uint256 hash);
138 uint256 WantedByOrphan(const CBlock* pblockOrphan);
139 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
140 void StakeMiner(CWallet *pwallet);
141 void ResendWalletTransactions(bool fForce=false);
142
143 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
144
145 class CDiskBlockPos
146 {
147 public:
148     int nFile;
149     unsigned int nPos;
150
151     IMPLEMENT_SERIALIZE(
152         READWRITE(VARINT(nFile));
153         READWRITE(VARINT(nPos));
154     )
155
156     friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
157         return (a.nFile == b.nFile && a.nPos == b.nPos);
158     }
159
160     friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
161         return !(a == b);
162     }
163
164     void SetNull() { nFile = -1; nPos = 0; }
165     bool IsNull() const { return (nFile == -1); }
166 };
167
168
169 /** An inpoint - a combination of a transaction and an index n into its vin */
170 class CInPoint
171 {
172 public:
173     CTransaction* ptx;
174     unsigned int n;
175
176     CInPoint() { SetNull(); }
177     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
178     void SetNull() { ptx = NULL; n = (unsigned int) -1; }
179     bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
180 };
181
182
183
184 /** An outpoint - a combination of a transaction hash and an index n into its vout */
185 class COutPoint
186 {
187 public:
188     uint256 hash;
189     unsigned int n;
190
191     COutPoint() { SetNull(); }
192     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
193     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
194     void SetNull() { hash = 0; n = (unsigned int) -1; }
195     bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
196
197     friend bool operator<(const COutPoint& a, const COutPoint& b)
198     {
199         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
200     }
201
202     friend bool operator==(const COutPoint& a, const COutPoint& b)
203     {
204         return (a.hash == b.hash && a.n == b.n);
205     }
206
207     friend bool operator!=(const COutPoint& a, const COutPoint& b)
208     {
209         return !(a == b);
210     }
211
212     std::string ToString() const
213     {
214         return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
215     }
216
217     void print() const
218     {
219         printf("%s\n", ToString().c_str());
220     }
221 };
222
223
224
225
226 /** An input of a transaction.  It contains the location of the previous
227  * transaction's output that it claims and a signature that matches the
228  * output's public key.
229  */
230 class CTxIn
231 {
232 public:
233     COutPoint prevout;
234     CScript scriptSig;
235     unsigned int nSequence;
236
237     CTxIn()
238     {
239         nSequence = std::numeric_limits<unsigned int>::max();
240     }
241
242     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
243     {
244         prevout = prevoutIn;
245         scriptSig = scriptSigIn;
246         nSequence = nSequenceIn;
247     }
248
249     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
250     {
251         prevout = COutPoint(hashPrevTx, nOut);
252         scriptSig = scriptSigIn;
253         nSequence = nSequenceIn;
254     }
255
256     IMPLEMENT_SERIALIZE
257     (
258         READWRITE(prevout);
259         READWRITE(scriptSig);
260         READWRITE(nSequence);
261     )
262
263     bool IsFinal() const
264     {
265         return (nSequence == std::numeric_limits<unsigned int>::max());
266     }
267
268     friend bool operator==(const CTxIn& a, const CTxIn& b)
269     {
270         return (a.prevout   == b.prevout &&
271                 a.scriptSig == b.scriptSig &&
272                 a.nSequence == b.nSequence);
273     }
274
275     friend bool operator!=(const CTxIn& a, const CTxIn& b)
276     {
277         return !(a == b);
278     }
279
280     std::string ToStringShort() const
281     {
282         return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
283     }
284
285     std::string ToString() const
286     {
287         std::string str;
288         str += "CTxIn(";
289         str += prevout.ToString();
290         if (prevout.IsNull())
291             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
292         else
293             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
294         if (nSequence != std::numeric_limits<unsigned int>::max())
295             str += strprintf(", nSequence=%u", nSequence);
296         str += ")";
297         return str;
298     }
299
300     void print() const
301     {
302         printf("%s\n", ToString().c_str());
303     }
304 };
305
306
307
308
309 /** An output of a transaction.  It contains the public key that the next input
310  * must be able to sign with to claim it.
311  */
312 class CTxOut
313 {
314 public:
315     int64 nValue;
316     CScript scriptPubKey;
317
318     CTxOut()
319     {
320         SetNull();
321     }
322
323     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
324     {
325         nValue = nValueIn;
326         scriptPubKey = scriptPubKeyIn;
327     }
328
329     IMPLEMENT_SERIALIZE
330     (
331         READWRITE(nValue);
332         READWRITE(scriptPubKey);
333     )
334
335     void SetNull()
336     {
337         nValue = -1;
338         scriptPubKey.clear();
339     }
340
341     bool IsNull() const
342     {
343         return (nValue == -1);
344     }
345
346     void SetEmpty()
347     {
348         nValue = 0;
349         scriptPubKey.clear();
350     }
351
352     bool IsEmpty() const
353     {
354         return (nValue == 0 && scriptPubKey.empty());
355     }
356
357     uint256 GetHash() const
358     {
359         return SerializeHash(*this);
360     }
361
362     friend bool operator==(const CTxOut& a, const CTxOut& b)
363     {
364         return (a.nValue       == b.nValue &&
365                 a.scriptPubKey == b.scriptPubKey);
366     }
367
368     friend bool operator!=(const CTxOut& a, const CTxOut& b)
369     {
370         return !(a == b);
371     }
372
373     std::string ToStringShort() const
374     {
375         return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString().substr(0, 10).c_str());
376     }
377
378     std::string ToString() const
379     {
380         if (IsEmpty()) return "CTxOut(empty)";
381         if (scriptPubKey.size() < 6)
382             return "CTxOut(error)";
383         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
384     }
385
386     void print() const
387     {
388         printf("%s\n", ToString().c_str());
389     }
390 };
391
392
393
394
395 enum GetMinFee_mode
396 {
397     GMF_BLOCK,
398     GMF_RELAY,
399     GMF_SEND,
400 };
401
402 // Modes for script/signature checking
403 enum CheckSig_mode
404 {
405     CS_NEVER,             // never validate scripts
406     CS_AFTER_CHECKPOINT,  // validate scripts after the last checkpoint
407     CS_ALWAYS             // always validate scripts
408 };
409
410 /** The basic transaction that is broadcasted on the network and contained in
411  * blocks.  A transaction can contain multiple inputs and outputs.
412  */
413 class CTransaction
414 {
415 public:
416     static const int CURRENT_VERSION=1;
417     int nVersion;
418     unsigned int nTime;
419     std::vector<CTxIn> vin;
420     std::vector<CTxOut> vout;
421     unsigned int nLockTime;
422
423     // Denial-of-service detection:
424     mutable int nDoS;
425     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
426
427     CTransaction()
428     {
429         SetNull();
430     }
431
432     IMPLEMENT_SERIALIZE
433     (
434         READWRITE(this->nVersion);
435         nVersion = this->nVersion;
436         READWRITE(nTime);
437         READWRITE(vin);
438         READWRITE(vout);
439         READWRITE(nLockTime);
440     )
441
442     void SetNull()
443     {
444         nVersion = CTransaction::CURRENT_VERSION;
445         nTime = GetAdjustedTime();
446         vin.clear();
447         vout.clear();
448         nLockTime = 0;
449         nDoS = 0;  // Denial-of-service prevention
450     }
451
452     bool IsNull() const
453     {
454         return (vin.empty() && vout.empty());
455     }
456
457     uint256 GetHash() const
458     {
459         return SerializeHash(*this);
460     }
461
462     uint256 GetMetaHash() const
463     {
464         return SignatureHash(CScript(), *this, 0, SIGHASH_ALL);
465     }
466
467     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
468     {
469         // Time based nLockTime implemented in 0.1.6
470         if (nLockTime == 0)
471             return true;
472         if (nBlockHeight == 0)
473             nBlockHeight = nBestHeight;
474         if (nBlockTime == 0)
475             nBlockTime = GetAdjustedTime();
476         if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
477             return true;
478         BOOST_FOREACH(const CTxIn& txin, vin)
479             if (!txin.IsFinal())
480                 return false;
481         return true;
482     }
483
484     bool IsNewerThan(const CTransaction& old) const
485     {
486         if (vin.size() != old.vin.size())
487             return false;
488         for (unsigned int i = 0; i < vin.size(); i++)
489             if (vin[i].prevout != old.vin[i].prevout)
490                 return false;
491
492         bool fNewer = false;
493         unsigned int nLowest = std::numeric_limits<unsigned int>::max();
494         for (unsigned int i = 0; i < vin.size(); i++)
495         {
496             if (vin[i].nSequence != old.vin[i].nSequence)
497             {
498                 if (vin[i].nSequence <= nLowest)
499                 {
500                     fNewer = false;
501                     nLowest = vin[i].nSequence;
502                 }
503                 if (old.vin[i].nSequence < nLowest)
504                 {
505                     fNewer = true;
506                     nLowest = old.vin[i].nSequence;
507                 }
508             }
509         }
510         return fNewer;
511     }
512
513     bool IsCoinBase() const
514     {
515         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
516     }
517
518     bool IsCoinStake() const
519     {
520         // ppcoin: the coin stake transaction is marked with the first output empty
521         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
522     }
523
524     /** Check for standard transaction types
525         @return True if all outputs (scriptPubKeys) use only standard transaction forms
526     */
527     bool IsStandard() const;
528
529     /** Check for standard transaction types
530         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
531         @return True if all inputs (scriptSigs) use only standard transaction forms
532         @see CTransaction::FetchInputs
533     */
534     bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
535
536     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
537         @return number of sigops this transaction's outputs will produce when spent
538         @see CTransaction::FetchInputs
539     */
540     unsigned int GetLegacySigOpCount() const;
541
542     /** Count ECDSA signature operations in pay-to-script-hash inputs.
543
544         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
545         @return maximum number of sigops required to validate this transaction's inputs
546         @see CTransaction::FetchInputs
547      */
548     unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
549
550     /** Amount of bitcoins spent by this transaction.
551         @return sum of all outputs (note: does not include fees)
552      */
553     int64 GetValueOut() const
554     {
555         int64 nValueOut = 0;
556         BOOST_FOREACH(const CTxOut& txout, vout)
557         {
558             nValueOut += txout.nValue;
559             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
560                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
561         }
562         return nValueOut;
563     }
564
565     /** Amount of bitcoins coming in to this transaction
566         Note that lightweight clients may not know anything besides the hash of previous transactions,
567         so may not be able to calculate this.
568
569         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
570         @return Sum of value of all inputs (scriptSigs)
571         @see CTransaction::FetchInputs
572      */
573     int64 GetValueIn(CCoinsViewCache& mapInputs) const;
574
575     static bool AllowFree(double dPriority)
576     {
577         // Large (in bytes) low-priority (new, small-coin) transactions
578         // need a fee.
579         return dPriority > COIN * 144 / 250;
580     }
581
582     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0, int64 nMinTxFee = MIN_TX_FEE, int64 nMinRelayTxFee = MIN_RELAY_TX_FEE) const;
583
584     friend bool operator==(const CTransaction& a, const CTransaction& b)
585     {
586         return (a.nVersion  == b.nVersion &&
587                 a.nTime     == b.nTime &&
588                 a.vin       == b.vin &&
589                 a.vout      == b.vout &&
590                 a.nLockTime == b.nLockTime);
591     }
592
593     friend bool operator!=(const CTransaction& a, const CTransaction& b)
594     {
595         return !(a == b);
596     }
597
598     std::string ToStringShort() const
599     {
600         std::string str;
601         str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
602         return str;
603     }
604
605     std::string ToString() const
606     {
607         std::string str;
608         str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
609         str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
610             GetHash().ToString().substr(0,10).c_str(),
611             nTime,
612             nVersion,
613             vin.size(),
614             vout.size(),
615             nLockTime);
616         for (unsigned int i = 0; i < vin.size(); i++)
617             str += "    " + vin[i].ToString() + "\n";
618         for (unsigned int i = 0; i < vout.size(); i++)
619             str += "    " + vout[i].ToString() + "\n";
620         return str;
621     }
622
623     void print() const
624     {
625         printf("%s", ToString().c_str());
626     }
627
628
629     // Do all possible client-mode checks
630     bool ClientCheckInputs() const;
631
632     // Check whether all prevouts of this transaction are present in the UTXO set represented by view
633     bool HaveInputs(CCoinsViewCache &view) const;
634
635     // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
636     // This does not modify the UTXO set
637     bool CheckInputs(CCoinsViewCache &view, enum CheckSig_mode csmode, bool fStrictPayToScriptHash=true, bool fStrictEncodings=true, CBlock *pblock=NULL) const;
638
639     // Apply the effects of this transaction on the UTXO set represented by view
640     bool UpdateCoins(CCoinsViewCache &view, CTxUndo &txundo, int nHeight, unsigned int nBlockTime, const uint256 &txhash) const;
641
642     // Context-independent validity checks
643     bool CheckTransaction() const;
644
645     // Try to accept this transaction into the memory pool
646     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
647     bool GetCoinAge(uint64& nCoinAge) const;  // Get transaction coin age
648 protected:
649     static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
650 };
651
652
653 /** wrapper for CTxOut that provides a more compact serialization */
654 class CTxOutCompressor
655 {
656 private:
657     CTxOut &txout;
658
659 public:
660     static uint64 CompressAmount(uint64 nAmount);
661     static uint64 DecompressAmount(uint64 nAmount);
662
663     CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
664
665     IMPLEMENT_SERIALIZE(({
666         if (!fRead) {
667             uint64 nVal = CompressAmount(txout.nValue);
668             READWRITE(VARINT(nVal));
669         } else {
670             uint64 nVal = 0;
671             READWRITE(VARINT(nVal));
672             txout.nValue = DecompressAmount(nVal);
673         }
674         CScriptCompressor cscript(REF(txout.scriptPubKey));
675         READWRITE(cscript);
676     });)
677 };
678
679 /** Undo information for a CTxIn
680  *
681  *  Contains the prevout's CTxOut being spent, and if this was the
682  *  last output of the affected transaction, its metadata as well
683  *  (coinbase or not, height, transaction version)
684  */
685 class CTxInUndo
686 {
687 public:
688     CTxOut txout;              // the txout data before being spent
689     bool fCoinBase;            // if the outpoint was the last unspent: whether it belonged to a coinbase
690     bool fCoinStake;           // if the outpoint was the last unspent: whether it belonged to a coinstake
691     unsigned int nHeight;      // if the outpoint was the last unspent: its height
692     int nVersion;              // if the outpoint was the last unspent: its version
693     unsigned int nTime;        // if the outpoint was the last unspent: its timestamp
694     unsigned int nBlockTime;   // if the outpoint was the last unspent: its block timestamp
695
696     CTxInUndo() : txout(), fCoinBase(false), fCoinStake(false), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) {}
697     CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, bool fCoinStakeIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0, int nTimeIn = 0, int nBlockTimeIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), fCoinStake(fCoinStakeIn), nHeight(nHeightIn), nVersion(nVersionIn), nTime(nTimeIn), nBlockTime(nBlockTimeIn) { }
698
699     unsigned int GetSerializeSize(int nType, int nVersion) const {
700         return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
701                ::GetSerializeSize(VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion) +
702                ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion) +
703                (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
704                ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
705     }
706
707     template<typename Stream>
708     void Serialize(Stream &s, int nType, int nVersion) const {
709         ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
710         ::Serialize(s, VARINT(nTime*2+(fCoinStake ? 1 : 0)), nType, nVersion);
711         ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
712         if (nHeight > 0)
713             ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
714         ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
715     }
716
717     template<typename Stream>
718     void Unserialize(Stream &s, int nType, int nVersion) {
719         unsigned int nCodeHeight = 0, nCodeTime = 0;
720         ::Unserialize(s, VARINT(nCodeHeight), nType, nVersion);
721         nHeight = nCodeHeight / 2;
722         fCoinBase = nCodeHeight & 1;
723         ::Unserialize(s, VARINT(nCodeTime), nType, nVersion);
724         nTime = nCodeTime / 2;
725         fCoinStake = nCodeTime & 1;
726         ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
727         if (nHeight > 0)
728             ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
729         ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
730     }
731 };
732
733 /** Undo information for a CTransaction */
734 class CTxUndo
735 {
736 public:
737     // undo information for all txins
738     std::vector<CTxInUndo> vprevout;
739
740     IMPLEMENT_SERIALIZE(
741         READWRITE(vprevout);
742     )
743 };
744
745 /** Undo information for a CBlock */
746 class CBlockUndo
747 {
748 public:
749     std::vector<CTxUndo> vtxundo; // for all but the coinbase
750
751     IMPLEMENT_SERIALIZE(
752         READWRITE(vtxundo);
753     )
754
755     bool WriteToDisk(CDiskBlockPos &pos)
756     {
757         // Open history file to append
758         CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
759         if (!fileout)
760             return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
761
762         // Write index header
763         unsigned int nSize = fileout.GetSerializeSize(*this);
764         fileout << FLATDATA(pchMessageStart) << nSize;
765
766         // Write undo data
767         long fileOutPos = ftell(fileout);
768         if (fileOutPos < 0)
769             return error("CBlockUndo::WriteToDisk() : ftell failed");
770         pos.nPos = (unsigned int)fileOutPos;
771         fileout << *this;
772
773         // Flush stdio buffers and commit to disk before returning
774         fflush(fileout);
775         if (!IsInitialBlockDownload())
776             FileCommit(fileout);
777
778         return true;
779     }
780
781 };
782
783 /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
784  *
785  * Serialized format:
786  * - VARINT(nVersion)
787  * - VARINT(nFlags)
788  * - VARINT(nCode)
789  * - unspentness bitvector, for vout[2] and further; least significant byte first
790  * - the non-spent CTxOuts (via CTxOutCompressor)
791  * - VARINT(nHeight)
792  * - VARINT(nTime + is_coinstake)
793  * - VARINT(nBlockTime)
794  *
795  * The nFlag value consists of:
796  * - bit 1: is coinbase
797  * - bit 2: is coinstake
798  * - bit 3: is pruned
799  *
800  * The nCode value consists of:
801  * - bit 2: vout[0] is not spent
802  * - bit 4: vout[1] is not spent
803  * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
804  *   - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
805  *     least one non-spent output).
806  *
807  * Example: 010004835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e40f1d75240f1d752
808  *          <><><><--------------------------------------------><----><------><------>
809  *          |  | \                  |                            /      /       /
810  *     version |  code            vout[1]                     height timestamp block timestamp
811  *           flags
812  *
813  *    - version = 1
814  *    - flags = 4
815  *    - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
816  *    - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
817  *    - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
818  *               * 8358: compact amount representation for 60000000000 (600 BTC)
819  *               * 00: special txout type pay-to-pubkey-hash
820  *               * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
821  *    - height = 203998
822  *    - time   = 1389883712
823  *    - is_coinbase = 0
824  *    - is_coinstake = 0
825  *    - block time   = 1389883712
826  *
827  *
828  * Example: 010508044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b40f1d75240f1d752
829  *          <><><><--><--------------------------------------------------><----------------------------------------------><----><------><------>
830  *          /  | \   \                     |                                                           |                     /      /       /
831  *     version | code unspentness       vout[4]                                                     vout[16]              height timestamp block timestamp
832  *           flags
833  *
834  *  - version = 1
835  *  - flags = 5
836  *  - code = 8 (neither vout[0] or vout[1] are unspent,
837  *                2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
838  *  - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
839  *  - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
840  *             * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
841  *             * 00: special txout type pay-to-pubkey-hash
842  *             * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
843  *  - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
844  *              * bbd123: compact amount representation for 110397 (0.001 BTC)
845  *              * 00: special txout type pay-to-pubkey-hash
846  *              * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
847  *  - height = 120891
848  *  - time   = 1389883712
849  *  - is_coinbase = 1
850  *  - is_coinstake = 0
851  *  - block time   = 1389883712
852  *
853  * Example: 010686af3b40f1d75240f1d752
854  *          <><><----><------><------>
855  *          /  |    \      |        \
856  *   version flags height timestamp block timestamp
857  *
858  *  - version = 1
859  *  - flags = 6 (00000110)
860  *  - height = 120891
861  *  - time   = 1389883712
862  *  - is_coinbase = 0
863  *  - is_coinstake = 1
864  *  - block time   = 1389883712
865  */
866 class CCoins
867 {
868 public:
869     // whether transaction is a coinbase
870     bool fCoinBase;
871
872     // whether transaction is a coinstake
873     bool fCoinStake;
874
875     // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
876     std::vector<CTxOut> vout;
877
878     // at which height this transaction was included in the active blockchain
879     int nHeight;
880
881     // version of the CTransaction; accesses to this value should probably check for nHeight as well,
882     // as new tx version will probably only be introduced at certain heights
883     int nVersion;
884
885     // transaction timestamp + coinstake flag
886     unsigned int nTime;
887
888     // block timestamp
889     unsigned int nBlockTime;
890
891     // construct a CCoins from a CTransaction, at a given height/timestamp
892     CCoins(const CTransaction &tx, int nHeightIn, int nBlockTimeIn) : fCoinBase(tx.IsCoinBase()), fCoinStake(tx.IsCoinStake()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion), nTime(tx.nTime), nBlockTime(nBlockTimeIn) { }
893
894     // empty constructor
895     CCoins() : fCoinBase(false), fCoinStake(false), vout(0), nHeight(0), nVersion(0), nTime(0), nBlockTime(0) { }
896
897     // remove spent outputs at the end of vout
898     void Cleanup() {
899         while (vout.size() > 0 && (vout.back().IsNull() || vout.back().IsEmpty()))
900             vout.pop_back();
901     }
902
903     // equality test
904     friend bool operator==(const CCoins &a, const CCoins &b) {
905          return a.fCoinBase == b.fCoinBase &&
906                 a.fCoinStake == b.fCoinStake &&
907                 a.nHeight == b.nHeight &&
908                 a.nVersion == b.nVersion &&
909                 a.nTime == b.nTime &&
910                 a.nBlockTime == b.nBlockTime &&
911                 a.vout == b.vout;
912     }
913     friend bool operator!=(const CCoins &a, const CCoins &b) {
914         return !(a == b);
915     }
916
917     // calculate number of bytes for the bitmask, and its number of non-zero bytes
918     // each bit in the bitmask represents the availability of one output, but the
919     // availabilities of the first two outputs are encoded separately
920     void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
921         unsigned int nLastUsedByte = 0;
922         for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
923             bool fZero = true;
924             for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
925                 if (!vout[2+b*8+i].IsNull()) {
926                     fZero = false;
927                     continue;
928                 }
929             }
930             if (!fZero) {
931                 nLastUsedByte = b + 1;
932                 nNonzeroBytes++;
933             }
934         }
935         nBytes += nLastUsedByte;
936     }
937
938     bool IsCoinBase() const {
939         return fCoinBase;
940     }
941
942     bool IsCoinStake() const {
943         return fCoinStake;
944     }
945
946     unsigned int GetSerializeSize(int nType, int nVersion) const {
947         unsigned int nSize = 0;
948         bool fPruned = IsPruned();
949
950         // version
951         nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
952         unsigned char nFlags = 0;
953         // coinbase, coinstake and prune flags
954         nFlags = (fCoinBase ? 1 : 0)<<0 | (fCoinStake ? 1 : 0)<<1 | (fPruned ? 1 : 0)<<2;
955         // size of flags
956         nSize += ::GetSerializeSize(VARINT(nFlags), nType, nVersion);
957
958         if (!IsPruned()) {
959             unsigned int nMaskSize = 0, nMaskCode = 0;
960             CalcMaskSize(nMaskSize, nMaskCode);
961             bool fFirst = vout.size() > 0 && !vout[0].IsNull();
962             bool fSecond = vout.size() > 1 && !vout[1].IsNull();
963
964             assert(fFirst || fSecond || nMaskCode);
965             unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
966             // size of header code
967             nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
968             // spentness bitmask
969             nSize += nMaskSize;
970             // txouts themself
971             for (unsigned int i = 0; i < vout.size(); i++)
972                 if (!vout[i].IsNull())
973                     nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
974             // height
975             nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
976             // timestamp and coinstake flag
977             nSize += ::GetSerializeSize(VARINT(nTime), nType, nVersion);
978             // block timestamp
979             nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
980         }
981         else {
982             // size of height
983             nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
984             // size of timestamp
985             nSize += ::GetSerializeSize(VARINT(nTime), nType, nVersion);
986             // size of block timestamp
987             nSize += ::GetSerializeSize(VARINT(nBlockTime), nType, nVersion);
988         }
989
990         return nSize;
991     }
992
993     template<typename Stream>
994     void Serialize(Stream &s, int nType, int nVersion) const {
995         bool fPruned = IsPruned();
996         unsigned char nFlags = 0;
997         nFlags = (fCoinBase ? 1 : 0)<<0 | (fCoinStake ? 1 : 0)<<1 | (fPruned ? 1 : 0)<<2;
998
999         // version
1000         ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
1001         // flags
1002         ::Serialize(s, VARINT(nFlags), nType, nVersion);
1003
1004         if (!fPruned) {
1005             unsigned int nMaskSize = 0, nMaskCode = 0;
1006             CalcMaskSize(nMaskSize, nMaskCode);
1007             bool fFirst = vout.size() > 0 && !vout[0].IsNull();
1008             bool fSecond = vout.size() > 1 && !vout[1].IsNull();
1009
1010             assert(fFirst || fSecond || nMaskCode);
1011
1012             unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
1013
1014             // header code
1015             ::Serialize(s, VARINT(nCode), nType, nVersion);
1016             // spentness bitmask
1017             for (unsigned int b = 0; b<nMaskSize; b++) {
1018                 unsigned char chAvail = 0;
1019                 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
1020                     if (!vout[2+b*8+i].IsNull())
1021                         chAvail |= (1 << i);
1022                 ::Serialize(s, chAvail, nType, nVersion);
1023             }
1024             // txouts themself
1025             for (unsigned int i = 0; i < vout.size(); i++) {
1026                 if (!vout[i].IsNull())
1027                     ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
1028             }
1029             // coinbase height
1030             ::Serialize(s, VARINT(nHeight), nType, nVersion);
1031             // transaction timestamp and coinstake flag
1032             ::Serialize(s, VARINT(nTime), nType, nVersion);
1033             // block timestamp
1034             ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
1035         }
1036         else {
1037             // coinbase height
1038             ::Serialize(s, VARINT(nHeight), nType, nVersion);
1039             // transaction timestamp
1040             ::Serialize(s, VARINT(nTime), nType, nVersion);
1041             // block timestamp
1042             ::Serialize(s, VARINT(nBlockTime), nType, nVersion);
1043         }
1044     }
1045
1046     template<typename Stream>
1047     void Unserialize(Stream &s, int nType, int nVersion) {
1048         unsigned char nFlags = 0;
1049
1050         // version
1051         ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
1052         // coinbase and coinstake flags
1053         ::Unserialize(s, VARINT(nFlags), nType, nVersion);
1054
1055         fCoinBase = nFlags & (1<<0);
1056         fCoinStake = nFlags & (1<<1);
1057         bool fPruned = nFlags & (1<<2);
1058
1059         if (!fPruned) {
1060             unsigned int nCode = 0;
1061             // header code
1062             ::Unserialize(s, VARINT(nCode), nType, nVersion);
1063             std::vector<bool> vAvail(2, false);
1064             vAvail[0] = nCode & 2;
1065             vAvail[1] = nCode & 4;
1066             unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
1067             // spentness bitmask
1068             while (nMaskCode > 0) {
1069                 unsigned char chAvail = 0;
1070                 ::Unserialize(s, chAvail, nType, nVersion);
1071                 for (unsigned int p = 0; p < 8; p++) {
1072                     bool f = (chAvail & (1 << p)) != 0;
1073                     vAvail.push_back(f);
1074                 }
1075                 if (chAvail != 0)
1076                     nMaskCode--;
1077             }
1078             // txouts themself
1079             vout.assign(vAvail.size(), CTxOut());
1080             for (unsigned int i = 0; i < vAvail.size(); i++) {
1081                 if (vAvail[i])
1082                     ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
1083             }
1084             // coinbase height
1085             ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1086             // transaction timestamp
1087             ::Unserialize(s, VARINT(nTime), nType, nVersion);
1088             nTime = nTime;
1089             // block timestamp
1090             ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1091         }
1092         else {
1093             // coinbase height
1094             ::Unserialize(s, VARINT(nHeight), nType, nVersion);
1095             // transaction timestamp
1096             ::Unserialize(s, VARINT(nTime), nType, nVersion);
1097             // block timestamp
1098             ::Unserialize(s, VARINT(nBlockTime), nType, nVersion);
1099         }
1100         Cleanup();
1101     }
1102
1103     // mark an outpoint spent, and construct undo information
1104     bool Spend(const COutPoint &out, CTxInUndo &undo) {
1105         if (out.n >= vout.size())
1106             return false;
1107         if (vout[out.n].IsNull())
1108             return false;
1109         undo = CTxInUndo(vout[out.n]);
1110         vout[out.n].SetNull();
1111         Cleanup();
1112         if (vout.size() == 0) {
1113             undo.nHeight = nHeight;
1114             undo.nTime = nTime;
1115             undo.nBlockTime = nBlockTime;
1116             undo.fCoinBase = fCoinBase;
1117             undo.fCoinStake = fCoinStake;
1118             undo.nVersion = this->nVersion;
1119         }
1120         return true;
1121     }
1122
1123     // mark a vout spent
1124     bool Spend(int nPos) {
1125         CTxInUndo undo;
1126         COutPoint out(0, nPos);
1127         return Spend(out, undo);
1128     }
1129
1130     // check whether a particular output is still available
1131     bool IsAvailable(unsigned int nPos) const {
1132         return (nPos < vout.size() && !vout[nPos].IsNull());
1133     }
1134
1135     // check whether the entire CCoins is spent
1136     // note that only !IsPruned() CCoins can be serialized
1137     bool IsPruned() const {
1138         if (vout.size() == 0)
1139             return true;
1140
1141         BOOST_FOREACH(const CTxOut &out, vout)
1142             if (!out.IsNull())
1143                 return false;
1144
1145         return true;
1146     }
1147 };
1148
1149
1150
1151
1152 /** A transaction with a merkle branch linking it to the block chain. */
1153 class CMerkleTx : public CTransaction
1154 {
1155 public:
1156     uint256 hashBlock;
1157     std::vector<uint256> vMerkleBranch;
1158     int nIndex;
1159
1160     // memory only
1161     mutable bool fMerkleVerified;
1162
1163
1164     CMerkleTx()
1165     {
1166         Init();
1167     }
1168
1169     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
1170     {
1171         Init();
1172     }
1173
1174     void Init()
1175     {
1176         hashBlock = 0;
1177         nIndex = -1;
1178         fMerkleVerified = false;
1179     }
1180
1181
1182     IMPLEMENT_SERIALIZE
1183     (
1184         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
1185         nVersion = this->nVersion;
1186         READWRITE(hashBlock);
1187         READWRITE(vMerkleBranch);
1188         READWRITE(nIndex);
1189     )
1190
1191
1192     int SetMerkleBranch(const CBlock* pblock=NULL);
1193     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
1194     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
1195     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
1196     int GetBlocksToMaturity() const;
1197     bool AcceptToMemoryPool(bool fCheckInputs=true);
1198 };
1199
1200
1201
1202 /** Nodes collect new transactions into a block, hash them into a hash tree,
1203  * and scan through nonce values to make the block's hash satisfy proof-of-work
1204  * requirements.  When they solve the proof-of-work, they broadcast the block
1205  * to everyone and the block is added to the block chain.  The first transaction
1206  * in the block is a special one that creates a new coin owned by the creator
1207  * of the block.
1208  */
1209 class CBlock
1210 {
1211 public:
1212     // header
1213     static const int CURRENT_VERSION=6;
1214     int nVersion;
1215     uint256 hashPrevBlock;
1216     uint256 hashMerkleRoot;
1217     unsigned int nTime;
1218     unsigned int nBits;
1219     unsigned int nNonce;
1220
1221     // network and disk
1222     std::vector<CTransaction> vtx;
1223
1224     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
1225     std::vector<unsigned char> vchBlockSig;
1226
1227     // memory only
1228     mutable std::vector<uint256> vMerkleTree;
1229
1230     // Denial-of-service detection:
1231     mutable int nDoS;
1232     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
1233
1234     CBlock()
1235     {
1236         SetNull();
1237     }
1238
1239     IMPLEMENT_SERIALIZE
1240     (
1241         READWRITE(this->nVersion);
1242         nVersion = this->nVersion;
1243         READWRITE(hashPrevBlock);
1244         READWRITE(hashMerkleRoot);
1245         READWRITE(nTime);
1246         READWRITE(nBits);
1247         READWRITE(nNonce);
1248
1249         // ConnectBlock depends on vtx following header to generate CDiskTxPos
1250         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1251         {
1252             READWRITE(vtx);
1253             READWRITE(vchBlockSig);
1254         }
1255         else if (fRead)
1256         {
1257             const_cast<CBlock*>(this)->vtx.clear();
1258             const_cast<CBlock*>(this)->vchBlockSig.clear();
1259         }
1260     )
1261
1262     void SetNull()
1263     {
1264         nVersion = CBlock::CURRENT_VERSION;
1265         hashPrevBlock = 0;
1266         hashMerkleRoot = 0;
1267         nTime = 0;
1268         nBits = 0;
1269         nNonce = 0;
1270         vtx.clear();
1271         vchBlockSig.clear();
1272         vMerkleTree.clear();
1273         nDoS = 0;
1274     }
1275
1276     bool IsNull() const
1277     {
1278         return (nBits == 0);
1279     }
1280
1281     uint256 GetHash() const
1282     {
1283         return scrypt_blockhash(CVOIDBEGIN(nVersion));
1284     }
1285
1286     int64 GetBlockTime() const
1287     {
1288         return (int64)nTime;
1289     }
1290
1291     void UpdateTime(const CBlockIndex* pindexPrev);
1292
1293     unsigned int GetStakeEntropyBit(unsigned int nTime) const;
1294
1295     // two types of block: proof-of-work or proof-of-stake
1296     bool IsProofOfStake() const
1297     {
1298         return (vtx.size() > 1 && vtx[1].IsCoinStake());
1299     }
1300
1301     bool IsProofOfWork() const
1302     {
1303         return !IsProofOfStake();
1304     }
1305
1306     std::pair<COutPoint, unsigned int> GetProofOfStake() const
1307     {
1308         return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1309     }
1310
1311     // get max transaction timestamp
1312     int64 GetMaxTransactionTime() const
1313     {
1314         int64 maxTransactionTime = 0;
1315         BOOST_FOREACH(const CTransaction& tx, vtx)
1316             maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1317         return maxTransactionTime;
1318     }
1319
1320     uint256 BuildMerkleTree() const
1321     {
1322         vMerkleTree.clear();
1323         BOOST_FOREACH(const CTransaction& tx, vtx)
1324             vMerkleTree.push_back(tx.GetHash());
1325         int j = 0;
1326         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1327         {
1328             for (int i = 0; i < nSize; i += 2)
1329             {
1330                 int i2 = std::min(i+1, nSize-1);
1331                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1332                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1333             }
1334             j += nSize;
1335         }
1336         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1337     }
1338
1339     const uint256 &GetTxHash(unsigned int nIndex) const {
1340         assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
1341         assert(nIndex < vtx.size());
1342         return vMerkleTree[nIndex];
1343     }
1344
1345     std::vector<uint256> GetMerkleBranch(int nIndex) const
1346     {
1347         if (vMerkleTree.empty())
1348             BuildMerkleTree();
1349         std::vector<uint256> vMerkleBranch;
1350         int j = 0;
1351         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1352         {
1353             int i = std::min(nIndex^1, nSize-1);
1354             vMerkleBranch.push_back(vMerkleTree[j+i]);
1355             nIndex >>= 1;
1356             j += nSize;
1357         }
1358         return vMerkleBranch;
1359     }
1360
1361     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1362     {
1363         if (nIndex == -1)
1364             return 0;
1365         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1366         {
1367             if (nIndex & 1)
1368                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1369             else
1370                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1371             nIndex >>= 1;
1372         }
1373         return hash;
1374     }
1375
1376     bool WriteToDisk(CDiskBlockPos &pos)
1377     {
1378         // Open history file to append
1379         CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1380         if (!fileout)
1381             return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1382
1383         // Write index header
1384         unsigned int nSize = fileout.GetSerializeSize(*this);
1385         fileout << FLATDATA(pchMessageStart) << nSize;
1386
1387         // Write block
1388         long fileOutPos = ftell(fileout);
1389         if (fileOutPos < 0)
1390             return error("CBlock::WriteToDisk() : ftell failed");
1391         pos.nPos = (unsigned int)fileOutPos;
1392         fileout << *this;
1393
1394         // Flush stdio buffers and commit to disk before returning
1395         fflush(fileout);
1396         if (!IsInitialBlockDownload())
1397             FileCommit(fileout);
1398
1399         return true;
1400     }
1401
1402     bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1403     {
1404         SetNull();
1405
1406         // Open history file to read
1407         CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1408         if (!filein)
1409             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1410         if (!fReadTransactions)
1411             filein.nType |= SER_BLOCKHEADERONLY;
1412
1413         // Read block
1414         try {
1415             filein >> *this;
1416         }
1417         catch (std::exception &e) {
1418             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1419         }
1420
1421         // Check the header
1422         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1423             return error("CBlock::ReadFromDisk() : errors in block header");
1424
1425         return true;
1426     }
1427
1428     void print() const
1429     {
1430         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1431             GetHash().ToString().c_str(),
1432             nVersion,
1433             hashPrevBlock.ToString().c_str(),
1434             hashMerkleRoot.ToString().c_str(),
1435             nTime, nBits, nNonce,
1436             vtx.size(),
1437             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1438         for (unsigned int i = 0; i < vtx.size(); i++)
1439         {
1440             printf("  ");
1441             vtx[i].print();
1442         }
1443         printf("  vMerkleTree: ");
1444         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1445             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1446         printf("\n");
1447     }
1448
1449     // Undo the effects of this block (with given index) on the UTXO set represented by coins
1450     bool DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins);
1451
1452     // Apply the effects of this block (with given index) on the UTXO set represented by coins
1453     bool ConnectBlock(CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
1454
1455     // Read a block from disk
1456     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1457
1458     // Add this block to the block index, and if necessary, switch the active block chain to this
1459     bool AddToBlockIndex(const CDiskBlockPos &pos);
1460
1461     // Context-independent validity checks
1462     bool CheckBlockHeader(bool fCheckPoW=true, bool fCheckSig=false) const;
1463     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=false) const;
1464
1465     // Store block on disk
1466     bool AcceptBlock();
1467
1468     // Get total coinage consumed
1469     bool GetCoinAge(uint64& nCoinAge) const;
1470
1471     // Generate proof-of-stake block signature
1472     bool SignBlock(CWallet& keystore);
1473
1474     // Get generator key
1475     bool GetGenerator(CKey& GeneratorKey) const;
1476
1477     // Validate proof-of-stake block signature
1478     bool CheckSignature(bool& fFatal, uint256& hashProofOfStake) const;
1479
1480     // Legacy proof-of-work signature
1481     bool CheckLegacySignature() const;
1482 };
1483
1484
1485 class CBlockFileInfo
1486 {
1487 public:
1488     unsigned int nBlocks;      // number of blocks stored in file
1489     unsigned int nSize;        // number of used bytes of block file
1490     unsigned int nUndoSize;    // number of used bytes in the undo file
1491     unsigned int nHeightFirst; // lowest height of block in file
1492     unsigned int nHeightLast;  // highest height of block in file
1493     uint64 nTimeFirst;         // earliest time of block in file
1494     uint64 nTimeLast;          // latest time of block in file
1495
1496     IMPLEMENT_SERIALIZE(
1497         READWRITE(VARINT(nBlocks));
1498         READWRITE(VARINT(nSize));
1499         READWRITE(VARINT(nUndoSize));
1500         READWRITE(VARINT(nHeightFirst));
1501         READWRITE(VARINT(nHeightLast));
1502         READWRITE(VARINT(nTimeFirst));
1503         READWRITE(VARINT(nTimeLast));
1504      )
1505
1506      void SetNull() {
1507          nBlocks = 0;
1508          nSize = 0;
1509          nUndoSize = 0;
1510          nHeightFirst = 0;
1511          nHeightLast = 0;
1512          nTimeFirst = 0;
1513          nTimeLast = 0;
1514      }
1515
1516      CBlockFileInfo() {
1517          SetNull();
1518      }
1519
1520      std::string ToString() const {
1521          return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u..%u, time=%s..%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
1522      }
1523
1524      // update statistics (does not update nSize)
1525      void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1526          if (nBlocks==0 || nHeightFirst > nHeightIn)
1527              nHeightFirst = nHeightIn;
1528          if (nBlocks==0 || nTimeFirst > nTimeIn)
1529              nTimeFirst = nTimeIn;
1530          nBlocks++;
1531          if (nHeightIn > nHeightFirst)
1532              nHeightLast = nHeightIn;
1533          if (nTimeIn > nTimeLast)
1534              nTimeLast = nTimeIn;
1535      }
1536 };
1537
1538
1539 extern CCriticalSection cs_LastBlockFile;
1540 extern CBlockFileInfo infoLastBlockFile;
1541 extern int nLastBlockFile;
1542
1543 enum BlockStatus {
1544     BLOCK_VALID_UNKNOWN      =    0,
1545     BLOCK_VALID_HEADER       =    1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
1546     BLOCK_VALID_TREE         =    2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
1547     BLOCK_VALID_TRANSACTIONS =    3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
1548     BLOCK_VALID_CHAIN        =    4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
1549     BLOCK_VALID_SCRIPTS      =    5, // scripts/signatures ok
1550     BLOCK_VALID_MASK         =    7,
1551
1552     BLOCK_HAVE_DATA          =    8, // full block available in blk*.dat
1553     BLOCK_HAVE_UNDO          =   16, // undo data available in rev*.dat
1554     BLOCK_HAVE_MASK          =   24,
1555
1556     BLOCK_FAILED_VALID       =   32, // stage after last reached validness failed
1557     BLOCK_FAILED_CHILD       =   64, // descends from failed block
1558     BLOCK_FAILED_MASK        =   96
1559 };
1560
1561 /** The block chain is a tree shaped structure starting with the
1562  * genesis block at the root, with each block potentially having multiple
1563  * candidates to be the next block.  pprev and pnext link a path through the
1564  * main/longest chain.  A blockindex may have multiple pprev pointing back
1565  * to it, but pnext will only point forward to the longest branch, or will
1566  * be null if the block is not part of the longest chain.
1567  */
1568 class CBlockIndex
1569 {
1570 public:
1571     // pointer to the hash of the block, if any. memory is owned by this CBlockIndex
1572     const uint256* phashBlock;
1573
1574     // pointer to the index of the predecessor of this block
1575     CBlockIndex* pprev;
1576
1577     // (memory only) pointer to the index of the *active* successor of this block
1578     CBlockIndex* pnext;
1579
1580     // height of the entry in the chain. The genesis block has height 0
1581     int nHeight;
1582
1583     // Which # file this block is stored in (blk?????.dat)
1584     int nFile;
1585
1586     // Byte offset within blk?????.dat where this block's data is stored
1587     unsigned int nDataPos;
1588
1589     // Byte offset within rev?????.dat where this block's undo data is stored
1590     unsigned int nUndoPos;
1591
1592     // (memory only) Trust score of block chain up to and including this block
1593     uint256 nChainTrust;
1594
1595     // Number of transactions in this block.
1596     unsigned int nTx;
1597
1598     // (memory only) Number of transactions in the chain up to and including this block
1599     unsigned int nChainTx;
1600
1601     // Verification status of this block. See enum BlockStatus for detailed info
1602     unsigned int nStatus;
1603
1604     // Coins amount created by this block
1605     int64 nMint;
1606
1607     // Total coins created in this block chain up to and including this block
1608     int64 nMoneySupply;
1609
1610     // Block flags
1611     unsigned int nFlags;
1612     enum
1613     {
1614         // is proof-of-stake block
1615         BLOCK_PROOF_OF_STAKE = (1 << 0),
1616         // entropy bit for stake modifier
1617         BLOCK_STAKE_ENTROPY  = (1 << 1),
1618         // regenerated stake modifier
1619         BLOCK_STAKE_MODIFIER = (1 << 2),
1620     };
1621
1622     // Hash modifier for proof-of-stake kernel
1623     uint64 nStakeModifier;
1624
1625     // Checksum of index in-memory only
1626     unsigned int nStakeModifierChecksum;
1627
1628     // Predecessor of coinstake transaction
1629     COutPoint prevoutStake;
1630
1631     // Timestamp of coinstake transaction
1632     unsigned int nStakeTime;
1633
1634     // Kernel hash
1635     uint256 hashProofOfStake;
1636
1637     // Block header
1638     int nVersion;
1639     uint256 hashMerkleRoot;
1640     unsigned int nTime;
1641     unsigned int nBits;
1642     unsigned int nNonce;
1643
1644     CBlockIndex()
1645     {
1646         phashBlock = NULL;
1647         pprev = NULL;
1648         pnext = NULL;
1649         nHeight = 0;
1650         nFile = 0;
1651         nDataPos = 0;
1652         nUndoPos = 0;
1653         nChainTrust = 0;
1654         nTx = 0;
1655         nChainTx = 0;
1656         nStatus = 0;
1657         nMint = 0;
1658         nMoneySupply = 0;
1659         nFlags = 0;
1660         nStakeModifier = 0;
1661         nStakeModifierChecksum = 0;
1662         hashProofOfStake = 0;
1663         prevoutStake.SetNull();
1664         nStakeTime = 0;
1665
1666         nVersion       = 0;
1667         hashMerkleRoot = 0;
1668         nTime          = 0;
1669         nBits          = 0;
1670         nNonce         = 0;
1671     }
1672
1673     CBlockIndex(CBlock& block)
1674     {
1675         phashBlock = NULL;
1676         pprev = NULL;
1677         pnext = NULL;
1678         nHeight = 0;
1679         nFile = 0;
1680         nDataPos = 0;
1681         nUndoPos = 0;
1682         nChainTrust = 0;
1683         nTx = 0;
1684         nChainTx = 0;
1685         nStatus = 0;
1686         nMint = 0;
1687         nMoneySupply = 0;
1688         nFlags = 0;
1689         nStakeModifier = 0;
1690         nStakeModifierChecksum = 0;
1691         hashProofOfStake = 0;
1692         if (block.IsProofOfStake())
1693         {
1694             SetProofOfStake();
1695             prevoutStake = block.vtx[1].vin[0].prevout;
1696             nStakeTime = block.vtx[1].nTime;
1697         }
1698         else
1699         {
1700             prevoutStake.SetNull();
1701             nStakeTime = 0;
1702         }
1703
1704         nVersion       = block.nVersion;
1705         hashMerkleRoot = block.hashMerkleRoot;
1706         nTime          = block.nTime;
1707         nBits          = block.nBits;
1708         nNonce         = block.nNonce;
1709     }
1710
1711     CDiskBlockPos GetBlockPos() const {
1712         CDiskBlockPos ret;
1713         if (nStatus & BLOCK_HAVE_DATA) {
1714             ret.nFile = nFile;
1715             ret.nPos  = nDataPos;
1716         } else
1717             ret.SetNull();
1718         return ret;
1719     }
1720
1721     CDiskBlockPos GetUndoPos() const {
1722         CDiskBlockPos ret;
1723         if (nStatus & BLOCK_HAVE_UNDO) {
1724             ret.nFile = nFile;
1725             ret.nPos  = nUndoPos;
1726         } else
1727             ret.SetNull();
1728         return ret;
1729     }
1730
1731     CBlock GetBlockHeader() const
1732     {
1733         CBlock block;
1734         block.nVersion       = nVersion;
1735         if (pprev)
1736             block.hashPrevBlock = pprev->GetBlockHash();
1737         block.hashMerkleRoot = hashMerkleRoot;
1738         block.nTime          = nTime;
1739         block.nBits          = nBits;
1740         block.nNonce         = nNonce;
1741         return block;
1742     }
1743
1744     uint256 GetBlockHash() const
1745     {
1746         return *phashBlock;
1747     }
1748
1749     int64 GetBlockTime() const
1750     {
1751         return (int64)nTime;
1752     }
1753
1754     uint256 GetBlockTrust() const;
1755
1756     bool IsInMainChain() const
1757     {
1758         return (pnext || this == pindexBest);
1759     }
1760
1761     bool CheckIndex() const
1762     {
1763         return true;
1764     }
1765
1766     enum { nMedianTimeSpan=11 };
1767
1768     int64 GetMedianTimePast() const
1769     {
1770         int64 pmedian[nMedianTimeSpan];
1771         int64* pbegin = &pmedian[nMedianTimeSpan];
1772         int64* pend = &pmedian[nMedianTimeSpan];
1773
1774         const CBlockIndex* pindex = this;
1775         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1776             *(--pbegin) = pindex->GetBlockTime();
1777
1778         std::sort(pbegin, pend);
1779         return pbegin[(pend - pbegin)/2];
1780     }
1781
1782     int64 GetMedianTime() const
1783     {
1784         const CBlockIndex* pindex = this;
1785         for (int i = 0; i < nMedianTimeSpan/2; i++)
1786         {
1787             if (!pindex->pnext)
1788                 return GetBlockTime();
1789             pindex = pindex->pnext;
1790         }
1791         return pindex->GetMedianTimePast();
1792     }
1793
1794     /**
1795      * Returns true if there are nRequired or more blocks of minVersion or above
1796      * in the last nToCheck blocks, starting at pstart and going backwards.
1797      */
1798     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1799                                 unsigned int nRequired, unsigned int nToCheck);
1800
1801     bool IsProofOfWork() const
1802     {
1803         return !(nFlags & BLOCK_PROOF_OF_STAKE);
1804     }
1805
1806     bool IsProofOfStake() const
1807     {
1808         return (nFlags & BLOCK_PROOF_OF_STAKE);
1809     }
1810
1811     void SetProofOfStake()
1812     {
1813         nFlags |= BLOCK_PROOF_OF_STAKE;
1814     }
1815
1816     unsigned int GetStakeEntropyBit() const
1817     {
1818         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1819     }
1820
1821     bool SetStakeEntropyBit(unsigned int nEntropyBit)
1822     {
1823         if (nEntropyBit > 1)
1824             return false;
1825         nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1826         return true;
1827     }
1828
1829     bool GeneratedStakeModifier() const
1830     {
1831         return (nFlags & BLOCK_STAKE_MODIFIER);
1832     }
1833
1834     void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1835     {
1836         nStakeModifier = nModifier;
1837         if (fGeneratedStakeModifier)
1838             nFlags |= BLOCK_STAKE_MODIFIER;
1839     }
1840
1841     std::string ToString() const
1842     {
1843         return strprintf("CBlockIndex(nprev=%p, pnext=%p 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)",
1844             pprev, pnext, nHeight,
1845             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1846             GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1847             nStakeModifier, nStakeModifierChecksum, 
1848             hashProofOfStake.ToString().c_str(),
1849             prevoutStake.ToString().c_str(), nStakeTime,
1850             hashMerkleRoot.ToString().c_str(),
1851             GetBlockHash().ToString().c_str());
1852     }
1853
1854
1855     void print() const
1856     {
1857         printf("%s\n", ToString().c_str());
1858     }
1859 };
1860
1861 struct CBlockIndexTrustComparator
1862 {
1863     bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
1864         if (pa->nChainTrust > pb->nChainTrust) return false;
1865         if (pa->nChainTrust < pb->nChainTrust) return true;
1866
1867         return false; // identical blocks
1868     }
1869 };
1870
1871 /** Used to marshal pointers into hashes for db storage. */
1872 class CDiskBlockIndex : public CBlockIndex
1873 {
1874 private:
1875     uint256 blockHash;
1876 public:
1877     uint256 hashPrev;
1878
1879     CDiskBlockIndex() {
1880         hashPrev = 0;
1881         blockHash = 0;
1882     }
1883
1884     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1885         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1886     }
1887
1888     IMPLEMENT_SERIALIZE
1889     (
1890         if (!(nType & SER_GETHASH))
1891             READWRITE(VARINT(nVersion));
1892
1893         READWRITE(VARINT(nHeight));
1894         READWRITE(VARINT(nStatus));
1895         READWRITE(VARINT(nTx));
1896         if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
1897             READWRITE(VARINT(nFile));
1898         if (nStatus & BLOCK_HAVE_DATA)
1899             READWRITE(VARINT(nDataPos));
1900         if (nStatus & BLOCK_HAVE_UNDO)
1901             READWRITE(VARINT(nUndoPos));
1902         READWRITE(nMint);
1903         READWRITE(nMoneySupply);
1904         READWRITE(nFlags);
1905         READWRITE(nStakeModifier);
1906         if (IsProofOfStake())
1907         {
1908             READWRITE(prevoutStake);
1909             READWRITE(nStakeTime);
1910             READWRITE(hashProofOfStake);
1911         }
1912         else if (fRead)
1913         {
1914             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1915             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1916             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1917         }
1918         READWRITE(blockHash);
1919
1920         // block header
1921         READWRITE(this->nVersion);
1922         READWRITE(hashPrev);
1923         READWRITE(hashMerkleRoot);
1924         READWRITE(nTime);
1925         READWRITE(nBits);
1926         READWRITE(nNonce);
1927     )
1928
1929     uint256 GetBlockHash() const
1930     {
1931         if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1932             return blockHash;
1933
1934         CBlock block;
1935         block.nVersion        = nVersion;
1936         block.hashPrevBlock   = hashPrev;
1937         block.hashMerkleRoot  = hashMerkleRoot;
1938         block.nTime           = nTime;
1939         block.nBits           = nBits;
1940         block.nNonce          = nNonce;
1941
1942         const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1943
1944         return blockHash;
1945     }
1946
1947
1948     std::string ToString() const
1949     {
1950         std::string str = "CDiskBlockIndex(";
1951         str += CBlockIndex::ToString();
1952         str += strprintf("\n                hashBlock=%s, hashPrev=%s)",
1953             GetBlockHash().ToString().c_str(),
1954             hashPrev.ToString().substr(0,20).c_str());
1955         return str;
1956     }
1957
1958     void print() const
1959     {
1960         printf("%s\n", ToString().c_str());
1961     }
1962 };
1963
1964
1965 /** Describes a place in the block chain to another node such that if the
1966  * other node doesn't have the same branch, it can find a recent common trunk.
1967  * The further back it is, the further before the fork it may be.
1968  */
1969 class CBlockLocator
1970 {
1971 protected:
1972     std::vector<uint256> vHave;
1973 public:
1974
1975     CBlockLocator()
1976     {
1977     }
1978
1979     explicit CBlockLocator(const CBlockIndex* pindex)
1980     {
1981         Set(pindex);
1982     }
1983
1984     explicit CBlockLocator(uint256 hashBlock)
1985     {
1986         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1987         if (mi != mapBlockIndex.end())
1988             Set((*mi).second);
1989     }
1990
1991     CBlockLocator(const std::vector<uint256>& vHaveIn)
1992     {
1993         vHave = vHaveIn;
1994     }
1995
1996     IMPLEMENT_SERIALIZE
1997     (
1998         if (!(nType & SER_GETHASH))
1999             READWRITE(nVersion);
2000         READWRITE(vHave);
2001     )
2002
2003     void SetNull()
2004     {
2005         vHave.clear();
2006     }
2007
2008     bool IsNull()
2009     {
2010         return vHave.empty();
2011     }
2012
2013     void Set(const CBlockIndex* pindex)
2014     {
2015         vHave.clear();
2016         int nStep = 1;
2017         while (pindex)
2018         {
2019             vHave.push_back(pindex->GetBlockHash());
2020
2021             // Exponentially larger steps back
2022             for (int i = 0; pindex && i < nStep; i++)
2023                 pindex = pindex->pprev;
2024             if (vHave.size() > 10)
2025                 nStep *= 2;
2026         }
2027         vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2028     }
2029
2030     int GetDistanceBack()
2031     {
2032         // Retrace how far back it was in the sender's branch
2033         int nDistance = 0;
2034         int nStep = 1;
2035         BOOST_FOREACH(const uint256& hash, vHave)
2036         {
2037             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2038             if (mi != mapBlockIndex.end())
2039             {
2040                 CBlockIndex* pindex = (*mi).second;
2041                 if (pindex->IsInMainChain())
2042                     return nDistance;
2043             }
2044             nDistance += nStep;
2045             if (nDistance > 10)
2046                 nStep *= 2;
2047         }
2048         return nDistance;
2049     }
2050
2051     CBlockIndex* GetBlockIndex()
2052     {
2053         // Find the first block the caller has in the main chain
2054         BOOST_FOREACH(const uint256& hash, vHave)
2055         {
2056             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2057             if (mi != mapBlockIndex.end())
2058             {
2059                 CBlockIndex* pindex = (*mi).second;
2060                 if (pindex->IsInMainChain())
2061                     return pindex;
2062             }
2063         }
2064         return pindexGenesisBlock;
2065     }
2066
2067     uint256 GetBlockHash()
2068     {
2069         // Find the first block the caller has in the main chain
2070         BOOST_FOREACH(const uint256& hash, vHave)
2071         {
2072             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
2073             if (mi != mapBlockIndex.end())
2074             {
2075                 CBlockIndex* pindex = (*mi).second;
2076                 if (pindex->IsInMainChain())
2077                     return hash;
2078             }
2079         }
2080         return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
2081     }
2082
2083     int GetHeight()
2084     {
2085         CBlockIndex* pindex = GetBlockIndex();
2086         if (!pindex)
2087             return 0;
2088         return pindex->nHeight;
2089     }
2090 };
2091
2092
2093
2094
2095
2096 class CTxMemPool
2097 {
2098 public:
2099     mutable CCriticalSection cs;
2100     std::map<uint256, CTransaction> mapTx;
2101     std::map<COutPoint, CInPoint> mapNextTx;
2102
2103     bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
2104     bool addUnchecked(const uint256& hash, CTransaction &tx);
2105     bool remove(CTransaction &tx);
2106     void clear();
2107     void queryHashes(std::vector<uint256>& vtxid);
2108     void pruneSpent(const uint256& hash, CCoins &coins);
2109
2110     unsigned long size()
2111     {
2112         LOCK(cs);
2113         return mapTx.size();
2114     }
2115
2116     bool exists(uint256 hash)
2117     {
2118         return (mapTx.count(hash) != 0);
2119     }
2120
2121     CTransaction& lookup(uint256 hash)
2122     {
2123         return mapTx[hash];
2124     }
2125 };
2126
2127 extern CTxMemPool mempool;
2128
2129 struct CCoinsStats
2130 {
2131     int nHeight;
2132     uint64 nTransactions;
2133     uint64 nPrunedTransactions;
2134     uint64 nTransactionOutputs;
2135     uint64 nSerializedSize;
2136
2137     CCoinsStats() : nHeight(0), nTransactions(0), nPrunedTransactions(0), nTransactionOutputs(0), nSerializedSize(0) {}
2138 };
2139
2140 /** Abstract view on the open txout dataset. */
2141 class CCoinsView
2142 {
2143 public:
2144     // Retrieve the CCoins (unspent transaction outputs) for a given txid
2145     virtual bool GetCoins(uint256 txid, CCoins &coins);
2146
2147     // Modify the CCoins for a given txid
2148     virtual bool SetCoins(uint256 txid, const CCoins &coins);
2149
2150     // Just check whether we have data for a given txid.
2151     // This may (but cannot always) return true for fully spent transactions
2152     virtual bool HaveCoins(uint256 txid);
2153
2154     // Retrieve the block index whose state this CCoinsView currently represents
2155     virtual CBlockIndex *GetBestBlock();
2156
2157     // Modify the currently active block index
2158     virtual bool SetBestBlock(CBlockIndex *pindex);
2159     virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2160     virtual bool GetStats(CCoinsStats &stats);
2161 };
2162
2163 /** CCoinsView backed by another CCoinsView */
2164 class CCoinsViewBacked : public CCoinsView
2165 {
2166 protected:
2167     CCoinsView *base;
2168
2169 public:
2170     CCoinsViewBacked(CCoinsView &viewIn);
2171     bool GetCoins(uint256 txid, CCoins &coins);
2172     bool SetCoins(uint256 txid, const CCoins &coins);
2173     bool HaveCoins(uint256 txid);
2174     CBlockIndex *GetBestBlock();
2175     bool SetBestBlock(CBlockIndex *pindex);
2176     void SetBackend(CCoinsView &viewIn);
2177     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2178     bool GetStats(CCoinsStats &stats);
2179 };
2180
2181 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2182 class CCoinsViewCache : public CCoinsViewBacked
2183 {
2184 protected:
2185     CBlockIndex *pindexTip;
2186     std::map<uint256,CCoins> cacheCoins;
2187     std::map<uint256,CCoins> cacheCoinsReadOnly;
2188
2189 public:
2190     CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2191     bool GetCoins(uint256 txid, CCoins &coins);
2192     bool GetCoinsReadOnly(uint256 txid, CCoins &coins);
2193     bool SetCoins(uint256 txid, const CCoins &coins);
2194     bool HaveCoins(uint256 txid);
2195     CCoins &GetCoins(uint256 txid);
2196     CBlockIndex *GetBestBlock();
2197     bool SetBestBlock(CBlockIndex *pindex);
2198     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2199     bool Flush();
2200     unsigned int GetCacheSize();
2201 private:
2202     std::map<uint256,CCoins>::iterator FetchCoins(uint256 txid);
2203 };
2204
2205 /** CCoinsView that brings transactions from a memorypool into view.
2206     It does not check for spendings by memory pool transactions. */
2207 class CCoinsViewMemPool : public CCoinsViewBacked
2208 {
2209 protected:
2210     CTxMemPool &mempool;
2211
2212 public:
2213     CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2214     bool GetCoins(uint256 txid, CCoins &coins);
2215     bool HaveCoins(uint256 txid);
2216 };
2217
2218 /** Global variable that points to the active CCoinsView (protected by cs_main) */
2219 extern CCoinsViewCache *pcoinsTip;
2220
2221 /** Global variable that points to the active block tree (protected by cs_main) */
2222 extern CBlockTreeDB *pblocktree;
2223
2224 #endif