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