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