Add checkpoint at block 14189, v3 lock-in since supermajority and bnProofOfStakeLimit...
[novacoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_MAIN_H
7 #define BITCOIN_MAIN_H
8
9 #include "bignum.h"
10 #include "net.h"
11 #include "script.h"
12 #include "scrypt_mine.h"
13
14 #ifdef WIN32
15 #include <io.h> /* for _commit */
16 #endif
17
18 #include <list>
19
20 class CWallet;
21 class CBlock;
22 class CBlockIndex;
23 class CKeyItem;
24 class CReserveKey;
25 class COutPoint;
26
27 class CAddress;
28 class CInv;
29 class CRequestTracker;
30 class CNode;
31
32 static const unsigned int MAX_BLOCK_SIZE = 1000000;
33 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
34 static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
35 static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
36 static const int64 MIN_TX_FEE = CENT;
37 static const int64 MIN_RELAY_TX_FEE = CENT;
38 static const int64 MAX_MONEY = 2000000000 * COIN;
39 static const int64 MAX_MINT_PROOF_OF_WORK = 100 * COIN;
40 static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY_PPC = 500;
43 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
44 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
45 static const int STAKE_TARGET_SPACING = 10 * 60; // 10-minute block spacing 
46 static const int STAKE_MIN_AGE = 60 * 60 * 24 * 30; // minimum age for coin age
47 static const int STAKE_MAX_AGE = 60 * 60 * 24 * 90; // stake age of full weight
48
49 #ifdef USE_UPNP
50 static const int fHaveUPnP = true;
51 #else
52 static const int fHaveUPnP = false;
53 #endif
54
55 static const uint256 hashGenesisBlockOfficial("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
56 static const uint256 hashGenesisBlockTestNet("0x00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4");
57
58 static const int64 nMaxClockDrift = 2 * 60 * 60;        // two hours
59
60 extern CScript COINBASE_FLAGS;
61
62
63
64
65
66
67 extern CCriticalSection cs_main;
68 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
69 extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
70 extern uint256 hashGenesisBlock;
71 extern unsigned int nStakeMinAge;
72 extern int nCoinbaseMaturity;
73 extern CBlockIndex* pindexGenesisBlock;
74 extern int nBestHeight;
75 extern CBigNum bnBestChainTrust;
76 extern CBigNum bnBestInvalidTrust;
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 double dHashesPerSec;
85 extern int64 nHPSTimerStart;
86 extern int64 nTimeBestReceived;
87 extern CCriticalSection cs_setpwalletRegistered;
88 extern std::set<CWallet*> setpwalletRegistered;
89 extern std::map<uint256, CBlock*> mapOrphanBlocks;
90
91 // Settings
92 extern int64 nTransactionFee;
93
94
95
96
97
98 class CReserveKey;
99 class CTxDB;
100 class CTxIndex;
101
102 void RegisterWallet(CWallet* pwalletIn);
103 void UnregisterWallet(CWallet* pwalletIn);
104 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
105 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
106 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
107 FILE* AppendBlockFile(unsigned int& nFileRet);
108 bool LoadBlockIndex(bool fAllowNew=true);
109 void PrintBlockTree();
110 bool ProcessMessages(CNode* pfrom);
111 bool SendMessages(CNode* pto, bool fSendTrickle);
112 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
113 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
114 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
115 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
116 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
117 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
118 int64 GetProofOfWorkReward(unsigned int nBits);
119 int64 GetProofOfStakeReward(int64 nCoinAge);
120 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime, bool fProofOfStake, int nHeight);
121 int GetNumBlocksOfPeers();
122 bool IsInitialBlockDownload();
123 std::string GetWarnings(std::string strFor);
124 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
125 uint256 WantedByOrphan(const CBlock* pblockOrphan);
126 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
127 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
128 void ResendWalletTransactions();
129
130
131
132
133
134
135
136 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
137
138 /** Position on disk for a particular transaction. */
139 class CDiskTxPos
140 {
141 public:
142     unsigned int nFile;
143     unsigned int nBlockPos;
144     unsigned int nTxPos;
145
146     CDiskTxPos()
147     {
148         SetNull();
149     }
150
151     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
152     {
153         nFile = nFileIn;
154         nBlockPos = nBlockPosIn;
155         nTxPos = nTxPosIn;
156     }
157
158     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
159     void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
160     bool IsNull() const { return (nFile == -1); }
161
162     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
163     {
164         return (a.nFile     == b.nFile &&
165                 a.nBlockPos == b.nBlockPos &&
166                 a.nTxPos    == b.nTxPos);
167     }
168
169     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
170     {
171         return !(a == b);
172     }
173
174     std::string ToString() const
175     {
176         if (IsNull())
177             return "null";
178         else
179             return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
180     }
181
182     void print() const
183     {
184         printf("%s", ToString().c_str());
185     }
186 };
187
188
189
190 /** An inpoint - a combination of a transaction and an index n into its vin */
191 class CInPoint
192 {
193 public:
194     CTransaction* ptx;
195     unsigned int n;
196
197     CInPoint() { SetNull(); }
198     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
199     void SetNull() { ptx = NULL; n = -1; }
200     bool IsNull() const { return (ptx == NULL && n == -1); }
201 };
202
203
204
205 /** An outpoint - a combination of a transaction hash and an index n into its vout */
206 class COutPoint
207 {
208 public:
209     uint256 hash;
210     unsigned int n;
211
212     COutPoint() { SetNull(); }
213     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
214     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
215     void SetNull() { hash = 0; n = -1; }
216     bool IsNull() const { return (hash == 0 && n == -1); }
217
218     friend bool operator<(const COutPoint& a, const COutPoint& b)
219     {
220         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
221     }
222
223     friend bool operator==(const COutPoint& a, const COutPoint& b)
224     {
225         return (a.hash == b.hash && a.n == b.n);
226     }
227
228     friend bool operator!=(const COutPoint& a, const COutPoint& b)
229     {
230         return !(a == b);
231     }
232
233     std::string ToString() const
234     {
235         return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
236     }
237
238     void print() const
239     {
240         printf("%s\n", ToString().c_str());
241     }
242 };
243
244
245
246
247 /** An input of a transaction.  It contains the location of the previous
248  * transaction's output that it claims and a signature that matches the
249  * output's public key.
250  */
251 class CTxIn
252 {
253 public:
254     COutPoint prevout;
255     CScript scriptSig;
256     unsigned int nSequence;
257
258     CTxIn()
259     {
260         nSequence = std::numeric_limits<unsigned int>::max();
261     }
262
263     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
264     {
265         prevout = prevoutIn;
266         scriptSig = scriptSigIn;
267         nSequence = nSequenceIn;
268     }
269
270     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
271     {
272         prevout = COutPoint(hashPrevTx, nOut);
273         scriptSig = scriptSigIn;
274         nSequence = nSequenceIn;
275     }
276
277     IMPLEMENT_SERIALIZE
278     (
279         READWRITE(prevout);
280         READWRITE(scriptSig);
281         READWRITE(nSequence);
282     )
283
284     bool IsFinal() const
285     {
286         return (nSequence == std::numeric_limits<unsigned int>::max());
287     }
288
289     friend bool operator==(const CTxIn& a, const CTxIn& b)
290     {
291         return (a.prevout   == b.prevout &&
292                 a.scriptSig == b.scriptSig &&
293                 a.nSequence == b.nSequence);
294     }
295
296     friend bool operator!=(const CTxIn& a, const CTxIn& b)
297     {
298         return !(a == b);
299     }
300
301     std::string ToStringShort() const
302     {
303         return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
304     }
305
306     std::string ToString() const
307     {
308         std::string str;
309         str += "CTxIn(";
310         str += prevout.ToString();
311         if (prevout.IsNull())
312             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
313         else
314             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
315         if (nSequence != std::numeric_limits<unsigned int>::max())
316             str += strprintf(", nSequence=%u", nSequence);
317         str += ")";
318         return str;
319     }
320
321     void print() const
322     {
323         printf("%s\n", ToString().c_str());
324     }
325 };
326
327
328
329
330 /** An output of a transaction.  It contains the public key that the next input
331  * must be able to sign with to claim it.
332  */
333 class CTxOut
334 {
335 public:
336     int64 nValue;
337     CScript scriptPubKey;
338
339     CTxOut()
340     {
341         SetNull();
342     }
343
344     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
345     {
346         nValue = nValueIn;
347         scriptPubKey = scriptPubKeyIn;
348     }
349
350     IMPLEMENT_SERIALIZE
351     (
352         READWRITE(nValue);
353         READWRITE(scriptPubKey);
354     )
355
356     void SetNull()
357     {
358         nValue = -1;
359         scriptPubKey.clear();
360     }
361
362     bool IsNull()
363     {
364         return (nValue == -1);
365     }
366
367     void SetEmpty()
368     {
369         nValue = 0;
370         scriptPubKey.clear();
371     }
372
373     bool IsEmpty() const
374     {
375         return (nValue == 0 && scriptPubKey.empty());
376     }
377
378     uint256 GetHash() const
379     {
380         return SerializeHash(*this);
381     }
382
383     friend bool operator==(const CTxOut& a, const CTxOut& b)
384     {
385         return (a.nValue       == b.nValue &&
386                 a.scriptPubKey == b.scriptPubKey);
387     }
388
389     friend bool operator!=(const CTxOut& a, const CTxOut& b)
390     {
391         return !(a == b);
392     }
393
394     std::string ToStringShort() const
395     {
396         return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
397     }
398
399     std::string ToString() const
400     {
401         if (IsEmpty()) return "CTxOut(empty)";
402         if (scriptPubKey.size() < 6)
403             return "CTxOut(error)";
404         return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
405     }
406
407     void print() const
408     {
409         printf("%s\n", ToString().c_str());
410     }
411 };
412
413
414
415
416 enum GetMinFee_mode
417 {
418     GMF_BLOCK,
419     GMF_RELAY,
420     GMF_SEND,
421 };
422
423 typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
424
425 /** The basic transaction that is broadcasted on the network and contained in
426  * blocks.  A transaction can contain multiple inputs and outputs.
427  */
428 class CTransaction
429 {
430 public:
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 = 1;
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         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
594         int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
595
596         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
597         unsigned int nNewBlockSize = nBlockSize + nBytes;
598         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
599
600         if (fAllowFree)
601         {
602             if (nBlockSize == 1)
603             {
604                 // Transactions under 10K are free
605                 // (about 4500bc if made of 50bc inputs)
606                 if (nBytes < 10000)
607                     nMinFee = 0;
608             }
609             else
610             {
611                 // Free transaction area
612                 if (nNewBlockSize < 27000)
613                     nMinFee = 0;
614             }
615         }
616
617         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
618         if (nMinFee < nBaseFee)
619         {
620             BOOST_FOREACH(const CTxOut& txout, vout)
621                 if (txout.nValue < CENT)
622                     nMinFee = nBaseFee;
623         }
624
625         // Raise the price as the block approaches full
626         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
627         {
628             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
629                 return MAX_MONEY;
630             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
631         }
632
633         if (!MoneyRange(nMinFee))
634             nMinFee = MAX_MONEY;
635         return nMinFee;
636     }
637
638
639     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
640     {
641         CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
642         if (!filein)
643             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
644
645         // Read transaction
646         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
647             return error("CTransaction::ReadFromDisk() : fseek failed");
648
649         try {
650             filein >> *this;
651         }
652         catch (std::exception &e) {
653             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
654         }
655
656         // Return file pointer
657         if (pfileRet)
658         {
659             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
660                 return error("CTransaction::ReadFromDisk() : second fseek failed");
661             *pfileRet = filein.release();
662         }
663         return true;
664     }
665
666     friend bool operator==(const CTransaction& a, const CTransaction& b)
667     {
668         return (a.nVersion  == b.nVersion &&
669                 a.nTime     == b.nTime &&
670                 a.vin       == b.vin &&
671                 a.vout      == b.vout &&
672                 a.nLockTime == b.nLockTime);
673     }
674
675     friend bool operator!=(const CTransaction& a, const CTransaction& b)
676     {
677         return !(a == b);
678     }
679
680
681     std::string ToStringShort() const
682     {
683         std::string str;
684         str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
685         return str;
686     }
687
688     std::string ToString() const
689     {
690         std::string str;
691         str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
692         str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
693             GetHash().ToString().substr(0,10).c_str(),
694             nTime,
695             nVersion,
696             vin.size(),
697             vout.size(),
698             nLockTime);
699         for (unsigned int i = 0; i < vin.size(); i++)
700             str += "    " + vin[i].ToString() + "\n";
701         for (unsigned int i = 0; i < vout.size(); i++)
702             str += "    " + vout[i].ToString() + "\n";
703         return str;
704     }
705
706     void print() const
707     {
708         printf("%s", ToString().c_str());
709     }
710
711
712     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
713     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
714     bool ReadFromDisk(COutPoint prevout);
715     bool DisconnectInputs(CTxDB& txdb);
716
717     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
718
719      @param[in] txdb    Transaction database
720      @param[in] mapTestPool     List of pending changes to the transaction index database
721      @param[in] fBlock  True if being called to add a new best-block to the chain
722      @param[in] fMiner  True if being called by CreateNewBlock
723      @param[out] inputsRet      Pointers to this transaction's inputs
724      @param[out] fInvalid       returns true if transaction is invalid
725      @return    Returns true if all inputs are in txdb or mapTestPool
726      */
727     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
728                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
729
730     /** Sanity check previous transactions, then, if all checks succeed,
731         mark them as spent by this transaction.
732
733         @param[in] inputs       Previous transactions (from FetchInputs)
734         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
735         @param[in] posThisTx    Position of this transaction on disk
736         @param[in] pindexBlock
737         @param[in] fBlock       true if called from ConnectBlock
738         @param[in] fMiner       true if called from CreateNewBlock
739         @param[in] fStrictPayToScriptHash       true if fully validating p2sh transactions
740         @return Returns true if all checks succeed
741      */
742     bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
743                        std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
744                        const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
745     bool ClientConnectInputs();
746     bool CheckTransaction() const;
747     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
748     bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const;  // ppcoin: get transaction coin age
749
750 protected:
751     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
752 };
753
754
755
756
757
758 /** A transaction with a merkle branch linking it to the block chain. */
759 class CMerkleTx : public CTransaction
760 {
761 public:
762     uint256 hashBlock;
763     std::vector<uint256> vMerkleBranch;
764     int nIndex;
765
766     // memory only
767     mutable bool fMerkleVerified;
768
769
770     CMerkleTx()
771     {
772         Init();
773     }
774
775     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
776     {
777         Init();
778     }
779
780     void Init()
781     {
782         hashBlock = 0;
783         nIndex = -1;
784         fMerkleVerified = false;
785     }
786
787
788     IMPLEMENT_SERIALIZE
789     (
790         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
791         nVersion = this->nVersion;
792         READWRITE(hashBlock);
793         READWRITE(vMerkleBranch);
794         READWRITE(nIndex);
795     )
796
797
798     int SetMerkleBranch(const CBlock* pblock=NULL);
799     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
800     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
801     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
802     int GetBlocksToMaturity() const;
803     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
804     bool AcceptToMemoryPool();
805 };
806
807
808
809
810 /**  A txdb record that contains the disk location of a transaction and the
811  * locations of transactions that spend its outputs.  vSpent is really only
812  * used as a flag, but having the location is very helpful for debugging.
813  */
814 class CTxIndex
815 {
816 public:
817     CDiskTxPos pos;
818     std::vector<CDiskTxPos> vSpent;
819
820     CTxIndex()
821     {
822         SetNull();
823     }
824
825     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
826     {
827         pos = posIn;
828         vSpent.resize(nOutputs);
829     }
830
831     IMPLEMENT_SERIALIZE
832     (
833         if (!(nType & SER_GETHASH))
834             READWRITE(nVersion);
835         READWRITE(pos);
836         READWRITE(vSpent);
837     )
838
839     void SetNull()
840     {
841         pos.SetNull();
842         vSpent.clear();
843     }
844
845     bool IsNull()
846     {
847         return pos.IsNull();
848     }
849
850     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
851     {
852         return (a.pos    == b.pos &&
853                 a.vSpent == b.vSpent);
854     }
855
856     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
857     {
858         return !(a == b);
859     }
860     int GetDepthInMainChain() const;
861 };
862
863
864
865
866
867 /** Nodes collect new transactions into a block, hash them into a hash tree,
868  * and scan through nonce values to make the block's hash satisfy proof-of-work
869  * requirements.  When they solve the proof-of-work, they broadcast the block
870  * to everyone and the block is added to the block chain.  The first transaction
871  * in the block is a special one that creates a new coin owned by the creator
872  * of the block.
873  *
874  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
875  * is indexed by CBlockIndex objects in memory.
876  */
877 class CBlock
878 {
879 public:
880     // header
881     int nVersion;
882     uint256 hashPrevBlock;
883     uint256 hashMerkleRoot;
884     unsigned int nTime;
885     unsigned int nBits;
886     unsigned int nNonce;
887
888     // network and disk
889     std::vector<CTransaction> vtx;
890
891     // ppcoin: block signature - signed by one of the coin base txout[N]'s owner
892     std::vector<unsigned char> vchBlockSig;
893
894     // memory only
895     mutable std::vector<uint256> vMerkleTree;
896
897     // Denial-of-service detection:
898     mutable int nDoS;
899     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
900
901     CBlock()
902     {
903         SetNull();
904     }
905
906     IMPLEMENT_SERIALIZE
907     (
908         READWRITE(this->nVersion);
909         nVersion = this->nVersion;
910         READWRITE(hashPrevBlock);
911         READWRITE(hashMerkleRoot);
912         READWRITE(nTime);
913         READWRITE(nBits);
914         READWRITE(nNonce);
915
916         // ConnectBlock depends on vtx following header to generate CDiskTxPos
917         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
918         {
919             READWRITE(vtx);
920             READWRITE(vchBlockSig);
921         }
922         else if (fRead)
923         {
924             const_cast<CBlock*>(this)->vtx.clear();
925             const_cast<CBlock*>(this)->vchBlockSig.clear();
926         }
927     )
928
929     void SetNull()
930     {
931         nVersion = 3;
932         hashPrevBlock = 0;
933         hashMerkleRoot = 0;
934         nTime = 0;
935         nBits = 0;
936         nNonce = 0;
937         vtx.clear();
938         vchBlockSig.clear();
939         vMerkleTree.clear();
940         nDoS = 0;
941     }
942
943     bool IsNull() const
944     {
945         return (nBits == 0);
946     }
947
948     uint256 GetHash() const
949     {
950         uint256 thash;
951         void * scratchbuff = scrypt_buffer_alloc();
952
953         scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff);
954
955         scrypt_buffer_free(scratchbuff);
956
957         return thash;
958     }
959
960     int GetBlockHeight() const;
961
962     int64 GetBlockTime() const
963     {
964         return (int64)nTime;
965     }
966
967     void UpdateTime(const CBlockIndex* pindexPrev);
968
969     // ppcoin: entropy bit for stake modifier if chosen by modifier
970     unsigned int GetStakeEntropyBit(unsigned int nHeight) const
971     {
972         // Protocol switch to support p2pool at novacoin block #9689
973         if (nHeight >= 9689)
974         {
975             // Take last bit of block hash as entropy bit
976             unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
977             if (fDebug && GetBoolArg("-printstakemodifier"))
978                 printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit);
979             return nEntropyBit;
980         }
981         // Before novacoin block #9689 - old protocol
982         uint160 hashSig = Hash160(vchBlockSig);
983         if (fDebug && GetBoolArg("-printstakemodifier"))
984             printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
985         hashSig >>= 159; // take the first bit of the hash
986         if (fDebug && GetBoolArg("-printstakemodifier"))
987             printf(" entropybit=%d\n", hashSig.Get64());
988         return hashSig.Get64();
989     }
990
991     // ppcoin: two types of block: proof-of-work or proof-of-stake
992     bool IsProofOfStake() const
993     {
994         return (vtx.size() > 1 && vtx[1].IsCoinStake());
995     }
996
997     bool IsProofOfWork() const
998     {
999         return !IsProofOfStake();
1000     }
1001
1002     std::pair<COutPoint, unsigned int> GetProofOfStake() const
1003     {
1004         return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
1005     }
1006
1007     // ppcoin: get max transaction timestamp
1008     int64 GetMaxTransactionTime() const
1009     {
1010         int64 maxTransactionTime = 0;
1011         BOOST_FOREACH(const CTransaction& tx, vtx)
1012             maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
1013         return maxTransactionTime;
1014     }
1015
1016     uint256 BuildMerkleTree() const
1017     {
1018         vMerkleTree.clear();
1019         BOOST_FOREACH(const CTransaction& tx, vtx)
1020             vMerkleTree.push_back(tx.GetHash());
1021         int j = 0;
1022         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1023         {
1024             for (int i = 0; i < nSize; i += 2)
1025             {
1026                 int i2 = std::min(i+1, nSize-1);
1027                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1028                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1029             }
1030             j += nSize;
1031         }
1032         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1033     }
1034
1035     std::vector<uint256> GetMerkleBranch(int nIndex) const
1036     {
1037         if (vMerkleTree.empty())
1038             BuildMerkleTree();
1039         std::vector<uint256> vMerkleBranch;
1040         int j = 0;
1041         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1042         {
1043             int i = std::min(nIndex^1, nSize-1);
1044             vMerkleBranch.push_back(vMerkleTree[j+i]);
1045             nIndex >>= 1;
1046             j += nSize;
1047         }
1048         return vMerkleBranch;
1049     }
1050
1051     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1052     {
1053         if (nIndex == -1)
1054             return 0;
1055         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1056         {
1057             if (nIndex & 1)
1058                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1059             else
1060                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1061             nIndex >>= 1;
1062         }
1063         return hash;
1064     }
1065
1066
1067     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1068     {
1069         // Open history file to append
1070         CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1071         if (!fileout)
1072             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1073
1074         // Write index header
1075         unsigned char pchMessageStart[4];
1076         GetMessageStart(pchMessageStart, true);
1077         unsigned int nSize = fileout.GetSerializeSize(*this);
1078         fileout << FLATDATA(pchMessageStart) << nSize;
1079
1080         // Write block
1081         long fileOutPos = ftell(fileout);
1082         if (fileOutPos < 0)
1083             return error("CBlock::WriteToDisk() : ftell failed");
1084         nBlockPosRet = fileOutPos;
1085         fileout << *this;
1086
1087         // Flush stdio buffers and commit to disk before returning
1088         fflush(fileout);
1089         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1090         {
1091 #ifdef WIN32
1092             _commit(_fileno(fileout));
1093 #else
1094             fsync(fileno(fileout));
1095 #endif
1096         }
1097
1098         return true;
1099     }
1100
1101     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1102     {
1103         SetNull();
1104
1105         // Open history file to read
1106         CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1107         if (!filein)
1108             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1109         if (!fReadTransactions)
1110             filein.nType |= SER_BLOCKHEADERONLY;
1111
1112         // Read block
1113         try {
1114             filein >> *this;
1115         }
1116         catch (std::exception &e) {
1117             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
1118         }
1119
1120         // Check the header
1121         if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1122             return error("CBlock::ReadFromDisk() : errors in block header");
1123
1124         return true;
1125     }
1126
1127
1128
1129     void print() const
1130     {
1131         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d, vchBlockSig=%s)\n",
1132             GetHash().ToString().substr(0,20).c_str(),
1133             nVersion,
1134             hashPrevBlock.ToString().substr(0,20).c_str(),
1135             hashMerkleRoot.ToString().substr(0,10).c_str(),
1136             nTime, nBits, nNonce,
1137             vtx.size(),
1138             HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1139         for (unsigned int i = 0; i < vtx.size(); i++)
1140         {
1141             printf("  ");
1142             vtx[i].print();
1143         }
1144         printf("  vMerkleTree: ");
1145         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1146             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1147         printf("\n");
1148     }
1149
1150
1151     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1152     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1153     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1154     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1155     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1156     bool CheckBlock() const;
1157     bool AcceptBlock();
1158     bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
1159     bool SignBlock(const CKeyStore& keystore);
1160     bool CheckBlockSignature() const;
1161
1162 private:
1163     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1164 };
1165
1166
1167
1168
1169
1170
1171 /** The block chain is a tree shaped structure starting with the
1172  * genesis block at the root, with each block potentially having multiple
1173  * candidates to be the next block.  pprev and pnext link a path through the
1174  * main/longest chain.  A blockindex may have multiple pprev pointing back
1175  * to it, but pnext will only point forward to the longest branch, or will
1176  * be null if the block is not part of the longest chain.
1177  */
1178 class CBlockIndex
1179 {
1180 public:
1181     const uint256* phashBlock;
1182     CBlockIndex* pprev;
1183     CBlockIndex* pnext;
1184     unsigned int nFile;
1185     unsigned int nBlockPos;
1186     CBigNum bnChainTrust; // ppcoin: trust score of block chain
1187     int nHeight;
1188     int64 nMint;
1189     int64 nMoneySupply;
1190
1191     unsigned int nFlags;  // ppcoin: block index flags
1192     enum  
1193     {
1194         BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
1195         BLOCK_STAKE_ENTROPY  = (1 << 1), // entropy bit for stake modifier
1196         BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
1197     };
1198
1199     uint64 nStakeModifier; // hash modifier for proof-of-stake
1200     unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
1201
1202     // proof-of-stake specific fields
1203     COutPoint prevoutStake;
1204     unsigned int nStakeTime;
1205     uint256 hashProofOfStake;
1206
1207     // block header
1208     int nVersion;
1209     uint256 hashMerkleRoot;
1210     unsigned int nTime;
1211     unsigned int nBits;
1212     unsigned int nNonce;
1213
1214
1215     CBlockIndex()
1216     {
1217         phashBlock = NULL;
1218         pprev = NULL;
1219         pnext = NULL;
1220         nFile = 0;
1221         nBlockPos = 0;
1222         nHeight = 0;
1223         bnChainTrust = 0;
1224         nMint = 0;
1225         nMoneySupply = 0;
1226         nFlags = 0;
1227         nStakeModifier = 0;
1228         nStakeModifierChecksum = 0;
1229         hashProofOfStake = 0;
1230         prevoutStake.SetNull();
1231         nStakeTime = 0;
1232
1233         nVersion       = 0;
1234         hashMerkleRoot = 0;
1235         nTime          = 0;
1236         nBits          = 0;
1237         nNonce         = 0;
1238     }
1239
1240     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1241     {
1242         phashBlock = NULL;
1243         pprev = NULL;
1244         pnext = NULL;
1245         nFile = nFileIn;
1246         nBlockPos = nBlockPosIn;
1247         nHeight = 0;
1248         bnChainTrust = 0;
1249         nMint = 0;
1250         nMoneySupply = 0;
1251         nFlags = 0;
1252         nStakeModifier = 0;
1253         nStakeModifierChecksum = 0;
1254         hashProofOfStake = 0;
1255         if (block.IsProofOfStake())
1256         {
1257             SetProofOfStake();
1258             prevoutStake = block.vtx[1].vin[0].prevout;
1259             nStakeTime = block.vtx[1].nTime;
1260         }
1261         else
1262         {
1263             prevoutStake.SetNull();
1264             nStakeTime = 0;
1265         }
1266
1267         nVersion       = block.nVersion;
1268         hashMerkleRoot = block.hashMerkleRoot;
1269         nTime          = block.nTime;
1270         nBits          = block.nBits;
1271         nNonce         = block.nNonce;
1272     }
1273
1274     CBlock GetBlockHeader() const
1275     {
1276         CBlock block;
1277         block.nVersion       = nVersion;
1278         if (pprev)
1279             block.hashPrevBlock = pprev->GetBlockHash();
1280         block.hashMerkleRoot = hashMerkleRoot;
1281         block.nTime          = nTime;
1282         block.nBits          = nBits;
1283         block.nNonce         = nNonce;
1284         return block;
1285     }
1286
1287     uint256 GetBlockHash() const
1288     {
1289         return *phashBlock;
1290     }
1291
1292     int64 GetBlockTime() const
1293     {
1294         return (int64)nTime;
1295     }
1296
1297     CBigNum GetBlockTrust() const
1298     {
1299         CBigNum bnTarget;
1300         bnTarget.SetCompact(nBits);
1301         if (bnTarget <= 0)
1302             return 0;
1303         return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1);
1304     }
1305
1306     bool IsInMainChain() const
1307     {
1308         return (pnext || this == pindexBest);
1309     }
1310
1311     bool CheckIndex() const
1312     {
1313         return true;
1314     }
1315
1316     bool EraseBlockFromDisk()
1317     {
1318         // Open history file
1319         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1320         if (!fileout)
1321             return false;
1322
1323         // Overwrite with empty null block
1324         CBlock block;
1325         block.SetNull();
1326         fileout << block;
1327
1328         return true;
1329     }
1330
1331     enum { nMedianTimeSpan=11 };
1332
1333     int64 GetMedianTimePast() const
1334     {
1335         int64 pmedian[nMedianTimeSpan];
1336         int64* pbegin = &pmedian[nMedianTimeSpan];
1337         int64* pend = &pmedian[nMedianTimeSpan];
1338
1339         const CBlockIndex* pindex = this;
1340         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1341             *(--pbegin) = pindex->GetBlockTime();
1342
1343         std::sort(pbegin, pend);
1344         return pbegin[(pend - pbegin)/2];
1345     }
1346
1347     int64 GetMedianTime() const
1348     {
1349         const CBlockIndex* pindex = this;
1350         for (int i = 0; i < nMedianTimeSpan/2; i++)
1351         {
1352             if (!pindex->pnext)
1353                 return GetBlockTime();
1354             pindex = pindex->pnext;
1355         }
1356         return pindex->GetMedianTimePast();
1357     }
1358
1359     bool IsProofOfWork() const
1360     {
1361         return !(nFlags & BLOCK_PROOF_OF_STAKE);
1362     }
1363
1364     bool IsProofOfStake() const
1365     {
1366         return (nFlags & BLOCK_PROOF_OF_STAKE);
1367     }
1368
1369     void SetProofOfStake()
1370     {
1371         nFlags |= BLOCK_PROOF_OF_STAKE;
1372     }
1373
1374     unsigned int GetStakeEntropyBit() const
1375     {
1376         return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
1377     }
1378
1379     bool SetStakeEntropyBit(unsigned int nEntropyBit)
1380     {
1381         if (nEntropyBit > 1)
1382             return false;
1383         nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
1384         return true;
1385     }
1386
1387     bool GeneratedStakeModifier() const
1388     {
1389         return (nFlags & BLOCK_STAKE_MODIFIER);
1390     }
1391
1392     void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
1393     {
1394         nStakeModifier = nModifier;
1395         if (fGeneratedStakeModifier)
1396             nFlags |= BLOCK_STAKE_MODIFIER;
1397     }
1398
1399     std::string ToString() const
1400     {
1401         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, 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)",
1402             pprev, pnext, nFile, nBlockPos, nHeight,
1403             FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
1404             GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
1405             nStakeModifier, nStakeModifierChecksum, 
1406             hashProofOfStake.ToString().c_str(),
1407             prevoutStake.ToString().c_str(), nStakeTime,
1408             hashMerkleRoot.ToString().substr(0,10).c_str(),
1409             GetBlockHash().ToString().substr(0,20).c_str());
1410     }
1411
1412     void print() const
1413     {
1414         printf("%s\n", ToString().c_str());
1415     }
1416 };
1417
1418
1419
1420 /** Used to marshal pointers into hashes for db storage. */
1421 class CDiskBlockIndex : public CBlockIndex
1422 {
1423 public:
1424     uint256 hashPrev;
1425     uint256 hashNext;
1426
1427     CDiskBlockIndex()
1428     {
1429         hashPrev = 0;
1430         hashNext = 0;
1431     }
1432
1433     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1434     {
1435         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1436         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1437     }
1438
1439     IMPLEMENT_SERIALIZE
1440     (
1441         if (!(nType & SER_GETHASH))
1442             READWRITE(nVersion);
1443
1444         READWRITE(hashNext);
1445         READWRITE(nFile);
1446         READWRITE(nBlockPos);
1447         READWRITE(nHeight);
1448         READWRITE(nMint);
1449         READWRITE(nMoneySupply);
1450         READWRITE(nFlags);
1451         READWRITE(nStakeModifier);
1452         if (IsProofOfStake())
1453         {
1454             READWRITE(prevoutStake);
1455             READWRITE(nStakeTime);
1456             READWRITE(hashProofOfStake);
1457         }
1458         else if (fRead)
1459         {
1460             const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
1461             const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
1462             const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
1463         }
1464
1465         // block header
1466         READWRITE(this->nVersion);
1467         READWRITE(hashPrev);
1468         READWRITE(hashMerkleRoot);
1469         READWRITE(nTime);
1470         READWRITE(nBits);
1471         READWRITE(nNonce);
1472     )
1473
1474     uint256 GetBlockHash() const
1475     {
1476         CBlock block;
1477         block.nVersion        = nVersion;
1478         block.hashPrevBlock   = hashPrev;
1479         block.hashMerkleRoot  = hashMerkleRoot;
1480         block.nTime           = nTime;
1481         block.nBits           = nBits;
1482         block.nNonce          = nNonce;
1483         return block.GetHash();
1484     }
1485
1486
1487     std::string ToString() const
1488     {
1489         std::string str = "CDiskBlockIndex(";
1490         str += CBlockIndex::ToString();
1491         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1492             GetBlockHash().ToString().c_str(),
1493             hashPrev.ToString().substr(0,20).c_str(),
1494             hashNext.ToString().substr(0,20).c_str());
1495         return str;
1496     }
1497
1498     void print() const
1499     {
1500         printf("%s\n", ToString().c_str());
1501     }
1502 };
1503
1504
1505
1506
1507
1508
1509
1510
1511 /** Describes a place in the block chain to another node such that if the
1512  * other node doesn't have the same branch, it can find a recent common trunk.
1513  * The further back it is, the further before the fork it may be.
1514  */
1515 class CBlockLocator
1516 {
1517 protected:
1518     std::vector<uint256> vHave;
1519 public:
1520
1521     CBlockLocator()
1522     {
1523     }
1524
1525     explicit CBlockLocator(const CBlockIndex* pindex)
1526     {
1527         Set(pindex);
1528     }
1529
1530     explicit CBlockLocator(uint256 hashBlock)
1531     {
1532         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1533         if (mi != mapBlockIndex.end())
1534             Set((*mi).second);
1535     }
1536
1537     CBlockLocator(const std::vector<uint256>& vHaveIn)
1538     {
1539         vHave = vHaveIn;
1540     }
1541
1542     IMPLEMENT_SERIALIZE
1543     (
1544         if (!(nType & SER_GETHASH))
1545             READWRITE(nVersion);
1546         READWRITE(vHave);
1547     )
1548
1549     void SetNull()
1550     {
1551         vHave.clear();
1552     }
1553
1554     bool IsNull()
1555     {
1556         return vHave.empty();
1557     }
1558
1559     void Set(const CBlockIndex* pindex)
1560     {
1561         vHave.clear();
1562         int nStep = 1;
1563         while (pindex)
1564         {
1565             vHave.push_back(pindex->GetBlockHash());
1566
1567             // Exponentially larger steps back
1568             for (int i = 0; pindex && i < nStep; i++)
1569                 pindex = pindex->pprev;
1570             if (vHave.size() > 10)
1571                 nStep *= 2;
1572         }
1573         vHave.push_back(hashGenesisBlock);
1574     }
1575
1576     int GetDistanceBack()
1577     {
1578         // Retrace how far back it was in the sender's branch
1579         int nDistance = 0;
1580         int nStep = 1;
1581         BOOST_FOREACH(const uint256& hash, vHave)
1582         {
1583             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1584             if (mi != mapBlockIndex.end())
1585             {
1586                 CBlockIndex* pindex = (*mi).second;
1587                 if (pindex->IsInMainChain())
1588                     return nDistance;
1589             }
1590             nDistance += nStep;
1591             if (nDistance > 10)
1592                 nStep *= 2;
1593         }
1594         return nDistance;
1595     }
1596
1597     CBlockIndex* GetBlockIndex()
1598     {
1599         // Find the first block the caller has in the main chain
1600         BOOST_FOREACH(const uint256& hash, vHave)
1601         {
1602             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1603             if (mi != mapBlockIndex.end())
1604             {
1605                 CBlockIndex* pindex = (*mi).second;
1606                 if (pindex->IsInMainChain())
1607                     return pindex;
1608             }
1609         }
1610         return pindexGenesisBlock;
1611     }
1612
1613     uint256 GetBlockHash()
1614     {
1615         // Find the first block the caller has in the main chain
1616         BOOST_FOREACH(const uint256& hash, vHave)
1617         {
1618             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1619             if (mi != mapBlockIndex.end())
1620             {
1621                 CBlockIndex* pindex = (*mi).second;
1622                 if (pindex->IsInMainChain())
1623                     return hash;
1624             }
1625         }
1626         return hashGenesisBlock;
1627     }
1628
1629     int GetHeight()
1630     {
1631         CBlockIndex* pindex = GetBlockIndex();
1632         if (!pindex)
1633             return 0;
1634         return pindex->nHeight;
1635     }
1636 };
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646 /** Alerts are for notifying old versions if they become too obsolete and
1647  * need to upgrade.  The message is displayed in the status bar.
1648  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1649  * not read the entire buffer if the alert is for a newer version, but older
1650  * versions can still relay the original data.
1651  */
1652 class CUnsignedAlert
1653 {
1654 public:
1655     int nVersion;
1656     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1657     int64 nExpiration;
1658     int nID;
1659     int nCancel;
1660     std::set<int> setCancel;
1661     int nMinVer;            // lowest version inclusive
1662     int nMaxVer;            // highest version inclusive
1663     std::set<std::string> setSubVer;  // empty matches all
1664     int nPriority;
1665
1666     // Actions
1667     std::string strComment;
1668     std::string strStatusBar;
1669     std::string strReserved;
1670
1671     IMPLEMENT_SERIALIZE
1672     (
1673         READWRITE(this->nVersion);
1674         nVersion = this->nVersion;
1675         READWRITE(nRelayUntil);
1676         READWRITE(nExpiration);
1677         READWRITE(nID);
1678         READWRITE(nCancel);
1679         READWRITE(setCancel);
1680         READWRITE(nMinVer);
1681         READWRITE(nMaxVer);
1682         READWRITE(setSubVer);
1683         READWRITE(nPriority);
1684
1685         READWRITE(strComment);
1686         READWRITE(strStatusBar);
1687         READWRITE(strReserved);
1688     )
1689
1690     void SetNull()
1691     {
1692         nVersion = 1;
1693         nRelayUntil = 0;
1694         nExpiration = 0;
1695         nID = 0;
1696         nCancel = 0;
1697         setCancel.clear();
1698         nMinVer = 0;
1699         nMaxVer = 0;
1700         setSubVer.clear();
1701         nPriority = 0;
1702
1703         strComment.clear();
1704         strStatusBar.clear();
1705         strReserved.clear();
1706     }
1707
1708     std::string ToString() const
1709     {
1710         std::string strSetCancel;
1711         BOOST_FOREACH(int n, setCancel)
1712             strSetCancel += strprintf("%d ", n);
1713         std::string strSetSubVer;
1714         BOOST_FOREACH(std::string str, setSubVer)
1715             strSetSubVer += "\"" + str + "\" ";
1716         return strprintf(
1717                 "CAlert(\n"
1718                 "    nVersion     = %d\n"
1719                 "    nRelayUntil  = %"PRI64d"\n"
1720                 "    nExpiration  = %"PRI64d"\n"
1721                 "    nID          = %d\n"
1722                 "    nCancel      = %d\n"
1723                 "    setCancel    = %s\n"
1724                 "    nMinVer      = %d\n"
1725                 "    nMaxVer      = %d\n"
1726                 "    setSubVer    = %s\n"
1727                 "    nPriority    = %d\n"
1728                 "    strComment   = \"%s\"\n"
1729                 "    strStatusBar = \"%s\"\n"
1730                 ")\n",
1731             nVersion,
1732             nRelayUntil,
1733             nExpiration,
1734             nID,
1735             nCancel,
1736             strSetCancel.c_str(),
1737             nMinVer,
1738             nMaxVer,
1739             strSetSubVer.c_str(),
1740             nPriority,
1741             strComment.c_str(),
1742             strStatusBar.c_str());
1743     }
1744
1745     void print() const
1746     {
1747         printf("%s", ToString().c_str());
1748     }
1749 };
1750
1751 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1752 class CAlert : public CUnsignedAlert
1753 {
1754 public:
1755     std::vector<unsigned char> vchMsg;
1756     std::vector<unsigned char> vchSig;
1757
1758     CAlert()
1759     {
1760         SetNull();
1761     }
1762
1763     IMPLEMENT_SERIALIZE
1764     (
1765         READWRITE(vchMsg);
1766         READWRITE(vchSig);
1767     )
1768
1769     void SetNull()
1770     {
1771         CUnsignedAlert::SetNull();
1772         vchMsg.clear();
1773         vchSig.clear();
1774     }
1775
1776     bool IsNull() const
1777     {
1778         return (nExpiration == 0);
1779     }
1780
1781     uint256 GetHash() const
1782     {
1783         return SerializeHash(*this);
1784     }
1785
1786     bool IsInEffect() const
1787     {
1788         return (GetAdjustedTime() < nExpiration);
1789     }
1790
1791     bool Cancels(const CAlert& alert) const
1792     {
1793         if (!IsInEffect())
1794             return false; // this was a no-op before 31403
1795         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1796     }
1797
1798     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1799     {
1800         // TODO: rework for client-version-embedded-in-strSubVer ?
1801         return (IsInEffect() &&
1802                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1803                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1804     }
1805
1806     bool AppliesToMe() const
1807     {
1808         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1809     }
1810
1811     bool RelayTo(CNode* pnode) const
1812     {
1813         if (!IsInEffect())
1814             return false;
1815         // returns true if wasn't already contained in the set
1816         if (pnode->setKnown.insert(GetHash()).second)
1817         {
1818             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1819                 AppliesToMe() ||
1820                 GetAdjustedTime() < nRelayUntil)
1821             {
1822                 pnode->PushMessage("alert", *this);
1823                 return true;
1824             }
1825         }
1826         return false;
1827     }
1828
1829     bool CheckSignature()
1830     {
1831         CKey key;
1832         if (!key.SetPubKey(ParseHex("043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195")))
1833             return error("CAlert::CheckSignature() : SetPubKey failed");
1834         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1835             return error("CAlert::CheckSignature() : verify signature failed");
1836
1837         // Now unserialize the data
1838         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1839         sMsg >> *(CUnsignedAlert*)this;
1840         return true;
1841     }
1842
1843     bool ProcessAlert();
1844 };
1845
1846 class CTxMemPool
1847 {
1848 public:
1849     mutable CCriticalSection cs;
1850     std::map<uint256, CTransaction> mapTx;
1851     std::map<COutPoint, CInPoint> mapNextTx;
1852
1853     bool accept(CTxDB& txdb, CTransaction &tx,
1854                 bool fCheckInputs, bool* pfMissingInputs);
1855     bool addUnchecked(CTransaction &tx);
1856     bool remove(CTransaction &tx);
1857
1858     unsigned long size()
1859     {
1860         LOCK(cs);
1861         return mapTx.size();
1862     }
1863
1864     bool exists(uint256 hash)
1865     {
1866         return (mapTx.count(hash) != 0);
1867     }
1868
1869     CTransaction& lookup(uint256 hash)
1870     {
1871         return mapTx[hash];
1872     }
1873 };
1874
1875 extern CTxMemPool mempool;
1876
1877 #endif