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