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