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