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