Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #ifndef BITCOIN_MAIN_H
0006 #define BITCOIN_MAIN_H
0007 
0008 #include "bignum.h"
0009 #include "net.h"
0010 #include "key.h"
0011 #include "script.h"
0012 #include "db.h"
0013 
0014 #include <list>
0015 
0016 class CBlock;
0017 class CBlockIndex;
0018 class CWalletTx;
0019 class CWallet;
0020 class CKeyItem;
0021 class CReserveKey;
0022 class CWalletDB;
0023 
0024 class CAddress;
0025 class CInv;
0026 class CRequestTracker;
0027 class CNode;
0028 class CBlockIndex;
0029 
0030 static const unsigned int MAX_BLOCK_SIZE = 1000000;
0031 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
0032 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
0033 static const int64 COIN = 100000000;
0034 static const int64 CENT = 1000000;
0035 static const int64 MIN_TX_FEE = 50000;
0036 static const int64 MIN_RELAY_TX_FEE = 10000;
0037 static const int64 MAX_MONEY = 21000000 * COIN;
0038 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
0039 static const int COINBASE_MATURITY = 100;
0040 // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
0041 static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov  5 00:53:20 1985 UTC
0042 
0043 
0044 
0045 
0046 
0047 
0048 extern CCriticalSection cs_main;
0049 extern std::map<uint256, CBlockIndex*> mapBlockIndex;
0050 extern uint256 hashGenesisBlock;
0051 extern CBlockIndex* pindexGenesisBlock;
0052 extern int nBestHeight;
0053 extern CBigNum bnBestChainWork;
0054 extern CBigNum bnBestInvalidWork;
0055 extern uint256 hashBestChain;
0056 extern CBlockIndex* pindexBest;
0057 extern unsigned int nTransactionsUpdated;
0058 extern double dHashesPerSec;
0059 extern int64 nHPSTimerStart;
0060 extern int64 nTimeBestReceived;
0061 extern CCriticalSection cs_setpwalletRegistered;
0062 extern std::set<CWallet*> setpwalletRegistered;
0063 
0064 // Settings
0065 extern int fGenerateBitcoins;
0066 extern int64 nTransactionFee;
0067 extern int fLimitProcessors;
0068 extern int nLimitProcessors;
0069 extern int fMinimizeToTray;
0070 extern int fMinimizeOnClose;
0071 
0072 
0073 
0074 
0075 
0076 class CReserveKey;
0077 class CTxDB;
0078 class CTxIndex;
0079 
0080 void RegisterWallet(CWallet* pwalletIn);
0081 void UnregisterWallet(CWallet* pwalletIn);
0082 bool ProcessBlock(CNode* pfrom, CBlock* pblock);
0083 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
0084 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
0085 FILE* AppendBlockFile(unsigned int& nFileRet);
0086 bool LoadBlockIndex(bool fAllowNew=true);
0087 void PrintBlockTree();
0088 bool ProcessMessages(CNode* pfrom);
0089 bool SendMessages(CNode* pto, bool fSendTrickle);
0090 void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
0091 CBlock* CreateNewBlock(CReserveKey& reservekey);
0092 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
0093 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
0094 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
0095 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
0096 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
0097 int GetNumBlocksOfPeers();
0098 bool IsInitialBlockDownload();
0099 std::string GetWarnings(std::string strFor);
0100 
0101 
0102 
0103 
0104 
0105 
0106 
0107 
0108 
0109 
0110 
0111 
0112 bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
0113 
0114 template<typename T>
0115 bool WriteSetting(const std::string& strKey, const T& value)
0116 {
0117     bool fOk = false;
0118     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0119     {
0120         std::string strWalletFile;
0121         if (!GetWalletFile(pwallet, strWalletFile))
0122             continue;
0123         fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
0124     }
0125     return fOk;
0126 }
0127 
0128 
0129 class CDiskTxPos
0130 {
0131 public:
0132     unsigned int nFile;
0133     unsigned int nBlockPos;
0134     unsigned int nTxPos;
0135 
0136     CDiskTxPos()
0137     {
0138         SetNull();
0139     }
0140 
0141     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
0142     {
0143         nFile = nFileIn;
0144         nBlockPos = nBlockPosIn;
0145         nTxPos = nTxPosIn;
0146     }
0147 
0148     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
0149     void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
0150     bool IsNull() const { return (nFile == -1); }
0151 
0152     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
0153     {
0154         return (a.nFile     == b.nFile &&
0155                 a.nBlockPos == b.nBlockPos &&
0156                 a.nTxPos    == b.nTxPos);
0157     }
0158 
0159     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
0160     {
0161         return !(a == b);
0162     }
0163 
0164     std::string ToString() const
0165     {
0166         if (IsNull())
0167             return strprintf("null");
0168         else
0169             return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
0170     }
0171 
0172     void print() const
0173     {
0174         printf("%s", ToString().c_str());
0175     }
0176 };
0177 
0178 
0179 
0180 
0181 class CInPoint
0182 {
0183 public:
0184     CTransaction* ptx;
0185     unsigned int n;
0186 
0187     CInPoint() { SetNull(); }
0188     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
0189     void SetNull() { ptx = NULL; n = -1; }
0190     bool IsNull() const { return (ptx == NULL && n == -1); }
0191 };
0192 
0193 
0194 
0195 
0196 class COutPoint
0197 {
0198 public:
0199     uint256 hash;
0200     unsigned int n;
0201 
0202     COutPoint() { SetNull(); }
0203     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
0204     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
0205     void SetNull() { hash = 0; n = -1; }
0206     bool IsNull() const { return (hash == 0 && n == -1); }
0207 
0208     friend bool operator<(const COutPoint& a, const COutPoint& b)
0209     {
0210         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
0211     }
0212 
0213     friend bool operator==(const COutPoint& a, const COutPoint& b)
0214     {
0215         return (a.hash == b.hash && a.n == b.n);
0216     }
0217 
0218     friend bool operator!=(const COutPoint& a, const COutPoint& b)
0219     {
0220         return !(a == b);
0221     }
0222 
0223     std::string ToString() const
0224     {
0225         return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
0226     }
0227 
0228     void print() const
0229     {
0230         printf("%s\n", ToString().c_str());
0231     }
0232 };
0233 
0234 
0235 
0236 
0237 //
0238 // An input of a transaction.  It contains the location of the previous
0239 // transaction's output that it claims and a signature that matches the
0240 // output's public key.
0241 //
0242 class CTxIn
0243 {
0244 public:
0245     COutPoint prevout;
0246     CScript scriptSig;
0247     unsigned int nSequence;
0248 
0249     CTxIn()
0250     {
0251         nSequence = UINT_MAX;
0252     }
0253 
0254     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
0255     {
0256         prevout = prevoutIn;
0257         scriptSig = scriptSigIn;
0258         nSequence = nSequenceIn;
0259     }
0260 
0261     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
0262     {
0263         prevout = COutPoint(hashPrevTx, nOut);
0264         scriptSig = scriptSigIn;
0265         nSequence = nSequenceIn;
0266     }
0267 
0268     IMPLEMENT_SERIALIZE
0269     (
0270         READWRITE(prevout);
0271         READWRITE(scriptSig);
0272         READWRITE(nSequence);
0273     )
0274 
0275     bool IsFinal() const
0276     {
0277         return (nSequence == UINT_MAX);
0278     }
0279 
0280     friend bool operator==(const CTxIn& a, const CTxIn& b)
0281     {
0282         return (a.prevout   == b.prevout &&
0283                 a.scriptSig == b.scriptSig &&
0284                 a.nSequence == b.nSequence);
0285     }
0286 
0287     friend bool operator!=(const CTxIn& a, const CTxIn& b)
0288     {
0289         return !(a == b);
0290     }
0291 
0292     std::string ToString() const
0293     {
0294         std::string str;
0295         str += strprintf("CTxIn(");
0296         str += prevout.ToString();
0297         if (prevout.IsNull())
0298             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
0299         else
0300             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
0301         if (nSequence != UINT_MAX)
0302             str += strprintf(", nSequence=%u", nSequence);
0303         str += ")";
0304         return str;
0305     }
0306 
0307     void print() const
0308     {
0309         printf("%s\n", ToString().c_str());
0310     }
0311 };
0312 
0313 
0314 
0315 
0316 //
0317 // An output of a transaction.  It contains the public key that the next input
0318 // must be able to sign with to claim it.
0319 //
0320 class CTxOut
0321 {
0322 public:
0323     int64 nValue;
0324     CScript scriptPubKey;
0325 
0326     CTxOut()
0327     {
0328         SetNull();
0329     }
0330 
0331     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
0332     {
0333         nValue = nValueIn;
0334         scriptPubKey = scriptPubKeyIn;
0335     }
0336 
0337     IMPLEMENT_SERIALIZE
0338     (
0339         READWRITE(nValue);
0340         READWRITE(scriptPubKey);
0341     )
0342 
0343     void SetNull()
0344     {
0345         nValue = -1;
0346         scriptPubKey.clear();
0347     }
0348 
0349     bool IsNull()
0350     {
0351         return (nValue == -1);
0352     }
0353 
0354     uint256 GetHash() const
0355     {
0356         return SerializeHash(*this);
0357     }
0358 
0359     friend bool operator==(const CTxOut& a, const CTxOut& b)
0360     {
0361         return (a.nValue       == b.nValue &&
0362                 a.scriptPubKey == b.scriptPubKey);
0363     }
0364 
0365     friend bool operator!=(const CTxOut& a, const CTxOut& b)
0366     {
0367         return !(a == b);
0368     }
0369 
0370     std::string ToString() const
0371     {
0372         if (scriptPubKey.size() < 6)
0373             return "CTxOut(error)";
0374         return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
0375     }
0376 
0377     void print() const
0378     {
0379         printf("%s\n", ToString().c_str());
0380     }
0381 };
0382 
0383 
0384 
0385 
0386 //
0387 // The basic transaction that is broadcasted on the network and contained in
0388 // blocks.  A transaction can contain multiple inputs and outputs.
0389 //
0390 class CTransaction
0391 {
0392 public:
0393     int nVersion;
0394     std::vector<CTxIn> vin;
0395     std::vector<CTxOut> vout;
0396     unsigned int nLockTime;
0397 
0398     // Denial-of-service detection:
0399     mutable int nDoS;
0400     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
0401 
0402     CTransaction()
0403     {
0404         SetNull();
0405     }
0406 
0407     IMPLEMENT_SERIALIZE
0408     (
0409         READWRITE(this->nVersion);
0410         nVersion = this->nVersion;
0411         READWRITE(vin);
0412         READWRITE(vout);
0413         READWRITE(nLockTime);
0414     )
0415 
0416     void SetNull()
0417     {
0418         nVersion = 1;
0419         vin.clear();
0420         vout.clear();
0421         nLockTime = 0;
0422         nDoS = 0;  // Denial-of-service prevention
0423     }
0424 
0425     bool IsNull() const
0426     {
0427         return (vin.empty() && vout.empty());
0428     }
0429 
0430     uint256 GetHash() const
0431     {
0432         return SerializeHash(*this);
0433     }
0434 
0435     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
0436     {
0437         // Time based nLockTime implemented in 0.1.6
0438         if (nLockTime == 0)
0439             return true;
0440         if (nBlockHeight == 0)
0441             nBlockHeight = nBestHeight;
0442         if (nBlockTime == 0)
0443             nBlockTime = GetAdjustedTime();
0444         if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
0445             return true;
0446         BOOST_FOREACH(const CTxIn& txin, vin)
0447             if (!txin.IsFinal())
0448                 return false;
0449         return true;
0450     }
0451 
0452     bool IsNewerThan(const CTransaction& old) const
0453     {
0454         if (vin.size() != old.vin.size())
0455             return false;
0456         for (int i = 0; i < vin.size(); i++)
0457             if (vin[i].prevout != old.vin[i].prevout)
0458                 return false;
0459 
0460         bool fNewer = false;
0461         unsigned int nLowest = UINT_MAX;
0462         for (int i = 0; i < vin.size(); i++)
0463         {
0464             if (vin[i].nSequence != old.vin[i].nSequence)
0465             {
0466                 if (vin[i].nSequence <= nLowest)
0467                 {
0468                     fNewer = false;
0469                     nLowest = vin[i].nSequence;
0470                 }
0471                 if (old.vin[i].nSequence < nLowest)
0472                 {
0473                     fNewer = true;
0474                     nLowest = old.vin[i].nSequence;
0475                 }
0476             }
0477         }
0478         return fNewer;
0479     }
0480 
0481     bool IsCoinBase() const
0482     {
0483         return (vin.size() == 1 && vin[0].prevout.IsNull());
0484     }
0485 
0486     int GetSigOpCount() const
0487     {
0488         int n = 0;
0489         BOOST_FOREACH(const CTxIn& txin, vin)
0490             n += txin.scriptSig.GetSigOpCount();
0491         BOOST_FOREACH(const CTxOut& txout, vout)
0492             n += txout.scriptPubKey.GetSigOpCount();
0493         return n;
0494     }
0495 
0496     bool IsStandard() const
0497     {
0498         BOOST_FOREACH(const CTxIn& txin, vin)
0499             if (!txin.scriptSig.IsPushOnly())
0500                 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
0501         BOOST_FOREACH(const CTxOut& txout, vout)
0502             if (!::IsStandard(txout.scriptPubKey))
0503                 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
0504         return true;
0505     }
0506 
0507     int64 GetValueOut() const
0508     {
0509         int64 nValueOut = 0;
0510         BOOST_FOREACH(const CTxOut& txout, vout)
0511         {
0512             nValueOut += txout.nValue;
0513             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
0514                 throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
0515         }
0516         return nValueOut;
0517     }
0518 
0519     static bool AllowFree(double dPriority)
0520     {
0521         // Large (in bytes) low-priority (new, small-coin) transactions
0522         // need a fee.
0523         return dPriority > COIN * 144 / 250;
0524     }
0525 
0526     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, bool fForRelay=false) const
0527     {
0528         // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
0529         int64 nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
0530 
0531         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
0532         unsigned int nNewBlockSize = nBlockSize + nBytes;
0533         int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
0534 
0535         if (fAllowFree)
0536         {
0537             if (nBlockSize == 1)
0538             {
0539                 // Transactions under 10K are free
0540                 // (about 4500bc if made of 50bc inputs)
0541                 if (nBytes < 10000)
0542                     nMinFee = 0;
0543             }
0544             else
0545             {
0546                 // Free transaction area
0547                 if (nNewBlockSize < 27000)
0548                     nMinFee = 0;
0549             }
0550         }
0551 
0552         // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
0553         if (nMinFee < nBaseFee)
0554             BOOST_FOREACH(const CTxOut& txout, vout)
0555                 if (txout.nValue < CENT)
0556                     nMinFee = nBaseFee;
0557 
0558         // Raise the price as the block approaches full
0559         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
0560         {
0561             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
0562                 return MAX_MONEY;
0563             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
0564         }
0565 
0566         if (!MoneyRange(nMinFee))
0567             nMinFee = MAX_MONEY;
0568         return nMinFee;
0569     }
0570 
0571 
0572     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
0573     {
0574         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
0575         if (!filein)
0576             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
0577 
0578         // Read transaction
0579         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
0580             return error("CTransaction::ReadFromDisk() : fseek failed");
0581         filein >> *this;
0582 
0583         // Return file pointer
0584         if (pfileRet)
0585         {
0586             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
0587                 return error("CTransaction::ReadFromDisk() : second fseek failed");
0588             *pfileRet = filein.release();
0589         }
0590         return true;
0591     }
0592 
0593     friend bool operator==(const CTransaction& a, const CTransaction& b)
0594     {
0595         return (a.nVersion  == b.nVersion &&
0596                 a.vin       == b.vin &&
0597                 a.vout      == b.vout &&
0598                 a.nLockTime == b.nLockTime);
0599     }
0600 
0601     friend bool operator!=(const CTransaction& a, const CTransaction& b)
0602     {
0603         return !(a == b);
0604     }
0605 
0606 
0607     std::string ToString() const
0608     {
0609         std::string str;
0610         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
0611             GetHash().ToString().substr(0,10).c_str(),
0612             nVersion,
0613             vin.size(),
0614             vout.size(),
0615             nLockTime);
0616         for (int i = 0; i < vin.size(); i++)
0617             str += "    " + vin[i].ToString() + "\n";
0618         for (int i = 0; i < vout.size(); i++)
0619             str += "    " + vout[i].ToString() + "\n";
0620         return str;
0621     }
0622 
0623     void print() const
0624     {
0625         printf("%s", ToString().c_str());
0626     }
0627 
0628 
0629     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
0630     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
0631     bool ReadFromDisk(COutPoint prevout);
0632     bool DisconnectInputs(CTxDB& txdb);
0633     bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
0634                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
0635                        bool& fInvalid);
0636     bool ClientConnectInputs();
0637     bool CheckTransaction() const;
0638     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
0639     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
0640 protected:
0641     bool AddToMemoryPoolUnchecked();
0642 public:
0643     bool RemoveFromMemoryPool();
0644 };
0645 
0646 
0647 
0648 
0649 
0650 //
0651 // A transaction with a merkle branch linking it to the block chain
0652 //
0653 class CMerkleTx : public CTransaction
0654 {
0655 public:
0656     uint256 hashBlock;
0657     std::vector<uint256> vMerkleBranch;
0658     int nIndex;
0659 
0660     // memory only
0661     mutable char fMerkleVerified;
0662 
0663 
0664     CMerkleTx()
0665     {
0666         Init();
0667     }
0668 
0669     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
0670     {
0671         Init();
0672     }
0673 
0674     void Init()
0675     {
0676         hashBlock = 0;
0677         nIndex = -1;
0678         fMerkleVerified = false;
0679     }
0680 
0681 
0682     IMPLEMENT_SERIALIZE
0683     (
0684         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
0685         nVersion = this->nVersion;
0686         READWRITE(hashBlock);
0687         READWRITE(vMerkleBranch);
0688         READWRITE(nIndex);
0689     )
0690 
0691 
0692     int SetMerkleBranch(const CBlock* pblock=NULL);
0693     int GetDepthInMainChain(int& nHeightRet) const;
0694     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
0695     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
0696     int GetBlocksToMaturity() const;
0697     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
0698     bool AcceptToMemoryPool();
0699 };
0700 
0701 
0702 
0703 
0704 //
0705 // A txdb record that contains the disk location of a transaction and the
0706 // locations of transactions that spend its outputs.  vSpent is really only
0707 // used as a flag, but having the location is very helpful for debugging.
0708 //
0709 class CTxIndex
0710 {
0711 public:
0712     CDiskTxPos pos;
0713     std::vector<CDiskTxPos> vSpent;
0714 
0715     CTxIndex()
0716     {
0717         SetNull();
0718     }
0719 
0720     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
0721     {
0722         pos = posIn;
0723         vSpent.resize(nOutputs);
0724     }
0725 
0726     IMPLEMENT_SERIALIZE
0727     (
0728         if (!(nType & SER_GETHASH))
0729             READWRITE(nVersion);
0730         READWRITE(pos);
0731         READWRITE(vSpent);
0732     )
0733 
0734     void SetNull()
0735     {
0736         pos.SetNull();
0737         vSpent.clear();
0738     }
0739 
0740     bool IsNull()
0741     {
0742         return pos.IsNull();
0743     }
0744 
0745     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
0746     {
0747         return (a.pos    == b.pos &&
0748                 a.vSpent == b.vSpent);
0749     }
0750 
0751     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
0752     {
0753         return !(a == b);
0754     }
0755     int GetDepthInMainChain() const;
0756 };
0757 
0758 
0759 
0760 
0761 
0762 //
0763 // Nodes collect new transactions into a block, hash them into a hash tree,
0764 // and scan through nonce values to make the block's hash satisfy proof-of-work
0765 // requirements.  When they solve the proof-of-work, they broadcast the block
0766 // to everyone and the block is added to the block chain.  The first transaction
0767 // in the block is a special one that creates a new coin owned by the creator
0768 // of the block.
0769 //
0770 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
0771 // is indexed by CBlockIndex objects in memory.
0772 //
0773 class CBlock
0774 {
0775 public:
0776     // header
0777     int nVersion;
0778     uint256 hashPrevBlock;
0779     uint256 hashMerkleRoot;
0780     unsigned int nTime;
0781     unsigned int nBits;
0782     unsigned int nNonce;
0783 
0784     // network and disk
0785     std::vector<CTransaction> vtx;
0786 
0787     // memory only
0788     mutable std::vector<uint256> vMerkleTree;
0789 
0790     // Denial-of-service detection:
0791     mutable int nDoS;
0792     bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
0793 
0794     CBlock()
0795     {
0796         SetNull();
0797     }
0798 
0799     IMPLEMENT_SERIALIZE
0800     (
0801         READWRITE(this->nVersion);
0802         nVersion = this->nVersion;
0803         READWRITE(hashPrevBlock);
0804         READWRITE(hashMerkleRoot);
0805         READWRITE(nTime);
0806         READWRITE(nBits);
0807         READWRITE(nNonce);
0808 
0809         // ConnectBlock depends on vtx being last so it can calculate offset
0810         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
0811             READWRITE(vtx);
0812         else if (fRead)
0813             const_cast<CBlock*>(this)->vtx.clear();
0814     )
0815 
0816     void SetNull()
0817     {
0818         nVersion = 1;
0819         hashPrevBlock = 0;
0820         hashMerkleRoot = 0;
0821         nTime = 0;
0822         nBits = 0;
0823         nNonce = 0;
0824         vtx.clear();
0825         vMerkleTree.clear();
0826         nDoS = 0;
0827     }
0828 
0829     bool IsNull() const
0830     {
0831         return (nBits == 0);
0832     }
0833 
0834     uint256 GetHash() const
0835     {
0836         return Hash(BEGIN(nVersion), END(nNonce));
0837     }
0838 
0839     int64 GetBlockTime() const
0840     {
0841         return (int64)nTime;
0842     }
0843 
0844     int GetSigOpCount() const
0845     {
0846         int n = 0;
0847         BOOST_FOREACH(const CTransaction& tx, vtx)
0848             n += tx.GetSigOpCount();
0849         return n;
0850     }
0851 
0852 
0853     uint256 BuildMerkleTree() const
0854     {
0855         vMerkleTree.clear();
0856         BOOST_FOREACH(const CTransaction& tx, vtx)
0857             vMerkleTree.push_back(tx.GetHash());
0858         int j = 0;
0859         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
0860         {
0861             for (int i = 0; i < nSize; i += 2)
0862             {
0863                 int i2 = std::min(i+1, nSize-1);
0864                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
0865                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
0866             }
0867             j += nSize;
0868         }
0869         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
0870     }
0871 
0872     std::vector<uint256> GetMerkleBranch(int nIndex) const
0873     {
0874         if (vMerkleTree.empty())
0875             BuildMerkleTree();
0876         std::vector<uint256> vMerkleBranch;
0877         int j = 0;
0878         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
0879         {
0880             int i = std::min(nIndex^1, nSize-1);
0881             vMerkleBranch.push_back(vMerkleTree[j+i]);
0882             nIndex >>= 1;
0883             j += nSize;
0884         }
0885         return vMerkleBranch;
0886     }
0887 
0888     static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
0889     {
0890         if (nIndex == -1)
0891             return 0;
0892         BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
0893         {
0894             if (nIndex & 1)
0895                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
0896             else
0897                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
0898             nIndex >>= 1;
0899         }
0900         return hash;
0901     }
0902 
0903 
0904     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
0905     {
0906         // Open history file to append
0907         CAutoFile fileout = AppendBlockFile(nFileRet);
0908         if (!fileout)
0909             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
0910 
0911         // Write index header
0912         unsigned int nSize = fileout.GetSerializeSize(*this);
0913         fileout << FLATDATA(pchMessageStart) << nSize;
0914 
0915         // Write block
0916         nBlockPosRet = ftell(fileout);
0917         if (nBlockPosRet == -1)
0918             return error("CBlock::WriteToDisk() : ftell failed");
0919         fileout << *this;
0920 
0921         // Flush stdio buffers and commit to disk before returning
0922         fflush(fileout);
0923         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
0924         {
0925             fsync(fileno(fileout));
0926         }
0927 
0928         return true;
0929     }
0930 
0931     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
0932     {
0933         SetNull();
0934 
0935         // Open history file to read
0936         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
0937         if (!filein)
0938             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
0939         if (!fReadTransactions)
0940             filein.nType |= SER_BLOCKHEADERONLY;
0941 
0942         // Read block
0943         filein >> *this;
0944 
0945         // Check the header
0946         if (!CheckProofOfWork(GetHash(), nBits))
0947             return error("CBlock::ReadFromDisk() : errors in block header");
0948 
0949         return true;
0950     }
0951 
0952 
0953 
0954     void print() const
0955     {
0956         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
0957             GetHash().ToString().substr(0,20).c_str(),
0958             nVersion,
0959             hashPrevBlock.ToString().substr(0,20).c_str(),
0960             hashMerkleRoot.ToString().substr(0,10).c_str(),
0961             nTime, nBits, nNonce,
0962             vtx.size());
0963         for (int i = 0; i < vtx.size(); i++)
0964         {
0965             printf("  ");
0966             vtx[i].print();
0967         }
0968         printf("  vMerkleTree: ");
0969         for (int i = 0; i < vMerkleTree.size(); i++)
0970             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
0971         printf("\n");
0972     }
0973 
0974 
0975     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
0976     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
0977     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
0978     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
0979     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
0980     bool CheckBlock() const;
0981     bool AcceptBlock();
0982 };
0983 
0984 
0985 
0986 
0987 
0988 
0989 //
0990 // The block chain is a tree shaped structure starting with the
0991 // genesis block at the root, with each block potentially having multiple
0992 // candidates to be the next block.  pprev and pnext link a path through the
0993 // main/longest chain.  A blockindex may have multiple pprev pointing back
0994 // to it, but pnext will only point forward to the longest branch, or will
0995 // be null if the block is not part of the longest chain.
0996 //
0997 class CBlockIndex
0998 {
0999 public:
1000     const uint256* phashBlock;
1001     CBlockIndex* pprev;
1002     CBlockIndex* pnext;
1003     unsigned int nFile;
1004     unsigned int nBlockPos;
1005     int nHeight;
1006     CBigNum bnChainWork;
1007 
1008     // block header
1009     int nVersion;
1010     uint256 hashMerkleRoot;
1011     unsigned int nTime;
1012     unsigned int nBits;
1013     unsigned int nNonce;
1014 
1015 
1016     CBlockIndex()
1017     {
1018         phashBlock = NULL;
1019         pprev = NULL;
1020         pnext = NULL;
1021         nFile = 0;
1022         nBlockPos = 0;
1023         nHeight = 0;
1024         bnChainWork = 0;
1025 
1026         nVersion       = 0;
1027         hashMerkleRoot = 0;
1028         nTime          = 0;
1029         nBits          = 0;
1030         nNonce         = 0;
1031     }
1032 
1033     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1034     {
1035         phashBlock = NULL;
1036         pprev = NULL;
1037         pnext = NULL;
1038         nFile = nFileIn;
1039         nBlockPos = nBlockPosIn;
1040         nHeight = 0;
1041         bnChainWork = 0;
1042 
1043         nVersion       = block.nVersion;
1044         hashMerkleRoot = block.hashMerkleRoot;
1045         nTime          = block.nTime;
1046         nBits          = block.nBits;
1047         nNonce         = block.nNonce;
1048     }
1049 
1050     CBlock GetBlockHeader() const
1051     {
1052         CBlock block;
1053         block.nVersion       = nVersion;
1054         if (pprev)
1055             block.hashPrevBlock = pprev->GetBlockHash();
1056         block.hashMerkleRoot = hashMerkleRoot;
1057         block.nTime          = nTime;
1058         block.nBits          = nBits;
1059         block.nNonce         = nNonce;
1060         return block;
1061     }
1062 
1063     uint256 GetBlockHash() const
1064     {
1065         return *phashBlock;
1066     }
1067 
1068     int64 GetBlockTime() const
1069     {
1070         return (int64)nTime;
1071     }
1072 
1073     CBigNum GetBlockWork() const
1074     {
1075         CBigNum bnTarget;
1076         bnTarget.SetCompact(nBits);
1077         if (bnTarget <= 0)
1078             return 0;
1079         return (CBigNum(1)<<256) / (bnTarget+1);
1080     }
1081 
1082     bool IsInMainChain() const
1083     {
1084         return (pnext || this == pindexBest);
1085     }
1086 
1087     bool CheckIndex() const
1088     {
1089         return CheckProofOfWork(GetBlockHash(), nBits);
1090     }
1091 
1092     bool EraseBlockFromDisk()
1093     {
1094         // Open history file
1095         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1096         if (!fileout)
1097             return false;
1098 
1099         // Overwrite with empty null block
1100         CBlock block;
1101         block.SetNull();
1102         fileout << block;
1103 
1104         return true;
1105     }
1106 
1107     enum { nMedianTimeSpan=11 };
1108 
1109     int64 GetMedianTimePast() const
1110     {
1111         int64 pmedian[nMedianTimeSpan];
1112         int64* pbegin = &pmedian[nMedianTimeSpan];
1113         int64* pend = &pmedian[nMedianTimeSpan];
1114 
1115         const CBlockIndex* pindex = this;
1116         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1117             *(--pbegin) = pindex->GetBlockTime();
1118 
1119         std::sort(pbegin, pend);
1120         return pbegin[(pend - pbegin)/2];
1121     }
1122 
1123     int64 GetMedianTime() const
1124     {
1125         const CBlockIndex* pindex = this;
1126         for (int i = 0; i < nMedianTimeSpan/2; i++)
1127         {
1128             if (!pindex->pnext)
1129                 return GetBlockTime();
1130             pindex = pindex->pnext;
1131         }
1132         return pindex->GetMedianTimePast();
1133     }
1134 
1135 
1136 
1137     std::string ToString() const
1138     {
1139         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1140             pprev, pnext, nFile, nBlockPos, nHeight,
1141             hashMerkleRoot.ToString().substr(0,10).c_str(),
1142             GetBlockHash().ToString().substr(0,20).c_str());
1143     }
1144 
1145     void print() const
1146     {
1147         printf("%s\n", ToString().c_str());
1148     }
1149 };
1150 
1151 
1152 
1153 //
1154 // Used to marshal pointers into hashes for db storage.
1155 //
1156 class CDiskBlockIndex : public CBlockIndex
1157 {
1158 public:
1159     uint256 hashPrev;
1160     uint256 hashNext;
1161 
1162     CDiskBlockIndex()
1163     {
1164         hashPrev = 0;
1165         hashNext = 0;
1166     }
1167 
1168     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1169     {
1170         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1171         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1172     }
1173 
1174     IMPLEMENT_SERIALIZE
1175     (
1176         if (!(nType & SER_GETHASH))
1177             READWRITE(nVersion);
1178 
1179         READWRITE(hashNext);
1180         READWRITE(nFile);
1181         READWRITE(nBlockPos);
1182         READWRITE(nHeight);
1183 
1184         // block header
1185         READWRITE(this->nVersion);
1186         READWRITE(hashPrev);
1187         READWRITE(hashMerkleRoot);
1188         READWRITE(nTime);
1189         READWRITE(nBits);
1190         READWRITE(nNonce);
1191     )
1192 
1193     uint256 GetBlockHash() const
1194     {
1195         CBlock block;
1196         block.nVersion        = nVersion;
1197         block.hashPrevBlock   = hashPrev;
1198         block.hashMerkleRoot  = hashMerkleRoot;
1199         block.nTime           = nTime;
1200         block.nBits           = nBits;
1201         block.nNonce          = nNonce;
1202         return block.GetHash();
1203     }
1204 
1205 
1206     std::string ToString() const
1207     {
1208         std::string str = "CDiskBlockIndex(";
1209         str += CBlockIndex::ToString();
1210         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1211             GetBlockHash().ToString().c_str(),
1212             hashPrev.ToString().substr(0,20).c_str(),
1213             hashNext.ToString().substr(0,20).c_str());
1214         return str;
1215     }
1216 
1217     void print() const
1218     {
1219         printf("%s\n", ToString().c_str());
1220     }
1221 };
1222 
1223 
1224 
1225 
1226 
1227 
1228 
1229 
1230 //
1231 // Describes a place in the block chain to another node such that if the
1232 // other node doesn't have the same branch, it can find a recent common trunk.
1233 // The further back it is, the further before the fork it may be.
1234 //
1235 class CBlockLocator
1236 {
1237 protected:
1238     std::vector<uint256> vHave;
1239 public:
1240 
1241     CBlockLocator()
1242     {
1243     }
1244 
1245     explicit CBlockLocator(const CBlockIndex* pindex)
1246     {
1247         Set(pindex);
1248     }
1249 
1250     explicit CBlockLocator(uint256 hashBlock)
1251     {
1252         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1253         if (mi != mapBlockIndex.end())
1254             Set((*mi).second);
1255     }
1256 
1257     IMPLEMENT_SERIALIZE
1258     (
1259         if (!(nType & SER_GETHASH))
1260             READWRITE(nVersion);
1261         READWRITE(vHave);
1262     )
1263 
1264     void SetNull()
1265     {
1266         vHave.clear();
1267     }
1268 
1269     bool IsNull()
1270     {
1271         return vHave.empty();
1272     }
1273 
1274     void Set(const CBlockIndex* pindex)
1275     {
1276         vHave.clear();
1277         int nStep = 1;
1278         while (pindex)
1279         {
1280             vHave.push_back(pindex->GetBlockHash());
1281 
1282             // Exponentially larger steps back
1283             for (int i = 0; pindex && i < nStep; i++)
1284                 pindex = pindex->pprev;
1285             if (vHave.size() > 10)
1286                 nStep *= 2;
1287         }
1288         vHave.push_back(hashGenesisBlock);
1289     }
1290 
1291     int GetDistanceBack()
1292     {
1293         // Retrace how far back it was in the sender's branch
1294         int nDistance = 0;
1295         int nStep = 1;
1296         BOOST_FOREACH(const uint256& hash, vHave)
1297         {
1298             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1299             if (mi != mapBlockIndex.end())
1300             {
1301                 CBlockIndex* pindex = (*mi).second;
1302                 if (pindex->IsInMainChain())
1303                     return nDistance;
1304             }
1305             nDistance += nStep;
1306             if (nDistance > 10)
1307                 nStep *= 2;
1308         }
1309         return nDistance;
1310     }
1311 
1312     CBlockIndex* GetBlockIndex()
1313     {
1314         // Find the first block the caller has in the main chain
1315         BOOST_FOREACH(const uint256& hash, vHave)
1316         {
1317             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1318             if (mi != mapBlockIndex.end())
1319             {
1320                 CBlockIndex* pindex = (*mi).second;
1321                 if (pindex->IsInMainChain())
1322                     return pindex;
1323             }
1324         }
1325         return pindexGenesisBlock;
1326     }
1327 
1328     uint256 GetBlockHash()
1329     {
1330         // Find the first block the caller has in the main chain
1331         BOOST_FOREACH(const uint256& hash, vHave)
1332         {
1333             std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1334             if (mi != mapBlockIndex.end())
1335             {
1336                 CBlockIndex* pindex = (*mi).second;
1337                 if (pindex->IsInMainChain())
1338                     return hash;
1339             }
1340         }
1341         return hashGenesisBlock;
1342     }
1343 
1344     int GetHeight()
1345     {
1346         CBlockIndex* pindex = GetBlockIndex();
1347         if (!pindex)
1348             return 0;
1349         return pindex->nHeight;
1350     }
1351 };
1352 
1353 #endif