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