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