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