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