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