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