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