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