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