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