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