Add CCoinsViewCache::GetCoinsReadOnly() method for read-only caching to decrease...
[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 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;
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     std::vector<uint256> GetMerkleBranch(int nIndex) const
1269     {
1270         if (vMerkleTree.empty())
1271             BuildMerkleTree();
1272         std::vector<uint256> vMerkleBranch;
1273         int j = 0;
1274         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1275         {
1276             int i = std::min(nIndex^1, nSize-1);
1277             vMerkleBranch.push_back(vMerkleTree[j+i]);
1278             nIndex >>= 1;
1279             j += nSize;
1280         }
1281         return vMerkleBranch;
1282     }
1283
1284     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1285     {
1286         if (nIndex == -1)
1287             return 0;
1288         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1289         {
1290             if (nIndex & 1)
1291                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1292             else
1293                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1294             nIndex >>= 1;
1295         }
1296         return hash;
1297     }
1298
1299     bool WriteToDisk(CDiskBlockPos &pos)
1300     {
1301         // Open history file to append
1302         CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
1303         if (!fileout)
1304             return error("CBlock::WriteToDisk() : OpenBlockFile failed");
1305
1306         // Write index header
1307         unsigned int nSize = fileout.GetSerializeSize(*this);
1308         fileout << FLATDATA(pchMessageStart) << nSize;
1309
1310         // Write block
1311         long fileOutPos = ftell(fileout);
1312         if (fileOutPos < 0)
1313             return error("CBlock::WriteToDisk() : ftell failed");
1314         pos.nPos = (unsigned int)fileOutPos;
1315         fileout << *this;
1316
1317         // Flush stdio buffers and commit to disk before returning
1318         fflush(fileout);
1319         if (!IsInitialBlockDownload())
1320             FileCommit(fileout);
1321
1322         return true;
1323     }
1324
1325     bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
1326     {
1327         SetNull();
1328
1329         // Open history file to read
1330         CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
1331         if (!filein)
1332             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1333         if (!fReadTransactions)
1334             filein.nType |= SER_BLOCKHEADERONLY;
1335
1336         // Read block
1337         try {
1338             filein >> *this;
1339         }
1340         catch (std::exception &e) {
1341             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1342         }
1343
1344         // Check the header
1345         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1346             return error("CBlock::ReadFromDisk() : errors in block header");
1347
1348         return true;
1349     }
1350
1351     void print() const
1352     {
1353         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1354             GetHash().ToString().c_str(),
1355             nVersion,
1356             hashPrevBlock.ToString().c_str(),
1357             hashMerkleRoot.ToString().c_str(),
1358             nTime, nBits, nNonce,
1359             vtx.size(),
1360             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1361         for (unsigned int i = 0; i < vtx.size(); i++)
1362         {
1363             printf("  ");
1364             vtx[i].print();
1365         }
1366         printf("  vMerkleTree: ");
1367         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1368             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1369         printf("\n");
1370     }
1371
1372     // Undo the effects of this block (with given index) on the UTXO set represented by coins
1373     bool DisconnectBlock(CBlockIndex *pindex, CCoinsView &coins);
1374
1375     // Apply the effects of this block (with given index) on the UTXO set represented by coins
1376     bool ConnectBlock(CBlockIndex *pindex, CCoinsView &coins, bool fJustCheck=false);
1377
1378     // Read a block from disk
1379     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1380
1381     // Make this block (with given index) the new tip of the active block chain
1382     bool SetBestChain(CBlockIndex* pindexNew);
1383
1384     // Add this block to the block index, and if necessary, switch the active block chain to this
1385     bool AddToBlockIndex(const CDiskBlockPos &pos);
1386
1387     // Context-independent validity checks
1388     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=false) const;
1389
1390     // Store block on disk
1391     bool AcceptBlock();
1392
1393     // Get total coinage consumed
1394     bool GetCoinAge(uint64& nCoinAge) const;
1395
1396     // Generate proof-of-stake block signature
1397     bool SignBlock(CWallet& keystore);
1398
1399     // Get generator key
1400     bool GetGenerator(CKey& GeneratorKey) const;
1401
1402     // Validate proof-of-stake block signature
1403     bool CheckSignature(bool& fFatal, uint256& hashProofOfStake) const;
1404
1405     // Legacy proof-of-work signature
1406     bool CheckLegacySignature() const;
1407 };
1408
1409
1410 class CBlockFileInfo
1411 {
1412 public:
1413     unsigned int nBlocks;      // number of blocks stored in file
1414     unsigned int nSize;        // number of used bytes of block file
1415     unsigned int nUndoSize;    // number of used bytes in the undo file
1416     unsigned int nHeightFirst; // lowest height of block in file
1417     unsigned int nHeightLast;  // highest height of block in file
1418     uint64 nTimeFirst;         // earliest time of block in file
1419     uint64 nTimeLast;          // latest time of block in file
1420
1421     IMPLEMENT_SERIALIZE(
1422         READWRITE(VARINT(nBlocks));
1423         READWRITE(VARINT(nSize));
1424         READWRITE(VARINT(nUndoSize));
1425         READWRITE(VARINT(nHeightFirst));
1426         READWRITE(VARINT(nHeightLast));
1427         READWRITE(VARINT(nTimeFirst));
1428         READWRITE(VARINT(nTimeLast));
1429      )
1430
1431      void SetNull() {
1432          nBlocks = 0;
1433          nSize = 0;
1434          nUndoSize = 0;
1435          nHeightFirst = 0;
1436          nHeightLast = 0;
1437          nTimeFirst = 0;
1438          nTimeLast = 0;
1439      }
1440
1441      CBlockFileInfo() {
1442          SetNull();
1443      }
1444
1445      std::string ToString() const {
1446          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());
1447      }
1448
1449      // update statistics (does not update nSize)
1450      void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
1451          if (nBlocks==0 || nHeightFirst > nHeightIn)
1452              nHeightFirst = nHeightIn;
1453          if (nBlocks==0 || nTimeFirst > nTimeIn)
1454              nTimeFirst = nTimeIn;
1455          nBlocks++;
1456          if (nHeightIn > nHeightFirst)
1457              nHeightLast = nHeightIn;
1458          if (nTimeIn > nTimeLast)
1459              nTimeLast = nTimeIn;
1460      }
1461 };
1462
1463
1464 extern CCriticalSection cs_LastBlockFile;
1465 extern CBlockFileInfo infoLastBlockFile;
1466 extern int nLastBlockFile;
1467
1468 /** The block chain is a tree shaped structure starting with the
1469  * genesis block at the root, with each block potentially having multiple
1470  * candidates to be the next block.  pprev and pnext link a path through the
1471  * main/longest chain.  A blockindex may have multiple pprev pointing back
1472  * to it, but pnext will only point forward to the longest branch, or will
1473  * be null if the block is not part of the longest chain.
1474  */
1475 class CBlockIndex
1476 {
1477 public:
1478     const uint256* phashBlock;
1479     CBlockIndex* pprev;
1480     CBlockIndex* pnext;
1481     int nHeight;
1482     CDiskBlockPos pos;
1483     unsigned int nUndoPos;
1484     uint256 nChainTrust; // trust score of block chain
1485
1486     int64 nMint;
1487     int64 nMoneySupply;
1488
1489     unsigned int nFlags;
1490     enum
1491     {
1492         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1493         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
1494         BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1495     };
1496
1497     uint64 nStakeModifier; // hash modifier for proof-of-stake
1498     unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1499
1500     // proof-of-stake specific fields
1501     COutPoint prevoutStake;
1502     unsigned int nStakeTime;
1503     uint256 hashProofOfStake;
1504
1505     // block header
1506     int nVersion;
1507     uint256 hashMerkleRoot;
1508     unsigned int nTime;
1509     unsigned int nBits;
1510     unsigned int nNonce;
1511
1512
1513     CBlockIndex()
1514     {
1515         phashBlock = NULL;
1516         pprev = NULL;
1517         pnext = NULL;
1518         nHeight = 0;
1519         pos.SetNull();
1520         nUndoPos = 0;
1521         nChainTrust = 0;
1522         nMint = 0;
1523         nMoneySupply = 0;
1524         nFlags = 0;
1525         nStakeModifier = 0;
1526         nStakeModifierChecksum = 0;
1527         hashProofOfStake = 0;
1528         prevoutStake.SetNull();
1529         nStakeTime = 0;
1530
1531         nVersion       = 0;
1532         hashMerkleRoot = 0;
1533         nTime          = 0;
1534         nBits          = 0;
1535         nNonce         = 0;
1536     }
1537
1538     CBlockIndex(CBlock& block)
1539     {
1540         phashBlock = NULL;
1541         pprev = NULL;
1542         pnext = NULL;
1543         nHeight = 0;
1544         pos.SetNull();
1545         nUndoPos = 0;
1546         nChainTrust = 0;
1547         nMint = 0;
1548         nMoneySupply = 0;
1549         nFlags = 0;
1550         nStakeModifier = 0;
1551         nStakeModifierChecksum = 0;
1552         hashProofOfStake = 0;
1553         if (block.IsProofOfStake())
1554         {
1555             SetProofOfStake();
1556             prevoutStake = block.vtx[1].vin[0].prevout;
1557             nStakeTime = block.vtx[1].nTime;
1558         }
1559         else
1560         {
1561             prevoutStake.SetNull();
1562             nStakeTime = 0;
1563         }
1564
1565         nVersion       = block.nVersion;
1566         hashMerkleRoot = block.hashMerkleRoot;
1567         nTime          = block.nTime;
1568         nBits          = block.nBits;
1569         nNonce         = block.nNonce;
1570     }
1571
1572     CDiskBlockPos GetBlockPos() const {
1573         return pos;
1574     }
1575
1576     CDiskBlockPos GetUndoPos() const {
1577         CDiskBlockPos ret = pos;
1578         if (nUndoPos == 0)
1579             ret.SetNull();
1580         else
1581             ret.nPos = nUndoPos - 1;
1582         return ret;
1583     }
1584
1585     CBlock GetBlockHeader() const
1586     {
1587         CBlock block;
1588         block.nVersion       = nVersion;
1589         if (pprev)
1590             block.hashPrevBlock = pprev->GetBlockHash();
1591         block.hashMerkleRoot = hashMerkleRoot;
1592         block.nTime          = nTime;
1593         block.nBits          = nBits;
1594         block.nNonce         = nNonce;
1595         return block;
1596     }
1597
1598     uint256 GetBlockHash() const
1599     {
1600         return *phashBlock;
1601     }
1602
1603     int64 GetBlockTime() const
1604     {
1605         return (int64)nTime;
1606     }
1607
1608     uint256 GetBlockTrust() const;
1609
1610     bool IsInMainChain() const
1611     {
1612         return (pnext || this == pindexBest);
1613     }
1614
1615     bool CheckIndex() const
1616     {
1617         return true;
1618     }
1619
1620     enum { nMedianTimeSpan=11 };
1621
1622     int64 GetMedianTimePast() const
1623     {
1624         int64 pmedian[nMedianTimeSpan];
1625         int64* pbegin = &pmedian[nMedianTimeSpan];
1626         int64* pend = &pmedian[nMedianTimeSpan];
1627
1628         const CBlockIndex* pindex = this;
1629         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1630             *(--pbegin) = pindex->GetBlockTime();
1631
1632         std::sort(pbegin, pend);
1633         return pbegin[(pend - pbegin)/2];
1634     }
1635
1636     int64 GetMedianTime() const
1637     {
1638         const CBlockIndex* pindex = this;
1639         for (int i = 0; i < nMedianTimeSpan/2; i++)
1640         {
1641             if (!pindex->pnext)
1642                 return GetBlockTime();
1643             pindex = pindex->pnext;
1644         }
1645         return pindex->GetMedianTimePast();
1646     }
1647
1648     /**
1649      * Returns true if there are nRequired or more blocks of minVersion or above
1650      * in the last nToCheck blocks, starting at pstart and going backwards.
1651      */
1652     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1653                                 unsigned int nRequired, unsigned int nToCheck);
1654
1655     bool IsProofOfWork() const
1656     {
1657         return !(nFlags & BLOCK_PROOF_OF_STAKE);
1658     }
1659
1660     bool IsProofOfStake() const
1661     {
1662         return (nFlags & BLOCK_PROOF_OF_STAKE);
1663     }
1664
1665     void SetProofOfStake()
1666     {
1667         nFlags |= BLOCK_PROOF_OF_STAKE;
1668     }
1669
1670     unsigned int GetStakeEntropyBit() const
1671     {
1672         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1673     }
1674
1675     bool SetStakeEntropyBit(unsigned int nEntropyBit)
1676     {
1677         if (nEntropyBit > 1)
1678             return false;
1679         nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1680         return true;
1681     }
1682
1683     bool GeneratedStakeModifier() const
1684     {
1685         return (nFlags & BLOCK_STAKE_MODIFIER);
1686     }
1687
1688     void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1689     {
1690         nStakeModifier = nModifier;
1691         if (fGeneratedStakeModifier)
1692             nFlags |= BLOCK_STAKE_MODIFIER;
1693     }
1694
1695     std::string ToString() const
1696     {
1697         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)",
1698             pprev, pnext, nHeight,
1699             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1700             GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1701             nStakeModifier, nStakeModifierChecksum, 
1702             hashProofOfStake.ToString().c_str(),
1703             prevoutStake.ToString().c_str(), nStakeTime,
1704             hashMerkleRoot.ToString().c_str(),
1705             GetBlockHash().ToString().c_str());
1706     }
1707
1708
1709     void print() const
1710     {
1711         printf("%s\n", ToString().c_str());
1712     }
1713 };
1714
1715 /** Used to marshal pointers into hashes for db storage. */
1716 class CDiskBlockIndex : public CBlockIndex
1717 {
1718 private:
1719     uint256 blockHash;
1720 public:
1721     uint256 hashPrev;
1722
1723     CDiskBlockIndex() {
1724         hashPrev = 0;
1725         blockHash = 0;
1726     }
1727
1728     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
1729         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1730     }
1731
1732     IMPLEMENT_SERIALIZE
1733     (
1734         if (!(nType & SER_GETHASH))
1735             READWRITE(nVersion);
1736
1737         READWRITE(nHeight);
1738         READWRITE(pos);
1739         READWRITE(nUndoPos);
1740         READWRITE(nMint);
1741         READWRITE(nMoneySupply);
1742         READWRITE(nFlags);
1743         READWRITE(nStakeModifier);
1744         if (IsProofOfStake())
1745         {
1746             READWRITE(prevoutStake);
1747             READWRITE(nStakeTime);
1748             READWRITE(hashProofOfStake);
1749         }
1750         else if (fRead)
1751         {
1752             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1753             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1754             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1755         }
1756         READWRITE(blockHash);
1757
1758         // block header
1759         READWRITE(this->nVersion);
1760         READWRITE(hashPrev);
1761         READWRITE(hashMerkleRoot);
1762         READWRITE(nTime);
1763         READWRITE(nBits);
1764         READWRITE(nNonce);
1765     )
1766
1767     uint256 GetBlockHash() const
1768     {
1769         if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
1770             return blockHash;
1771
1772         CBlock block;
1773         block.nVersion        = nVersion;
1774         block.hashPrevBlock   = hashPrev;
1775         block.hashMerkleRoot  = hashMerkleRoot;
1776         block.nTime           = nTime;
1777         block.nBits           = nBits;
1778         block.nNonce          = nNonce;
1779
1780         const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
1781
1782         return blockHash;
1783     }
1784
1785
1786     std::string ToString() const
1787     {
1788         std::string str = "CDiskBlockIndex(";
1789         str += CBlockIndex::ToString();
1790         str += strprintf("\n                hashBlock=%s, hashPrev=%s)",
1791             GetBlockHash().ToString().c_str(),
1792             hashPrev.ToString().substr(0,20).c_str());
1793         return str;
1794     }
1795
1796     void print() const
1797     {
1798         printf("%s\n", ToString().c_str());
1799     }
1800 };
1801
1802
1803 /** Describes a place in the block chain to another node such that if the
1804  * other node doesn't have the same branch, it can find a recent common trunk.
1805  * The further back it is, the further before the fork it may be.
1806  */
1807 class CBlockLocator
1808 {
1809 protected:
1810     std::vector<uint256> vHave;
1811 public:
1812
1813     CBlockLocator()
1814     {
1815     }
1816
1817     explicit CBlockLocator(const CBlockIndex* pindex)
1818     {
1819         Set(pindex);
1820     }
1821
1822     explicit CBlockLocator(uint256 hashBlock)
1823     {
1824         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1825         if (mi != mapBlockIndex.end())
1826             Set((*mi).second);
1827     }
1828
1829     CBlockLocator(const std::vector<uint256>& vHaveIn)
1830     {
1831         vHave = vHaveIn;
1832     }
1833
1834     IMPLEMENT_SERIALIZE
1835     (
1836         if (!(nType & SER_GETHASH))
1837             READWRITE(nVersion);
1838         READWRITE(vHave);
1839     )
1840
1841     void SetNull()
1842     {
1843         vHave.clear();
1844     }
1845
1846     bool IsNull()
1847     {
1848         return vHave.empty();
1849     }
1850
1851     void Set(const CBlockIndex* pindex)
1852     {
1853         vHave.clear();
1854         int nStep = 1;
1855         while (pindex)
1856         {
1857             vHave.push_back(pindex->GetBlockHash());
1858
1859             // Exponentially larger steps back
1860             for (int i = 0; pindex && i < nStep; i++)
1861                 pindex = pindex->pprev;
1862             if (vHave.size() > 10)
1863                 nStep *= 2;
1864         }
1865         vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1866     }
1867
1868     int GetDistanceBack()
1869     {
1870         // Retrace how far back it was in the sender's branch
1871         int nDistance = 0;
1872         int nStep = 1;
1873         BOOST_FOREACH(const uint256& hash, vHave)
1874         {
1875             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1876             if (mi != mapBlockIndex.end())
1877             {
1878                 CBlockIndex* pindex = (*mi).second;
1879                 if (pindex->IsInMainChain())
1880                     return nDistance;
1881             }
1882             nDistance += nStep;
1883             if (nDistance > 10)
1884                 nStep *= 2;
1885         }
1886         return nDistance;
1887     }
1888
1889     CBlockIndex* GetBlockIndex()
1890     {
1891         // Find the first block the caller has in the main chain
1892         BOOST_FOREACH(const uint256& hash, vHave)
1893         {
1894             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1895             if (mi != mapBlockIndex.end())
1896             {
1897                 CBlockIndex* pindex = (*mi).second;
1898                 if (pindex->IsInMainChain())
1899                     return pindex;
1900             }
1901         }
1902         return pindexGenesisBlock;
1903     }
1904
1905     uint256 GetBlockHash()
1906     {
1907         // Find the first block the caller has in the main chain
1908         BOOST_FOREACH(const uint256& hash, vHave)
1909         {
1910             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1911             if (mi != mapBlockIndex.end())
1912             {
1913                 CBlockIndex* pindex = (*mi).second;
1914                 if (pindex->IsInMainChain())
1915                     return hash;
1916             }
1917         }
1918         return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1919     }
1920
1921     int GetHeight()
1922     {
1923         CBlockIndex* pindex = GetBlockIndex();
1924         if (!pindex)
1925             return 0;
1926         return pindex->nHeight;
1927     }
1928 };
1929
1930
1931
1932
1933
1934 class CTxMemPool
1935 {
1936 public:
1937     mutable CCriticalSection cs;
1938     std::map<uint256, CTransaction> mapTx;
1939     std::map<COutPoint, CInPoint> mapNextTx;
1940
1941     bool accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs);
1942     bool addUnchecked(const uint256& hash, CTransaction &tx);
1943     bool remove(CTransaction &tx);
1944     void clear();
1945     void queryHashes(std::vector<uint256>& vtxid);
1946     void pruneSpent(const uint256& hash, CCoins &coins);
1947
1948     unsigned long size()
1949     {
1950         LOCK(cs);
1951         return mapTx.size();
1952     }
1953
1954     bool exists(uint256 hash)
1955     {
1956         return (mapTx.count(hash) != 0);
1957     }
1958
1959     CTransaction& lookup(uint256 hash)
1960     {
1961         return mapTx[hash];
1962     }
1963 };
1964
1965 extern CTxMemPool mempool;
1966
1967 /** Abstract view on the open txout dataset. */
1968 class CCoinsView
1969 {
1970 public:
1971     // Retrieve the CCoins (unspent transaction outputs) for a given txid
1972     virtual bool GetCoins(uint256 txid, CCoins &coins);
1973
1974     // Modify the CCoins for a given txid
1975     virtual bool SetCoins(uint256 txid, const CCoins &coins);
1976
1977     // Just check whether we have data for a given txid.
1978     // This may (but cannot always) return true for fully spent transactions
1979     virtual bool HaveCoins(uint256 txid);
1980
1981     // Retrieve the block index whose state this CCoinsView currently represents
1982     virtual CBlockIndex *GetBestBlock();
1983
1984     // Modify the currently active block index
1985     virtual bool SetBestBlock(CBlockIndex *pindex);
1986     virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
1987 };
1988
1989 /** CCoinsView backed by another CCoinsView */
1990 class CCoinsViewBacked : public CCoinsView
1991 {
1992 protected:
1993     CCoinsView *base;
1994
1995 public:
1996     CCoinsViewBacked(CCoinsView &viewIn);
1997     bool GetCoins(uint256 txid, CCoins &coins);
1998     bool SetCoins(uint256 txid, const CCoins &coins);
1999     bool HaveCoins(uint256 txid);
2000     CBlockIndex *GetBestBlock();
2001     bool SetBestBlock(CBlockIndex *pindex);
2002     void SetBackend(CCoinsView &viewIn);
2003     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2004 };
2005
2006 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
2007 class CCoinsViewCache : public CCoinsViewBacked
2008 {
2009 protected:
2010     CBlockIndex *pindexTip;
2011     std::map<uint256,CCoins> cacheCoins;
2012     std::map<uint256,CCoins> cacheCoinsReadOnly;
2013
2014 public:
2015     CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
2016     bool GetCoins(uint256 txid, CCoins &coins);
2017     bool GetCoinsReadOnly(uint256 txid, CCoins &coins);
2018     bool SetCoins(uint256 txid, const CCoins &coins);
2019     bool HaveCoins(uint256 txid);
2020     CBlockIndex *GetBestBlock();
2021     bool SetBestBlock(CBlockIndex *pindex);
2022     bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
2023     bool Flush();
2024     unsigned int GetCacheSize();
2025 };
2026
2027 /** CCoinsView that brings transactions from a memorypool into view.
2028     It does not check for spendings by memory pool transactions. */
2029 class CCoinsViewMemPool : public CCoinsViewBacked
2030 {
2031 protected:
2032     CTxMemPool &mempool;
2033
2034 public:
2035     CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
2036     bool GetCoins(uint256 txid, CCoins &coins);
2037     bool HaveCoins(uint256 txid);
2038 };
2039
2040 extern CCoinsViewCache *pcoinsTip;
2041
2042 #endif