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