a1fb548f087844ef31cf6311ff2c6eb964aefa31
[novacoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_MAIN_H
6 #define BITCOIN_MAIN_H
7
8 #include "bignum.h"
9 #include "net.h"
10 #include "key.h"
11 #include "script.h"
12 #include "db.h"
13
14 #include <list>
15
16 class CBlock;
17 class CBlockIndex;
18 class CWalletTx;
19 class CWallet;
20 class CKeyItem;
21 class CReserveKey;
22 class CWalletDB;
23
24 class CAddress;
25 class CInv;
26 class CRequestTracker;
27 class CNode;
28 class CBlockIndex;
29
30 static const unsigned int MAX_BLOCK_SIZE = 1000000;
31 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
32 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
33 static const int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
34 static const int64 COIN = 100000000;
35 static const int64 CENT = 1000000;
36 static const int64 MIN_TX_FEE = 50000;
37 static const int64 MIN_RELAY_TX_FEE = 10000;
38 static const int64 MAX_MONEY = 21000000 * COIN;
39 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
40 static const int COINBASE_MATURITY = 100;
41 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
42 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
43 #ifdef USE_UPNP
44 static const int fHaveUPnP = true;
45 #else
46 static const int fHaveUPnP = false;
47 #endif
48
49
50
51
52
53
54 extern CCriticalSection cs_main;
55 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
56 extern uint256 hashGenesisBlock;
57 extern CBlockIndex* pindexGenesisBlock;
58 extern int nBestHeight;
59 extern CBigNum bnBestChainWork;
60 extern CBigNum bnBestInvalidWork;
61 extern uint256 hashBestChain;
62 extern CBlockIndex* pindexBest;
63 extern unsigned int nTransactionsUpdated;
64 extern double dHashesPerSec;
65 extern int64 nHPSTimerStart;
66 extern int64 nTimeBestReceived;
67 extern CCriticalSection cs_setpwalletRegistered;
68 extern std::set<CWallet*> setpwalletRegistered;
69
70 // Settings
71 extern int fGenerateBitcoins;
72 extern int64 nTransactionFee;
73 extern int fLimitProcessors;
74 extern int nLimitProcessors;
75 extern int fMinimizeToTray;
76 extern int fMinimizeOnClose;
77 extern int fUseUPnP;
78
79
80
81
82
83 class CReserveKey;
84 class CTxDB;
85 class CTxIndex;
86
87 void RegisterWallet(CWallet* pwalletIn);
88 void UnregisterWallet(CWallet* pwalletIn);
89 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
90 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
91 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
92 FILE* AppendBlockFile(unsigned int& nFileRet);
93 bool LoadBlockIndex(bool fAllowNew=true);
94 void PrintBlockTree();
95 bool ProcessMessages(CNode* pfrom);
96 bool SendMessages(CNode* pto, bool fSendTrickle);
97 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
98 CBlock* CreateNewBlock(CReserveKey& reservekey);
99 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
100 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
101 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
102 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
103 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
104 int GetNumBlocksOfPeers();
105 bool IsInitialBlockDownload();
106 std::string GetWarnings(std::string strFor);
107
108
109
110
111
112
113
114
115
116
117
118
119 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
120
121 template<typename T>
122 bool WriteSetting(const std::string& strKey, const T& value)
123 {
124     bool fOk = false;
125     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126     {
127         std::string strWalletFile;
128         if (!GetWalletFile(pwallet, strWalletFile))
129             continue;
130         fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
131     }
132     return fOk;
133 }
134
135
136 class CDiskTxPos
137 {
138 public:
139     unsigned int nFile;
140     unsigned int nBlockPos;
141     unsigned int nTxPos;
142
143     CDiskTxPos()
144     {
145         SetNull();
146     }
147
148     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
149     {
150         nFile = nFileIn;
151         nBlockPos = nBlockPosIn;
152         nTxPos = nTxPosIn;
153     }
154
155     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
156     void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
157     bool IsNull() const { return (nFile == -1); }
158
159     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
160     {
161         return (a.nFile     == b.nFile &&
162                 a.nBlockPos == b.nBlockPos &&
163                 a.nTxPos    == b.nTxPos);
164     }
165
166     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
167     {
168         return !(a == b);
169     }
170
171     std::string ToString() const
172     {
173         if (IsNull())
174             return strprintf("null");
175         else
176             return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
177     }
178
179     void print() const
180     {
181         printf("%s", ToString().c_str());
182     }
183 };
184
185
186
187
188 class CInPoint
189 {
190 public:
191     CTransaction* ptx;
192     unsigned int n;
193
194     CInPoint() { SetNull(); }
195     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
196     void SetNull() { ptx = NULL; n = -1; }
197     bool IsNull() const { return (ptx == NULL && n == -1); }
198 };
199
200
201
202
203 class COutPoint
204 {
205 public:
206     uint256 hash;
207     unsigned int n;
208
209     COutPoint() { SetNull(); }
210     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
211     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
212     void SetNull() { hash = 0; n = -1; }
213     bool IsNull() const { return (hash == 0 && n == -1); }
214
215     friend bool operator<(const COutPoint& a, const COutPoint& b)
216     {
217         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
218     }
219
220     friend bool operator==(const COutPoint& a, const COutPoint& b)
221     {
222         return (a.hash == b.hash && a.n == b.n);
223     }
224
225     friend bool operator!=(const COutPoint& a, const COutPoint& b)
226     {
227         return !(a == b);
228     }
229
230     std::string ToString() const
231     {
232         return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
233     }
234
235     void print() const
236     {
237         printf("%s\n", ToString().c_str());
238     }
239 };
240
241
242
243
244 //
245 // An input of a transaction.  It contains the location of the previous
246 // transaction's output that it claims and a signature that matches the
247 // output's public key.
248 //
249 class CTxIn
250 {
251 public:
252     COutPoint prevout;
253     CScript scriptSig;
254     unsigned int nSequence;
255
256     CTxIn()
257     {
258         nSequence = UINT_MAX;
259     }
260
261     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
262     {
263         prevout = prevoutIn;
264         scriptSig = scriptSigIn;
265         nSequence = nSequenceIn;
266     }
267
268     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
269     {
270         prevout = COutPoint(hashPrevTx, nOut);
271         scriptSig = scriptSigIn;
272         nSequence = nSequenceIn;
273     }
274
275     IMPLEMENT_SERIALIZE
276     (
277         READWRITE(prevout);
278         READWRITE(scriptSig);
279         READWRITE(nSequence);
280     )
281
282     bool IsFinal() const
283     {
284         return (nSequence == UINT_MAX);
285     }
286
287     friend bool operator==(const CTxIn& a, const CTxIn& b)
288     {
289         return (a.prevout   == b.prevout &&
290                 a.scriptSig == b.scriptSig &&
291                 a.nSequence == b.nSequence);
292     }
293
294     friend bool operator!=(const CTxIn& a, const CTxIn& b)
295     {
296         return !(a == b);
297     }
298
299     std::string ToString() const
300     {
301         std::string str;
302         str += strprintf("CTxIn(");
303         str += prevout.ToString();
304         if (prevout.IsNull())
305             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
306         else
307             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
308         if (nSequence != UINT_MAX)
309             str += strprintf(", nSequence=%u", nSequence);
310         str += ")";
311         return str;
312     }
313
314     void print() const
315     {
316         printf("%s\n", ToString().c_str());
317     }
318 };
319
320
321
322
323 //
324 // An output of a transaction.  It contains the public key that the next input
325 // must be able to sign with to claim it.
326 //
327 class CTxOut
328 {
329 public:
330     int64 nValue;
331     CScript scriptPubKey;
332
333     CTxOut()
334     {
335         SetNull();
336     }
337
338     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
339     {
340         nValue = nValueIn;
341         scriptPubKey = scriptPubKeyIn;
342     }
343
344     IMPLEMENT_SERIALIZE
345     (
346         READWRITE(nValue);
347         READWRITE(scriptPubKey);
348     )
349
350     void SetNull()
351     {
352         nValue = -1;
353         scriptPubKey.clear();
354     }
355
356     bool IsNull()
357     {
358         return (nValue == -1);
359     }
360
361     uint256 GetHash() const
362     {
363         return SerializeHash(*this);
364     }
365
366     friend bool operator==(const CTxOut& a, const CTxOut& b)
367     {
368         return (a.nValue       == b.nValue &&
369                 a.scriptPubKey == b.scriptPubKey);
370     }
371
372     friend bool operator!=(const CTxOut& a, const CTxOut& b)
373     {
374         return !(a == b);
375     }
376
377     std::string ToString() const
378     {
379         if (scriptPubKey.size() < 6)
380             return "CTxOut(error)";
381         return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
382     }
383
384     void print() const
385     {
386         printf("%s\n", ToString().c_str());
387     }
388 };
389
390
391
392
393 //
394 // The basic transaction that is broadcasted on the network and contained in
395 // blocks.  A transaction can contain multiple inputs and outputs.
396 //
397 class CTransaction
398 {
399 public:
400     int nVersion;
401     std::vector<CTxIn> vin;
402     std::vector<CTxOut> vout;
403     unsigned int nLockTime;
404
405     // Denial-of-service detection:
406     mutable int nDoS;
407     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
408
409     CTransaction()
410     {
411         SetNull();
412     }
413
414     IMPLEMENT_SERIALIZE
415     (
416         READWRITE(this->nVersion);
417         nVersion = this->nVersion;
418         READWRITE(vin);
419         READWRITE(vout);
420         READWRITE(nLockTime);
421     )
422
423     void SetNull()
424     {
425         nVersion = 1;
426         vin.clear();
427         vout.clear();
428         nLockTime = 0;
429         nDoS = 0;  // Denial-of-service prevention
430     }
431
432     bool IsNull() const
433     {
434         return (vin.empty() && vout.empty());
435     }
436
437     uint256 GetHash() const
438     {
439         return SerializeHash(*this);
440     }
441
442     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
443     {
444         // Time based nLockTime implemented in 0.1.6
445         if (nLockTime == 0)
446             return true;
447         if (nBlockHeight == 0)
448             nBlockHeight = nBestHeight;
449         if (nBlockTime == 0)
450             nBlockTime = GetAdjustedTime();
451         if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
452             return true;
453         BOOST_FOREACH(const CTxIn& txin, vin)
454             if (!txin.IsFinal())
455                 return false;
456         return true;
457     }
458
459     bool IsNewerThan(const CTransaction& old) const
460     {
461         if (vin.size() != old.vin.size())
462             return false;
463         for (int i = 0; i < vin.size(); i++)
464             if (vin[i].prevout != old.vin[i].prevout)
465                 return false;
466
467         bool fNewer = false;
468         unsigned int nLowest = UINT_MAX;
469         for (int i = 0; i < vin.size(); i++)
470         {
471             if (vin[i].nSequence != old.vin[i].nSequence)
472             {
473                 if (vin[i].nSequence <= nLowest)
474                 {
475                     fNewer = false;
476                     nLowest = vin[i].nSequence;
477                 }
478                 if (old.vin[i].nSequence < nLowest)
479                 {
480                     fNewer = true;
481                     nLowest = old.vin[i].nSequence;
482                 }
483             }
484         }
485         return fNewer;
486     }
487
488     bool IsCoinBase() const
489     {
490         return (vin.size() == 1 && vin[0].prevout.IsNull());
491     }
492
493     int GetSigOpCount() const
494     {
495         int n = 0;
496         BOOST_FOREACH(const CTxIn& txin, vin)
497             n += txin.scriptSig.GetSigOpCount();
498         BOOST_FOREACH(const CTxOut& txout, vout)
499             n += txout.scriptPubKey.GetSigOpCount();
500         return n;
501     }
502
503     bool IsStandard() const
504     {
505         BOOST_FOREACH(const CTxIn& txin, vin)
506             if (!txin.scriptSig.IsPushOnly())
507                 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
508         BOOST_FOREACH(const CTxOut& txout, vout)
509             if (!::IsStandard(txout.scriptPubKey))
510                 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
511         return true;
512     }
513
514     int64 GetValueOut() const
515     {
516         int64 nValueOut = 0;
517         BOOST_FOREACH(const CTxOut& txout, vout)
518         {
519             nValueOut += txout.nValue;
520             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
521                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
522         }
523         return nValueOut;
524     }
525
526     static bool AllowFree(double dPriority)
527     {
528         // Large (in bytes) low-priority (new, small-coin) transactions
529         // need a fee.
530         return dPriority > COIN * 144 / 250;
531     }
532
533     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
534     {
535         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
536         int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
537
538         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
539         unsigned int nNewBlockSize = nBlockSize + nBytes;
540         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
541
542         if (fAllowFree)
543         {
544             if (nBlockSize == 1)
545             {
546                 // Transactions under 10K are free
547                 // (about 4500bc if made of 50bc inputs)
548                 if (nBytes < 10000)
549                     nMinFee = 0;
550             }
551             else
552             {
553                 // Free transaction area
554                 if (nNewBlockSize < 27000)
555                     nMinFee = 0;
556             }
557         }
558
559         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
560         if (nMinFee < nBaseFee)
561             BOOST_FOREACH(const CTxOut& txout, vout)
562                 if (txout.nValue < CENT)
563                     nMinFee = nBaseFee;
564
565         // Raise the price as the block approaches full
566         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
567         {
568             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
569                 return MAX_MONEY;
570             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
571         }
572
573         if (!MoneyRange(nMinFee))
574             nMinFee = MAX_MONEY;
575         return nMinFee;
576     }
577
578
579     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
580     {
581         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
582         if (!filein)
583             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
584
585         // Read transaction
586         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
587             return error("CTransaction::ReadFromDisk() : fseek failed");
588         filein >> *this;
589
590         // Return file pointer
591         if (pfileRet)
592         {
593             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
594                 return error("CTransaction::ReadFromDisk() : second fseek failed");
595             *pfileRet = filein.release();
596         }
597         return true;
598     }
599
600     friend bool operator==(const CTransaction& a, const CTransaction& b)
601     {
602         return (a.nVersion  == b.nVersion &&
603                 a.vin       == b.vin &&
604                 a.vout      == b.vout &&
605                 a.nLockTime == b.nLockTime);
606     }
607
608     friend bool operator!=(const CTransaction& a, const CTransaction& b)
609     {
610         return !(a == b);
611     }
612
613
614     std::string ToString() const
615     {
616         std::string str;
617         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
618             GetHash().ToString().substr(0,10).c_str(),
619             nVersion,
620             vin.size(),
621             vout.size(),
622             nLockTime);
623         for (int i = 0; i < vin.size(); i++)
624             str += "    " + vin[i].ToString() + "\n";
625         for (int i = 0; i < vout.size(); i++)
626             str += "    " + vout[i].ToString() + "\n";
627         return str;
628     }
629
630     void print() const
631     {
632         printf("%s", ToString().c_str());
633     }
634
635
636     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
637     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
638     bool ReadFromDisk(COutPoint prevout);
639     bool DisconnectInputs(CTxDB& txdb);
640     bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
641                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
642                        bool& fInvalid);
643     bool ClientConnectInputs();
644     bool CheckTransaction() const;
645     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
646     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
647 protected:
648     bool AddToMemoryPoolUnchecked();
649 public:
650     bool RemoveFromMemoryPool();
651 };
652
653
654
655
656
657 //
658 // A transaction with a merkle branch linking it to the block chain
659 //
660 class CMerkleTx : public CTransaction
661 {
662 public:
663     uint256 hashBlock;
664     std::vector<uint256> vMerkleBranch;
665     int nIndex;
666
667     // memory only
668     mutable char fMerkleVerified;
669
670
671     CMerkleTx()
672     {
673         Init();
674     }
675
676     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
677     {
678         Init();
679     }
680
681     void Init()
682     {
683         hashBlock = 0;
684         nIndex = -1;
685         fMerkleVerified = false;
686     }
687
688
689     IMPLEMENT_SERIALIZE
690     (
691         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
692         nVersion = this->nVersion;
693         READWRITE(hashBlock);
694         READWRITE(vMerkleBranch);
695         READWRITE(nIndex);
696     )
697
698
699     int SetMerkleBranch(const CBlock* pblock=NULL);
700     int GetDepthInMainChain(int& nHeightRet) const;
701     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
702     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
703     int GetBlocksToMaturity() const;
704     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
705     bool AcceptToMemoryPool();
706 };
707
708
709
710
711 //
712 // A txdb record that contains the disk location of a transaction and the
713 // locations of transactions that spend its outputs.  vSpent is really only
714 // used as a flag, but having the location is very helpful for debugging.
715 //
716 class CTxIndex
717 {
718 public:
719     CDiskTxPos pos;
720     std::vector<CDiskTxPos> vSpent;
721
722     CTxIndex()
723     {
724         SetNull();
725     }
726
727     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
728     {
729         pos = posIn;
730         vSpent.resize(nOutputs);
731     }
732
733     IMPLEMENT_SERIALIZE
734     (
735         if (!(nType & SER_GETHASH))
736             READWRITE(nVersion);
737         READWRITE(pos);
738         READWRITE(vSpent);
739     )
740
741     void SetNull()
742     {
743         pos.SetNull();
744         vSpent.clear();
745     }
746
747     bool IsNull()
748     {
749         return pos.IsNull();
750     }
751
752     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
753     {
754         return (a.pos    == b.pos &&
755                 a.vSpent == b.vSpent);
756     }
757
758     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
759     {
760         return !(a == b);
761     }
762     int GetDepthInMainChain() const;
763 };
764
765
766
767
768
769 //
770 // Nodes collect new transactions into a block, hash them into a hash tree,
771 // and scan through nonce values to make the block's hash satisfy proof-of-work
772 // requirements.  When they solve the proof-of-work, they broadcast the block
773 // to everyone and the block is added to the block chain.  The first transaction
774 // in the block is a special one that creates a new coin owned by the creator
775 // of the block.
776 //
777 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
778 // is indexed by CBlockIndex objects in memory.
779 //
780 class CBlock
781 {
782 public:
783     // header
784     int nVersion;
785     uint256 hashPrevBlock;
786     uint256 hashMerkleRoot;
787     unsigned int nTime;
788     unsigned int nBits;
789     unsigned int nNonce;
790
791     // network and disk
792     std::vector<CTransaction> vtx;
793
794     // memory only
795     mutable std::vector<uint256> vMerkleTree;
796
797     // Denial-of-service detection:
798     mutable int nDoS;
799     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
800
801     CBlock()
802     {
803         SetNull();
804     }
805
806     IMPLEMENT_SERIALIZE
807     (
808         READWRITE(this->nVersion);
809         nVersion = this->nVersion;
810         READWRITE(hashPrevBlock);
811         READWRITE(hashMerkleRoot);
812         READWRITE(nTime);
813         READWRITE(nBits);
814         READWRITE(nNonce);
815
816         // ConnectBlock depends on vtx being last so it can calculate offset
817         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
818             READWRITE(vtx);
819         else if (fRead)
820             const_cast<CBlock*>(this)->vtx.clear();
821     )
822
823     void SetNull()
824     {
825         nVersion = 1;
826         hashPrevBlock = 0;
827         hashMerkleRoot = 0;
828         nTime = 0;
829         nBits = 0;
830         nNonce = 0;
831         vtx.clear();
832         vMerkleTree.clear();
833         nDoS = 0;
834     }
835
836     bool IsNull() const
837     {
838         return (nBits == 0);
839     }
840
841     uint256 GetHash() const
842     {
843         return Hash(BEGIN(nVersion), END(nNonce));
844     }
845
846     int64 GetBlockTime() const
847     {
848         return (int64)nTime;
849     }
850
851     int GetSigOpCount() const
852     {
853         int n = 0;
854         BOOST_FOREACH(const CTransaction& tx, vtx)
855             n += tx.GetSigOpCount();
856         return n;
857     }
858
859
860     uint256 BuildMerkleTree() const
861     {
862         vMerkleTree.clear();
863         BOOST_FOREACH(const CTransaction& tx, vtx)
864             vMerkleTree.push_back(tx.GetHash());
865         int j = 0;
866         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
867         {
868             for (int i = 0; i < nSize; i += 2)
869             {
870                 int i2 = std::min(i+1, nSize-1);
871                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
872                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
873             }
874             j += nSize;
875         }
876         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
877     }
878
879     std::vector<uint256> GetMerkleBranch(int nIndex) const
880     {
881         if (vMerkleTree.empty())
882             BuildMerkleTree();
883         std::vector<uint256> vMerkleBranch;
884         int j = 0;
885         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
886         {
887             int i = std::min(nIndex^1, nSize-1);
888             vMerkleBranch.push_back(vMerkleTree[j+i]);
889             nIndex >>= 1;
890             j += nSize;
891         }
892         return vMerkleBranch;
893     }
894
895     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
896     {
897         if (nIndex == -1)
898             return 0;
899         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
900         {
901             if (nIndex & 1)
902                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
903             else
904                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
905             nIndex >>= 1;
906         }
907         return hash;
908     }
909
910
911     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
912     {
913         // Open history file to append
914         CAutoFile fileout = AppendBlockFile(nFileRet);
915         if (!fileout)
916             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
917
918         // Write index header
919         unsigned int nSize = fileout.GetSerializeSize(*this);
920         fileout << FLATDATA(pchMessageStart) << nSize;
921
922         // Write block
923         nBlockPosRet = ftell(fileout);
924         if (nBlockPosRet == -1)
925             return error("CBlock::WriteToDisk() : ftell failed");
926         fileout << *this;
927
928         // Flush stdio buffers and commit to disk before returning
929         fflush(fileout);
930         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
931         {
932 #ifdef WIN32
933             _commit(_fileno(fileout));
934 #else
935             fsync(fileno(fileout));
936 #endif
937         }
938
939         return true;
940     }
941
942     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
943     {
944         SetNull();
945
946         // Open history file to read
947         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
948         if (!filein)
949             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
950         if (!fReadTransactions)
951             filein.nType |= SER_BLOCKHEADERONLY;
952
953         // Read block
954         filein >> *this;
955
956         // Check the header
957         if (!CheckProofOfWork(GetHash(), nBits))
958             return error("CBlock::ReadFromDisk() : errors in block header");
959
960         return true;
961     }
962
963
964
965     void print() const
966     {
967         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
968             GetHash().ToString().substr(0,20).c_str(),
969             nVersion,
970             hashPrevBlock.ToString().substr(0,20).c_str(),
971             hashMerkleRoot.ToString().substr(0,10).c_str(),
972             nTime, nBits, nNonce,
973             vtx.size());
974         for (int i = 0; i < vtx.size(); i++)
975         {
976             printf("  ");
977             vtx[i].print();
978         }
979         printf("  vMerkleTree: ");
980         for (int i = 0; i < vMerkleTree.size(); i++)
981             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
982         printf("\n");
983     }
984
985
986     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
987     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
988     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
989     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
990     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
991     bool CheckBlock() const;
992     bool AcceptBlock();
993 };
994
995
996
997
998
999
1000 //
1001 // The block chain is a tree shaped structure starting with the
1002 // genesis block at the root, with each block potentially having multiple
1003 // candidates to be the next block.  pprev and pnext link a path through the
1004 // main/longest chain.  A blockindex may have multiple pprev pointing back
1005 // to it, but pnext will only point forward to the longest branch, or will
1006 // be null if the block is not part of the longest chain.
1007 //
1008 class CBlockIndex
1009 {
1010 public:
1011     const uint256* phashBlock;
1012     CBlockIndex* pprev;
1013     CBlockIndex* pnext;
1014     unsigned int nFile;
1015     unsigned int nBlockPos;
1016     int nHeight;
1017     CBigNum bnChainWork;
1018
1019     // block header
1020     int nVersion;
1021     uint256 hashMerkleRoot;
1022     unsigned int nTime;
1023     unsigned int nBits;
1024     unsigned int nNonce;
1025
1026
1027     CBlockIndex()
1028     {
1029         phashBlock = NULL;
1030         pprev = NULL;
1031         pnext = NULL;
1032         nFile = 0;
1033         nBlockPos = 0;
1034         nHeight = 0;
1035         bnChainWork = 0;
1036
1037         nVersion       = 0;
1038         hashMerkleRoot = 0;
1039         nTime          = 0;
1040         nBits          = 0;
1041         nNonce         = 0;
1042     }
1043
1044     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1045     {
1046         phashBlock = NULL;
1047         pprev = NULL;
1048         pnext = NULL;
1049         nFile = nFileIn;
1050         nBlockPos = nBlockPosIn;
1051         nHeight = 0;
1052         bnChainWork = 0;
1053
1054         nVersion       = block.nVersion;
1055         hashMerkleRoot = block.hashMerkleRoot;
1056         nTime          = block.nTime;
1057         nBits          = block.nBits;
1058         nNonce         = block.nNonce;
1059     }
1060
1061     CBlock GetBlockHeader() const
1062     {
1063         CBlock block;
1064         block.nVersion       = nVersion;
1065         if (pprev)
1066             block.hashPrevBlock = pprev->GetBlockHash();
1067         block.hashMerkleRoot = hashMerkleRoot;
1068         block.nTime          = nTime;
1069         block.nBits          = nBits;
1070         block.nNonce         = nNonce;
1071         return block;
1072     }
1073
1074     uint256 GetBlockHash() const
1075     {
1076         return *phashBlock;
1077     }
1078
1079     int64 GetBlockTime() const
1080     {
1081         return (int64)nTime;
1082     }
1083
1084     CBigNum GetBlockWork() const
1085     {
1086         CBigNum bnTarget;
1087         bnTarget.SetCompact(nBits);
1088         if (bnTarget <= 0)
1089             return 0;
1090         return (CBigNum(1)<<256) / (bnTarget+1);
1091     }
1092
1093     bool IsInMainChain() const
1094     {
1095         return (pnext || this == pindexBest);
1096     }
1097
1098     bool CheckIndex() const
1099     {
1100         return CheckProofOfWork(GetBlockHash(), nBits);
1101     }
1102
1103     bool EraseBlockFromDisk()
1104     {
1105         // Open history file
1106         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1107         if (!fileout)
1108             return false;
1109
1110         // Overwrite with empty null block
1111         CBlock block;
1112         block.SetNull();
1113         fileout << block;
1114
1115         return true;
1116     }
1117
1118     enum { nMedianTimeSpan=11 };
1119
1120     int64 GetMedianTimePast() const
1121     {
1122         int64 pmedian[nMedianTimeSpan];
1123         int64* pbegin = &pmedian[nMedianTimeSpan];
1124         int64* pend = &pmedian[nMedianTimeSpan];
1125
1126         const CBlockIndex* pindex = this;
1127         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1128             *(--pbegin) = pindex->GetBlockTime();
1129
1130         std::sort(pbegin, pend);
1131         return pbegin[(pend - pbegin)/2];
1132     }
1133
1134     int64 GetMedianTime() const
1135     {
1136         const CBlockIndex* pindex = this;
1137         for (int i = 0; i < nMedianTimeSpan/2; i++)
1138         {
1139             if (!pindex->pnext)
1140                 return GetBlockTime();
1141             pindex = pindex->pnext;
1142         }
1143         return pindex->GetMedianTimePast();
1144     }
1145
1146
1147
1148     std::string ToString() const
1149     {
1150         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1151             pprev, pnext, nFile, nBlockPos, nHeight,
1152             hashMerkleRoot.ToString().substr(0,10).c_str(),
1153             GetBlockHash().ToString().substr(0,20).c_str());
1154     }
1155
1156     void print() const
1157     {
1158         printf("%s\n", ToString().c_str());
1159     }
1160 };
1161
1162
1163
1164 //
1165 // Used to marshal pointers into hashes for db storage.
1166 //
1167 class CDiskBlockIndex : public CBlockIndex
1168 {
1169 public:
1170     uint256 hashPrev;
1171     uint256 hashNext;
1172
1173     CDiskBlockIndex()
1174     {
1175         hashPrev = 0;
1176         hashNext = 0;
1177     }
1178
1179     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1180     {
1181         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1182         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1183     }
1184
1185     IMPLEMENT_SERIALIZE
1186     (
1187         if (!(nType & SER_GETHASH))
1188             READWRITE(nVersion);
1189
1190         READWRITE(hashNext);
1191         READWRITE(nFile);
1192         READWRITE(nBlockPos);
1193         READWRITE(nHeight);
1194
1195         // block header
1196         READWRITE(this->nVersion);
1197         READWRITE(hashPrev);
1198         READWRITE(hashMerkleRoot);
1199         READWRITE(nTime);
1200         READWRITE(nBits);
1201         READWRITE(nNonce);
1202     )
1203
1204     uint256 GetBlockHash() const
1205     {
1206         CBlock block;
1207         block.nVersion        = nVersion;
1208         block.hashPrevBlock   = hashPrev;
1209         block.hashMerkleRoot  = hashMerkleRoot;
1210         block.nTime           = nTime;
1211         block.nBits           = nBits;
1212         block.nNonce          = nNonce;
1213         return block.GetHash();
1214     }
1215
1216
1217     std::string ToString() const
1218     {
1219         std::string str = "CDiskBlockIndex(";
1220         str += CBlockIndex::ToString();
1221         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1222             GetBlockHash().ToString().c_str(),
1223             hashPrev.ToString().substr(0,20).c_str(),
1224             hashNext.ToString().substr(0,20).c_str());
1225         return str;
1226     }
1227
1228     void print() const
1229     {
1230         printf("%s\n", ToString().c_str());
1231     }
1232 };
1233
1234
1235
1236
1237
1238
1239
1240
1241 //
1242 // Describes a place in the block chain to another node such that if the
1243 // other node doesn't have the same branch, it can find a recent common trunk.
1244 // The further back it is, the further before the fork it may be.
1245 //
1246 class CBlockLocator
1247 {
1248 protected:
1249     std::vector<uint256> vHave;
1250 public:
1251
1252     CBlockLocator()
1253     {
1254     }
1255
1256     explicit CBlockLocator(const CBlockIndex* pindex)
1257     {
1258         Set(pindex);
1259     }
1260
1261     explicit CBlockLocator(uint256 hashBlock)
1262     {
1263         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1264         if (mi != mapBlockIndex.end())
1265             Set((*mi).second);
1266     }
1267
1268     IMPLEMENT_SERIALIZE
1269     (
1270         if (!(nType & SER_GETHASH))
1271             READWRITE(nVersion);
1272         READWRITE(vHave);
1273     )
1274
1275     void SetNull()
1276     {
1277         vHave.clear();
1278     }
1279
1280     bool IsNull()
1281     {
1282         return vHave.empty();
1283     }
1284
1285     void Set(const CBlockIndex* pindex)
1286     {
1287         vHave.clear();
1288         int nStep = 1;
1289         while (pindex)
1290         {
1291             vHave.push_back(pindex->GetBlockHash());
1292
1293             // Exponentially larger steps back
1294             for (int i = 0; pindex && i < nStep; i++)
1295                 pindex = pindex->pprev;
1296             if (vHave.size() > 10)
1297                 nStep *= 2;
1298         }
1299         vHave.push_back(hashGenesisBlock);
1300     }
1301
1302     int GetDistanceBack()
1303     {
1304         // Retrace how far back it was in the sender's branch
1305         int nDistance = 0;
1306         int nStep = 1;
1307         BOOST_FOREACH(const uint256& hash, vHave)
1308         {
1309             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1310             if (mi != mapBlockIndex.end())
1311             {
1312                 CBlockIndex* pindex = (*mi).second;
1313                 if (pindex->IsInMainChain())
1314                     return nDistance;
1315             }
1316             nDistance += nStep;
1317             if (nDistance > 10)
1318                 nStep *= 2;
1319         }
1320         return nDistance;
1321     }
1322
1323     CBlockIndex* GetBlockIndex()
1324     {
1325         // Find the first block the caller has in the main chain
1326         BOOST_FOREACH(const uint256& hash, vHave)
1327         {
1328             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1329             if (mi != mapBlockIndex.end())
1330             {
1331                 CBlockIndex* pindex = (*mi).second;
1332                 if (pindex->IsInMainChain())
1333                     return pindex;
1334             }
1335         }
1336         return pindexGenesisBlock;
1337     }
1338
1339     uint256 GetBlockHash()
1340     {
1341         // Find the first block the caller has in the main chain
1342         BOOST_FOREACH(const uint256& hash, vHave)
1343         {
1344             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1345             if (mi != mapBlockIndex.end())
1346             {
1347                 CBlockIndex* pindex = (*mi).second;
1348                 if (pindex->IsInMainChain())
1349                     return hash;
1350             }
1351         }
1352         return hashGenesisBlock;
1353     }
1354
1355     int GetHeight()
1356     {
1357         CBlockIndex* pindex = GetBlockIndex();
1358         if (!pindex)
1359             return 0;
1360         return pindex->nHeight;
1361     }
1362 };
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372 //
1373 // Alerts are for notifying old versions if they become too obsolete and
1374 // need to upgrade.  The message is displayed in the status bar.
1375 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1376 // not read the entire buffer if the alert is for a newer version, but older
1377 // versions can still relay the original data.
1378 //
1379 class CUnsignedAlert
1380 {
1381 public:
1382     int nVersion;
1383     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1384     int64 nExpiration;
1385     int nID;
1386     int nCancel;
1387     std::set<int> setCancel;
1388     int nMinVer;            // lowest version inclusive
1389     int nMaxVer;            // highest version inclusive
1390     std::set<std::string> setSubVer;  // empty matches all
1391     int nPriority;
1392
1393     // Actions
1394     std::string strComment;
1395     std::string strStatusBar;
1396     std::string strReserved;
1397
1398     IMPLEMENT_SERIALIZE
1399     (
1400         READWRITE(this->nVersion);
1401         nVersion = this->nVersion;
1402         READWRITE(nRelayUntil);
1403         READWRITE(nExpiration);
1404         READWRITE(nID);
1405         READWRITE(nCancel);
1406         READWRITE(setCancel);
1407         READWRITE(nMinVer);
1408         READWRITE(nMaxVer);
1409         READWRITE(setSubVer);
1410         READWRITE(nPriority);
1411
1412         READWRITE(strComment);
1413         READWRITE(strStatusBar);
1414         READWRITE(strReserved);
1415     )
1416
1417     void SetNull()
1418     {
1419         nVersion = 1;
1420         nRelayUntil = 0;
1421         nExpiration = 0;
1422         nID = 0;
1423         nCancel = 0;
1424         setCancel.clear();
1425         nMinVer = 0;
1426         nMaxVer = 0;
1427         setSubVer.clear();
1428         nPriority = 0;
1429
1430         strComment.clear();
1431         strStatusBar.clear();
1432         strReserved.clear();
1433     }
1434
1435     std::string ToString() const
1436     {
1437         std::string strSetCancel;
1438         BOOST_FOREACH(int n, setCancel)
1439             strSetCancel += strprintf("%d ", n);
1440         std::string strSetSubVer;
1441         BOOST_FOREACH(std::string str, setSubVer)
1442             strSetSubVer += "\"" + str + "\" ";
1443         return strprintf(
1444                 "CAlert(\n"
1445                 "    nVersion     = %d\n"
1446                 "    nRelayUntil  = %"PRI64d"\n"
1447                 "    nExpiration  = %"PRI64d"\n"
1448                 "    nID          = %d\n"
1449                 "    nCancel      = %d\n"
1450                 "    setCancel    = %s\n"
1451                 "    nMinVer      = %d\n"
1452                 "    nMaxVer      = %d\n"
1453                 "    setSubVer    = %s\n"
1454                 "    nPriority    = %d\n"
1455                 "    strComment   = \"%s\"\n"
1456                 "    strStatusBar = \"%s\"\n"
1457                 ")\n",
1458             nVersion,
1459             nRelayUntil,
1460             nExpiration,
1461             nID,
1462             nCancel,
1463             strSetCancel.c_str(),
1464             nMinVer,
1465             nMaxVer,
1466             strSetSubVer.c_str(),
1467             nPriority,
1468             strComment.c_str(),
1469             strStatusBar.c_str());
1470     }
1471
1472     void print() const
1473     {
1474         printf("%s", ToString().c_str());
1475     }
1476 };
1477
1478 class CAlert : public CUnsignedAlert
1479 {
1480 public:
1481     std::vector<unsigned char> vchMsg;
1482     std::vector<unsigned char> vchSig;
1483
1484     CAlert()
1485     {
1486         SetNull();
1487     }
1488
1489     IMPLEMENT_SERIALIZE
1490     (
1491         READWRITE(vchMsg);
1492         READWRITE(vchSig);
1493     )
1494
1495     void SetNull()
1496     {
1497         CUnsignedAlert::SetNull();
1498         vchMsg.clear();
1499         vchSig.clear();
1500     }
1501
1502     bool IsNull() const
1503     {
1504         return (nExpiration == 0);
1505     }
1506
1507     uint256 GetHash() const
1508     {
1509         return SerializeHash(*this);
1510     }
1511
1512     bool IsInEffect() const
1513     {
1514         return (GetAdjustedTime() < nExpiration);
1515     }
1516
1517     bool Cancels(const CAlert& alert) const
1518     {
1519         if (!IsInEffect())
1520             return false; // this was a no-op before 31403
1521         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1522     }
1523
1524     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1525     {
1526         return (IsInEffect() &&
1527                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1528                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1529     }
1530
1531     bool AppliesToMe() const
1532     {
1533         return AppliesTo(VERSION, ::pszSubVer);
1534     }
1535
1536     bool RelayTo(CNode* pnode) const
1537     {
1538         if (!IsInEffect())
1539             return false;
1540         // returns true if wasn't already contained in the set
1541         if (pnode->setKnown.insert(GetHash()).second)
1542         {
1543             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1544                 AppliesToMe() ||
1545                 GetAdjustedTime() < nRelayUntil)
1546             {
1547                 pnode->PushMessage("alert", *this);
1548                 return true;
1549             }
1550         }
1551         return false;
1552     }
1553
1554     bool CheckSignature()
1555     {
1556         CKey key;
1557         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1558             return error("CAlert::CheckSignature() : SetPubKey failed");
1559         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1560             return error("CAlert::CheckSignature() : verify signature failed");
1561
1562         // Now unserialize the data
1563         CDataStream sMsg(vchMsg);
1564         sMsg >> *(CUnsignedAlert*)this;
1565         return true;
1566     }
1567
1568     bool ProcessAlert();
1569 };
1570
1571 #endif