Update README now that main svn has -testnet built in
[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
26
27
28
29
30
31 extern CCriticalSection cs_main;
32 extern map<uint256, CBlockIndex*> mapBlockIndex;
33 extern uint256 hashGenesisBlock;
34 extern CBigNum bnProofOfWorkLimit;
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, CReserveKey& reservekey, int64& nFeeRequiredRet);
80 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
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,10).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,30).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     int GetSigOpCount() const
473     {
474         int n = 0;
475         foreach(const CTxIn& txin, vin)
476             n += txin.scriptSig.GetSigOpCount();
477         foreach(const CTxOut& txout, vout)
478             n += txout.scriptPubKey.GetSigOpCount();
479         return n;
480     }
481
482     bool IsMine() const
483     {
484         foreach(const CTxOut& txout, vout)
485             if (txout.IsMine())
486                 return true;
487         return false;
488     }
489
490     int64 GetDebit() const
491     {
492         int64 nDebit = 0;
493         foreach(const CTxIn& txin, vin)
494         {
495             nDebit += txin.GetDebit();
496             if (!MoneyRange(nDebit))
497                 throw runtime_error("CTransaction::GetDebit() : value out of range");
498         }
499         return nDebit;
500     }
501
502     int64 GetCredit() const
503     {
504         int64 nCredit = 0;
505         foreach(const CTxOut& txout, vout)
506         {
507             nCredit += txout.GetCredit();
508             if (!MoneyRange(nCredit))
509                 throw runtime_error("CTransaction::GetCredit() : value out of range");
510         }
511         return nCredit;
512     }
513
514     int64 GetValueOut() const
515     {
516         int64 nValueOut = 0;
517         foreach(const CTxOut& txout, vout)
518         {
519             nValueOut += txout.nValue;
520             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
521                 throw runtime_error("CTransaction::GetValueOut() : value out of range");
522         }
523         return nValueOut;
524     }
525
526     int64 GetMinFee(unsigned int nBlockSize=1) const
527     {
528         // Base fee is 1 cent per kilobyte
529         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
530         unsigned int nNewBlockSize = nBlockSize + nBytes;
531         int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;
532
533         // Transactions under 25K are free as long as block size is under 40K
534         // (about 11,000bc if made of 50bc inputs)
535         if (nBytes < 25000 && nNewBlockSize < 40000)
536             nMinFee = 0;
537
538         // Transactions under 3K are free as long as block size is under 50K
539         if (nBytes < 3000 && nNewBlockSize < 50000)
540             nMinFee = 0;
541
542         // To limit dust spam, require a 0.01 fee if any output is less than 0.01
543         if (nMinFee < CENT)
544             foreach(const CTxOut& txout, vout)
545                 if (txout.nValue < CENT)
546                     nMinFee = CENT;
547
548         // Raise the price as the block approaches full
549         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
550         {
551             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
552                 return MAX_MONEY;
553             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
554         }
555
556         if (!MoneyRange(nMinFee))
557             nMinFee = MAX_MONEY;
558         return nMinFee;
559     }
560
561
562     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
563     {
564         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
565         if (!filein)
566             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
567
568         // Read transaction
569         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
570             return error("CTransaction::ReadFromDisk() : fseek failed");
571         filein >> *this;
572
573         // Return file pointer
574         if (pfileRet)
575         {
576             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
577                 return error("CTransaction::ReadFromDisk() : second fseek failed");
578             *pfileRet = filein.release();
579         }
580         return true;
581     }
582
583
584     friend bool operator==(const CTransaction& a, const CTransaction& b)
585     {
586         return (a.nVersion  == b.nVersion &&
587                 a.vin       == b.vin &&
588                 a.vout      == b.vout &&
589                 a.nLockTime == b.nLockTime);
590     }
591
592     friend bool operator!=(const CTransaction& a, const CTransaction& b)
593     {
594         return !(a == b);
595     }
596
597
598     string ToString() const
599     {
600         string str;
601         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
602             GetHash().ToString().substr(0,10).c_str(),
603             nVersion,
604             vin.size(),
605             vout.size(),
606             nLockTime);
607         for (int i = 0; i < vin.size(); i++)
608             str += "    " + vin[i].ToString() + "\n";
609         for (int i = 0; i < vout.size(); i++)
610             str += "    " + vout[i].ToString() + "\n";
611         return str;
612     }
613
614     void print() const
615     {
616         printf("%s", ToString().c_str());
617     }
618
619
620     bool DisconnectInputs(CTxDB& txdb);
621     bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
622                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
623     bool ClientConnectInputs();
624     bool CheckTransaction() const;
625     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
626     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
627     {
628         CTxDB txdb("r");
629         return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
630     }
631 protected:
632     bool AddToMemoryPoolUnchecked();
633 public:
634     bool RemoveFromMemoryPool();
635 };
636
637
638
639
640
641 //
642 // A transaction with a merkle branch linking it to the block chain
643 //
644 class CMerkleTx : public CTransaction
645 {
646 public:
647     uint256 hashBlock;
648     vector<uint256> vMerkleBranch;
649     int nIndex;
650
651     // memory only
652     mutable char fMerkleVerified;
653
654
655     CMerkleTx()
656     {
657         Init();
658     }
659
660     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
661     {
662         Init();
663     }
664
665     void Init()
666     {
667         hashBlock = 0;
668         nIndex = -1;
669         fMerkleVerified = false;
670     }
671
672     IMPLEMENT_SERIALIZE
673     (
674         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
675         nVersion = this->nVersion;
676         READWRITE(hashBlock);
677         READWRITE(vMerkleBranch);
678         READWRITE(nIndex);
679     )
680
681
682     int SetMerkleBranch(const CBlock* pblock=NULL);
683     int GetDepthInMainChain(int& nHeightRet) const;
684     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
685     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
686     int GetBlocksToMaturity() const;
687     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
688     bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
689 };
690
691
692
693
694 //
695 // A transaction with a bunch of additional info that only the owner cares
696 // about.  It includes any unrecorded transactions needed to link it back
697 // to the block chain.
698 //
699 class CWalletTx : public CMerkleTx
700 {
701 public:
702     vector<CMerkleTx> vtxPrev;
703     map<string, string> mapValue;
704     vector<pair<string, string> > vOrderForm;
705     unsigned int fTimeReceivedIsTxTime;
706     unsigned int nTimeReceived;  // time received by this node
707     char fFromMe;
708     char fSpent;
709     //// probably need to sign the order info so know it came from payer
710
711     // memory only
712     mutable char fDebitCached;
713     mutable char fCreditCached;
714     mutable int64 nDebitCached;
715     mutable int64 nCreditCached;
716
717     // memory only UI hints
718     mutable unsigned int nTimeDisplayed;
719     mutable int nLinesDisplayed;
720     mutable char fConfirmedDisplayed;
721
722
723     CWalletTx()
724     {
725         Init();
726     }
727
728     CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
729     {
730         Init();
731     }
732
733     CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
734     {
735         Init();
736     }
737
738     void Init()
739     {
740         fTimeReceivedIsTxTime = false;
741         nTimeReceived = 0;
742         fFromMe = false;
743         fSpent = false;
744         fDebitCached = false;
745         fCreditCached = false;
746         nDebitCached = 0;
747         nCreditCached = 0;
748         nTimeDisplayed = 0;
749         nLinesDisplayed = 0;
750     }
751
752     IMPLEMENT_SERIALIZE
753     (
754         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);
755         nVersion = this->nVersion;
756         READWRITE(vtxPrev);
757         READWRITE(mapValue);
758         READWRITE(vOrderForm);
759         READWRITE(fTimeReceivedIsTxTime);
760         READWRITE(nTimeReceived);
761         READWRITE(fFromMe);
762         READWRITE(fSpent);
763     )
764
765     int64 GetDebit() const
766     {
767         if (vin.empty())
768             return 0;
769         if (fDebitCached)
770             return nDebitCached;
771         nDebitCached = CTransaction::GetDebit();
772         fDebitCached = true;
773         return nDebitCached;
774     }
775
776     int64 GetCredit(bool fUseCache=false) const
777     {
778         // Must wait until coinbase is safely deep enough in the chain before valuing it
779         if (IsCoinBase() && GetBlocksToMaturity() > 0)
780             return 0;
781
782         // GetBalance can assume transactions in mapWallet won't change
783         if (fUseCache && fCreditCached)
784             return nCreditCached;
785         nCreditCached = CTransaction::GetCredit();
786         fCreditCached = true;
787         return nCreditCached;
788     }
789
790     bool IsConfirmed() const
791     {
792         map<uint256, const CMerkleTx*> mapPrev;
793         vector<const CMerkleTx*> vWorkQueue;
794         vWorkQueue.reserve(vtxPrev.size()+1);
795         vWorkQueue.push_back(this);
796         for (int i = 0; i < vWorkQueue.size(); i++)
797         {
798             const CMerkleTx* ptx = vWorkQueue[i];
799
800             if (!ptx->IsFinal())
801                 return false;
802             if (ptx->GetDepthInMainChain() >= 1)
803                 return true;
804             if (ptx->GetDebit() <= 0)
805                 return false;
806
807             if (mapPrev.empty())
808                 foreach(const CMerkleTx& tx, vtxPrev)
809                     mapPrev[tx.GetHash()] = &tx;
810
811             foreach(const CTxIn& txin, ptx->vin)
812             {
813                 if (!mapPrev.count(txin.prevout.hash))
814                     return false;
815                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
816             }
817         }
818         return true;
819     }
820
821     bool WriteToDisk()
822     {
823         return CWalletDB().WriteTx(GetHash(), *this);
824     }
825
826
827     int64 GetTxTime() const;
828     int GetRequestCount() const;
829
830     void AddSupportingTransactions(CTxDB& txdb);
831
832     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
833     bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
834
835     void RelayWalletTransaction(CTxDB& txdb);
836     void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
837 };
838
839
840
841
842 //
843 // A txdb record that contains the disk location of a transaction and the
844 // locations of transactions that spend its outputs.  vSpent is really only
845 // used as a flag, but having the location is very helpful for debugging.
846 //
847 class CTxIndex
848 {
849 public:
850     CDiskTxPos pos;
851     vector<CDiskTxPos> vSpent;
852
853     CTxIndex()
854     {
855         SetNull();
856     }
857
858     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
859     {
860         pos = posIn;
861         vSpent.resize(nOutputs);
862     }
863
864     IMPLEMENT_SERIALIZE
865     (
866         if (!(nType & SER_GETHASH))
867             READWRITE(nVersion);
868         READWRITE(pos);
869         READWRITE(vSpent);
870     )
871
872     void SetNull()
873     {
874         pos.SetNull();
875         vSpent.clear();
876     }
877
878     bool IsNull()
879     {
880         return pos.IsNull();
881     }
882
883     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
884     {
885         return (a.pos    == b.pos &&
886                 a.vSpent == b.vSpent);
887     }
888
889     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
890     {
891         return !(a == b);
892     }
893 };
894
895
896
897
898
899 //
900 // Nodes collect new transactions into a block, hash them into a hash tree,
901 // and scan through nonce values to make the block's hash satisfy proof-of-work
902 // requirements.  When they solve the proof-of-work, they broadcast the block
903 // to everyone and the block is added to the block chain.  The first transaction
904 // in the block is a special one that creates a new coin owned by the creator
905 // of the block.
906 //
907 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
908 // is indexed by CBlockIndex objects in memory.
909 //
910 class CBlock
911 {
912 public:
913     // header
914     int nVersion;
915     uint256 hashPrevBlock;
916     uint256 hashMerkleRoot;
917     unsigned int nTime;
918     unsigned int nBits;
919     unsigned int nNonce;
920
921     // network and disk
922     vector<CTransaction> vtx;
923
924     // memory only
925     mutable vector<uint256> vMerkleTree;
926
927
928     CBlock()
929     {
930         SetNull();
931     }
932
933     IMPLEMENT_SERIALIZE
934     (
935         READWRITE(this->nVersion);
936         nVersion = this->nVersion;
937         READWRITE(hashPrevBlock);
938         READWRITE(hashMerkleRoot);
939         READWRITE(nTime);
940         READWRITE(nBits);
941         READWRITE(nNonce);
942
943         // ConnectBlock depends on vtx being last so it can calculate offset
944         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
945             READWRITE(vtx);
946         else if (fRead)
947             const_cast<CBlock*>(this)->vtx.clear();
948     )
949
950     void SetNull()
951     {
952         nVersion = 1;
953         hashPrevBlock = 0;
954         hashMerkleRoot = 0;
955         nTime = 0;
956         nBits = 0;
957         nNonce = 0;
958         vtx.clear();
959         vMerkleTree.clear();
960     }
961
962     bool IsNull() const
963     {
964         return (nBits == 0);
965     }
966
967     uint256 GetHash() const
968     {
969         return Hash(BEGIN(nVersion), END(nNonce));
970     }
971
972     int64 GetBlockTime() const
973     {
974         return (int64)nTime;
975     }
976
977     int GetSigOpCount() const
978     {
979         int n = 0;
980         foreach(const CTransaction& tx, vtx)
981             n += tx.GetSigOpCount();
982         return n;
983     }
984
985
986     uint256 BuildMerkleTree() const
987     {
988         vMerkleTree.clear();
989         foreach(const CTransaction& tx, vtx)
990             vMerkleTree.push_back(tx.GetHash());
991         int j = 0;
992         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
993         {
994             for (int i = 0; i < nSize; i += 2)
995             {
996                 int i2 = min(i+1, nSize-1);
997                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
998                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
999             }
1000             j += nSize;
1001         }
1002         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1003     }
1004
1005     vector<uint256> GetMerkleBranch(int nIndex) const
1006     {
1007         if (vMerkleTree.empty())
1008             BuildMerkleTree();
1009         vector<uint256> vMerkleBranch;
1010         int j = 0;
1011         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1012         {
1013             int i = min(nIndex^1, nSize-1);
1014             vMerkleBranch.push_back(vMerkleTree[j+i]);
1015             nIndex >>= 1;
1016             j += nSize;
1017         }
1018         return vMerkleBranch;
1019     }
1020
1021     static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1022     {
1023         if (nIndex == -1)
1024             return 0;
1025         foreach(const uint256& otherside, vMerkleBranch)
1026         {
1027             if (nIndex & 1)
1028                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1029             else
1030                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1031             nIndex >>= 1;
1032         }
1033         return hash;
1034     }
1035
1036
1037     bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)
1038     {
1039         // Open history file to append
1040         CAutoFile fileout = AppendBlockFile(nFileRet);
1041         if (!fileout)
1042             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1043         if (!fWriteTransactions)
1044             fileout.nType |= SER_BLOCKHEADERONLY;
1045
1046         // Write index header
1047         unsigned int nSize = fileout.GetSerializeSize(*this);
1048         fileout << FLATDATA(pchMessageStart) << nSize;
1049
1050         // Write block
1051         nBlockPosRet = ftell(fileout);
1052         if (nBlockPosRet == -1)
1053             return error("CBlock::WriteToDisk() : ftell failed");
1054         fileout << *this;
1055
1056         // Flush stdio buffers and commit to disk before returning
1057         fflush(fileout);
1058         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1059         {
1060 #ifdef __WXMSW__
1061             _commit(_fileno(fileout));
1062 #else
1063             fsync(fileno(fileout));
1064 #endif
1065         }
1066
1067         return true;
1068     }
1069
1070     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1071     {
1072         SetNull();
1073
1074         // Open history file to read
1075         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1076         if (!filein)
1077             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1078         if (!fReadTransactions)
1079             filein.nType |= SER_BLOCKHEADERONLY;
1080
1081         // Read block
1082         filein >> *this;
1083
1084         // Check the header
1085         if (!CheckProofOfWork(GetHash(), nBits))
1086             return error("CBlock::ReadFromDisk() : errors in block header");
1087
1088         return true;
1089     }
1090
1091
1092
1093     void print() const
1094     {
1095         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1096             GetHash().ToString().substr(0,20).c_str(),
1097             nVersion,
1098             hashPrevBlock.ToString().substr(0,20).c_str(),
1099             hashMerkleRoot.ToString().substr(0,10).c_str(),
1100             nTime, nBits, nNonce,
1101             vtx.size());
1102         for (int i = 0; i < vtx.size(); i++)
1103         {
1104             printf("  ");
1105             vtx[i].print();
1106         }
1107         printf("  vMerkleTree: ");
1108         for (int i = 0; i < vMerkleTree.size(); i++)
1109             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1110         printf("\n");
1111     }
1112
1113
1114     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1115     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1116     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1117     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1118     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1119     bool CheckBlock() const;
1120     bool AcceptBlock();
1121 };
1122
1123
1124
1125
1126
1127
1128 //
1129 // The block chain is a tree shaped structure starting with the
1130 // genesis block at the root, with each block potentially having multiple
1131 // candidates to be the next block.  pprev and pnext link a path through the
1132 // main/longest chain.  A blockindex may have multiple pprev pointing back
1133 // to it, but pnext will only point forward to the longest branch, or will
1134 // be null if the block is not part of the longest chain.
1135 //
1136 class CBlockIndex
1137 {
1138 public:
1139     const uint256* phashBlock;
1140     CBlockIndex* pprev;
1141     CBlockIndex* pnext;
1142     unsigned int nFile;
1143     unsigned int nBlockPos;
1144     int nHeight;
1145     CBigNum bnChainWork;
1146
1147     // block header
1148     int nVersion;
1149     uint256 hashMerkleRoot;
1150     unsigned int nTime;
1151     unsigned int nBits;
1152     unsigned int nNonce;
1153
1154
1155     CBlockIndex()
1156     {
1157         phashBlock = NULL;
1158         pprev = NULL;
1159         pnext = NULL;
1160         nFile = 0;
1161         nBlockPos = 0;
1162         nHeight = 0;
1163         bnChainWork = 0;
1164
1165         nVersion       = 0;
1166         hashMerkleRoot = 0;
1167         nTime          = 0;
1168         nBits          = 0;
1169         nNonce         = 0;
1170     }
1171
1172     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1173     {
1174         phashBlock = NULL;
1175         pprev = NULL;
1176         pnext = NULL;
1177         nFile = nFileIn;
1178         nBlockPos = nBlockPosIn;
1179         nHeight = 0;
1180         bnChainWork = 0;
1181
1182         nVersion       = block.nVersion;
1183         hashMerkleRoot = block.hashMerkleRoot;
1184         nTime          = block.nTime;
1185         nBits          = block.nBits;
1186         nNonce         = block.nNonce;
1187     }
1188
1189     uint256 GetBlockHash() const
1190     {
1191         return *phashBlock;
1192     }
1193
1194     int64 GetBlockTime() const
1195     {
1196         return (int64)nTime;
1197     }
1198
1199     CBigNum GetBlockWork() const
1200     {
1201         CBigNum bnTarget;
1202         bnTarget.SetCompact(nBits);
1203         if (bnTarget <= 0)
1204             return 0;
1205         return (CBigNum(1)<<256) / (bnTarget+1);
1206     }
1207
1208     bool IsInMainChain() const
1209     {
1210         return (pnext || this == pindexBest);
1211     }
1212
1213     bool CheckIndex() const
1214     {
1215         return CheckProofOfWork(GetBlockHash(), nBits);
1216     }
1217
1218     bool EraseBlockFromDisk()
1219     {
1220         // Open history file
1221         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1222         if (!fileout)
1223             return false;
1224
1225         // Overwrite with empty null block
1226         CBlock block;
1227         block.SetNull();
1228         fileout << block;
1229
1230         return true;
1231     }
1232
1233     enum { nMedianTimeSpan=11 };
1234
1235     int64 GetMedianTimePast() const
1236     {
1237         int64 pmedian[nMedianTimeSpan];
1238         int64* pbegin = &pmedian[nMedianTimeSpan];
1239         int64* pend = &pmedian[nMedianTimeSpan];
1240
1241         const CBlockIndex* pindex = this;
1242         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1243             *(--pbegin) = pindex->GetBlockTime();
1244
1245         sort(pbegin, pend);
1246         return pbegin[(pend - pbegin)/2];
1247     }
1248
1249     int64 GetMedianTime() const
1250     {
1251         const CBlockIndex* pindex = this;
1252         for (int i = 0; i < nMedianTimeSpan/2; i++)
1253         {
1254             if (!pindex->pnext)
1255                 return GetBlockTime();
1256             pindex = pindex->pnext;
1257         }
1258         return pindex->GetMedianTimePast();
1259     }
1260
1261
1262
1263     string ToString() const
1264     {
1265         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1266             pprev, pnext, nFile, nBlockPos, nHeight,
1267             hashMerkleRoot.ToString().substr(0,10).c_str(),
1268             GetBlockHash().ToString().substr(0,20).c_str());
1269     }
1270
1271     void print() const
1272     {
1273         printf("%s\n", ToString().c_str());
1274     }
1275 };
1276
1277
1278
1279 //
1280 // Used to marshal pointers into hashes for db storage.
1281 //
1282 class CDiskBlockIndex : public CBlockIndex
1283 {
1284 public:
1285     uint256 hashPrev;
1286     uint256 hashNext;
1287
1288     CDiskBlockIndex()
1289     {
1290         hashPrev = 0;
1291         hashNext = 0;
1292     }
1293
1294     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1295     {
1296         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1297         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1298     }
1299
1300     IMPLEMENT_SERIALIZE
1301     (
1302         if (!(nType & SER_GETHASH))
1303             READWRITE(nVersion);
1304
1305         READWRITE(hashNext);
1306         READWRITE(nFile);
1307         READWRITE(nBlockPos);
1308         READWRITE(nHeight);
1309
1310         // block header
1311         READWRITE(this->nVersion);
1312         READWRITE(hashPrev);
1313         READWRITE(hashMerkleRoot);
1314         READWRITE(nTime);
1315         READWRITE(nBits);
1316         READWRITE(nNonce);
1317     )
1318
1319     uint256 GetBlockHash() const
1320     {
1321         CBlock block;
1322         block.nVersion        = nVersion;
1323         block.hashPrevBlock   = hashPrev;
1324         block.hashMerkleRoot  = hashMerkleRoot;
1325         block.nTime           = nTime;
1326         block.nBits           = nBits;
1327         block.nNonce          = nNonce;
1328         return block.GetHash();
1329     }
1330
1331
1332     string ToString() const
1333     {
1334         string str = "CDiskBlockIndex(";
1335         str += CBlockIndex::ToString();
1336         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1337             GetBlockHash().ToString().c_str(),
1338             hashPrev.ToString().substr(0,20).c_str(),
1339             hashNext.ToString().substr(0,20).c_str());
1340         return str;
1341     }
1342
1343     void print() const
1344     {
1345         printf("%s\n", ToString().c_str());
1346     }
1347 };
1348
1349
1350
1351
1352
1353
1354
1355
1356 //
1357 // Describes a place in the block chain to another node such that if the
1358 // other node doesn't have the same branch, it can find a recent common trunk.
1359 // The further back it is, the further before the fork it may be.
1360 //
1361 class CBlockLocator
1362 {
1363 protected:
1364     vector<uint256> vHave;
1365 public:
1366
1367     CBlockLocator()
1368     {
1369     }
1370
1371     explicit CBlockLocator(const CBlockIndex* pindex)
1372     {
1373         Set(pindex);
1374     }
1375
1376     explicit CBlockLocator(uint256 hashBlock)
1377     {
1378         map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1379         if (mi != mapBlockIndex.end())
1380             Set((*mi).second);
1381     }
1382
1383     IMPLEMENT_SERIALIZE
1384     (
1385         if (!(nType & SER_GETHASH))
1386             READWRITE(nVersion);
1387         READWRITE(vHave);
1388     )
1389
1390     void Set(const CBlockIndex* pindex)
1391     {
1392         vHave.clear();
1393         int nStep = 1;
1394         while (pindex)
1395         {
1396             vHave.push_back(pindex->GetBlockHash());
1397
1398             // Exponentially larger steps back
1399             for (int i = 0; pindex && i < nStep; i++)
1400                 pindex = pindex->pprev;
1401             if (vHave.size() > 10)
1402                 nStep *= 2;
1403         }
1404         vHave.push_back(hashGenesisBlock);
1405     }
1406
1407     int GetDistanceBack()
1408     {
1409         // Retrace how far back it was in the sender's branch
1410         int nDistance = 0;
1411         int nStep = 1;
1412         foreach(const uint256& hash, vHave)
1413         {
1414             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1415             if (mi != mapBlockIndex.end())
1416             {
1417                 CBlockIndex* pindex = (*mi).second;
1418                 if (pindex->IsInMainChain())
1419                     return nDistance;
1420             }
1421             nDistance += nStep;
1422             if (nDistance > 10)
1423                 nStep *= 2;
1424         }
1425         return nDistance;
1426     }
1427
1428     CBlockIndex* GetBlockIndex()
1429     {
1430         // Find the first block the caller has in the main chain
1431         foreach(const uint256& hash, vHave)
1432         {
1433             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1434             if (mi != mapBlockIndex.end())
1435             {
1436                 CBlockIndex* pindex = (*mi).second;
1437                 if (pindex->IsInMainChain())
1438                     return pindex;
1439             }
1440         }
1441         return pindexGenesisBlock;
1442     }
1443
1444     uint256 GetBlockHash()
1445     {
1446         // Find the first block the caller has in the main chain
1447         foreach(const uint256& hash, vHave)
1448         {
1449             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1450             if (mi != mapBlockIndex.end())
1451             {
1452                 CBlockIndex* pindex = (*mi).second;
1453                 if (pindex->IsInMainChain())
1454                     return hash;
1455             }
1456         }
1457         return hashGenesisBlock;
1458     }
1459
1460     int GetHeight()
1461     {
1462         CBlockIndex* pindex = GetBlockIndex();
1463         if (!pindex)
1464             return 0;
1465         return pindex->nHeight;
1466     }
1467 };
1468
1469
1470
1471
1472
1473
1474 //
1475 // Private key that includes an expiration date in case it never gets used.
1476 //
1477 class CWalletKey
1478 {
1479 public:
1480     CPrivKey vchPrivKey;
1481     int64 nTimeCreated;
1482     int64 nTimeExpires;
1483     string strComment;
1484     //// todo: add something to note what created it (user, getnewaddress, change)
1485     ////   maybe should have a map<string, string> property map
1486
1487     CWalletKey(int64 nExpires=0)
1488     {
1489         nTimeCreated = (nExpires ? GetTime() : 0);
1490         nTimeExpires = nExpires;
1491     }
1492
1493     IMPLEMENT_SERIALIZE
1494     (
1495         if (!(nType & SER_GETHASH))
1496             READWRITE(nVersion);
1497         READWRITE(vchPrivKey);
1498         READWRITE(nTimeCreated);
1499         READWRITE(nTimeExpires);
1500         READWRITE(strComment);
1501     )
1502 };
1503
1504
1505
1506
1507
1508
1509 //
1510 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1511 // not read the entire buffer if the alert is for a newer version, but older
1512 // versions can still relay the original data.
1513 //
1514 class CUnsignedAlert
1515 {
1516 public:
1517     int nVersion;
1518     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1519     int64 nExpiration;
1520     int nID;
1521     int nCancel;
1522     set<int> setCancel;
1523     int nMinVer;            // lowest version inclusive
1524     int nMaxVer;            // highest version inclusive
1525     set<string> setSubVer;  // empty matches all
1526     int nPriority;
1527
1528     // Actions
1529     string strComment;
1530     string strStatusBar;
1531     string strRPCError;
1532
1533     IMPLEMENT_SERIALIZE
1534     (
1535         READWRITE(this->nVersion);
1536         nVersion = this->nVersion;
1537         READWRITE(nRelayUntil);
1538         READWRITE(nExpiration);
1539         READWRITE(nID);
1540         READWRITE(nCancel);
1541         READWRITE(setCancel);
1542         READWRITE(nMinVer);
1543         READWRITE(nMaxVer);
1544         READWRITE(setSubVer);
1545         READWRITE(nPriority);
1546
1547         READWRITE(strComment);
1548         READWRITE(strStatusBar);
1549         READWRITE(strRPCError);
1550     )
1551
1552     void SetNull()
1553     {
1554         nVersion = 1;
1555         nRelayUntil = 0;
1556         nExpiration = 0;
1557         nID = 0;
1558         nCancel = 0;
1559         setCancel.clear();
1560         nMinVer = 0;
1561         nMaxVer = 0;
1562         setSubVer.clear();
1563         nPriority = 0;
1564
1565         strComment.clear();
1566         strStatusBar.clear();
1567         strRPCError.clear();
1568     }
1569
1570     string ToString() const
1571     {
1572         string strSetCancel;
1573         foreach(int n, setCancel)
1574             strSetCancel += strprintf("%d ", n);
1575         string strSetSubVer;
1576         foreach(string str, setSubVer)
1577             strSetSubVer += "\"" + str + "\" ";
1578         return strprintf(
1579                 "CAlert(\n"
1580                 "    nVersion     = %d\n"
1581                 "    nRelayUntil  = %"PRI64d"\n"
1582                 "    nExpiration  = %"PRI64d"\n"
1583                 "    nID          = %d\n"
1584                 "    nCancel      = %d\n"
1585                 "    setCancel    = %s\n"
1586                 "    nMinVer      = %d\n"
1587                 "    nMaxVer      = %d\n"
1588                 "    setSubVer    = %s\n"
1589                 "    nPriority    = %d\n"
1590                 "    strComment   = \"%s\"\n"
1591                 "    strStatusBar = \"%s\"\n"
1592                 "    strRPCError  = \"%s\"\n"
1593                 ")\n",
1594             nVersion,
1595             nRelayUntil,
1596             nExpiration,
1597             nID,
1598             nCancel,
1599             strSetCancel.c_str(),
1600             nMinVer,
1601             nMaxVer,
1602             strSetSubVer.c_str(),
1603             nPriority,
1604             strComment.c_str(),
1605             strStatusBar.c_str(),
1606             strRPCError.c_str());
1607     }
1608
1609     void print() const
1610     {
1611         printf("%s", ToString().c_str());
1612     }
1613 };
1614
1615 class CAlert : public CUnsignedAlert
1616 {
1617 public:
1618     vector<unsigned char> vchMsg;
1619     vector<unsigned char> vchSig;
1620
1621     CAlert()
1622     {
1623         SetNull();
1624     }
1625
1626     IMPLEMENT_SERIALIZE
1627     (
1628         READWRITE(vchMsg);
1629         READWRITE(vchSig);
1630     )
1631
1632     void SetNull()
1633     {
1634         CUnsignedAlert::SetNull();
1635         vchMsg.clear();
1636         vchSig.clear();
1637     }
1638
1639     bool IsNull() const
1640     {
1641         return (nExpiration == 0);
1642     }
1643
1644     uint256 GetHash() const
1645     {
1646         return SerializeHash(*this);
1647     }
1648
1649     bool IsInEffect() const
1650     {
1651         return (GetAdjustedTime() < nExpiration);
1652     }
1653
1654     bool Cancels(const CAlert& alert) const
1655     {
1656         if (!IsInEffect())
1657             false;
1658         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1659     }
1660
1661     bool AppliesTo(int nVersion, string strSubVerIn) const
1662     {
1663         return (IsInEffect() &&
1664                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1665                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1666     }
1667
1668     bool AppliesToMe() const
1669     {
1670         return AppliesTo(VERSION, ::pszSubVer);
1671     }
1672
1673     bool RelayTo(CNode* pnode) const
1674     {
1675         if (!IsInEffect())
1676             return false;
1677         // returns true if wasn't already contained in the set
1678         if (pnode->setKnown.insert(GetHash()).second)
1679         {
1680             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1681                 AppliesToMe() ||
1682                 GetAdjustedTime() < nRelayUntil)
1683             {
1684                 pnode->PushMessage("alert", *this);
1685                 return true;
1686             }
1687         }
1688         return false;
1689     }
1690
1691     bool CheckSignature()
1692     {
1693         CKey key;
1694         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1695             return error("CAlert::CheckSignature() : SetPubKey failed");
1696         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1697             return error("CAlert::CheckSignature() : verify signature failed");
1698
1699         // Now unserialize the data
1700         CDataStream sMsg(vchMsg);
1701         sMsg >> *(CUnsignedAlert*)this;
1702         return true;
1703     }
1704
1705     bool ProcessAlert();
1706 };
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717 extern map<uint256, CTransaction> mapTransactions;
1718 extern map<uint256, CWalletTx> mapWallet;
1719 extern vector<uint256> vWalletUpdated;
1720 extern CCriticalSection cs_mapWallet;
1721 extern map<vector<unsigned char>, CPrivKey> mapKeys;
1722 extern map<uint160, vector<unsigned char> > mapPubKeys;
1723 extern CCriticalSection cs_mapKeys;
1724 extern CKey keyUser;