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