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