Revert "Update gitian descriptors to point at stable git repo"
[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 COPYING 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
598         try {
599             filein >> *this;
600         }
601         catch (std::exception &e) {
602             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
603         }
604
605         // Return file pointer
606         if (pfileRet)
607         {
608             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
609                 return error("CTransaction::ReadFromDisk() : second fseek failed");
610             *pfileRet = filein.release();
611         }
612         return true;
613     }
614
615     friend bool operator==(const CTransaction& a, const CTransaction& b)
616     {
617         return (a.nVersion  == b.nVersion &&
618                 a.vin       == b.vin &&
619                 a.vout      == b.vout &&
620                 a.nLockTime == b.nLockTime);
621     }
622
623     friend bool operator!=(const CTransaction& a, const CTransaction& b)
624     {
625         return !(a == b);
626     }
627
628
629     std::string ToString() const
630     {
631         std::string str;
632         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
633             GetHash().ToString().substr(0,10).c_str(),
634             nVersion,
635             vin.size(),
636             vout.size(),
637             nLockTime);
638         for (unsigned int i = 0; i < vin.size(); i++)
639             str += "    " + vin[i].ToString() + "\n";
640         for (unsigned int i = 0; i < vout.size(); i++)
641             str += "    " + vout[i].ToString() + "\n";
642         return str;
643     }
644
645     void print() const
646     {
647         printf("%s", ToString().c_str());
648     }
649
650
651     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
652     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
653     bool ReadFromDisk(COutPoint prevout);
654     bool DisconnectInputs(CTxDB& txdb);
655
656     /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
657
658      @param[in] txdb    Transaction database
659      @param[in] mapTestPool     List of pending changes to the transaction index database
660      @param[in] fBlock  True if being called to add a new best-block to the chain
661      @param[in] fMiner  True if being called by CreateNewBlock
662      @param[out] inputsRet      Pointers to this transaction's inputs
663      @param[out] fInvalid       returns true if transaction is invalid
664      @return    Returns true if all inputs are in txdb or mapTestPool
665      */
666     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
667                      bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
668
669     /** Sanity check previous transactions, then, if all checks succeed,
670         mark them as spent by this transaction.
671
672         @param[in] inputs       Previous transactions (from FetchInputs)
673         @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
674         @param[in] posThisTx    Position of this transaction on disk
675         @param[in] pindexBlock
676         @param[in] fBlock       true if called from ConnectBlock
677         @param[in] fMiner       true if called from CreateNewBlock
678         @param[in] fStrictPayToScriptHash       true if fully validating p2sh transactions
679         @return Returns true if all checks succeed
680      */
681     bool ConnectInputs(MapPrevTx inputs,
682                        std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
683                        const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
684     bool ClientConnectInputs();
685     bool CheckTransaction() const;
686     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
687
688 protected:
689     const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
690 };
691
692
693
694
695
696 /** A transaction with a merkle branch linking it to the block chain. */
697 class CMerkleTx : public CTransaction
698 {
699 public:
700     uint256 hashBlock;
701     std::vector<uint256> vMerkleBranch;
702     int nIndex;
703
704     // memory only
705     mutable bool fMerkleVerified;
706
707
708     CMerkleTx()
709     {
710         Init();
711     }
712
713     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
714     {
715         Init();
716     }
717
718     void Init()
719     {
720         hashBlock = 0;
721         nIndex = -1;
722         fMerkleVerified = false;
723     }
724
725
726     IMPLEMENT_SERIALIZE
727     (
728         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
729         nVersion = this->nVersion;
730         READWRITE(hashBlock);
731         READWRITE(vMerkleBranch);
732         READWRITE(nIndex);
733     )
734
735
736     int SetMerkleBranch(const CBlock* pblock=NULL);
737     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
738     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
739     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
740     int GetBlocksToMaturity() const;
741     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
742     bool AcceptToMemoryPool();
743 };
744
745
746
747
748 /**  A txdb record that contains the disk location of a transaction and the
749  * locations of transactions that spend its outputs.  vSpent is really only
750  * used as a flag, but having the location is very helpful for debugging.
751  */
752 class CTxIndex
753 {
754 public:
755     CDiskTxPos pos;
756     std::vector<CDiskTxPos> vSpent;
757
758     CTxIndex()
759     {
760         SetNull();
761     }
762
763     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
764     {
765         pos = posIn;
766         vSpent.resize(nOutputs);
767     }
768
769     IMPLEMENT_SERIALIZE
770     (
771         if (!(nType & SER_GETHASH))
772             READWRITE(nVersion);
773         READWRITE(pos);
774         READWRITE(vSpent);
775     )
776
777     void SetNull()
778     {
779         pos.SetNull();
780         vSpent.clear();
781     }
782
783     bool IsNull()
784     {
785         return pos.IsNull();
786     }
787
788     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
789     {
790         return (a.pos    == b.pos &&
791                 a.vSpent == b.vSpent);
792     }
793
794     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
795     {
796         return !(a == b);
797     }
798     int GetDepthInMainChain() const;
799  
800 };
801
802
803
804
805
806 /** Nodes collect new transactions into a block, hash them into a hash tree,
807  * and scan through nonce values to make the block's hash satisfy proof-of-work
808  * requirements.  When they solve the proof-of-work, they broadcast the block
809  * to everyone and the block is added to the block chain.  The first transaction
810  * in the block is a special one that creates a new coin owned by the creator
811  * of the block.
812  *
813  * Blocks are appended to blk0001.dat files on disk.  Their location on disk
814  * is indexed by CBlockIndex objects in memory.
815  */
816 class CBlock
817 {
818 public:
819     // header
820     int nVersion;
821     uint256 hashPrevBlock;
822     uint256 hashMerkleRoot;
823     unsigned int nTime;
824     unsigned int nBits;
825     unsigned int nNonce;
826
827     // network and disk
828     std::vector<CTransaction> vtx;
829
830     // memory only
831     mutable std::vector<uint256> vMerkleTree;
832
833     // Denial-of-service detection:
834     mutable int nDoS;
835     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
836
837     CBlock()
838     {
839         SetNull();
840     }
841
842     IMPLEMENT_SERIALIZE
843     (
844         READWRITE(this->nVersion);
845         nVersion = this->nVersion;
846         READWRITE(hashPrevBlock);
847         READWRITE(hashMerkleRoot);
848         READWRITE(nTime);
849         READWRITE(nBits);
850         READWRITE(nNonce);
851
852         // ConnectBlock depends on vtx being last so it can calculate offset
853         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
854             READWRITE(vtx);
855         else if (fRead)
856             const_cast<CBlock*>(this)->vtx.clear();
857     )
858
859     void SetNull()
860     {
861         nVersion = 1;
862         hashPrevBlock = 0;
863         hashMerkleRoot = 0;
864         nTime = 0;
865         nBits = 0;
866         nNonce = 0;
867         vtx.clear();
868         vMerkleTree.clear();
869         nDoS = 0;
870     }
871
872     bool IsNull() const
873     {
874         return (nBits == 0);
875     }
876
877     uint256 GetHash() const
878     {
879         return Hash(BEGIN(nVersion), END(nNonce));
880     }
881
882     int64 GetBlockTime() const
883     {
884         return (int64)nTime;
885     }
886
887     void UpdateTime(const CBlockIndex* pindexPrev);
888
889
890     uint256 BuildMerkleTree() const
891     {
892         vMerkleTree.clear();
893         BOOST_FOREACH(const CTransaction& tx, vtx)
894             vMerkleTree.push_back(tx.GetHash());
895         int j = 0;
896         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
897         {
898             for (int i = 0; i < nSize; i += 2)
899             {
900                 int i2 = std::min(i+1, nSize-1);
901                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
902                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
903             }
904             j += nSize;
905         }
906         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
907     }
908
909     std::vector<uint256> GetMerkleBranch(int nIndex) const
910     {
911         if (vMerkleTree.empty())
912             BuildMerkleTree();
913         std::vector<uint256> vMerkleBranch;
914         int j = 0;
915         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
916         {
917             int i = std::min(nIndex^1, nSize-1);
918             vMerkleBranch.push_back(vMerkleTree[j+i]);
919             nIndex >>= 1;
920             j += nSize;
921         }
922         return vMerkleBranch;
923     }
924
925     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
926     {
927         if (nIndex == -1)
928             return 0;
929         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
930         {
931             if (nIndex & 1)
932                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
933             else
934                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
935             nIndex >>= 1;
936         }
937         return hash;
938     }
939
940
941     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
942     {
943         // Open history file to append
944         CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
945         if (!fileout)
946             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
947
948         // Write index header
949         unsigned int nSize = fileout.GetSerializeSize(*this);
950         fileout << FLATDATA(pchMessageStart) << nSize;
951
952         // Write block
953         long fileOutPos = ftell(fileout);
954         if (fileOutPos < 0)
955             return error("CBlock::WriteToDisk() : ftell failed");
956         nBlockPosRet = fileOutPos;
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 = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
979         if (!filein)
980             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
981         if (!fReadTransactions)
982             filein.nType |= SER_BLOCKHEADERONLY;
983
984         // Read block
985         try {
986             filein >> *this;
987         }
988         catch (std::exception &e) {
989             return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
990         }
991
992         // Check the header
993         if (!CheckProofOfWork(GetHash(), nBits))
994             return error("CBlock::ReadFromDisk() : errors in block header");
995
996         return true;
997     }
998
999
1000
1001     void print() const
1002     {
1003         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1004             GetHash().ToString().substr(0,20).c_str(),
1005             nVersion,
1006             hashPrevBlock.ToString().substr(0,20).c_str(),
1007             hashMerkleRoot.ToString().substr(0,10).c_str(),
1008             nTime, nBits, nNonce,
1009             vtx.size());
1010         for (unsigned int i = 0; i < vtx.size(); i++)
1011         {
1012             printf("  ");
1013             vtx[i].print();
1014         }
1015         printf("  vMerkleTree: ");
1016         for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1017             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1018         printf("\n");
1019     }
1020
1021
1022     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1023     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1024     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1025     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1026     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1027     bool CheckBlock() const;
1028     bool AcceptBlock();
1029
1030 private:
1031     bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
1032 };
1033
1034
1035
1036
1037
1038
1039 /** The block chain is a tree shaped structure starting with the
1040  * genesis block at the root, with each block potentially having multiple
1041  * candidates to be the next block.  pprev and pnext link a path through the
1042  * main/longest chain.  A blockindex may have multiple pprev pointing back
1043  * to it, but pnext will only point forward to the longest branch, or will
1044  * be null if the block is not part of the longest chain.
1045  */
1046 class CBlockIndex
1047 {
1048 public:
1049     const uint256* phashBlock;
1050     CBlockIndex* pprev;
1051     CBlockIndex* pnext;
1052     unsigned int nFile;
1053     unsigned int nBlockPos;
1054     int nHeight;
1055     CBigNum bnChainWork;
1056
1057     // block header
1058     int nVersion;
1059     uint256 hashMerkleRoot;
1060     unsigned int nTime;
1061     unsigned int nBits;
1062     unsigned int nNonce;
1063
1064
1065     CBlockIndex()
1066     {
1067         phashBlock = NULL;
1068         pprev = NULL;
1069         pnext = NULL;
1070         nFile = 0;
1071         nBlockPos = 0;
1072         nHeight = 0;
1073         bnChainWork = 0;
1074
1075         nVersion       = 0;
1076         hashMerkleRoot = 0;
1077         nTime          = 0;
1078         nBits          = 0;
1079         nNonce         = 0;
1080     }
1081
1082     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1083     {
1084         phashBlock = NULL;
1085         pprev = NULL;
1086         pnext = NULL;
1087         nFile = nFileIn;
1088         nBlockPos = nBlockPosIn;
1089         nHeight = 0;
1090         bnChainWork = 0;
1091
1092         nVersion       = block.nVersion;
1093         hashMerkleRoot = block.hashMerkleRoot;
1094         nTime          = block.nTime;
1095         nBits          = block.nBits;
1096         nNonce         = block.nNonce;
1097     }
1098
1099     CBlock GetBlockHeader() const
1100     {
1101         CBlock block;
1102         block.nVersion       = nVersion;
1103         if (pprev)
1104             block.hashPrevBlock = pprev->GetBlockHash();
1105         block.hashMerkleRoot = hashMerkleRoot;
1106         block.nTime          = nTime;
1107         block.nBits          = nBits;
1108         block.nNonce         = nNonce;
1109         return block;
1110     }
1111
1112     uint256 GetBlockHash() const
1113     {
1114         return *phashBlock;
1115     }
1116
1117     int64 GetBlockTime() const
1118     {
1119         return (int64)nTime;
1120     }
1121
1122     CBigNum GetBlockWork() const
1123     {
1124         CBigNum bnTarget;
1125         bnTarget.SetCompact(nBits);
1126         if (bnTarget <= 0)
1127             return 0;
1128         return (CBigNum(1)<<256) / (bnTarget+1);
1129     }
1130
1131     bool IsInMainChain() const
1132     {
1133         return (pnext || this == pindexBest);
1134     }
1135
1136     bool CheckIndex() const
1137     {
1138         return CheckProofOfWork(GetBlockHash(), nBits);
1139     }
1140
1141     bool EraseBlockFromDisk()
1142     {
1143         // Open history file
1144         CAutoFile fileout = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb+"), SER_DISK, CLIENT_VERSION);
1145         if (!fileout)
1146             return false;
1147
1148         // Overwrite with empty null block
1149         CBlock block;
1150         block.SetNull();
1151         fileout << block;
1152
1153         return true;
1154     }
1155
1156     enum { nMedianTimeSpan=11 };
1157
1158     int64 GetMedianTimePast() const
1159     {
1160         int64 pmedian[nMedianTimeSpan];
1161         int64* pbegin = &pmedian[nMedianTimeSpan];
1162         int64* pend = &pmedian[nMedianTimeSpan];
1163
1164         const CBlockIndex* pindex = this;
1165         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1166             *(--pbegin) = pindex->GetBlockTime();
1167
1168         std::sort(pbegin, pend);
1169         return pbegin[(pend - pbegin)/2];
1170     }
1171
1172     int64 GetMedianTime() const
1173     {
1174         const CBlockIndex* pindex = this;
1175         for (int i = 0; i < nMedianTimeSpan/2; i++)
1176         {
1177             if (!pindex->pnext)
1178                 return GetBlockTime();
1179             pindex = pindex->pnext;
1180         }
1181         return pindex->GetMedianTimePast();
1182     }
1183
1184
1185
1186     std::string ToString() const
1187     {
1188         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1189             pprev, pnext, nFile, nBlockPos, nHeight,
1190             hashMerkleRoot.ToString().substr(0,10).c_str(),
1191             GetBlockHash().ToString().substr(0,20).c_str());
1192     }
1193
1194     void print() const
1195     {
1196         printf("%s\n", ToString().c_str());
1197     }
1198 };
1199
1200
1201
1202 /** Used to marshal pointers into hashes for db storage. */
1203 class CDiskBlockIndex : public CBlockIndex
1204 {
1205 public:
1206     uint256 hashPrev;
1207     uint256 hashNext;
1208
1209     CDiskBlockIndex()
1210     {
1211         hashPrev = 0;
1212         hashNext = 0;
1213     }
1214
1215     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1216     {
1217         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1218         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1219     }
1220
1221     IMPLEMENT_SERIALIZE
1222     (
1223         if (!(nType & SER_GETHASH))
1224             READWRITE(nVersion);
1225
1226         READWRITE(hashNext);
1227         READWRITE(nFile);
1228         READWRITE(nBlockPos);
1229         READWRITE(nHeight);
1230
1231         // block header
1232         READWRITE(this->nVersion);
1233         READWRITE(hashPrev);
1234         READWRITE(hashMerkleRoot);
1235         READWRITE(nTime);
1236         READWRITE(nBits);
1237         READWRITE(nNonce);
1238     )
1239
1240     uint256 GetBlockHash() const
1241     {
1242         CBlock block;
1243         block.nVersion        = nVersion;
1244         block.hashPrevBlock   = hashPrev;
1245         block.hashMerkleRoot  = hashMerkleRoot;
1246         block.nTime           = nTime;
1247         block.nBits           = nBits;
1248         block.nNonce          = nNonce;
1249         return block.GetHash();
1250     }
1251
1252
1253     std::string ToString() const
1254     {
1255         std::string str = "CDiskBlockIndex(";
1256         str += CBlockIndex::ToString();
1257         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1258             GetBlockHash().ToString().c_str(),
1259             hashPrev.ToString().substr(0,20).c_str(),
1260             hashNext.ToString().substr(0,20).c_str());
1261         return str;
1262     }
1263
1264     void print() const
1265     {
1266         printf("%s\n", ToString().c_str());
1267     }
1268 };
1269
1270
1271
1272
1273
1274
1275
1276
1277 /** Describes a place in the block chain to another node such that if the
1278  * other node doesn't have the same branch, it can find a recent common trunk.
1279  * The further back it is, the further before the fork it may be.
1280  */
1281 class CBlockLocator
1282 {
1283 protected:
1284     std::vector<uint256> vHave;
1285 public:
1286
1287     CBlockLocator()
1288     {
1289     }
1290
1291     explicit CBlockLocator(const CBlockIndex* pindex)
1292     {
1293         Set(pindex);
1294     }
1295
1296     explicit CBlockLocator(uint256 hashBlock)
1297     {
1298         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1299         if (mi != mapBlockIndex.end())
1300             Set((*mi).second);
1301     }
1302
1303     CBlockLocator(const std::vector<uint256>& vHaveIn)
1304     {
1305         vHave = vHaveIn;
1306     }
1307
1308     IMPLEMENT_SERIALIZE
1309     (
1310         if (!(nType & SER_GETHASH))
1311             READWRITE(nVersion);
1312         READWRITE(vHave);
1313     )
1314
1315     void SetNull()
1316     {
1317         vHave.clear();
1318     }
1319
1320     bool IsNull()
1321     {
1322         return vHave.empty();
1323     }
1324
1325     void Set(const CBlockIndex* pindex)
1326     {
1327         vHave.clear();
1328         int nStep = 1;
1329         while (pindex)
1330         {
1331             vHave.push_back(pindex->GetBlockHash());
1332
1333             // Exponentially larger steps back
1334             for (int i = 0; pindex && i < nStep; i++)
1335                 pindex = pindex->pprev;
1336             if (vHave.size() > 10)
1337                 nStep *= 2;
1338         }
1339         vHave.push_back(hashGenesisBlock);
1340     }
1341
1342     int GetDistanceBack()
1343     {
1344         // Retrace how far back it was in the sender's branch
1345         int nDistance = 0;
1346         int nStep = 1;
1347         BOOST_FOREACH(const uint256& hash, vHave)
1348         {
1349             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1350             if (mi != mapBlockIndex.end())
1351             {
1352                 CBlockIndex* pindex = (*mi).second;
1353                 if (pindex->IsInMainChain())
1354                     return nDistance;
1355             }
1356             nDistance += nStep;
1357             if (nDistance > 10)
1358                 nStep *= 2;
1359         }
1360         return nDistance;
1361     }
1362
1363     CBlockIndex* GetBlockIndex()
1364     {
1365         // Find the first block the caller has in the main chain
1366         BOOST_FOREACH(const uint256& hash, vHave)
1367         {
1368             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1369             if (mi != mapBlockIndex.end())
1370             {
1371                 CBlockIndex* pindex = (*mi).second;
1372                 if (pindex->IsInMainChain())
1373                     return pindex;
1374             }
1375         }
1376         return pindexGenesisBlock;
1377     }
1378
1379     uint256 GetBlockHash()
1380     {
1381         // Find the first block the caller has in the main chain
1382         BOOST_FOREACH(const uint256& hash, vHave)
1383         {
1384             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1385             if (mi != mapBlockIndex.end())
1386             {
1387                 CBlockIndex* pindex = (*mi).second;
1388                 if (pindex->IsInMainChain())
1389                     return hash;
1390             }
1391         }
1392         return hashGenesisBlock;
1393     }
1394
1395     int GetHeight()
1396     {
1397         CBlockIndex* pindex = GetBlockIndex();
1398         if (!pindex)
1399             return 0;
1400         return pindex->nHeight;
1401     }
1402 };
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412 /** Alerts are for notifying old versions if they become too obsolete and
1413  * need to upgrade.  The message is displayed in the status bar.
1414  * Alert messages are broadcast as a vector of signed data.  Unserializing may
1415  * not read the entire buffer if the alert is for a newer version, but older
1416  * versions can still relay the original data.
1417  */
1418 class CUnsignedAlert
1419 {
1420 public:
1421     int nVersion;
1422     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1423     int64 nExpiration;
1424     int nID;
1425     int nCancel;
1426     std::set<int> setCancel;
1427     int nMinVer;            // lowest version inclusive
1428     int nMaxVer;            // highest version inclusive
1429     std::set<std::string> setSubVer;  // empty matches all
1430     int nPriority;
1431
1432     // Actions
1433     std::string strComment;
1434     std::string strStatusBar;
1435     std::string strReserved;
1436
1437     IMPLEMENT_SERIALIZE
1438     (
1439         READWRITE(this->nVersion);
1440         nVersion = this->nVersion;
1441         READWRITE(nRelayUntil);
1442         READWRITE(nExpiration);
1443         READWRITE(nID);
1444         READWRITE(nCancel);
1445         READWRITE(setCancel);
1446         READWRITE(nMinVer);
1447         READWRITE(nMaxVer);
1448         READWRITE(setSubVer);
1449         READWRITE(nPriority);
1450
1451         READWRITE(strComment);
1452         READWRITE(strStatusBar);
1453         READWRITE(strReserved);
1454     )
1455
1456     void SetNull()
1457     {
1458         nVersion = 1;
1459         nRelayUntil = 0;
1460         nExpiration = 0;
1461         nID = 0;
1462         nCancel = 0;
1463         setCancel.clear();
1464         nMinVer = 0;
1465         nMaxVer = 0;
1466         setSubVer.clear();
1467         nPriority = 0;
1468
1469         strComment.clear();
1470         strStatusBar.clear();
1471         strReserved.clear();
1472     }
1473
1474     std::string ToString() const
1475     {
1476         std::string strSetCancel;
1477         BOOST_FOREACH(int n, setCancel)
1478             strSetCancel += strprintf("%d ", n);
1479         std::string strSetSubVer;
1480         BOOST_FOREACH(std::string str, setSubVer)
1481             strSetSubVer += "\"" + str + "\" ";
1482         return strprintf(
1483                 "CAlert(\n"
1484                 "    nVersion     = %d\n"
1485                 "    nRelayUntil  = %"PRI64d"\n"
1486                 "    nExpiration  = %"PRI64d"\n"
1487                 "    nID          = %d\n"
1488                 "    nCancel      = %d\n"
1489                 "    setCancel    = %s\n"
1490                 "    nMinVer      = %d\n"
1491                 "    nMaxVer      = %d\n"
1492                 "    setSubVer    = %s\n"
1493                 "    nPriority    = %d\n"
1494                 "    strComment   = \"%s\"\n"
1495                 "    strStatusBar = \"%s\"\n"
1496                 ")\n",
1497             nVersion,
1498             nRelayUntil,
1499             nExpiration,
1500             nID,
1501             nCancel,
1502             strSetCancel.c_str(),
1503             nMinVer,
1504             nMaxVer,
1505             strSetSubVer.c_str(),
1506             nPriority,
1507             strComment.c_str(),
1508             strStatusBar.c_str());
1509     }
1510
1511     void print() const
1512     {
1513         printf("%s", ToString().c_str());
1514     }
1515 };
1516
1517 /** An alert is a combination of a serialized CUnsignedAlert and a signature. */
1518 class CAlert : public CUnsignedAlert
1519 {
1520 public:
1521     std::vector<unsigned char> vchMsg;
1522     std::vector<unsigned char> vchSig;
1523
1524     CAlert()
1525     {
1526         SetNull();
1527     }
1528
1529     IMPLEMENT_SERIALIZE
1530     (
1531         READWRITE(vchMsg);
1532         READWRITE(vchSig);
1533     )
1534
1535     void SetNull()
1536     {
1537         CUnsignedAlert::SetNull();
1538         vchMsg.clear();
1539         vchSig.clear();
1540     }
1541
1542     bool IsNull() const
1543     {
1544         return (nExpiration == 0);
1545     }
1546
1547     uint256 GetHash() const
1548     {
1549         return SerializeHash(*this);
1550     }
1551
1552     bool IsInEffect() const
1553     {
1554         return (GetAdjustedTime() < nExpiration);
1555     }
1556
1557     bool Cancels(const CAlert& alert) const
1558     {
1559         if (!IsInEffect())
1560             return false; // this was a no-op before 31403
1561         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1562     }
1563
1564     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1565     {
1566         // TODO: rework for client-version-embedded-in-strSubVer ?
1567         return (IsInEffect() &&
1568                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1569                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1570     }
1571
1572     bool AppliesToMe() const
1573     {
1574         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1575     }
1576
1577     bool RelayTo(CNode* pnode) const
1578     {
1579         if (!IsInEffect())
1580             return false;
1581         // returns true if wasn't already contained in the set
1582         if (pnode->setKnown.insert(GetHash()).second)
1583         {
1584             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1585                 AppliesToMe() ||
1586                 GetAdjustedTime() < nRelayUntil)
1587             {
1588                 pnode->PushMessage("alert", *this);
1589                 return true;
1590             }
1591         }
1592         return false;
1593     }
1594
1595     bool CheckSignature()
1596     {
1597         CKey key;
1598         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1599             return error("CAlert::CheckSignature() : SetPubKey failed");
1600         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1601             return error("CAlert::CheckSignature() : verify signature failed");
1602
1603         // Now unserialize the data
1604         CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
1605         sMsg >> *(CUnsignedAlert*)this;
1606         return true;
1607     }
1608
1609     bool ProcessAlert();
1610 };
1611
1612 class CTxMemPool
1613 {
1614 public:
1615     mutable CCriticalSection cs;
1616     std::map<uint256, CTransaction> mapTx;
1617     std::map<COutPoint, CInPoint> mapNextTx;
1618
1619     bool accept(CTxDB& txdb, CTransaction &tx,
1620                 bool fCheckInputs, bool* pfMissingInputs);
1621     bool addUnchecked(CTransaction &tx);
1622     bool remove(CTransaction &tx);
1623
1624     unsigned long size()
1625     {
1626         LOCK(cs);
1627         return mapTx.size();
1628     }
1629
1630     bool exists(uint256 hash)
1631     {
1632         return (mapTx.count(hash) != 0);
1633     }
1634
1635     CTransaction& lookup(uint256 hash)
1636     {
1637         return mapTx[hash];
1638     }
1639 };
1640
1641 extern CTxMemPool mempool;
1642
1643 #endif