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