33c489273244343ed0f07557f1e4a3be37ec6e07
[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 MAX_MONEY = 21000000 * COIN;
41 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
42 static const int COINBASE_MATURITY = 100;
43 #ifdef USE_UPNP
44 static const int fHaveUPnP = true;
45 #else
46 static const int fHaveUPnP = false;
47 #endif
48
49
50
51
52
53
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern uint256 hashGenesisBlock;
57 extern CBigNum bnProofOfWorkLimit;
58 extern CBlockIndex* pindexGenesisBlock;
59 extern int nBestHeight;
60 extern CBigNum bnBestChainWork;
61 extern CBigNum bnBestInvalidWork;
62 extern uint256 hashBestChain;
63 extern CBlockIndex* pindexBest;
64 extern unsigned int nTransactionsUpdated;
65 extern std::map<uint256, int> mapRequestCount;
66 extern CCriticalSection cs_mapRequestCount;
67 extern std::map<std::string, std::string> mapAddressBook;
68 extern CCriticalSection cs_mapAddressBook;
69 extern std::vector<unsigned char> vchDefaultKey;
70 extern double dHashesPerSec;
71 extern int64 nHPSTimerStart;
72
73 // Settings
74 extern int fGenerateBitcoins;
75 extern int64 nTransactionFee;
76 extern CAddress addrIncoming;
77 extern int fLimitProcessors;
78 extern int nLimitProcessors;
79 extern int fMinimizeToTray;
80 extern int fMinimizeOnClose;
81 extern int fUseUPnP;
82
83
84
85
86
87 class CReserveKey;
88 class CTxDB;
89 class CTxIndex;
90
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);
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) const
613     {
614         // Base fee is 1 cent per kilobyte
615         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
616         unsigned int nNewBlockSize = nBlockSize + nBytes;
617         int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
618
619         if (fAllowFree)
620         {
621             if (nBlockSize == 1)
622             {
623                 // Transactions under 10K are free
624                 // (about 4500bc if made of 50bc inputs)
625                 if (nBytes < 10000)
626                     nMinFee = 0;
627             }
628             else
629             {
630                 // Free transaction area
631                 if (nNewBlockSize < 27000)
632                     nMinFee = 0;
633             }
634         }
635
636         // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
637         if (nMinFee < MIN_TX_FEE)
638             BOOST_FOREACH(const CTxOut& txout, vout)
639                 if (txout.nValue < CENT)
640                     nMinFee = MIN_TX_FEE;
641
642         // Raise the price as the block approaches full
643         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
644         {
645             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
646                 return MAX_MONEY;
647             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
648         }
649
650         if (!MoneyRange(nMinFee))
651             nMinFee = MAX_MONEY;
652         return nMinFee;
653     }
654
655
656     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
657     {
658         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
659         if (!filein)
660             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
661
662         // Read transaction
663         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
664             return error("CTransaction::ReadFromDisk() : fseek failed");
665         filein >> *this;
666
667         // Return file pointer
668         if (pfileRet)
669         {
670             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
671                 return error("CTransaction::ReadFromDisk() : second fseek failed");
672             *pfileRet = filein.release();
673         }
674         return true;
675     }
676
677     friend bool operator==(const CTransaction& a, const CTransaction& b)
678     {
679         return (a.nVersion  == b.nVersion &&
680                 a.vin       == b.vin &&
681                 a.vout      == b.vout &&
682                 a.nLockTime == b.nLockTime);
683     }
684
685     friend bool operator!=(const CTransaction& a, const CTransaction& b)
686     {
687         return !(a == b);
688     }
689
690
691     std::string ToString() const
692     {
693         std::string str;
694         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
695             GetHash().ToString().substr(0,10).c_str(),
696             nVersion,
697             vin.size(),
698             vout.size(),
699             nLockTime);
700         for (int i = 0; i < vin.size(); i++)
701             str += "    " + vin[i].ToString() + "\n";
702         for (int i = 0; i < vout.size(); i++)
703             str += "    " + vout[i].ToString() + "\n";
704         return str;
705     }
706
707     void print() const
708     {
709         printf("%s", ToString().c_str());
710     }
711
712
713     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
714     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
715     bool ReadFromDisk(COutPoint prevout);
716     bool DisconnectInputs(CTxDB& txdb);
717     bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
718                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
719     bool ClientConnectInputs();
720     bool CheckTransaction() const;
721     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
722     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
723     {
724         CTxDB txdb("r");
725         return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
726     }
727 protected:
728     bool AddToMemoryPoolUnchecked();
729 public:
730     bool RemoveFromMemoryPool();
731 };
732
733
734
735
736
737 //
738 // A transaction with a merkle branch linking it to the block chain
739 //
740 class CMerkleTx : public CTransaction
741 {
742 public:
743     uint256 hashBlock;
744     std::vector<uint256> vMerkleBranch;
745     int nIndex;
746
747     // memory only
748     mutable char fMerkleVerified;
749
750
751     CMerkleTx()
752     {
753         Init();
754     }
755
756     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
757     {
758         Init();
759     }
760
761     void Init()
762     {
763         hashBlock = 0;
764         nIndex = -1;
765         fMerkleVerified = false;
766     }
767
768
769     IMPLEMENT_SERIALIZE
770     (
771         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
772         nVersion = this->nVersion;
773         READWRITE(hashBlock);
774         READWRITE(vMerkleBranch);
775         READWRITE(nIndex);
776     )
777
778
779     int SetMerkleBranch(const CBlock* pblock=NULL);
780     int GetDepthInMainChain(int& nHeightRet) const;
781     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
782     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
783     int GetBlocksToMaturity() const;
784     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
785     bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
786 };
787
788
789
790
791 //
792 // A transaction with a bunch of additional info that only the owner cares
793 // about.  It includes any unrecorded transactions needed to link it back
794 // to the block chain.
795 //
796 class CWalletTx : public CMerkleTx
797 {
798 public:
799     std::vector<CMerkleTx> vtxPrev;
800     std::map<std::string, std::string> mapValue;
801     std::vector<std::pair<std::string, std::string> > vOrderForm;
802     unsigned int fTimeReceivedIsTxTime;
803     unsigned int nTimeReceived;  // time received by this node
804     char fFromMe;
805     std::string strFromAccount;
806     std::vector<char> vfSpent;
807
808     // memory only
809     mutable char fDebitCached;
810     mutable char fCreditCached;
811     mutable char fAvailableCreditCached;
812     mutable char fChangeCached;
813     mutable int64 nDebitCached;
814     mutable int64 nCreditCached;
815     mutable int64 nAvailableCreditCached;
816     mutable int64 nChangeCached;
817
818     // memory only UI hints
819     mutable unsigned int nTimeDisplayed;
820     mutable int nLinesDisplayed;
821     mutable char fConfirmedDisplayed;
822
823
824     CWalletTx()
825     {
826         Init();
827     }
828
829     CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
830     {
831         Init();
832     }
833
834     CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
835     {
836         Init();
837     }
838
839     void Init()
840     {
841         vtxPrev.clear();
842         mapValue.clear();
843         vOrderForm.clear();
844         fTimeReceivedIsTxTime = false;
845         nTimeReceived = 0;
846         fFromMe = false;
847         strFromAccount.clear();
848         vfSpent.clear();
849         fDebitCached = false;
850         fCreditCached = false;
851         fAvailableCreditCached = false;
852         fChangeCached = false;
853         nDebitCached = 0;
854         nCreditCached = 0;
855         nAvailableCreditCached = 0;
856         nChangeCached = 0;
857         nTimeDisplayed = 0;
858         nLinesDisplayed = 0;
859         fConfirmedDisplayed = false;
860     }
861
862     IMPLEMENT_SERIALIZE
863     (
864         CWalletTx* pthis = const_cast<CWalletTx*>(this);
865         if (fRead)
866             pthis->Init();
867         char fSpent = false;
868
869         if (!fRead)
870         {
871             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
872
873             std::string str;
874             BOOST_FOREACH(char f, vfSpent)
875             {
876                 str += (f ? '1' : '0');
877                 if (f)
878                     fSpent = true;
879             }
880             pthis->mapValue["spent"] = str;
881         }
882
883         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
884         READWRITE(vtxPrev);
885         READWRITE(mapValue);
886         READWRITE(vOrderForm);
887         READWRITE(fTimeReceivedIsTxTime);
888         READWRITE(nTimeReceived);
889         READWRITE(fFromMe);
890         READWRITE(fSpent);
891
892         if (fRead)
893         {
894             pthis->strFromAccount = pthis->mapValue["fromaccount"];
895
896             if (mapValue.count("spent"))
897                 BOOST_FOREACH(char c, pthis->mapValue["spent"])
898                     pthis->vfSpent.push_back(c != '0');
899             else
900                 pthis->vfSpent.assign(vout.size(), fSpent);
901         }
902
903         pthis->mapValue.erase("fromaccount");
904         pthis->mapValue.erase("version");
905         pthis->mapValue.erase("spent");
906     )
907
908     // marks certain txout's as spent
909     // returns true if any update took place
910     bool UpdateSpent(const std::vector<char>& vfNewSpent)
911     {
912         bool fReturn = false;
913         for (int i=0; i < vfNewSpent.size(); i++)
914         {
915             if (i == vfSpent.size())
916                 break;
917
918             if (vfNewSpent[i] && !vfSpent[i])
919             {
920                 vfSpent[i] = true;
921                 fReturn = true;
922                 fAvailableCreditCached = false;
923             }
924         }
925         return fReturn;
926     }
927
928     void MarkDirty()
929     {
930         fCreditCached = false;
931         fAvailableCreditCached = false;
932         fDebitCached = false;
933         fChangeCached = false;
934     }
935
936     void MarkSpent(unsigned int nOut)
937     {
938         if (nOut >= vout.size())
939             throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
940         vfSpent.resize(vout.size());
941         if (!vfSpent[nOut])
942         {
943             vfSpent[nOut] = true;
944             fAvailableCreditCached = false;
945         }
946     }
947
948     bool IsSpent(unsigned int nOut) const
949     {
950         if (nOut >= vout.size())
951             throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
952         if (nOut >= vfSpent.size())
953             return false;
954         return (!!vfSpent[nOut]);
955     }
956
957     int64 GetDebit() const
958     {
959         if (vin.empty())
960             return 0;
961         if (fDebitCached)
962             return nDebitCached;
963         nDebitCached = CTransaction::GetDebit();
964         fDebitCached = true;
965         return nDebitCached;
966     }
967
968     int64 GetCredit(bool fUseCache=true) const
969     {
970         // Must wait until coinbase is safely deep enough in the chain before valuing it
971         if (IsCoinBase() && GetBlocksToMaturity() > 0)
972             return 0;
973
974         // GetBalance can assume transactions in mapWallet won't change
975         if (fUseCache && fCreditCached)
976             return nCreditCached;
977         nCreditCached = CTransaction::GetCredit();
978         fCreditCached = true;
979         return nCreditCached;
980     }
981
982     int64 GetAvailableCredit(bool fUseCache=true) const
983     {
984         // Must wait until coinbase is safely deep enough in the chain before valuing it
985         if (IsCoinBase() && GetBlocksToMaturity() > 0)
986             return 0;
987
988         if (fUseCache && fAvailableCreditCached)
989             return nAvailableCreditCached;
990
991         int64 nCredit = 0;
992         for (int i = 0; i < vout.size(); i++)
993         {
994             if (!IsSpent(i))
995             {
996                 const CTxOut &txout = vout[i];
997                 nCredit += txout.GetCredit();
998                 if (!MoneyRange(nCredit))
999                     throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1000             }
1001         }
1002
1003         nAvailableCreditCached = nCredit;
1004         fAvailableCreditCached = true;
1005         return nCredit;
1006     }
1007
1008
1009     int64 GetChange() const
1010     {
1011         if (fChangeCached)
1012             return nChangeCached;
1013         nChangeCached = CTransaction::GetChange();
1014         fChangeCached = true;
1015         return nChangeCached;
1016     }
1017
1018     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
1019                     std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
1020
1021     void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
1022                            int64& nSent, int64& nFee) const;
1023
1024     bool IsFromMe() const
1025     {
1026         return (GetDebit() > 0);
1027     }
1028
1029     bool IsConfirmed() const
1030     {
1031         // Quick answer in most cases
1032         if (!IsFinal())
1033             return false;
1034         if (GetDepthInMainChain() >= 1)
1035             return true;
1036         if (!IsFromMe()) // using wtx's cached debit
1037             return false;
1038
1039         // If no confirmations but it's from us, we can still
1040         // consider it confirmed if all dependencies are confirmed
1041         std::map<uint256, const CMerkleTx*> mapPrev;
1042         std::vector<const CMerkleTx*> vWorkQueue;
1043         vWorkQueue.reserve(vtxPrev.size()+1);
1044         vWorkQueue.push_back(this);
1045         for (int i = 0; i < vWorkQueue.size(); i++)
1046         {
1047             const CMerkleTx* ptx = vWorkQueue[i];
1048
1049             if (!ptx->IsFinal())
1050                 return false;
1051             if (ptx->GetDepthInMainChain() >= 1)
1052                 continue;
1053             if (!ptx->IsFromMe())
1054                 return false;
1055
1056             if (mapPrev.empty())
1057                 BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
1058                     mapPrev[tx.GetHash()] = &tx;
1059
1060             BOOST_FOREACH(const CTxIn& txin, ptx->vin)
1061             {
1062                 if (!mapPrev.count(txin.prevout.hash))
1063                     return false;
1064                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1065             }
1066         }
1067         return true;
1068     }
1069
1070     bool WriteToDisk()
1071     {
1072         return CWalletDB().WriteTx(GetHash(), *this);
1073     }
1074
1075
1076     int64 GetTxTime() const;
1077     int GetRequestCount() const;
1078
1079     void AddSupportingTransactions(CTxDB& txdb);
1080
1081     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1082     bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1083
1084     void RelayWalletTransaction(CTxDB& txdb);
1085     void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1086 };
1087
1088
1089
1090
1091 //
1092 // A txdb record that contains the disk location of a transaction and the
1093 // locations of transactions that spend its outputs.  vSpent is really only
1094 // used as a flag, but having the location is very helpful for debugging.
1095 //
1096 class CTxIndex
1097 {
1098 public:
1099     CDiskTxPos pos;
1100     std::vector<CDiskTxPos> vSpent;
1101
1102     CTxIndex()
1103     {
1104         SetNull();
1105     }
1106
1107     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1108     {
1109         pos = posIn;
1110         vSpent.resize(nOutputs);
1111     }
1112
1113     IMPLEMENT_SERIALIZE
1114     (
1115         if (!(nType & SER_GETHASH))
1116             READWRITE(nVersion);
1117         READWRITE(pos);
1118         READWRITE(vSpent);
1119     )
1120
1121     void SetNull()
1122     {
1123         pos.SetNull();
1124         vSpent.clear();
1125     }
1126
1127     bool IsNull()
1128     {
1129         return pos.IsNull();
1130     }
1131
1132     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1133     {
1134         return (a.pos    == b.pos &&
1135                 a.vSpent == b.vSpent);
1136     }
1137
1138     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1139     {
1140         return !(a == b);
1141     }
1142     int GetDepthInMainChain() const;
1143 };
1144
1145
1146
1147
1148
1149 //
1150 // Nodes collect new transactions into a block, hash them into a hash tree,
1151 // and scan through nonce values to make the block's hash satisfy proof-of-work
1152 // requirements.  When they solve the proof-of-work, they broadcast the block
1153 // to everyone and the block is added to the block chain.  The first transaction
1154 // in the block is a special one that creates a new coin owned by the creator
1155 // of the block.
1156 //
1157 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
1158 // is indexed by CBlockIndex objects in memory.
1159 //
1160 class CBlock
1161 {
1162 public:
1163     // header
1164     int nVersion;
1165     uint256 hashPrevBlock;
1166     uint256 hashMerkleRoot;
1167     unsigned int nTime;
1168     unsigned int nBits;
1169     unsigned int nNonce;
1170
1171     // network and disk
1172     std::vector<CTransaction> vtx;
1173
1174     // memory only
1175     mutable std::vector<uint256> vMerkleTree;
1176
1177
1178     CBlock()
1179     {
1180         SetNull();
1181     }
1182
1183     IMPLEMENT_SERIALIZE
1184     (
1185         READWRITE(this->nVersion);
1186         nVersion = this->nVersion;
1187         READWRITE(hashPrevBlock);
1188         READWRITE(hashMerkleRoot);
1189         READWRITE(nTime);
1190         READWRITE(nBits);
1191         READWRITE(nNonce);
1192
1193         // ConnectBlock depends on vtx being last so it can calculate offset
1194         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1195             READWRITE(vtx);
1196         else if (fRead)
1197             const_cast<CBlock*>(this)->vtx.clear();
1198     )
1199
1200     void SetNull()
1201     {
1202         nVersion = 1;
1203         hashPrevBlock = 0;
1204         hashMerkleRoot = 0;
1205         nTime = 0;
1206         nBits = 0;
1207         nNonce = 0;
1208         vtx.clear();
1209         vMerkleTree.clear();
1210     }
1211
1212     bool IsNull() const
1213     {
1214         return (nBits == 0);
1215     }
1216
1217     uint256 GetHash() const
1218     {
1219         return Hash(BEGIN(nVersion), END(nNonce));
1220     }
1221
1222     int64 GetBlockTime() const
1223     {
1224         return (int64)nTime;
1225     }
1226
1227     int GetSigOpCount() const
1228     {
1229         int n = 0;
1230         BOOST_FOREACH(const CTransaction& tx, vtx)
1231             n += tx.GetSigOpCount();
1232         return n;
1233     }
1234
1235
1236     uint256 BuildMerkleTree() const
1237     {
1238         vMerkleTree.clear();
1239         BOOST_FOREACH(const CTransaction& tx, vtx)
1240             vMerkleTree.push_back(tx.GetHash());
1241         int j = 0;
1242         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1243         {
1244             for (int i = 0; i < nSize; i += 2)
1245             {
1246                 int i2 = std::min(i+1, nSize-1);
1247                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1248                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1249             }
1250             j += nSize;
1251         }
1252         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1253     }
1254
1255     std::vector<uint256> GetMerkleBranch(int nIndex) const
1256     {
1257         if (vMerkleTree.empty())
1258             BuildMerkleTree();
1259         std::vector<uint256> vMerkleBranch;
1260         int j = 0;
1261         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1262         {
1263             int i = std::min(nIndex^1, nSize-1);
1264             vMerkleBranch.push_back(vMerkleTree[j+i]);
1265             nIndex >>= 1;
1266             j += nSize;
1267         }
1268         return vMerkleBranch;
1269     }
1270
1271     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
1272     {
1273         if (nIndex == -1)
1274             return 0;
1275         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
1276         {
1277             if (nIndex & 1)
1278                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1279             else
1280                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1281             nIndex >>= 1;
1282         }
1283         return hash;
1284     }
1285
1286
1287     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1288     {
1289         // Open history file to append
1290         CAutoFile fileout = AppendBlockFile(nFileRet);
1291         if (!fileout)
1292             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1293
1294         // Write index header
1295         unsigned int nSize = fileout.GetSerializeSize(*this);
1296         fileout << FLATDATA(pchMessageStart) << nSize;
1297
1298         // Write block
1299         nBlockPosRet = ftell(fileout);
1300         if (nBlockPosRet == -1)
1301             return error("CBlock::WriteToDisk() : ftell failed");
1302         fileout << *this;
1303
1304         // Flush stdio buffers and commit to disk before returning
1305         fflush(fileout);
1306         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1307         {
1308 #ifdef __WXMSW__
1309             _commit(_fileno(fileout));
1310 #else
1311             fsync(fileno(fileout));
1312 #endif
1313         }
1314
1315         return true;
1316     }
1317
1318     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1319     {
1320         SetNull();
1321
1322         // Open history file to read
1323         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1324         if (!filein)
1325             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1326         if (!fReadTransactions)
1327             filein.nType |= SER_BLOCKHEADERONLY;
1328
1329         // Read block
1330         filein >> *this;
1331
1332         // Check the header
1333         if (!CheckProofOfWork(GetHash(), nBits))
1334             return error("CBlock::ReadFromDisk() : errors in block header");
1335
1336         return true;
1337     }
1338
1339
1340
1341     void print() const
1342     {
1343         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1344             GetHash().ToString().substr(0,20).c_str(),
1345             nVersion,
1346             hashPrevBlock.ToString().substr(0,20).c_str(),
1347             hashMerkleRoot.ToString().substr(0,10).c_str(),
1348             nTime, nBits, nNonce,
1349             vtx.size());
1350         for (int i = 0; i < vtx.size(); i++)
1351         {
1352             printf("  ");
1353             vtx[i].print();
1354         }
1355         printf("  vMerkleTree: ");
1356         for (int i = 0; i < vMerkleTree.size(); i++)
1357             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1358         printf("\n");
1359     }
1360
1361
1362     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1363     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1364     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1365     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1366     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1367     bool CheckBlock() const;
1368     bool AcceptBlock();
1369 };
1370
1371
1372
1373
1374
1375
1376 //
1377 // The block chain is a tree shaped structure starting with the
1378 // genesis block at the root, with each block potentially having multiple
1379 // candidates to be the next block.  pprev and pnext link a path through the
1380 // main/longest chain.  A blockindex may have multiple pprev pointing back
1381 // to it, but pnext will only point forward to the longest branch, or will
1382 // be null if the block is not part of the longest chain.
1383 //
1384 class CBlockIndex
1385 {
1386 public:
1387     const uint256* phashBlock;
1388     CBlockIndex* pprev;
1389     CBlockIndex* pnext;
1390     unsigned int nFile;
1391     unsigned int nBlockPos;
1392     int nHeight;
1393     CBigNum bnChainWork;
1394
1395     // block header
1396     int nVersion;
1397     uint256 hashMerkleRoot;
1398     unsigned int nTime;
1399     unsigned int nBits;
1400     unsigned int nNonce;
1401
1402
1403     CBlockIndex()
1404     {
1405         phashBlock = NULL;
1406         pprev = NULL;
1407         pnext = NULL;
1408         nFile = 0;
1409         nBlockPos = 0;
1410         nHeight = 0;
1411         bnChainWork = 0;
1412
1413         nVersion       = 0;
1414         hashMerkleRoot = 0;
1415         nTime          = 0;
1416         nBits          = 0;
1417         nNonce         = 0;
1418     }
1419
1420     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1421     {
1422         phashBlock = NULL;
1423         pprev = NULL;
1424         pnext = NULL;
1425         nFile = nFileIn;
1426         nBlockPos = nBlockPosIn;
1427         nHeight = 0;
1428         bnChainWork = 0;
1429
1430         nVersion       = block.nVersion;
1431         hashMerkleRoot = block.hashMerkleRoot;
1432         nTime          = block.nTime;
1433         nBits          = block.nBits;
1434         nNonce         = block.nNonce;
1435     }
1436
1437     CBlock GetBlockHeader() const
1438     {
1439         CBlock block;
1440         block.nVersion       = nVersion;
1441         if (pprev)
1442             block.hashPrevBlock = pprev->GetBlockHash();
1443         block.hashMerkleRoot = hashMerkleRoot;
1444         block.nTime          = nTime;
1445         block.nBits          = nBits;
1446         block.nNonce         = nNonce;
1447         return block;
1448     }
1449
1450     uint256 GetBlockHash() const
1451     {
1452         return *phashBlock;
1453     }
1454
1455     int64 GetBlockTime() const
1456     {
1457         return (int64)nTime;
1458     }
1459
1460     CBigNum GetBlockWork() const
1461     {
1462         CBigNum bnTarget;
1463         bnTarget.SetCompact(nBits);
1464         if (bnTarget <= 0)
1465             return 0;
1466         return (CBigNum(1)<<256) / (bnTarget+1);
1467     }
1468
1469     bool IsInMainChain() const
1470     {
1471         return (pnext || this == pindexBest);
1472     }
1473
1474     bool CheckIndex() const
1475     {
1476         return CheckProofOfWork(GetBlockHash(), nBits);
1477     }
1478
1479     bool EraseBlockFromDisk()
1480     {
1481         // Open history file
1482         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1483         if (!fileout)
1484             return false;
1485
1486         // Overwrite with empty null block
1487         CBlock block;
1488         block.SetNull();
1489         fileout << block;
1490
1491         return true;
1492     }
1493
1494     enum { nMedianTimeSpan=11 };
1495
1496     int64 GetMedianTimePast() const
1497     {
1498         int64 pmedian[nMedianTimeSpan];
1499         int64* pbegin = &pmedian[nMedianTimeSpan];
1500         int64* pend = &pmedian[nMedianTimeSpan];
1501
1502         const CBlockIndex* pindex = this;
1503         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1504             *(--pbegin) = pindex->GetBlockTime();
1505
1506         std::sort(pbegin, pend);
1507         return pbegin[(pend - pbegin)/2];
1508     }
1509
1510     int64 GetMedianTime() const
1511     {
1512         const CBlockIndex* pindex = this;
1513         for (int i = 0; i < nMedianTimeSpan/2; i++)
1514         {
1515             if (!pindex->pnext)
1516                 return GetBlockTime();
1517             pindex = pindex->pnext;
1518         }
1519         return pindex->GetMedianTimePast();
1520     }
1521
1522
1523
1524     std::string ToString() const
1525     {
1526         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1527             pprev, pnext, nFile, nBlockPos, nHeight,
1528             hashMerkleRoot.ToString().substr(0,10).c_str(),
1529             GetBlockHash().ToString().substr(0,20).c_str());
1530     }
1531
1532     void print() const
1533     {
1534         printf("%s\n", ToString().c_str());
1535     }
1536 };
1537
1538
1539
1540 //
1541 // Used to marshal pointers into hashes for db storage.
1542 //
1543 class CDiskBlockIndex : public CBlockIndex
1544 {
1545 public:
1546     uint256 hashPrev;
1547     uint256 hashNext;
1548
1549     CDiskBlockIndex()
1550     {
1551         hashPrev = 0;
1552         hashNext = 0;
1553     }
1554
1555     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1556     {
1557         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1558         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1559     }
1560
1561     IMPLEMENT_SERIALIZE
1562     (
1563         if (!(nType & SER_GETHASH))
1564             READWRITE(nVersion);
1565
1566         READWRITE(hashNext);
1567         READWRITE(nFile);
1568         READWRITE(nBlockPos);
1569         READWRITE(nHeight);
1570
1571         // block header
1572         READWRITE(this->nVersion);
1573         READWRITE(hashPrev);
1574         READWRITE(hashMerkleRoot);
1575         READWRITE(nTime);
1576         READWRITE(nBits);
1577         READWRITE(nNonce);
1578     )
1579
1580     uint256 GetBlockHash() const
1581     {
1582         CBlock block;
1583         block.nVersion        = nVersion;
1584         block.hashPrevBlock   = hashPrev;
1585         block.hashMerkleRoot  = hashMerkleRoot;
1586         block.nTime           = nTime;
1587         block.nBits           = nBits;
1588         block.nNonce          = nNonce;
1589         return block.GetHash();
1590     }
1591
1592
1593     std::string ToString() const
1594     {
1595         std::string str = "CDiskBlockIndex(";
1596         str += CBlockIndex::ToString();
1597         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1598             GetBlockHash().ToString().c_str(),
1599             hashPrev.ToString().substr(0,20).c_str(),
1600             hashNext.ToString().substr(0,20).c_str());
1601         return str;
1602     }
1603
1604     void print() const
1605     {
1606         printf("%s\n", ToString().c_str());
1607     }
1608 };
1609
1610
1611
1612
1613
1614
1615
1616
1617 //
1618 // Describes a place in the block chain to another node such that if the
1619 // other node doesn't have the same branch, it can find a recent common trunk.
1620 // The further back it is, the further before the fork it may be.
1621 //
1622 class CBlockLocator
1623 {
1624 protected:
1625     std::vector<uint256> vHave;
1626 public:
1627
1628     CBlockLocator()
1629     {
1630     }
1631
1632     explicit CBlockLocator(const CBlockIndex* pindex)
1633     {
1634         Set(pindex);
1635     }
1636
1637     explicit CBlockLocator(uint256 hashBlock)
1638     {
1639         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1640         if (mi != mapBlockIndex.end())
1641             Set((*mi).second);
1642     }
1643
1644     IMPLEMENT_SERIALIZE
1645     (
1646         if (!(nType & SER_GETHASH))
1647             READWRITE(nVersion);
1648         READWRITE(vHave);
1649     )
1650
1651     void SetNull()
1652     {
1653         vHave.clear();
1654     }
1655
1656     bool IsNull()
1657     {
1658         return vHave.empty();
1659     }
1660
1661     void Set(const CBlockIndex* pindex)
1662     {
1663         vHave.clear();
1664         int nStep = 1;
1665         while (pindex)
1666         {
1667             vHave.push_back(pindex->GetBlockHash());
1668
1669             // Exponentially larger steps back
1670             for (int i = 0; pindex && i < nStep; i++)
1671                 pindex = pindex->pprev;
1672             if (vHave.size() > 10)
1673                 nStep *= 2;
1674         }
1675         vHave.push_back(hashGenesisBlock);
1676     }
1677
1678     int GetDistanceBack()
1679     {
1680         // Retrace how far back it was in the sender's branch
1681         int nDistance = 0;
1682         int nStep = 1;
1683         BOOST_FOREACH(const uint256& hash, vHave)
1684         {
1685             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1686             if (mi != mapBlockIndex.end())
1687             {
1688                 CBlockIndex* pindex = (*mi).second;
1689                 if (pindex->IsInMainChain())
1690                     return nDistance;
1691             }
1692             nDistance += nStep;
1693             if (nDistance > 10)
1694                 nStep *= 2;
1695         }
1696         return nDistance;
1697     }
1698
1699     CBlockIndex* GetBlockIndex()
1700     {
1701         // Find the first block the caller has in the main chain
1702         BOOST_FOREACH(const uint256& hash, vHave)
1703         {
1704             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1705             if (mi != mapBlockIndex.end())
1706             {
1707                 CBlockIndex* pindex = (*mi).second;
1708                 if (pindex->IsInMainChain())
1709                     return pindex;
1710             }
1711         }
1712         return pindexGenesisBlock;
1713     }
1714
1715     uint256 GetBlockHash()
1716     {
1717         // Find the first block the caller has in the main chain
1718         BOOST_FOREACH(const uint256& hash, vHave)
1719         {
1720             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1721             if (mi != mapBlockIndex.end())
1722             {
1723                 CBlockIndex* pindex = (*mi).second;
1724                 if (pindex->IsInMainChain())
1725                     return hash;
1726             }
1727         }
1728         return hashGenesisBlock;
1729     }
1730
1731     int GetHeight()
1732     {
1733         CBlockIndex* pindex = GetBlockIndex();
1734         if (!pindex)
1735             return 0;
1736         return pindex->nHeight;
1737     }
1738 };
1739
1740
1741
1742
1743
1744
1745 //
1746 // Private key that includes an expiration date in case it never gets used.
1747 //
1748 class CWalletKey
1749 {
1750 public:
1751     CPrivKey vchPrivKey;
1752     int64 nTimeCreated;
1753     int64 nTimeExpires;
1754     std::string strComment;
1755     //// todo: add something to note what created it (user, getnewaddress, change)
1756     ////   maybe should have a map<string, string> property map
1757
1758     CWalletKey(int64 nExpires=0)
1759     {
1760         nTimeCreated = (nExpires ? GetTime() : 0);
1761         nTimeExpires = nExpires;
1762     }
1763
1764     IMPLEMENT_SERIALIZE
1765     (
1766         if (!(nType & SER_GETHASH))
1767             READWRITE(nVersion);
1768         READWRITE(vchPrivKey);
1769         READWRITE(nTimeCreated);
1770         READWRITE(nTimeExpires);
1771         READWRITE(strComment);
1772     )
1773 };
1774
1775
1776
1777
1778
1779
1780 //
1781 // Account information.
1782 // Stored in wallet with key "acc"+string account name
1783 //
1784 class CAccount
1785 {
1786 public:
1787     std::vector<unsigned char> vchPubKey;
1788
1789     CAccount()
1790     {
1791         SetNull();
1792     }
1793
1794     void SetNull()
1795     {
1796         vchPubKey.clear();
1797     }
1798
1799     IMPLEMENT_SERIALIZE
1800     (
1801         if (!(nType & SER_GETHASH))
1802             READWRITE(nVersion);
1803         READWRITE(vchPubKey);
1804     )
1805 };
1806
1807
1808
1809 //
1810 // Internal transfers.
1811 // Database key is acentry<account><counter>
1812 //
1813 class CAccountingEntry
1814 {
1815 public:
1816     std::string strAccount;
1817     int64 nCreditDebit;
1818     int64 nTime;
1819     std::string strOtherAccount;
1820     std::string strComment;
1821
1822     CAccountingEntry()
1823     {
1824         SetNull();
1825     }
1826
1827     void SetNull()
1828     {
1829         nCreditDebit = 0;
1830         nTime = 0;
1831         strAccount.clear();
1832         strOtherAccount.clear();
1833         strComment.clear();
1834     }
1835
1836     IMPLEMENT_SERIALIZE
1837     (
1838         if (!(nType & SER_GETHASH))
1839             READWRITE(nVersion);
1840         // Note: strAccount is serialized as part of the key, not here.
1841         READWRITE(nCreditDebit);
1842         READWRITE(nTime);
1843         READWRITE(strOtherAccount);
1844         READWRITE(strComment);
1845     )
1846 };
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856 //
1857 // Alerts are for notifying old versions if they become too obsolete and
1858 // need to upgrade.  The message is displayed in the status bar.
1859 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1860 // not read the entire buffer if the alert is for a newer version, but older
1861 // versions can still relay the original data.
1862 //
1863 class CUnsignedAlert
1864 {
1865 public:
1866     int nVersion;
1867     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1868     int64 nExpiration;
1869     int nID;
1870     int nCancel;
1871     std::set<int> setCancel;
1872     int nMinVer;            // lowest version inclusive
1873     int nMaxVer;            // highest version inclusive
1874     std::set<std::string> setSubVer;  // empty matches all
1875     int nPriority;
1876
1877     // Actions
1878     std::string strComment;
1879     std::string strStatusBar;
1880     std::string strReserved;
1881
1882     IMPLEMENT_SERIALIZE
1883     (
1884         READWRITE(this->nVersion);
1885         nVersion = this->nVersion;
1886         READWRITE(nRelayUntil);
1887         READWRITE(nExpiration);
1888         READWRITE(nID);
1889         READWRITE(nCancel);
1890         READWRITE(setCancel);
1891         READWRITE(nMinVer);
1892         READWRITE(nMaxVer);
1893         READWRITE(setSubVer);
1894         READWRITE(nPriority);
1895
1896         READWRITE(strComment);
1897         READWRITE(strStatusBar);
1898         READWRITE(strReserved);
1899     )
1900
1901     void SetNull()
1902     {
1903         nVersion = 1;
1904         nRelayUntil = 0;
1905         nExpiration = 0;
1906         nID = 0;
1907         nCancel = 0;
1908         setCancel.clear();
1909         nMinVer = 0;
1910         nMaxVer = 0;
1911         setSubVer.clear();
1912         nPriority = 0;
1913
1914         strComment.clear();
1915         strStatusBar.clear();
1916         strReserved.clear();
1917     }
1918
1919     std::string ToString() const
1920     {
1921         std::string strSetCancel;
1922         BOOST_FOREACH(int n, setCancel)
1923             strSetCancel += strprintf("%d ", n);
1924         std::string strSetSubVer;
1925         BOOST_FOREACH(std::string str, setSubVer)
1926             strSetSubVer += "\"" + str + "\" ";
1927         return strprintf(
1928                 "CAlert(\n"
1929                 "    nVersion     = %d\n"
1930                 "    nRelayUntil  = %"PRI64d"\n"
1931                 "    nExpiration  = %"PRI64d"\n"
1932                 "    nID          = %d\n"
1933                 "    nCancel      = %d\n"
1934                 "    setCancel    = %s\n"
1935                 "    nMinVer      = %d\n"
1936                 "    nMaxVer      = %d\n"
1937                 "    setSubVer    = %s\n"
1938                 "    nPriority    = %d\n"
1939                 "    strComment   = \"%s\"\n"
1940                 "    strStatusBar = \"%s\"\n"
1941                 ")\n",
1942             nVersion,
1943             nRelayUntil,
1944             nExpiration,
1945             nID,
1946             nCancel,
1947             strSetCancel.c_str(),
1948             nMinVer,
1949             nMaxVer,
1950             strSetSubVer.c_str(),
1951             nPriority,
1952             strComment.c_str(),
1953             strStatusBar.c_str());
1954     }
1955
1956     void print() const
1957     {
1958         printf("%s", ToString().c_str());
1959     }
1960 };
1961
1962 class CAlert : public CUnsignedAlert
1963 {
1964 public:
1965     std::vector<unsigned char> vchMsg;
1966     std::vector<unsigned char> vchSig;
1967
1968     CAlert()
1969     {
1970         SetNull();
1971     }
1972
1973     IMPLEMENT_SERIALIZE
1974     (
1975         READWRITE(vchMsg);
1976         READWRITE(vchSig);
1977     )
1978
1979     void SetNull()
1980     {
1981         CUnsignedAlert::SetNull();
1982         vchMsg.clear();
1983         vchSig.clear();
1984     }
1985
1986     bool IsNull() const
1987     {
1988         return (nExpiration == 0);
1989     }
1990
1991     uint256 GetHash() const
1992     {
1993         return SerializeHash(*this);
1994     }
1995
1996     bool IsInEffect() const
1997     {
1998         return (GetAdjustedTime() < nExpiration);
1999     }
2000
2001     bool Cancels(const CAlert& alert) const
2002     {
2003         if (!IsInEffect())
2004             return false; // this was a no-op before 31403
2005         return (alert.nID <= nCancel || setCancel.count(alert.nID));
2006     }
2007
2008     bool AppliesTo(int nVersion, std::string strSubVerIn) const
2009     {
2010         return (IsInEffect() &&
2011                 nMinVer <= nVersion && nVersion <= nMaxVer &&
2012                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
2013     }
2014
2015     bool AppliesToMe() const
2016     {
2017         return AppliesTo(VERSION, ::pszSubVer);
2018     }
2019
2020     bool RelayTo(CNode* pnode) const
2021     {
2022         if (!IsInEffect())
2023             return false;
2024         // returns true if wasn't already contained in the set
2025         if (pnode->setKnown.insert(GetHash()).second)
2026         {
2027             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2028                 AppliesToMe() ||
2029                 GetAdjustedTime() < nRelayUntil)
2030             {
2031                 pnode->PushMessage("alert", *this);
2032                 return true;
2033             }
2034         }
2035         return false;
2036     }
2037
2038     bool CheckSignature()
2039     {
2040         CKey key;
2041         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2042             return error("CAlert::CheckSignature() : SetPubKey failed");
2043         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2044             return error("CAlert::CheckSignature() : verify signature failed");
2045
2046         // Now unserialize the data
2047         CDataStream sMsg(vchMsg);
2048         sMsg >> *(CUnsignedAlert*)this;
2049         return true;
2050     }
2051
2052     bool ProcessAlert();
2053 };
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064 extern std::map<uint256, CTransaction> mapTransactions;
2065 extern std::map<uint256, CWalletTx> mapWallet;
2066 extern std::vector<uint256> vWalletUpdated;
2067 extern CCriticalSection cs_mapWallet;
2068 extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
2069 extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
2070 extern CCriticalSection cs_mapKeys;
2071 extern CKey keyUser;
2072
2073 #endif