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