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