GetMinFee takes a mode parameter (GMF_{BLOCK,RELAY,SEND}) instead of fForRelay
[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 enum GetMinFee_mode
391 {
392     GMF_BLOCK,
393     GMF_RELAY,
394     GMF_SEND,
395 };
396
397 //
398 // The basic transaction that is broadcasted on the network and contained in
399 // blocks.  A transaction can contain multiple inputs and outputs.
400 //
401 class CTransaction
402 {
403 public:
404     int nVersion;
405     std::vector<CTxIn> vin;
406     std::vector<CTxOut> vout;
407     unsigned int nLockTime;
408
409
410     CTransaction()
411     {
412         SetNull();
413     }
414
415     IMPLEMENT_SERIALIZE
416     (
417         READWRITE(this->nVersion);
418         nVersion = this->nVersion;
419         READWRITE(vin);
420         READWRITE(vout);
421         READWRITE(nLockTime);
422     )
423
424     void SetNull()
425     {
426         nVersion = 1;
427         vin.clear();
428         vout.clear();
429         nLockTime = 0;
430     }
431
432     bool IsNull() const
433     {
434         return (vin.empty() && vout.empty());
435     }
436
437     uint256 GetHash() const
438     {
439         return SerializeHash(*this);
440     }
441
442     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
443     {
444         // Time based nLockTime implemented in 0.1.6
445         if (nLockTime == 0)
446             return true;
447         if (nBlockHeight == 0)
448             nBlockHeight = nBestHeight;
449         if (nBlockTime == 0)
450             nBlockTime = GetAdjustedTime();
451         if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
452             return true;
453         BOOST_FOREACH(const CTxIn& txin, vin)
454             if (!txin.IsFinal())
455                 return false;
456         return true;
457     }
458
459     bool IsNewerThan(const CTransaction& old) const
460     {
461         if (vin.size() != old.vin.size())
462             return false;
463         for (int i = 0; i < vin.size(); i++)
464             if (vin[i].prevout != old.vin[i].prevout)
465                 return false;
466
467         bool fNewer = false;
468         unsigned int nLowest = UINT_MAX;
469         for (int i = 0; i < vin.size(); i++)
470         {
471             if (vin[i].nSequence != old.vin[i].nSequence)
472             {
473                 if (vin[i].nSequence <= nLowest)
474                 {
475                     fNewer = false;
476                     nLowest = vin[i].nSequence;
477                 }
478                 if (old.vin[i].nSequence < nLowest)
479                 {
480                     fNewer = true;
481                     nLowest = old.vin[i].nSequence;
482                 }
483             }
484         }
485         return fNewer;
486     }
487
488     bool IsCoinBase() const
489     {
490         return (vin.size() == 1 && vin[0].prevout.IsNull());
491     }
492
493     int GetSigOpCount() const
494     {
495         int n = 0;
496         BOOST_FOREACH(const CTxIn& txin, vin)
497             n += txin.scriptSig.GetSigOpCount();
498         BOOST_FOREACH(const CTxOut& txout, vout)
499             n += txout.scriptPubKey.GetSigOpCount();
500         return n;
501     }
502
503     bool IsStandard() const
504     {
505         BOOST_FOREACH(const CTxIn& txin, vin)
506             if (!txin.scriptSig.IsPushOnly())
507                 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
508         BOOST_FOREACH(const CTxOut& txout, vout)
509             if (!::IsStandard(txout.scriptPubKey))
510                 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
511         return true;
512     }
513
514     int64 GetValueOut() const
515     {
516         int64 nValueOut = 0;
517         BOOST_FOREACH(const CTxOut& txout, vout)
518         {
519             nValueOut += txout.nValue;
520             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
521                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
522         }
523         return nValueOut;
524     }
525
526     static bool AllowFree(double dPriority)
527     {
528         // Large (in bytes) low-priority (new, small-coin) transactions
529         // need a fee.
530         return dPriority > COIN * 144 / 250;
531     }
532
533     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
534     {
535         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
536         int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
537
538         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
539         unsigned int nNewBlockSize = nBlockSize + nBytes;
540         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
541
542         if (fAllowFree)
543         {
544             if (nBlockSize == 1)
545             {
546                 // Transactions under 10K are free
547                 // (about 4500bc if made of 50bc inputs)
548                 if (nBytes < 10000)
549                     nMinFee = 0;
550             }
551             else
552             {
553                 // Free transaction area
554                 if (nNewBlockSize < 27000)
555                     nMinFee = 0;
556             }
557         }
558
559         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
560         if (nMinFee < nBaseFee)
561             BOOST_FOREACH(const CTxOut& txout, vout)
562                 if (txout.nValue < CENT)
563                     nMinFee = nBaseFee;
564
565         // Raise the price as the block approaches full
566         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
567         {
568             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
569                 return MAX_MONEY;
570             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
571         }
572
573         if (!MoneyRange(nMinFee))
574             nMinFee = MAX_MONEY;
575         return nMinFee;
576     }
577
578
579     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
580     {
581         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
582         if (!filein)
583             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
584
585         // Read transaction
586         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
587             return error("CTransaction::ReadFromDisk() : fseek failed");
588         filein >> *this;
589
590         // Return file pointer
591         if (pfileRet)
592         {
593             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
594                 return error("CTransaction::ReadFromDisk() : second fseek failed");
595             *pfileRet = filein.release();
596         }
597         return true;
598     }
599
600     friend bool operator==(const CTransaction& a, const CTransaction& b)
601     {
602         return (a.nVersion  == b.nVersion &&
603                 a.vin       == b.vin &&
604                 a.vout      == b.vout &&
605                 a.nLockTime == b.nLockTime);
606     }
607
608     friend bool operator!=(const CTransaction& a, const CTransaction& b)
609     {
610         return !(a == b);
611     }
612
613
614     std::string ToString() const
615     {
616         std::string str;
617         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
618             GetHash().ToString().substr(0,10).c_str(),
619             nVersion,
620             vin.size(),
621             vout.size(),
622             nLockTime);
623         for (int i = 0; i < vin.size(); i++)
624             str += "    " + vin[i].ToString() + "\n";
625         for (int i = 0; i < vout.size(); i++)
626             str += "    " + vout[i].ToString() + "\n";
627         return str;
628     }
629
630     void print() const
631     {
632         printf("%s", ToString().c_str());
633     }
634
635
636     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
637     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
638     bool ReadFromDisk(COutPoint prevout);
639     bool DisconnectInputs(CTxDB& txdb);
640     bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
641                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
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
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     }
830
831     bool IsNull() const
832     {
833         return (nBits == 0);
834     }
835
836     uint256 GetHash() const
837     {
838         return Hash(BEGIN(nVersion), END(nNonce));
839     }
840
841     int64 GetBlockTime() const
842     {
843         return (int64)nTime;
844     }
845
846     int GetSigOpCount() const
847     {
848         int n = 0;
849         BOOST_FOREACH(const CTransaction& tx, vtx)
850             n += tx.GetSigOpCount();
851         return n;
852     }
853
854
855     uint256 BuildMerkleTree() const
856     {
857         vMerkleTree.clear();
858         BOOST_FOREACH(const CTransaction& tx, vtx)
859             vMerkleTree.push_back(tx.GetHash());
860         int j = 0;
861         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
862         {
863             for (int i = 0; i < nSize; i += 2)
864             {
865                 int i2 = std::min(i+1, nSize-1);
866                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
867                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
868             }
869             j += nSize;
870         }
871         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
872     }
873
874     std::vector<uint256> GetMerkleBranch(int nIndex) const
875     {
876         if (vMerkleTree.empty())
877             BuildMerkleTree();
878         std::vector<uint256> vMerkleBranch;
879         int j = 0;
880         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
881         {
882             int i = std::min(nIndex^1, nSize-1);
883             vMerkleBranch.push_back(vMerkleTree[j+i]);
884             nIndex >>= 1;
885             j += nSize;
886         }
887         return vMerkleBranch;
888     }
889
890     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
891     {
892         if (nIndex == -1)
893             return 0;
894         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
895         {
896             if (nIndex & 1)
897                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
898             else
899                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
900             nIndex >>= 1;
901         }
902         return hash;
903     }
904
905
906     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
907     {
908         // Open history file to append
909         CAutoFile fileout = AppendBlockFile(nFileRet);
910         if (!fileout)
911             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
912
913         // Write index header
914         unsigned int nSize = fileout.GetSerializeSize(*this);
915         fileout << FLATDATA(pchMessageStart) << nSize;
916
917         // Write block
918         nBlockPosRet = ftell(fileout);
919         if (nBlockPosRet == -1)
920             return error("CBlock::WriteToDisk() : ftell failed");
921         fileout << *this;
922
923         // Flush stdio buffers and commit to disk before returning
924         fflush(fileout);
925         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
926         {
927 #ifdef __WXMSW__
928             _commit(_fileno(fileout));
929 #else
930             fsync(fileno(fileout));
931 #endif
932         }
933
934         return true;
935     }
936
937     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
938     {
939         SetNull();
940
941         // Open history file to read
942         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
943         if (!filein)
944             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
945         if (!fReadTransactions)
946             filein.nType |= SER_BLOCKHEADERONLY;
947
948         // Read block
949         filein >> *this;
950
951         // Check the header
952         if (!CheckProofOfWork(GetHash(), nBits))
953             return error("CBlock::ReadFromDisk() : errors in block header");
954
955         return true;
956     }
957
958
959
960     void print() const
961     {
962         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
963             GetHash().ToString().substr(0,20).c_str(),
964             nVersion,
965             hashPrevBlock.ToString().substr(0,20).c_str(),
966             hashMerkleRoot.ToString().substr(0,10).c_str(),
967             nTime, nBits, nNonce,
968             vtx.size());
969         for (int i = 0; i < vtx.size(); i++)
970         {
971             printf("  ");
972             vtx[i].print();
973         }
974         printf("  vMerkleTree: ");
975         for (int i = 0; i < vMerkleTree.size(); i++)
976             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
977         printf("\n");
978     }
979
980
981     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
982     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
983     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
984     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
985     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
986     bool CheckBlock() const;
987     bool AcceptBlock();
988 };
989
990
991
992
993
994
995 //
996 // The block chain is a tree shaped structure starting with the
997 // genesis block at the root, with each block potentially having multiple
998 // candidates to be the next block.  pprev and pnext link a path through the
999 // main/longest chain.  A blockindex may have multiple pprev pointing back
1000 // to it, but pnext will only point forward to the longest branch, or will
1001 // be null if the block is not part of the longest chain.
1002 //
1003 class CBlockIndex
1004 {
1005 public:
1006     const uint256* phashBlock;
1007     CBlockIndex* pprev;
1008     CBlockIndex* pnext;
1009     unsigned int nFile;
1010     unsigned int nBlockPos;
1011     int nHeight;
1012     CBigNum bnChainWork;
1013
1014     // block header
1015     int nVersion;
1016     uint256 hashMerkleRoot;
1017     unsigned int nTime;
1018     unsigned int nBits;
1019     unsigned int nNonce;
1020
1021
1022     CBlockIndex()
1023     {
1024         phashBlock = NULL;
1025         pprev = NULL;
1026         pnext = NULL;
1027         nFile = 0;
1028         nBlockPos = 0;
1029         nHeight = 0;
1030         bnChainWork = 0;
1031
1032         nVersion       = 0;
1033         hashMerkleRoot = 0;
1034         nTime          = 0;
1035         nBits          = 0;
1036         nNonce         = 0;
1037     }
1038
1039     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1040     {
1041         phashBlock = NULL;
1042         pprev = NULL;
1043         pnext = NULL;
1044         nFile = nFileIn;
1045         nBlockPos = nBlockPosIn;
1046         nHeight = 0;
1047         bnChainWork = 0;
1048
1049         nVersion       = block.nVersion;
1050         hashMerkleRoot = block.hashMerkleRoot;
1051         nTime          = block.nTime;
1052         nBits          = block.nBits;
1053         nNonce         = block.nNonce;
1054     }
1055
1056     CBlock GetBlockHeader() const
1057     {
1058         CBlock block;
1059         block.nVersion       = nVersion;
1060         if (pprev)
1061             block.hashPrevBlock = pprev->GetBlockHash();
1062         block.hashMerkleRoot = hashMerkleRoot;
1063         block.nTime          = nTime;
1064         block.nBits          = nBits;
1065         block.nNonce         = nNonce;
1066         return block;
1067     }
1068
1069     uint256 GetBlockHash() const
1070     {
1071         return *phashBlock;
1072     }
1073
1074     int64 GetBlockTime() const
1075     {
1076         return (int64)nTime;
1077     }
1078
1079     CBigNum GetBlockWork() const
1080     {
1081         CBigNum bnTarget;
1082         bnTarget.SetCompact(nBits);
1083         if (bnTarget <= 0)
1084             return 0;
1085         return (CBigNum(1)<<256) / (bnTarget+1);
1086     }
1087
1088     bool IsInMainChain() const
1089     {
1090         return (pnext || this == pindexBest);
1091     }
1092
1093     bool CheckIndex() const
1094     {
1095         return CheckProofOfWork(GetBlockHash(), nBits);
1096     }
1097
1098     bool EraseBlockFromDisk()
1099     {
1100         // Open history file
1101         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1102         if (!fileout)
1103             return false;
1104
1105         // Overwrite with empty null block
1106         CBlock block;
1107         block.SetNull();
1108         fileout << block;
1109
1110         return true;
1111     }
1112
1113     enum { nMedianTimeSpan=11 };
1114
1115     int64 GetMedianTimePast() const
1116     {
1117         int64 pmedian[nMedianTimeSpan];
1118         int64* pbegin = &pmedian[nMedianTimeSpan];
1119         int64* pend = &pmedian[nMedianTimeSpan];
1120
1121         const CBlockIndex* pindex = this;
1122         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1123             *(--pbegin) = pindex->GetBlockTime();
1124
1125         std::sort(pbegin, pend);
1126         return pbegin[(pend - pbegin)/2];
1127     }
1128
1129     int64 GetMedianTime() const
1130     {
1131         const CBlockIndex* pindex = this;
1132         for (int i = 0; i < nMedianTimeSpan/2; i++)
1133         {
1134             if (!pindex->pnext)
1135                 return GetBlockTime();
1136             pindex = pindex->pnext;
1137         }
1138         return pindex->GetMedianTimePast();
1139     }
1140
1141
1142
1143     std::string ToString() const
1144     {
1145         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1146             pprev, pnext, nFile, nBlockPos, nHeight,
1147             hashMerkleRoot.ToString().substr(0,10).c_str(),
1148             GetBlockHash().ToString().substr(0,20).c_str());
1149     }
1150
1151     void print() const
1152     {
1153         printf("%s\n", ToString().c_str());
1154     }
1155 };
1156
1157
1158
1159 //
1160 // Used to marshal pointers into hashes for db storage.
1161 //
1162 class CDiskBlockIndex : public CBlockIndex
1163 {
1164 public:
1165     uint256 hashPrev;
1166     uint256 hashNext;
1167
1168     CDiskBlockIndex()
1169     {
1170         hashPrev = 0;
1171         hashNext = 0;
1172     }
1173
1174     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1175     {
1176         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1177         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1178     }
1179
1180     IMPLEMENT_SERIALIZE
1181     (
1182         if (!(nType & SER_GETHASH))
1183             READWRITE(nVersion);
1184
1185         READWRITE(hashNext);
1186         READWRITE(nFile);
1187         READWRITE(nBlockPos);
1188         READWRITE(nHeight);
1189
1190         // block header
1191         READWRITE(this->nVersion);
1192         READWRITE(hashPrev);
1193         READWRITE(hashMerkleRoot);
1194         READWRITE(nTime);
1195         READWRITE(nBits);
1196         READWRITE(nNonce);
1197     )
1198
1199     uint256 GetBlockHash() const
1200     {
1201         CBlock block;
1202         block.nVersion        = nVersion;
1203         block.hashPrevBlock   = hashPrev;
1204         block.hashMerkleRoot  = hashMerkleRoot;
1205         block.nTime           = nTime;
1206         block.nBits           = nBits;
1207         block.nNonce          = nNonce;
1208         return block.GetHash();
1209     }
1210
1211
1212     std::string ToString() const
1213     {
1214         std::string str = "CDiskBlockIndex(";
1215         str += CBlockIndex::ToString();
1216         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1217             GetBlockHash().ToString().c_str(),
1218             hashPrev.ToString().substr(0,20).c_str(),
1219             hashNext.ToString().substr(0,20).c_str());
1220         return str;
1221     }
1222
1223     void print() const
1224     {
1225         printf("%s\n", ToString().c_str());
1226     }
1227 };
1228
1229
1230
1231
1232
1233
1234
1235
1236 //
1237 // Describes a place in the block chain to another node such that if the
1238 // other node doesn't have the same branch, it can find a recent common trunk.
1239 // The further back it is, the further before the fork it may be.
1240 //
1241 class CBlockLocator
1242 {
1243 protected:
1244     std::vector<uint256> vHave;
1245 public:
1246
1247     CBlockLocator()
1248     {
1249     }
1250
1251     explicit CBlockLocator(const CBlockIndex* pindex)
1252     {
1253         Set(pindex);
1254     }
1255
1256     explicit CBlockLocator(uint256 hashBlock)
1257     {
1258         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1259         if (mi != mapBlockIndex.end())
1260             Set((*mi).second);
1261     }
1262
1263     IMPLEMENT_SERIALIZE
1264     (
1265         if (!(nType & SER_GETHASH))
1266             READWRITE(nVersion);
1267         READWRITE(vHave);
1268     )
1269
1270     void SetNull()
1271     {
1272         vHave.clear();
1273     }
1274
1275     bool IsNull()
1276     {
1277         return vHave.empty();
1278     }
1279
1280     void Set(const CBlockIndex* pindex)
1281     {
1282         vHave.clear();
1283         int nStep = 1;
1284         while (pindex)
1285         {
1286             vHave.push_back(pindex->GetBlockHash());
1287
1288             // Exponentially larger steps back
1289             for (int i = 0; pindex && i < nStep; i++)
1290                 pindex = pindex->pprev;
1291             if (vHave.size() > 10)
1292                 nStep *= 2;
1293         }
1294         vHave.push_back(hashGenesisBlock);
1295     }
1296
1297     int GetDistanceBack()
1298     {
1299         // Retrace how far back it was in the sender's branch
1300         int nDistance = 0;
1301         int nStep = 1;
1302         BOOST_FOREACH(const uint256& hash, vHave)
1303         {
1304             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1305             if (mi != mapBlockIndex.end())
1306             {
1307                 CBlockIndex* pindex = (*mi).second;
1308                 if (pindex->IsInMainChain())
1309                     return nDistance;
1310             }
1311             nDistance += nStep;
1312             if (nDistance > 10)
1313                 nStep *= 2;
1314         }
1315         return nDistance;
1316     }
1317
1318     CBlockIndex* GetBlockIndex()
1319     {
1320         // Find the first block the caller has in the main chain
1321         BOOST_FOREACH(const uint256& hash, vHave)
1322         {
1323             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1324             if (mi != mapBlockIndex.end())
1325             {
1326                 CBlockIndex* pindex = (*mi).second;
1327                 if (pindex->IsInMainChain())
1328                     return pindex;
1329             }
1330         }
1331         return pindexGenesisBlock;
1332     }
1333
1334     uint256 GetBlockHash()
1335     {
1336         // Find the first block the caller has in the main chain
1337         BOOST_FOREACH(const uint256& hash, vHave)
1338         {
1339             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1340             if (mi != mapBlockIndex.end())
1341             {
1342                 CBlockIndex* pindex = (*mi).second;
1343                 if (pindex->IsInMainChain())
1344                     return hash;
1345             }
1346         }
1347         return hashGenesisBlock;
1348     }
1349
1350     int GetHeight()
1351     {
1352         CBlockIndex* pindex = GetBlockIndex();
1353         if (!pindex)
1354             return 0;
1355         return pindex->nHeight;
1356     }
1357 };
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367 //
1368 // Alerts are for notifying old versions if they become too obsolete and
1369 // need to upgrade.  The message is displayed in the status bar.
1370 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1371 // not read the entire buffer if the alert is for a newer version, but older
1372 // versions can still relay the original data.
1373 //
1374 class CUnsignedAlert
1375 {
1376 public:
1377     int nVersion;
1378     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1379     int64 nExpiration;
1380     int nID;
1381     int nCancel;
1382     std::set<int> setCancel;
1383     int nMinVer;            // lowest version inclusive
1384     int nMaxVer;            // highest version inclusive
1385     std::set<std::string> setSubVer;  // empty matches all
1386     int nPriority;
1387
1388     // Actions
1389     std::string strComment;
1390     std::string strStatusBar;
1391     std::string strReserved;
1392
1393     IMPLEMENT_SERIALIZE
1394     (
1395         READWRITE(this->nVersion);
1396         nVersion = this->nVersion;
1397         READWRITE(nRelayUntil);
1398         READWRITE(nExpiration);
1399         READWRITE(nID);
1400         READWRITE(nCancel);
1401         READWRITE(setCancel);
1402         READWRITE(nMinVer);
1403         READWRITE(nMaxVer);
1404         READWRITE(setSubVer);
1405         READWRITE(nPriority);
1406
1407         READWRITE(strComment);
1408         READWRITE(strStatusBar);
1409         READWRITE(strReserved);
1410     )
1411
1412     void SetNull()
1413     {
1414         nVersion = 1;
1415         nRelayUntil = 0;
1416         nExpiration = 0;
1417         nID = 0;
1418         nCancel = 0;
1419         setCancel.clear();
1420         nMinVer = 0;
1421         nMaxVer = 0;
1422         setSubVer.clear();
1423         nPriority = 0;
1424
1425         strComment.clear();
1426         strStatusBar.clear();
1427         strReserved.clear();
1428     }
1429
1430     std::string ToString() const
1431     {
1432         std::string strSetCancel;
1433         BOOST_FOREACH(int n, setCancel)
1434             strSetCancel += strprintf("%d ", n);
1435         std::string strSetSubVer;
1436         BOOST_FOREACH(std::string str, setSubVer)
1437             strSetSubVer += "\"" + str + "\" ";
1438         return strprintf(
1439                 "CAlert(\n"
1440                 "    nVersion     = %d\n"
1441                 "    nRelayUntil  = %"PRI64d"\n"
1442                 "    nExpiration  = %"PRI64d"\n"
1443                 "    nID          = %d\n"
1444                 "    nCancel      = %d\n"
1445                 "    setCancel    = %s\n"
1446                 "    nMinVer      = %d\n"
1447                 "    nMaxVer      = %d\n"
1448                 "    setSubVer    = %s\n"
1449                 "    nPriority    = %d\n"
1450                 "    strComment   = \"%s\"\n"
1451                 "    strStatusBar = \"%s\"\n"
1452                 ")\n",
1453             nVersion,
1454             nRelayUntil,
1455             nExpiration,
1456             nID,
1457             nCancel,
1458             strSetCancel.c_str(),
1459             nMinVer,
1460             nMaxVer,
1461             strSetSubVer.c_str(),
1462             nPriority,
1463             strComment.c_str(),
1464             strStatusBar.c_str());
1465     }
1466
1467     void print() const
1468     {
1469         printf("%s", ToString().c_str());
1470     }
1471 };
1472
1473 class CAlert : public CUnsignedAlert
1474 {
1475 public:
1476     std::vector<unsigned char> vchMsg;
1477     std::vector<unsigned char> vchSig;
1478
1479     CAlert()
1480     {
1481         SetNull();
1482     }
1483
1484     IMPLEMENT_SERIALIZE
1485     (
1486         READWRITE(vchMsg);
1487         READWRITE(vchSig);
1488     )
1489
1490     void SetNull()
1491     {
1492         CUnsignedAlert::SetNull();
1493         vchMsg.clear();
1494         vchSig.clear();
1495     }
1496
1497     bool IsNull() const
1498     {
1499         return (nExpiration == 0);
1500     }
1501
1502     uint256 GetHash() const
1503     {
1504         return SerializeHash(*this);
1505     }
1506
1507     bool IsInEffect() const
1508     {
1509         return (GetAdjustedTime() < nExpiration);
1510     }
1511
1512     bool Cancels(const CAlert& alert) const
1513     {
1514         if (!IsInEffect())
1515             return false; // this was a no-op before 31403
1516         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1517     }
1518
1519     bool AppliesTo(int nVersion, std::string strSubVerIn) const
1520     {
1521         return (IsInEffect() &&
1522                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1523                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1524     }
1525
1526     bool AppliesToMe() const
1527     {
1528         return AppliesTo(VERSION, ::pszSubVer);
1529     }
1530
1531     bool RelayTo(CNode* pnode) const
1532     {
1533         if (!IsInEffect())
1534             return false;
1535         // returns true if wasn't already contained in the set
1536         if (pnode->setKnown.insert(GetHash()).second)
1537         {
1538             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
1539                 AppliesToMe() ||
1540                 GetAdjustedTime() < nRelayUntil)
1541             {
1542                 pnode->PushMessage("alert", *this);
1543                 return true;
1544             }
1545         }
1546         return false;
1547     }
1548
1549     bool CheckSignature()
1550     {
1551         CKey key;
1552         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
1553             return error("CAlert::CheckSignature() : SetPubKey failed");
1554         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
1555             return error("CAlert::CheckSignature() : verify signature failed");
1556
1557         // Now unserialize the data
1558         CDataStream sMsg(vchMsg);
1559         sMsg >> *(CUnsignedAlert*)this;
1560         return true;
1561     }
1562
1563     bool ProcessAlert();
1564 };
1565
1566 #endif