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