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