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