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