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