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