OP_EVAL implementation
[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     bool IsStandard() const;
497     bool IsStandardInputs(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const;
498
499     int64 GetValueOut() const
500     {
501         int64 nValueOut = 0;
502         BOOST_FOREACH(const CTxOut& txout, vout)
503         {
504             nValueOut += txout.nValue;
505             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
506                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
507         }
508         return nValueOut;
509     }
510
511     static bool AllowFree(double dPriority)
512     {
513         // Large (in bytes) low-priority (new, small-coin) transactions
514         // need a fee.
515         return dPriority > COIN * 144 / 250;
516     }
517
518     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
519     {
520         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
521         int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
522
523         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
524         unsigned int nNewBlockSize = nBlockSize + nBytes;
525         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
526
527         if (fAllowFree)
528         {
529             if (nBlockSize == 1)
530             {
531                 // Transactions under 10K are free
532                 // (about 4500bc if made of 50bc inputs)
533                 if (nBytes < 10000)
534                     nMinFee = 0;
535             }
536             else
537             {
538                 // Free transaction area
539                 if (nNewBlockSize < 27000)
540                     nMinFee = 0;
541             }
542         }
543
544         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
545         if (nMinFee < nBaseFee)
546             BOOST_FOREACH(const CTxOut& txout, vout)
547                 if (txout.nValue < CENT)
548                     nMinFee = nBaseFee;
549
550         // Raise the price as the block approaches full
551         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
552         {
553             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
554                 return MAX_MONEY;
555             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
556         }
557
558         if (!MoneyRange(nMinFee))
559             nMinFee = MAX_MONEY;
560         return nMinFee;
561     }
562
563
564     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
565     {
566         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
567         if (!filein)
568             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
569
570         // Read transaction
571         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
572             return error("CTransaction::ReadFromDisk() : fseek failed");
573         filein >> *this;
574
575         // Return file pointer
576         if (pfileRet)
577         {
578             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
579                 return error("CTransaction::ReadFromDisk() : second fseek failed");
580             *pfileRet = filein.release();
581         }
582         return true;
583     }
584
585     friend bool operator==(const CTransaction& a, const CTransaction& b)
586     {
587         return (a.nVersion  == b.nVersion &&
588                 a.vin       == b.vin &&
589                 a.vout      == b.vout &&
590                 a.nLockTime == b.nLockTime);
591     }
592
593     friend bool operator!=(const CTransaction& a, const CTransaction& b)
594     {
595         return !(a == b);
596     }
597
598
599     std::string ToString() const
600     {
601         std::string str;
602         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
603             GetHash().ToString().substr(0,10).c_str(),
604             nVersion,
605             vin.size(),
606             vout.size(),
607             nLockTime);
608         for (int i = 0; i < vin.size(); i++)
609             str += "    " + vin[i].ToString() + "\n";
610         for (int i = 0; i < vout.size(); i++)
611             str += "    " + vout[i].ToString() + "\n";
612         return str;
613     }
614
615     void print() const
616     {
617         printf("%s", ToString().c_str());
618     }
619
620
621     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
622     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
623     bool ReadFromDisk(COutPoint prevout);
624     bool DisconnectInputs(CTxDB& txdb);
625     bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
626                      bool fBlock, bool fMiner, std::map<uint256, std::pair<CTxIndex, CTransaction> >& inputsRet);
627     bool ConnectInputs(std::map<uint256, std::pair<CTxIndex, CTransaction> > inputs,
628                        std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
629                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee=0);
630     bool ClientConnectInputs();
631     bool CheckTransaction() const;
632     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
633     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
634 protected:
635     bool AddToMemoryPoolUnchecked();
636 public:
637     bool RemoveFromMemoryPool();
638 };
639
640
641
642
643
644 //
645 // A transaction with a merkle branch linking it to the block chain
646 //
647 class CMerkleTx : public CTransaction
648 {
649 public:
650     uint256 hashBlock;
651     std::vector<uint256> vMerkleBranch;
652     int nIndex;
653
654     // memory only
655     mutable char fMerkleVerified;
656
657
658     CMerkleTx()
659     {
660         Init();
661     }
662
663     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
664     {
665         Init();
666     }
667
668     void Init()
669     {
670         hashBlock = 0;
671         nIndex = -1;
672         fMerkleVerified = false;
673     }
674
675
676     IMPLEMENT_SERIALIZE
677     (
678         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
679         nVersion = this->nVersion;
680         READWRITE(hashBlock);
681         READWRITE(vMerkleBranch);
682         READWRITE(nIndex);
683     )
684
685
686     int SetMerkleBranch(const CBlock* pblock=NULL);
687     int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
688     int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
689     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
690     int GetBlocksToMaturity() const;
691     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
692     bool AcceptToMemoryPool();
693 };
694
695
696
697
698 //
699 // A txdb record that contains the disk location of a transaction and the
700 // locations of transactions that spend its outputs.  vSpent is really only
701 // used as a flag, but having the location is very helpful for debugging.
702 //
703 class CTxIndex
704 {
705 public:
706     CDiskTxPos pos;
707     std::vector<CDiskTxPos> vSpent;
708
709     CTxIndex()
710     {
711         SetNull();
712     }
713
714     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
715     {
716         pos = posIn;
717         vSpent.resize(nOutputs);
718     }
719
720     IMPLEMENT_SERIALIZE
721     (
722         if (!(nType & SER_GETHASH))
723             READWRITE(nVersion);
724         READWRITE(pos);
725         READWRITE(vSpent);
726     )
727
728     void SetNull()
729     {
730         pos.SetNull();
731         vSpent.clear();
732     }
733
734     bool IsNull()
735     {
736         return pos.IsNull();
737     }
738
739     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
740     {
741         return (a.pos    == b.pos &&
742                 a.vSpent == b.vSpent);
743     }
744
745     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
746     {
747         return !(a == b);
748     }
749     int GetDepthInMainChain() const;
750  
751 };
752
753
754
755
756
757 //
758 // Nodes collect new transactions into a block, hash them into a hash tree,
759 // and scan through nonce values to make the block's hash satisfy proof-of-work
760 // requirements.  When they solve the proof-of-work, they broadcast the block
761 // to everyone and the block is added to the block chain.  The first transaction
762 // in the block is a special one that creates a new coin owned by the creator
763 // of the block.
764 //
765 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
766 // is indexed by CBlockIndex objects in memory.
767 //
768 class CBlock
769 {
770 public:
771     // header
772     int nVersion;
773     uint256 hashPrevBlock;
774     uint256 hashMerkleRoot;
775     unsigned int nTime;
776     unsigned int nBits;
777     unsigned int nNonce;
778
779     // network and disk
780     std::vector<CTransaction> vtx;
781
782     // memory only
783     mutable std::vector<uint256> vMerkleTree;
784
785     // Denial-of-service detection:
786     mutable int nDoS;
787     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
788
789     CBlock()
790     {
791         SetNull();
792     }
793
794     IMPLEMENT_SERIALIZE
795     (
796         READWRITE(this->nVersion);
797         nVersion = this->nVersion;
798         READWRITE(hashPrevBlock);
799         READWRITE(hashMerkleRoot);
800         READWRITE(nTime);
801         READWRITE(nBits);
802         READWRITE(nNonce);
803
804         // ConnectBlock depends on vtx being last so it can calculate offset
805         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
806             READWRITE(vtx);
807         else if (fRead)
808             const_cast<CBlock*>(this)->vtx.clear();
809     )
810
811     void SetNull()
812     {
813         nVersion = 1;
814         hashPrevBlock = 0;
815         hashMerkleRoot = 0;
816         nTime = 0;
817         nBits = 0;
818         nNonce = 0;
819         vtx.clear();
820         vMerkleTree.clear();
821         nDoS = 0;
822     }
823
824     bool IsNull() const
825     {
826         return (nBits == 0);
827     }
828
829     uint256 GetHash() const
830     {
831         return Hash(BEGIN(nVersion), END(nNonce));
832     }
833
834     int64 GetBlockTime() const
835     {
836         return (int64)nTime;
837     }
838
839
840
841     uint256 BuildMerkleTree() const
842     {
843         vMerkleTree.clear();
844         BOOST_FOREACH(const CTransaction& tx, vtx)
845             vMerkleTree.push_back(tx.GetHash());
846         int j = 0;
847         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
848         {
849             for (int i = 0; i < nSize; i += 2)
850             {
851                 int i2 = std::min(i+1, nSize-1);
852                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
853                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
854             }
855             j += nSize;
856         }
857         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
858     }
859
860     std::vector<uint256> GetMerkleBranch(int nIndex) const
861     {
862         if (vMerkleTree.empty())
863             BuildMerkleTree();
864         std::vector<uint256> vMerkleBranch;
865         int j = 0;
866         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
867         {
868             int i = std::min(nIndex^1, nSize-1);
869             vMerkleBranch.push_back(vMerkleTree[j+i]);
870             nIndex >>= 1;
871             j += nSize;
872         }
873         return vMerkleBranch;
874     }
875
876     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
877     {
878         if (nIndex == -1)
879             return 0;
880         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
881         {
882             if (nIndex & 1)
883                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
884             else
885                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
886             nIndex >>= 1;
887         }
888         return hash;
889     }
890
891
892     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
893     {
894         // Open history file to append
895         CAutoFile fileout = AppendBlockFile(nFileRet);
896         if (!fileout)
897             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
898
899         // Write index header
900         unsigned int nSize = fileout.GetSerializeSize(*this);
901         fileout << FLATDATA(pchMessageStart) << nSize;
902
903         // Write block
904         nBlockPosRet = ftell(fileout);
905         if (nBlockPosRet == -1)
906             return error("CBlock::WriteToDisk() : ftell failed");
907         fileout << *this;
908
909         // Flush stdio buffers and commit to disk before returning
910         fflush(fileout);
911         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
912         {
913 #ifdef WIN32
914             _commit(_fileno(fileout));
915 #else
916             fsync(fileno(fileout));
917 #endif
918         }
919
920         return true;
921     }
922
923     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
924     {
925         SetNull();
926
927         // Open history file to read
928         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
929         if (!filein)
930             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
931         if (!fReadTransactions)
932             filein.nType |= SER_BLOCKHEADERONLY;
933
934         // Read block
935         filein >> *this;
936
937         // Check the header
938         if (!CheckProofOfWork(GetHash(), nBits))
939             return error("CBlock::ReadFromDisk() : errors in block header");
940
941         return true;
942     }
943
944
945
946     void print() const
947     {
948         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
949             GetHash().ToString().substr(0,20).c_str(),
950             nVersion,
951             hashPrevBlock.ToString().substr(0,20).c_str(),
952             hashMerkleRoot.ToString().substr(0,10).c_str(),
953             nTime, nBits, nNonce,
954             vtx.size());
955         for (int i = 0; i < vtx.size(); i++)
956         {
957             printf("  ");
958             vtx[i].print();
959         }
960         printf("  vMerkleTree: ");
961         for (int i = 0; i < vMerkleTree.size(); i++)
962             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
963         printf("\n");
964     }
965
966
967     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
968     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
969     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
970     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
971     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
972     bool CheckBlock() const;
973     bool AcceptBlock();
974 };
975
976
977
978
979
980
981 //
982 // The block chain is a tree shaped structure starting with the
983 // genesis block at the root, with each block potentially having multiple
984 // candidates to be the next block.  pprev and pnext link a path through the
985 // main/longest chain.  A blockindex may have multiple pprev pointing back
986 // to it, but pnext will only point forward to the longest branch, or will
987 // be null if the block is not part of the longest chain.
988 //
989 class CBlockIndex
990 {
991 public:
992     const uint256* phashBlock;
993     CBlockIndex* pprev;
994     CBlockIndex* pnext;
995     unsigned int nFile;
996     unsigned int nBlockPos;
997     int nHeight;
998     CBigNum bnChainWork;
999
1000     // block header
1001     int nVersion;
1002     uint256 hashMerkleRoot;
1003     unsigned int nTime;
1004     unsigned int nBits;
1005     unsigned int nNonce;
1006
1007
1008     CBlockIndex()
1009     {
1010         phashBlock = NULL;
1011         pprev = NULL;
1012         pnext = NULL;
1013         nFile = 0;
1014         nBlockPos = 0;
1015         nHeight = 0;
1016         bnChainWork = 0;
1017
1018         nVersion       = 0;
1019         hashMerkleRoot = 0;
1020         nTime          = 0;
1021         nBits          = 0;
1022         nNonce         = 0;
1023     }
1024
1025     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1026     {
1027         phashBlock = NULL;
1028         pprev = NULL;
1029         pnext = NULL;
1030         nFile = nFileIn;
1031         nBlockPos = nBlockPosIn;
1032         nHeight = 0;
1033         bnChainWork = 0;
1034
1035         nVersion       = block.nVersion;
1036         hashMerkleRoot = block.hashMerkleRoot;
1037         nTime          = block.nTime;
1038         nBits          = block.nBits;
1039         nNonce         = block.nNonce;
1040     }
1041
1042     CBlock GetBlockHeader() const
1043     {
1044         CBlock block;
1045         block.nVersion       = nVersion;
1046         if (pprev)
1047             block.hashPrevBlock = pprev->GetBlockHash();
1048         block.hashMerkleRoot = hashMerkleRoot;
1049         block.nTime          = nTime;
1050         block.nBits          = nBits;
1051         block.nNonce         = nNonce;
1052         return block;
1053     }
1054
1055     uint256 GetBlockHash() const
1056     {
1057         return *phashBlock;
1058     }
1059
1060     int64 GetBlockTime() const
1061     {
1062         return (int64)nTime;
1063     }
1064
1065     CBigNum GetBlockWork() const
1066     {
1067         CBigNum bnTarget;
1068         bnTarget.SetCompact(nBits);
1069         if (bnTarget <= 0)
1070             return 0;
1071         return (CBigNum(1)<<256) / (bnTarget+1);
1072     }
1073
1074     bool IsInMainChain() const
1075     {
1076         return (pnext || this == pindexBest);
1077     }
1078
1079     bool CheckIndex() const
1080     {
1081         return CheckProofOfWork(GetBlockHash(), nBits);
1082     }
1083
1084     bool EraseBlockFromDisk()
1085     {
1086         // Open history file
1087         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1088         if (!fileout)
1089             return false;
1090
1091         // Overwrite with empty null block
1092         CBlock block;
1093         block.SetNull();
1094         fileout << block;
1095
1096         return true;
1097     }
1098
1099     enum { nMedianTimeSpan=11 };
1100
1101     int64 GetMedianTimePast() const
1102     {
1103         int64 pmedian[nMedianTimeSpan];
1104         int64* pbegin = &pmedian[nMedianTimeSpan];
1105         int64* pend = &pmedian[nMedianTimeSpan];
1106
1107         const CBlockIndex* pindex = this;
1108         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1109             *(--pbegin) = pindex->GetBlockTime();
1110
1111         std::sort(pbegin, pend);
1112         return pbegin[(pend - pbegin)/2];
1113     }
1114
1115     int64 GetMedianTime() const
1116     {
1117         const CBlockIndex* pindex = this;
1118         for (int i = 0; i < nMedianTimeSpan/2; i++)
1119         {
1120             if (!pindex->pnext)
1121                 return GetBlockTime();
1122             pindex = pindex->pnext;
1123         }
1124         return pindex->GetMedianTimePast();
1125     }
1126
1127
1128
1129     std::string ToString() const
1130     {
1131         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1132             pprev, pnext, nFile, nBlockPos, nHeight,
1133             hashMerkleRoot.ToString().substr(0,10).c_str(),
1134             GetBlockHash().ToString().substr(0,20).c_str());
1135     }
1136
1137     void print() const
1138     {
1139         printf("%s\n", ToString().c_str());
1140     }
1141 };
1142
1143
1144
1145 //
1146 // Used to marshal pointers into hashes for db storage.
1147 //
1148 class CDiskBlockIndex : public CBlockIndex
1149 {
1150 public:
1151     uint256 hashPrev;
1152     uint256 hashNext;
1153
1154     CDiskBlockIndex()
1155     {
1156         hashPrev = 0;
1157         hashNext = 0;
1158     }
1159
1160     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1161     {
1162         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1163         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1164     }
1165
1166     IMPLEMENT_SERIALIZE
1167     (
1168         if (!(nType & SER_GETHASH))
1169             READWRITE(nVersion);
1170
1171         READWRITE(hashNext);
1172         READWRITE(nFile);
1173         READWRITE(nBlockPos);
1174         READWRITE(nHeight);
1175
1176         // block header
1177         READWRITE(this->nVersion);
1178         READWRITE(hashPrev);
1179         READWRITE(hashMerkleRoot);
1180         READWRITE(nTime);
1181         READWRITE(nBits);
1182         READWRITE(nNonce);
1183     )
1184
1185     uint256 GetBlockHash() const
1186     {
1187         CBlock block;
1188         block.nVersion        = nVersion;
1189         block.hashPrevBlock   = hashPrev;
1190         block.hashMerkleRoot  = hashMerkleRoot;
1191         block.nTime           = nTime;
1192         block.nBits           = nBits;
1193         block.nNonce          = nNonce;
1194         return block.GetHash();
1195     }
1196
1197
1198     std::string ToString() const
1199     {
1200         std::string str = "CDiskBlockIndex(";
1201         str += CBlockIndex::ToString();
1202         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1203             GetBlockHash().ToString().c_str(),
1204             hashPrev.ToString().substr(0,20).c_str(),
1205             hashNext.ToString().substr(0,20).c_str());
1206         return str;
1207     }
1208
1209     void print() const
1210     {
1211         printf("%s\n", ToString().c_str());
1212     }
1213 };
1214
1215
1216
1217
1218
1219
1220
1221
1222 //
1223 // Describes a place in the block chain to another node such that if the
1224 // other node doesn't have the same branch, it can find a recent common trunk.
1225 // The further back it is, the further before the fork it may be.
1226 //
1227 class CBlockLocator
1228 {
1229 protected:
1230     std::vector<uint256> vHave;
1231 public:
1232
1233     CBlockLocator()
1234     {
1235     }
1236
1237     explicit CBlockLocator(const CBlockIndex* pindex)
1238     {
1239         Set(pindex);
1240     }
1241
1242     explicit CBlockLocator(uint256 hashBlock)
1243     {
1244         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1245         if (mi != mapBlockIndex.end())
1246             Set((*mi).second);
1247     }
1248
1249     CBlockLocator(const std::vector<uint256>& vHaveIn)
1250     {
1251         vHave = vHaveIn;
1252     }
1253
1254     IMPLEMENT_SERIALIZE
1255     (
1256         if (!(nType & SER_GETHASH))
1257             READWRITE(nVersion);
1258         READWRITE(vHave);
1259     )
1260
1261     void SetNull()
1262     {
1263         vHave.clear();
1264     }
1265
1266     bool IsNull()
1267     {
1268         return vHave.empty();
1269     }
1270
1271     void Set(const CBlockIndex* pindex)
1272     {
1273         vHave.clear();
1274         int nStep = 1;
1275         while (pindex)
1276         {
1277             vHave.push_back(pindex->GetBlockHash());
1278
1279             // Exponentially larger steps back
1280             for (int i = 0; pindex && i < nStep; i++)
1281                 pindex = pindex->pprev;
1282             if (vHave.size() > 10)
1283                 nStep *= 2;
1284         }
1285         vHave.push_back(hashGenesisBlock);
1286     }
1287
1288     int GetDistanceBack()
1289     {
1290         // Retrace how far back it was in the sender's branch
1291         int nDistance = 0;
1292         int nStep = 1;
1293         BOOST_FOREACH(const uint256& hash, vHave)
1294         {
1295             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1296             if (mi != mapBlockIndex.end())
1297             {
1298                 CBlockIndex* pindex = (*mi).second;
1299                 if (pindex->IsInMainChain())
1300                     return nDistance;
1301             }
1302             nDistance += nStep;
1303             if (nDistance > 10)
1304                 nStep *= 2;
1305         }
1306         return nDistance;
1307     }
1308
1309     CBlockIndex* GetBlockIndex()
1310     {
1311         // Find the first block the caller has in the main chain
1312         BOOST_FOREACH(const uint256& hash, vHave)
1313         {
1314             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1315             if (mi != mapBlockIndex.end())
1316             {
1317                 CBlockIndex* pindex = (*mi).second;
1318                 if (pindex->IsInMainChain())
1319                     return pindex;
1320             }
1321         }
1322         return pindexGenesisBlock;
1323     }
1324
1325     uint256 GetBlockHash()
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 hash;
1336             }
1337         }
1338         return hashGenesisBlock;
1339     }
1340
1341     int GetHeight()
1342     {
1343         CBlockIndex* pindex = GetBlockIndex();
1344         if (!pindex)
1345             return 0;
1346         return pindex->nHeight;
1347     }
1348 };
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358 //
1359 // Alerts are for notifying old versions if they become too obsolete and
1360 // need to upgrade.  The message is displayed in the status bar.
1361 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1362 // not read the entire buffer if the alert is for a newer version, but older
1363 // versions can still relay the original data.
1364 //
1365 class CUnsignedAlert
1366 {
1367 public:
1368     int nVersion;
1369     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1370     int64 nExpiration;
1371     int nID;
1372     int nCancel;
1373     std::set<int> setCancel;
1374     int nMinVer;            // lowest version inclusive
1375     int nMaxVer;            // highest version inclusive
1376     std::set<std::string> setSubVer;  // empty matches all
1377     int nPriority;
1378
1379     // Actions
1380     std::string strComment;
1381     std::string strStatusBar;
1382     std::string strReserved;
1383
1384     IMPLEMENT_SERIALIZE
1385     (
1386         READWRITE(this->nVersion);
1387         nVersion = this->nVersion;
1388         READWRITE(nRelayUntil);
1389         READWRITE(nExpiration);
1390         READWRITE(nID);
1391         READWRITE(nCancel);
1392         READWRITE(setCancel);
1393         READWRITE(nMinVer);
1394         READWRITE(nMaxVer);
1395         READWRITE(setSubVer);
1396         READWRITE(nPriority);
1397
1398         READWRITE(strComment);
1399         READWRITE(strStatusBar);
1400         READWRITE(strReserved);
1401     )
1402
1403     void SetNull()
1404     {
1405         nVersion = 1;
1406         nRelayUntil = 0;
1407         nExpiration = 0;
1408         nID = 0;
1409         nCancel = 0;
1410         setCancel.clear();
1411         nMinVer = 0;
1412         nMaxVer = 0;
1413         setSubVer.clear();
1414         nPriority = 0;
1415
1416         strComment.clear();
1417         strStatusBar.clear();
1418         strReserved.clear();
1419     }
1420
1421     std::string ToString() const
1422     {
1423         std::string strSetCancel;
1424         BOOST_FOREACH(int n, setCancel)
1425             strSetCancel += strprintf("%d ", n);
1426         std::string strSetSubVer;
1427         BOOST_FOREACH(std::string str, setSubVer)
1428             strSetSubVer += "\"" + str + "\" ";
1429         return strprintf(
1430                 "CAlert(\n"
1431                 "    nVersion     = %d\n"
1432                 "    nRelayUntil  = %"PRI64d"\n"
1433                 "    nExpiration  = %"PRI64d"\n"
1434                 "    nID          = %d\n"
1435                 "    nCancel      = %d\n"
1436                 "    setCancel    = %s\n"
1437                 "    nMinVer      = %d\n"
1438                 "    nMaxVer      = %d\n"
1439                 "    setSubVer    = %s\n"
1440                 "    nPriority    = %d\n"
1441                 "    strComment   = \"%s\"\n"
1442                 "    strStatusBar = \"%s\"\n"
1443                 ")\n",
1444             nVersion,
1445             nRelayUntil,
1446             nExpiration,
1447             nID,
1448             nCancel,
1449             strSetCancel.c_str(),
1450             nMinVer,
1451             nMaxVer,
1452             strSetSubVer.c_str(),
1453             nPriority,
1454             strComment.c_str(),
1455             strStatusBar.c_str());
1456     }
1457
1458     void print() const
1459     {
1460         printf("%s", ToString().c_str());
1461     }
1462 };
1463
1464 class CAlert : public CUnsignedAlert
1465 {
1466 public:
1467     std::vector<unsigned char> vchMsg;
1468     std::vector<unsigned char> vchSig;
1469
1470     CAlert()
1471     {
1472         SetNull();
1473     }
1474
1475     IMPLEMENT_SERIALIZE
1476     (
1477         READWRITE(vchMsg);
1478         READWRITE(vchSig);
1479     )
1480
1481     void SetNull()
1482     {
1483         CUnsignedAlert::SetNull();
1484         vchMsg.clear();
1485         vchSig.clear();
1486     }
1487
1488     bool IsNull() const
1489     {
1490         return (nExpiration == 0);
1491     }
1492
1493     uint256 GetHash() const
1494     {
1495         return SerializeHash(*this);
1496     }
1497
1498     bool IsInEffect() const
1499     {
1500         return (GetAdjustedTime() < nExpiration);
1501     }
1502
1503     bool Cancels(const CAlert& alert) const
1504     {
1505         if (!IsInEffect())
1506             return false; // this was a no-op before 31403
1507         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1508     }
1509
1510     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1511     {
1512         // TODO: rework for client-version-embedded-in-strSubVer ?
1513         return (IsInEffect() &&
1514                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1515                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1516     }
1517
1518     bool AppliesToMe() const
1519     {
1520         return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
1521     }
1522
1523     bool RelayTo(CNode* pnode) const
1524     {
1525         if (!IsInEffect())
1526             return false;
1527         // returns true if wasn't already contained in the set
1528         if (pnode->setKnown.insert(GetHash()).second)
1529         {
1530             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1531                 AppliesToMe() ||
1532                 GetAdjustedTime() < nRelayUntil)
1533             {
1534                 pnode->PushMessage("alert", *this);
1535                 return true;
1536             }
1537         }
1538         return false;
1539     }
1540
1541     bool CheckSignature()
1542     {
1543         CKey key;
1544         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1545             return error("CAlert::CheckSignature() : SetPubKey failed");
1546         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1547             return error("CAlert::CheckSignature() : verify signature failed");
1548
1549         // Now unserialize the data
1550         CDataStream sMsg(vchMsg);
1551         sMsg >> *(CUnsignedAlert*)this;
1552         return true;
1553     }
1554
1555     bool ProcessAlert();
1556 };
1557
1558 #endif