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