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