update to 0.4.1
[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_mine.h"
13
14 #include <list>
15
16 class CWallet;
17 class CBlock;
18 class CBlockIndex;
19 class CKeyItem;
20 class CReserveKey;
21 class COutPoint;
22
23 class CAddress;
24 class CInv;
25 class CRequestTracker;
26 class CNode;
27
28 static const unsigned int MAX_BLOCK_SIZE = 1000000;
29 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
30 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
31 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
32 static const unsigned int MAX_INV_SZ = 50000;
33 static const int64 MIN_TX_FEE = CENT;
34 static const int64 MIN_RELAY_TX_FEE = CENT;
35 static const int64 MAX_MONEY = 2000000000 * COIN;
36 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
37 static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
38 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
39 static const unsigned int PROTOCOL_SWITCH_TIME = 1371686400; // 20 Jun 2013 00:00:00
40
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
43 static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
44
45 #ifdef USE_UPNP
46 static const int fHaveUPnP = true;
47 #else
48 static const int fHaveUPnP = false;
49 #endif
50
51 static const uint256 hashGenesisBlock("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
52 static const uint256 hashGenesisBlockTestNet("0x000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb");
53
54 static const int64 nMaxClockDrift = 2 * 60 * 60;        // two hours
55
56 extern CScript COINBASE_FLAGS;
57
58
59 extern CCriticalSection cs_main;
60 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
61 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
62 extern CBlockIndex* pindexGenesisBlock;
63 extern unsigned int nStakeMinAge;
64 extern int nCoinbaseMaturity;
65 extern int nBestHeight;
66 extern CBigNum bnBestChainTrust;
67 extern CBigNum bnBestInvalidTrust;
68 extern uint256 hashBestChain;
69 extern CBlockIndex* pindexBest;
70 extern unsigned int nTransactionsUpdated;
71 extern uint64 nLastBlockTx;
72 extern uint64 nLastBlockSize;
73 extern int64 nLastCoinStakeSearchInterval;
74 extern const std::string strMessageMagic;
75 extern double dHashesPerSec;
76 extern int64 nHPSTimerStart;
77 extern int64 nTimeBestReceived;
78 extern CCriticalSection cs_setpwalletRegistered;
79 extern std::set<CWallet*> setpwalletRegistered;
80 extern unsigned char pchMessageStart[4];
81 extern std::map<uint256, CBlock*> mapOrphanBlocks;
82
83 // Settings
84 extern int64 nTransactionFee;
85
86 // Minimum disk space required - used in CheckDiskSpace()
87 static const uint64 nMinDiskSpace = 52428800;
88
89
90 class CReserveKey;
91 class CTxDB;
92 class CTxIndex;
93
94 void RegisterWallet(CWallet* pwalletIn);
95 void UnregisterWallet(CWallet* pwalletIn);
96 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
97 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
98 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
99 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
100 FILE* AppendBlockFile(unsigned int& nFileRet);
101 bool LoadBlockIndex(bool fAllowNew=true);
102 void PrintBlockTree();
103 CBlockIndex* FindBlockByHeight(int nHeight);
104 bool ProcessMessages(CNode* pfrom);
105 bool SendMessages(CNode* pto, bool fSendTrickle);
106 bool LoadExternalBlockFile(FILE* fileIn);
107 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
108 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
109 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
110 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
111 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
112 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
113 int64 GetProofOfWorkReward(unsigned int nBits);
114 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime);
115 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
116 int GetNumBlocksOfPeers();
117 bool IsInitialBlockDownload();
118 std::string GetWarnings(std::string strFor);
119 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
120 uint256 WantedByOrphan(const CBlock* pblockOrphan);
121 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
122 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
123 void ResendWalletTransactions();
124
125
126
127
128
129
130
131
132
133
134 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
135
136 /** Position on disk for a particular transaction. */
137 class CDiskTxPos
138 {
139 public:
140     unsigned int nFile;
141     unsigned int nBlockPos;
142     unsigned int nTxPos;
143
144     CDiskTxPos()
145     {
146         SetNull();
147     }
148
149     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
150     {
151         nFile = nFileIn;
152         nBlockPos = nBlockPosIn;
153         nTxPos = nTxPosIn;
154     }
155
156     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
157     void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
158     bool IsNull() const { return (nFile == (unsigned int) -1); }
159
160     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
161     {
162         return (a.nFile     == b.nFile &&
163                 a.nBlockPos == b.nBlockPos &&
164                 a.nTxPos    == b.nTxPos);
165     }
166
167     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
168     {
169         return !(a == b);
170     }
171
172
173     std::string ToString() const
174     {
175         if (IsNull())
176             return "null";
177         else
178             return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
179     }
180
181     void print() const
182     {
183         printf("%s", ToString().c_str());
184     }
185 };
186
187
188
189 /** An inpoint - a combination of a transaction and an index n into its vin */
190 class CInPoint
191 {
192 public:
193     CTransaction* ptx;
194     unsigned int n;
195
196     CInPoint() { SetNull(); }
197     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
198     void SetNull() { ptx = NULL; n = (unsigned int) -1; }
199     bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
200 };
201
202
203
204 /** An outpoint - a combination of a transaction hash and an index n into its vout */
205 class COutPoint
206 {
207 public:
208     uint256 hash;
209     unsigned int n;
210
211     COutPoint() { SetNull(); }
212     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
213     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
214     void SetNull() { hash = 0; n = (unsigned int) -1; }
215     bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
216
217     friend bool operator<(const COutPoint& a, const COutPoint& b)
218     {
219         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
220     }
221
222     friend bool operator==(const COutPoint& a, const COutPoint& b)
223     {
224         return (a.hash == b.hash && a.n == b.n);
225     }
226
227     friend bool operator!=(const COutPoint& a, const COutPoint& b)
228     {
229         return !(a == b);
230     }
231
232     std::string ToString() const
233     {
234         return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
235     }
236
237     void print() const
238     {
239         printf("%s\n", ToString().c_str());
240     }
241 };
242
243
244
245
246 /** An input of a transaction.  It contains the location of the previous
247  * transaction's output that it claims and a signature that matches the
248  * output's public key.
249  */
250 class CTxIn
251 {
252 public:
253     COutPoint prevout;
254     CScript scriptSig;
255     unsigned int nSequence;
256
257     CTxIn()
258     {
259         nSequence = std::numeric_limits<unsigned int>::max();
260     }
261
262     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
263     {
264         prevout = prevoutIn;
265         scriptSig = scriptSigIn;
266         nSequence = nSequenceIn;
267     }
268
269     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
270     {
271         prevout = COutPoint(hashPrevTx, nOut);
272         scriptSig = scriptSigIn;
273         nSequence = nSequenceIn;
274     }
275
276     IMPLEMENT_SERIALIZE
277     (
278         READWRITE(prevout);
279         READWRITE(scriptSig);
280         READWRITE(nSequence);
281     )
282
283     bool IsFinal() const
284     {
285         return (nSequence == std::numeric_limits<unsigned int>::max());
286     }
287
288     friend bool operator==(const CTxIn& a, const CTxIn& b)
289     {
290         return (a.prevout   == b.prevout &&
291                 a.scriptSig == b.scriptSig &&
292                 a.nSequence == b.nSequence);
293     }
294
295     friend bool operator!=(const CTxIn& a, const CTxIn& b)
296     {
297         return !(a == b);
298     }
299
300     std::string ToStringShort() const
301     {
302         return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
303     }
304
305     std::string ToString() const
306     {
307         std::string str;
308         str += "CTxIn(";
309         str += prevout.ToString();
310         if (prevout.IsNull())
311             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
312         else
313             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
314         if (nSequence != std::numeric_limits<unsigned int>::max())
315             str += strprintf(", nSequence=%u", nSequence);
316         str += ")";
317         return str;
318     }
319
320     void print() const
321     {
322         printf("%s\n", ToString().c_str());
323     }
324 };
325
326
327
328
329 /** An output of a transaction.  It contains the public key that the next input
330  * must be able to sign with to claim it.
331  */
332 class CTxOut
333 {
334 public:
335     int64 nValue;
336     CScript scriptPubKey;
337
338     CTxOut()
339     {
340         SetNull();
341     }
342
343     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
344     {
345         nValue = nValueIn;
346         scriptPubKey = scriptPubKeyIn;
347     }
348
349     IMPLEMENT_SERIALIZE
350     (
351         READWRITE(nValue);
352         READWRITE(scriptPubKey);
353     )
354
355     void SetNull()
356     {
357         nValue = -1;
358         scriptPubKey.clear();
359     }
360
361     bool IsNull()
362     {
363         return (nValue == -1);
364     }
365
366     void SetEmpty()
367     {
368         nValue = 0;
369         scriptPubKey.clear();
370     }
371
372     bool IsEmpty() const
373     {
374         return (nValue == 0 && scriptPubKey.empty());
375     }
376
377     uint256 GetHash() const
378     {
379         return SerializeHash(*this);
380     }
381
382     friend bool operator==(const CTxOut& a, const CTxOut& b)
383     {
384         return (a.nValue       == b.nValue &&
385                 a.scriptPubKey == b.scriptPubKey);
386     }
387
388     friend bool operator!=(const CTxOut& a, const CTxOut& b)
389     {
390         return !(a == b);
391     }
392
393     std::string ToStringShort() const
394     {
395         return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
396     }
397
398     std::string ToString() const
399     {
400         if (IsEmpty()) return "CTxOut(empty)";
401         if (scriptPubKey.size() < 6)
402             return "CTxOut(error)";
403         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
404     }
405
406     void print() const
407     {
408         printf("%s\n", ToString().c_str());
409     }
410 };
411
412
413
414
415 enum GetMinFee_mode
416 {
417     GMF_BLOCK,
418     GMF_RELAY,
419     GMF_SEND,
420 };
421
422 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
423
424 /** The basic transaction that is broadcasted on the network and contained in
425  * blocks.  A transaction can contain multiple inputs and outputs.
426  */
427 class CTransaction
428 {
429 public:
430     static const int CURRENT_VERSION=1;
431     int nVersion;
432     unsigned int nTime;
433     std::vector<CTxIn> vin;
434     std::vector<CTxOut> vout;
435     unsigned int nLockTime;
436
437     // Denial-of-service detection:
438     mutable int nDoS;
439     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
440
441     CTransaction()
442     {
443         SetNull();
444     }
445
446     IMPLEMENT_SERIALIZE
447     (
448         READWRITE(this->nVersion);
449         nVersion = this->nVersion;
450         READWRITE(nTime);
451         READWRITE(vin);
452         READWRITE(vout);
453         READWRITE(nLockTime);
454     )
455
456     void SetNull()
457     {
458         nVersion = CTransaction::CURRENT_VERSION;
459         nTime = GetAdjustedTime();
460         vin.clear();
461         vout.clear();
462         nLockTime = 0;
463         nDoS = 0;  // Denial-of-service prevention
464     }
465
466     bool IsNull() const
467     {
468         return (vin.empty() && vout.empty());
469     }
470
471     uint256 GetHash() const
472     {
473         return SerializeHash(*this);
474     }
475
476     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
477     {
478         // Time based nLockTime implemented in 0.1.6
479         if (nLockTime == 0)
480             return true;
481         if (nBlockHeight == 0)
482             nBlockHeight = nBestHeight;
483         if (nBlockTime == 0)
484             nBlockTime = GetAdjustedTime();
485         if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
486             return true;
487         BOOST_FOREACH(const CTxIn& txin, vin)
488             if (!txin.IsFinal())
489                 return false;
490         return true;
491     }
492
493     bool IsNewerThan(const CTransaction& old) const
494     {
495         if (vin.size() != old.vin.size())
496             return false;
497         for (unsigned int i = 0; i < vin.size(); i++)
498             if (vin[i].prevout != old.vin[i].prevout)
499                 return false;
500
501         bool fNewer = false;
502         unsigned int nLowest = std::numeric_limits<unsigned int>::max();
503         for (unsigned int i = 0; i < vin.size(); i++)
504         {
505             if (vin[i].nSequence != old.vin[i].nSequence)
506             {
507                 if (vin[i].nSequence <= nLowest)
508                 {
509                     fNewer = false;
510                     nLowest = vin[i].nSequence;
511                 }
512                 if (old.vin[i].nSequence < nLowest)
513                 {
514                     fNewer = true;
515                     nLowest = old.vin[i].nSequence;
516                 }
517             }
518         }
519         return fNewer;
520     }
521
522     bool IsCoinBase() const
523     {
524         return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
525     }
526
527     bool IsCoinStake() const
528     {
529         // ppcoin: the coin stake transaction is marked with the first output empty
530         return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
531     }
532
533     /** Check for standard transaction types
534         @return True if all outputs (scriptPubKeys) use only standard transaction forms
535     */
536     bool IsStandard() const;
537
538     /** Check for standard transaction types
539         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
540         @return True if all inputs (scriptSigs) use only standard transaction forms
541         @see CTransaction::FetchInputs
542     */
543     bool AreInputsStandard(const MapPrevTx& mapInputs) const;
544
545     /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
546         @return number of sigops this transaction's outputs will produce when spent
547         @see CTransaction::FetchInputs
548     */
549     unsigned int GetLegacySigOpCount() const;
550
551     /** Count ECDSA signature operations in pay-to-script-hash inputs.
552
553         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
554         @return maximum number of sigops required to validate this transaction's inputs
555         @see CTransaction::FetchInputs
556      */
557     unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
558
559     /** Amount of bitcoins spent by this transaction.
560         @return sum of all outputs (note: does not include fees)
561      */
562     int64 GetValueOut() const
563     {
564         int64 nValueOut = 0;
565         BOOST_FOREACH(const CTxOut& txout, vout)
566         {
567             nValueOut += txout.nValue;
568             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
569                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
570         }
571         return nValueOut;
572     }
573
574     /** Amount of bitcoins coming in to this transaction
575         Note that lightweight clients may not know anything besides the hash of previous transactions,
576         so may not be able to calculate this.
577
578         @param[in] mapInputs    Map of previous transactions that have outputs we're spending
579         @return Sum of value of all inputs (scriptSigs)
580         @see CTransaction::FetchInputs
581      */
582     int64 GetValueIn(const MapPrevTx& mapInputs) const;
583
584     static bool AllowFree(double dPriority)
585     {
586         // Large (in bytes) low-priority (new, small-coin) transactions
587         // need a fee.
588         return dPriority > COIN * 144 / 250;
589     }
590
591     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const;
592
593     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
594     {
595         CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
596         if (!filein)
597             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
598
599         // Read transaction
600         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
601             return error("CTransaction::ReadFromDisk() : fseek failed");
602
603         try {
604             filein >> *this;
605         }
606         catch (std::exception &e) {
607             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
608         }
609
610         // Return file pointer
611         if (pfileRet)
612         {
613             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
614                 return error("CTransaction::ReadFromDisk() : second fseek failed");
615             *pfileRet = filein.release();
616         }
617         return true;
618     }
619
620     friend bool operator==(const CTransaction& a, const CTransaction& b)
621     {
622         return (a.nVersion  == b.nVersion &&
623                 a.nTime     == b.nTime &&
624                 a.vin       == b.vin &&
625                 a.vout      == b.vout &&
626                 a.nLockTime == b.nLockTime);
627     }
628
629     friend bool operator!=(const CTransaction& a, const CTransaction& b)
630     {
631         return !(a == b);
632     }
633
634     std::string ToStringShort() const
635     {
636         std::string str;
637         str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
638         return str;
639     }
640
641     std::string ToString() const
642     {
643         std::string str;
644         str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
645         str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
646             GetHash().ToString().substr(0,10).c_str(),
647             nTime,
648             nVersion,
649             vin.size(),
650             vout.size(),
651             nLockTime);
652         for (unsigned int i = 0; i < vin.size(); i++)
653             str += "    " + vin[i].ToString() + "\n";
654         for (unsigned int i = 0; i < vout.size(); i++)
655             str += "    " + vout[i].ToString() + "\n";
656         return str;
657     }
658
659     void print() const
660     {
661         printf("%s", ToString().c_str());
662     }
663
664
665     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
666     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
667     bool ReadFromDisk(COutPoint prevout);
668     bool DisconnectInputs(CTxDB& txdb);
669
670     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
671
672      @param[in] txdb    Transaction database
673      @param[in] mapTestPool     List of pending changes to the transaction index database
674      @param[in] fBlock  True if being called to add a new best-block to the chain
675      @param[in] fMiner  True if being called by CreateNewBlock
676      @param[out] inputsRet      Pointers to this transaction's inputs
677      @param[out] fInvalid       returns true if transaction is invalid
678      @return    Returns true if all inputs are in txdb or mapTestPool
679      */
680     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
681                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
682
683     /** Sanity check previous transactions, then, if all checks succeed,
684         mark them as spent by this transaction.
685
686         @param[in] inputs       Previous transactions (from FetchInputs)
687         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
688         @param[in] posThisTx    Position of this transaction on disk
689         @param[in] pindexBlock
690         @param[in] fBlock       true if called from ConnectBlock
691         @param[in] fMiner       true if called from CreateNewBlock
692         @param[in] fStrictPayToScriptHash       true if fully validating p2sh transactions
693         @return Returns true if all checks succeed
694      */
695     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
696                        std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
697                        const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
698     bool ClientConnectInputs();
699     bool CheckTransaction() const;
700     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
701     bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const;  // ppcoin: get transaction coin age
702
703 protected:
704     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
705 };
706
707
708
709
710
711 /** A transaction with a merkle branch linking it to the block chain. */
712 class CMerkleTx : public CTransaction
713 {
714 public:
715     uint256 hashBlock;
716     std::vector<uint256> vMerkleBranch;
717     int nIndex;
718
719     // memory only
720     mutable bool fMerkleVerified;
721
722
723     CMerkleTx()
724     {
725         Init();
726     }
727
728     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
729     {
730         Init();
731     }
732
733     void Init()
734     {
735         hashBlock = 0;
736         nIndex = -1;
737         fMerkleVerified = false;
738     }
739
740
741     IMPLEMENT_SERIALIZE
742     (
743         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
744         nVersion = this->nVersion;
745         READWRITE(hashBlock);
746         READWRITE(vMerkleBranch);
747         READWRITE(nIndex);
748     )
749
750
751     int SetMerkleBranch(const CBlock* pblock=NULL);
752     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
753     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
754     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
755     int GetBlocksToMaturity() const;
756     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
757     bool AcceptToMemoryPool();
758 };
759
760
761
762
763 /**  A txdb record that contains the disk location of a transaction and the
764  * locations of transactions that spend its outputs.  vSpent is really only
765  * used as a flag, but having the location is very helpful for debugging.
766  */
767 class CTxIndex
768 {
769 public:
770     CDiskTxPos pos;
771     std::vector<CDiskTxPos> vSpent;
772
773     CTxIndex()
774     {
775         SetNull();
776     }
777
778     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
779     {
780         pos = posIn;
781         vSpent.resize(nOutputs);
782     }
783
784     IMPLEMENT_SERIALIZE
785     (
786         if (!(nType & SER_GETHASH))
787             READWRITE(nVersion);
788         READWRITE(pos);
789         READWRITE(vSpent);
790     )
791
792     void SetNull()
793     {
794         pos.SetNull();
795         vSpent.clear();
796     }
797
798     bool IsNull()
799     {
800         return pos.IsNull();
801     }
802
803     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
804     {
805         return (a.pos    == b.pos &&
806                 a.vSpent == b.vSpent);
807     }
808
809     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
810     {
811         return !(a == b);
812     }
813     int GetDepthInMainChain() const;
814
815 };
816
817
818
819
820
821 /** Nodes collect new transactions into a block, hash them into a hash tree,
822  * and scan through nonce values to make the block's hash satisfy proof-of-work
823  * requirements.  When they solve the proof-of-work, they broadcast the block
824  * to everyone and the block is added to the block chain.  The first transaction
825  * in the block is a special one that creates a new coin owned by the creator
826  * of the block.
827  *
828  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
829  * is indexed by CBlockIndex objects in memory.
830  */
831 class CBlock
832 {
833 public:
834     // header
835     static const int CURRENT_VERSION=4;
836     int nVersion;
837     uint256 hashPrevBlock;
838     uint256 hashMerkleRoot;
839     unsigned int nTime;
840     unsigned int nBits;
841     unsigned int nNonce;
842
843     // network and disk
844     std::vector<CTransaction> vtx;
845
846     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
847     std::vector<unsigned char> vchBlockSig;
848
849     // memory only
850     mutable std::vector<uint256> vMerkleTree;
851
852     // Denial-of-service detection:
853     mutable int nDoS;
854     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
855
856     CBlock()
857     {
858         SetNull();
859     }
860
861     IMPLEMENT_SERIALIZE
862     (
863         READWRITE(this->nVersion);
864         nVersion = this->nVersion;
865         READWRITE(hashPrevBlock);
866         READWRITE(hashMerkleRoot);
867         READWRITE(nTime);
868         READWRITE(nBits);
869         READWRITE(nNonce);
870
871         // ConnectBlock depends on vtx following header to generate CDiskTxPos
872         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
873         {
874             READWRITE(vtx);
875             READWRITE(vchBlockSig);
876         }
877         else if (fRead)
878         {
879             const_cast<CBlock*>(this)->vtx.clear();
880             const_cast<CBlock*>(this)->vchBlockSig.clear();
881         }
882     )
883
884     void SetNull()
885     {
886         nVersion = CBlock::CURRENT_VERSION;
887         hashPrevBlock = 0;
888         hashMerkleRoot = 0;
889         nTime = 0;
890         nBits = 0;
891         nNonce = 0;
892         vtx.clear();
893         vchBlockSig.clear();
894         vMerkleTree.clear();
895         nDoS = 0;
896     }
897
898     bool IsNull() const
899     {
900         return (nBits == 0);
901     }
902
903     uint256 GetHash() const
904     {
905         uint256 thash;
906         void * scratchbuff = scrypt_buffer_alloc();
907
908         scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
909
910         scrypt_buffer_free(scratchbuff);
911
912         return thash;
913     }
914
915     int64 GetBlockTime() const
916     {
917         return (int64)nTime;
918     }
919
920     void UpdateTime(const CBlockIndex* pindexPrev);
921
922     // ppcoin: entropy bit for stake modifier if chosen by modifier
923     unsigned int GetStakeEntropyBit(unsigned int nHeight) const
924     {
925         // Protocol switch to support p2pool at novacoin block #9689
926         if (nHeight >= 9689 || fTestNet)
927         {
928             // Take last bit of block hash as entropy bit
929             unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
930             if (fDebug && GetBoolArg("-printstakemodifier"))
931                 printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit);
932             return nEntropyBit;
933         }
934         // Before novacoin block #9689 - old protocol
935         uint160 hashSig = Hash160(vchBlockSig);
936         if (fDebug && GetBoolArg("-printstakemodifier"))
937             printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
938         hashSig >>= 159; // take the first bit of the hash
939         if (fDebug && GetBoolArg("-printstakemodifier"))
940             printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
941         return hashSig.Get64();
942     }
943
944     // ppcoin: two types of block: proof-of-work or proof-of-stake
945     bool IsProofOfStake() const
946     {
947         return (vtx.size() > 1 && vtx[1].IsCoinStake());
948     }
949
950     bool IsProofOfWork() const
951     {
952         return !IsProofOfStake();
953     }
954
955     std::pair<COutPoint, unsigned int> GetProofOfStake() const
956     {
957         return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
958     }
959
960     // ppcoin: get max transaction timestamp
961     int64 GetMaxTransactionTime() const
962     {
963         int64 maxTransactionTime = 0;
964         BOOST_FOREACH(const CTransaction& tx, vtx)
965             maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
966         return maxTransactionTime;
967     }
968
969     uint256 BuildMerkleTree() const
970     {
971         vMerkleTree.clear();
972         BOOST_FOREACH(const CTransaction& tx, vtx)
973             vMerkleTree.push_back(tx.GetHash());
974         int j = 0;
975         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
976         {
977             for (int i = 0; i < nSize; i += 2)
978             {
979                 int i2 = std::min(i+1, nSize-1);
980                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
981                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
982             }
983             j += nSize;
984         }
985         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
986     }
987
988     std::vector<uint256> GetMerkleBranch(int nIndex) const
989     {
990         if (vMerkleTree.empty())
991             BuildMerkleTree();
992         std::vector<uint256> vMerkleBranch;
993         int j = 0;
994         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
995         {
996             int i = std::min(nIndex^1, nSize-1);
997             vMerkleBranch.push_back(vMerkleTree[j+i]);
998             nIndex >>= 1;
999             j += nSize;
1000         }
1001         return vMerkleBranch;
1002     }
1003
1004     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1005     {
1006         if (nIndex == -1)
1007             return 0;
1008         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1009         {
1010             if (nIndex & 1)
1011                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1012             else
1013                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1014             nIndex >>= 1;
1015         }
1016         return hash;
1017     }
1018
1019
1020     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1021     {
1022         // Open history file to append
1023         CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1024         if (!fileout)
1025             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1026
1027         // Write index header
1028         unsigned int nSize = fileout.GetSerializeSize(*this);
1029         fileout << FLATDATA(pchMessageStart) << nSize;
1030
1031         // Write block
1032         long fileOutPos = ftell(fileout);
1033         if (fileOutPos < 0)
1034             return error("CBlock::WriteToDisk() : ftell failed");
1035         nBlockPosRet = fileOutPos;
1036         fileout << *this;
1037
1038         // Flush stdio buffers and commit to disk before returning
1039         fflush(fileout);
1040         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1041             FileCommit(fileout);
1042
1043         return true;
1044     }
1045
1046     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1047     {
1048         SetNull();
1049
1050         // Open history file to read
1051         CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1052         if (!filein)
1053             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1054         if (!fReadTransactions)
1055             filein.nType |= SER_BLOCKHEADERONLY;
1056
1057         // Read block
1058         try {
1059             filein >> *this;
1060         }
1061         catch (std::exception &e) {
1062             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1063         }
1064
1065         // Check the header
1066         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1067             return error("CBlock::ReadFromDisk() : errors in block header");
1068
1069         return true;
1070     }
1071
1072
1073
1074     void print() const
1075     {
1076         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
1077             GetHash().ToString().c_str(),
1078             nVersion,
1079             hashPrevBlock.ToString().c_str(),
1080             hashMerkleRoot.ToString().c_str(),
1081             nTime, nBits, nNonce,
1082             vtx.size(),
1083             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1084         for (unsigned int i = 0; i < vtx.size(); i++)
1085         {
1086             printf("  ");
1087             vtx[i].print();
1088         }
1089         printf("  vMerkleTree: ");
1090         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1091             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1092         printf("\n");
1093     }
1094
1095
1096     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1097     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
1098     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1099     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1100     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1101     bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
1102     bool AcceptBlock();
1103     bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1104     bool SignBlock(const CKeyStore& keystore);
1105     bool CheckBlockSignature() const;
1106
1107 private:
1108     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1109 };
1110
1111
1112
1113
1114
1115
1116 /** The block chain is a tree shaped structure starting with the
1117  * genesis block at the root, with each block potentially having multiple
1118  * candidates to be the next block.  pprev and pnext link a path through the
1119  * main/longest chain.  A blockindex may have multiple pprev pointing back
1120  * to it, but pnext will only point forward to the longest branch, or will
1121  * be null if the block is not part of the longest chain.
1122  */
1123 class CBlockIndex
1124 {
1125 public:
1126     const uint256* phashBlock;
1127     CBlockIndex* pprev;
1128     CBlockIndex* pnext;
1129     unsigned int nFile;
1130     unsigned int nBlockPos;
1131     CBigNum bnChainTrust; // ppcoin: trust score of block chain
1132     int nHeight;
1133
1134     int64 nMint;
1135     int64 nMoneySupply;
1136
1137     unsigned int nFlags;  // ppcoin: block index flags
1138     enum  
1139     {
1140         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1141         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
1142         BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1143     };
1144
1145     uint64 nStakeModifier; // hash modifier for proof-of-stake
1146     unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1147
1148     // proof-of-stake specific fields
1149     COutPoint prevoutStake;
1150     unsigned int nStakeTime;
1151     uint256 hashProofOfStake;
1152
1153     // block header
1154     int nVersion;
1155     uint256 hashMerkleRoot;
1156     unsigned int nTime;
1157     unsigned int nBits;
1158     unsigned int nNonce;
1159
1160     CBlockIndex()
1161     {
1162         phashBlock = NULL;
1163         pprev = NULL;
1164         pnext = NULL;
1165         nFile = 0;
1166         nBlockPos = 0;
1167         nHeight = 0;
1168         bnChainTrust = 0;
1169         nMint = 0;
1170         nMoneySupply = 0;
1171         nFlags = 0;
1172         nStakeModifier = 0;
1173         nStakeModifierChecksum = 0;
1174         hashProofOfStake = 0;
1175         prevoutStake.SetNull();
1176         nStakeTime = 0;
1177
1178         nVersion       = 0;
1179         hashMerkleRoot = 0;
1180         nTime          = 0;
1181         nBits          = 0;
1182         nNonce         = 0;
1183     }
1184
1185     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1186     {
1187         phashBlock = NULL;
1188         pprev = NULL;
1189         pnext = NULL;
1190         nFile = nFileIn;
1191         nBlockPos = nBlockPosIn;
1192         nHeight = 0;
1193         bnChainTrust = 0;
1194         nMint = 0;
1195         nMoneySupply = 0;
1196         nFlags = 0;
1197         nStakeModifier = 0;
1198         nStakeModifierChecksum = 0;
1199         hashProofOfStake = 0;
1200         if (block.IsProofOfStake())
1201         {
1202             SetProofOfStake();
1203             prevoutStake = block.vtx[1].vin[0].prevout;
1204             nStakeTime = block.vtx[1].nTime;
1205         }
1206         else
1207         {
1208             prevoutStake.SetNull();
1209             nStakeTime = 0;
1210         }
1211
1212         nVersion       = block.nVersion;
1213         hashMerkleRoot = block.hashMerkleRoot;
1214         nTime          = block.nTime;
1215         nBits          = block.nBits;
1216         nNonce         = block.nNonce;
1217     }
1218
1219     CBlock GetBlockHeader() const
1220     {
1221         CBlock block;
1222         block.nVersion       = nVersion;
1223         if (pprev)
1224             block.hashPrevBlock = pprev->GetBlockHash();
1225         block.hashMerkleRoot = hashMerkleRoot;
1226         block.nTime          = nTime;
1227         block.nBits          = nBits;
1228         block.nNonce         = nNonce;
1229         return block;
1230     }
1231
1232     uint256 GetBlockHash() const
1233     {
1234         return *phashBlock;
1235     }
1236
1237     int64 GetBlockTime() const
1238     {
1239         return (int64)nTime;
1240     }
1241
1242     CBigNum GetBlockTrust() const
1243     {
1244         CBigNum bnTarget;
1245         bnTarget.SetCompact(nBits);
1246         if (bnTarget <= 0)
1247             return 0;
1248         return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1249     }
1250
1251     bool IsInMainChain() const
1252     {
1253         return (pnext || this == pindexBest);
1254     }
1255
1256     bool CheckIndex() const
1257     {
1258         return true;
1259     }
1260
1261     enum { nMedianTimeSpan=11 };
1262
1263     int64 GetMedianTimePast() const
1264     {
1265         int64 pmedian[nMedianTimeSpan];
1266         int64* pbegin = &pmedian[nMedianTimeSpan];
1267         int64* pend = &pmedian[nMedianTimeSpan];
1268
1269         const CBlockIndex* pindex = this;
1270         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1271             *(--pbegin) = pindex->GetBlockTime();
1272
1273         std::sort(pbegin, pend);
1274         return pbegin[(pend - pbegin)/2];
1275     }
1276
1277     int64 GetMedianTime() const
1278     {
1279         const CBlockIndex* pindex = this;
1280         for (int i = 0; i < nMedianTimeSpan/2; i++)
1281         {
1282             if (!pindex->pnext)
1283                 return GetBlockTime();
1284             pindex = pindex->pnext;
1285         }
1286         return pindex->GetMedianTimePast();
1287     }
1288
1289     /**
1290      * Returns true if there are nRequired or more blocks of minVersion or above
1291      * in the last nToCheck blocks, starting at pstart and going backwards.
1292      */
1293     static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
1294                                 unsigned int nRequired, unsigned int nToCheck);
1295
1296
1297     bool IsProofOfWork() const
1298     {
1299         return !(nFlags & BLOCK_PROOF_OF_STAKE);
1300     }
1301
1302     bool IsProofOfStake() const
1303     {
1304         return (nFlags & BLOCK_PROOF_OF_STAKE);
1305     }
1306
1307     void SetProofOfStake()
1308     {
1309         nFlags |= BLOCK_PROOF_OF_STAKE;
1310     }
1311
1312     unsigned int GetStakeEntropyBit() const
1313     {
1314         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1315     }
1316
1317     bool SetStakeEntropyBit(unsigned int nEntropyBit)
1318     {
1319         if (nEntropyBit > 1)
1320             return false;
1321         nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1322         return true;
1323     }
1324
1325     bool GeneratedStakeModifier() const
1326     {
1327         return (nFlags & BLOCK_STAKE_MODIFIER);
1328     }
1329
1330     void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1331     {
1332         nStakeModifier = nModifier;
1333         if (fGeneratedStakeModifier)
1334             nFlags |= BLOCK_STAKE_MODIFIER;
1335     }
1336
1337     std::string ToString() const
1338     {
1339         return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d 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)",
1340             pprev, pnext, nFile, nBlockPos, nHeight,
1341             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1342             GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1343             nStakeModifier, nStakeModifierChecksum, 
1344             hashProofOfStake.ToString().c_str(),
1345             prevoutStake.ToString().c_str(), nStakeTime,
1346             hashMerkleRoot.ToString().c_str(),
1347             GetBlockHash().ToString().c_str());
1348     }
1349
1350     void print() const
1351     {
1352         printf("%s\n", ToString().c_str());
1353     }
1354 };
1355
1356
1357
1358 /** Used to marshal pointers into hashes for db storage. */
1359 class CDiskBlockIndex : public CBlockIndex
1360 {
1361 public:
1362     uint256 hashPrev;
1363     uint256 hashNext;
1364
1365     CDiskBlockIndex()
1366     {
1367         hashPrev = 0;
1368         hashNext = 0;
1369     }
1370
1371     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1372     {
1373         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1374         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1375     }
1376
1377     IMPLEMENT_SERIALIZE
1378     (
1379         if (!(nType & SER_GETHASH))
1380             READWRITE(nVersion);
1381
1382         READWRITE(hashNext);
1383         READWRITE(nFile);
1384         READWRITE(nBlockPos);
1385         READWRITE(nHeight);
1386         READWRITE(nMint);
1387         READWRITE(nMoneySupply);
1388         READWRITE(nFlags);
1389         READWRITE(nStakeModifier);
1390         if (IsProofOfStake())
1391         {
1392             READWRITE(prevoutStake);
1393             READWRITE(nStakeTime);
1394             READWRITE(hashProofOfStake);
1395         }
1396         else if (fRead)
1397         {
1398             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1399             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1400             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1401         }
1402
1403         // block header
1404         READWRITE(this->nVersion);
1405         READWRITE(hashPrev);
1406         READWRITE(hashMerkleRoot);
1407         READWRITE(nTime);
1408         READWRITE(nBits);
1409         READWRITE(nNonce);
1410     )
1411
1412     uint256 GetBlockHash() const
1413     {
1414         CBlock block;
1415         block.nVersion        = nVersion;
1416         block.hashPrevBlock   = hashPrev;
1417         block.hashMerkleRoot  = hashMerkleRoot;
1418         block.nTime           = nTime;
1419         block.nBits           = nBits;
1420         block.nNonce          = nNonce;
1421         return block.GetHash();
1422     }
1423
1424
1425     std::string ToString() const
1426     {
1427         std::string str = "CDiskBlockIndex(";
1428         str += CBlockIndex::ToString();
1429         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1430             GetBlockHash().ToString().c_str(),
1431             hashPrev.ToString().c_str(),
1432             hashNext.ToString().c_str());
1433         return str;
1434     }
1435
1436     void print() const
1437     {
1438         printf("%s\n", ToString().c_str());
1439     }
1440 };
1441
1442
1443
1444
1445
1446
1447
1448
1449 /** Describes a place in the block chain to another node such that if the
1450  * other node doesn't have the same branch, it can find a recent common trunk.
1451  * The further back it is, the further before the fork it may be.
1452  */
1453 class CBlockLocator
1454 {
1455 protected:
1456     std::vector<uint256> vHave;
1457 public:
1458
1459     CBlockLocator()
1460     {
1461     }
1462
1463     explicit CBlockLocator(const CBlockIndex* pindex)
1464     {
1465         Set(pindex);
1466     }
1467
1468     explicit CBlockLocator(uint256 hashBlock)
1469     {
1470         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1471         if (mi != mapBlockIndex.end())
1472             Set((*mi).second);
1473     }
1474
1475     CBlockLocator(const std::vector<uint256>& vHaveIn)
1476     {
1477         vHave = vHaveIn;
1478     }
1479
1480     IMPLEMENT_SERIALIZE
1481     (
1482         if (!(nType & SER_GETHASH))
1483             READWRITE(nVersion);
1484         READWRITE(vHave);
1485     )
1486
1487     void SetNull()
1488     {
1489         vHave.clear();
1490     }
1491
1492     bool IsNull()
1493     {
1494         return vHave.empty();
1495     }
1496
1497     void Set(const CBlockIndex* pindex)
1498     {
1499         vHave.clear();
1500         int nStep = 1;
1501         while (pindex)
1502         {
1503             vHave.push_back(pindex->GetBlockHash());
1504
1505             // Exponentially larger steps back
1506             for (int i = 0; pindex && i < nStep; i++)
1507                 pindex = pindex->pprev;
1508             if (vHave.size() > 10)
1509                 nStep *= 2;
1510         }
1511         vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
1512     }
1513
1514     int GetDistanceBack()
1515     {
1516         // Retrace how far back it was in the sender's branch
1517         int nDistance = 0;
1518         int nStep = 1;
1519         BOOST_FOREACH(const uint256& hash, vHave)
1520         {
1521             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1522             if (mi != mapBlockIndex.end())
1523             {
1524                 CBlockIndex* pindex = (*mi).second;
1525                 if (pindex->IsInMainChain())
1526                     return nDistance;
1527             }
1528             nDistance += nStep;
1529             if (nDistance > 10)
1530                 nStep *= 2;
1531         }
1532         return nDistance;
1533     }
1534
1535     CBlockIndex* GetBlockIndex()
1536     {
1537         // Find the first block the caller has in the main chain
1538         BOOST_FOREACH(const uint256& hash, vHave)
1539         {
1540             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1541             if (mi != mapBlockIndex.end())
1542             {
1543                 CBlockIndex* pindex = (*mi).second;
1544                 if (pindex->IsInMainChain())
1545                     return pindex;
1546             }
1547         }
1548         return pindexGenesisBlock;
1549     }
1550
1551     uint256 GetBlockHash()
1552     {
1553         // Find the first block the caller has in the main chain
1554         BOOST_FOREACH(const uint256& hash, vHave)
1555         {
1556             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1557             if (mi != mapBlockIndex.end())
1558             {
1559                 CBlockIndex* pindex = (*mi).second;
1560                 if (pindex->IsInMainChain())
1561                     return hash;
1562             }
1563         }
1564         return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
1565     }
1566
1567     int GetHeight()
1568     {
1569         CBlockIndex* pindex = GetBlockIndex();
1570         if (!pindex)
1571             return 0;
1572         return pindex->nHeight;
1573     }
1574 };
1575
1576
1577
1578
1579
1580
1581
1582
1583 class CTxMemPool
1584 {
1585 public:
1586     mutable CCriticalSection cs;
1587     std::map<uint256, CTransaction> mapTx;
1588     std::map<COutPoint, CInPoint> mapNextTx;
1589
1590     bool accept(CTxDB& txdb, CTransaction &tx,
1591                 bool fCheckInputs, bool* pfMissingInputs);
1592     bool addUnchecked(const uint256& hash, CTransaction &tx);
1593     bool remove(CTransaction &tx);
1594     void clear();
1595     void queryHashes(std::vector<uint256>& vtxid);
1596
1597     unsigned long size()
1598     {
1599         LOCK(cs);
1600         return mapTx.size();
1601     }
1602
1603     bool exists(uint256 hash)
1604     {
1605         return (mapTx.count(hash) != 0);
1606     }
1607
1608     CTransaction& lookup(uint256 hash)
1609     {
1610         return mapTx[hash];
1611     }
1612 };
1613
1614 extern CTxMemPool mempool;
1615
1616 #endif