Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.1.0 · 2009-01-08

main.h

1,317 lines · plain text · MIT license (license.txt)
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45class COutPoint;6class CInPoint;7class CDiskTxPos;8class CCoinBase;9class CTxIn;10class CTxOut;11class CTransaction;12class CBlock;13class CBlockIndex;14class CWalletTx;15class CKeyItem;1617static const unsigned int MAX_SIZE = 0x02000000;18static const int64 COIN = 100000000;19static const int64 CENT = 1000000;20static const int COINBASE_MATURITY = 100;2122static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);23242526272829extern CCriticalSection cs_main;30extern map<uint256, CBlockIndex*> mapBlockIndex;31extern const uint256 hashGenesisBlock;32extern CBlockIndex* pindexGenesisBlock;33extern int nBestHeight;34extern uint256 hashBestChain;35extern CBlockIndex* pindexBest;36extern unsigned int nTransactionsUpdated;37extern string strSetDataDir;38extern int nDropMessagesTest;3940// Settings41extern int fGenerateBitcoins;42extern int64 nTransactionFee;43extern CAddress addrIncoming;4445464748495051string GetAppDir();52FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");53FILE* AppendBlockFile(unsigned int& nFileRet);54bool AddKey(const CKey& key);55vector<unsigned char> GenerateNewKey();56bool AddToWallet(const CWalletTx& wtxIn);57void ReacceptWalletTransactions();58void RelayWalletTransactions();59bool LoadBlockIndex(bool fAllowNew=true);60void PrintBlockTree();61bool BitcoinMiner();62bool ProcessMessages(CNode* pfrom);63bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);64bool SendMessages(CNode* pto);65int64 GetBalance();66bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& txNew, int64& nFeeRequiredRet);67bool CommitTransactionSpent(const CWalletTx& wtxNew);68bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew);697071727374757677787980class CDiskTxPos81{82public:83    unsigned int nFile;84    unsigned int nBlockPos;85    unsigned int nTxPos;8687    CDiskTxPos()88    {89        SetNull();90    }9192    CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)93    {94        nFile = nFileIn;95        nBlockPos = nBlockPosIn;96        nTxPos = nTxPosIn;97    }9899    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )100    void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }101    bool IsNull() const { return (nFile == -1); }102103    friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)104    {105        return (a.nFile     == b.nFile &&106                a.nBlockPos == b.nBlockPos &&107                a.nTxPos    == b.nTxPos);108    }109110    friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)111    {112        return !(a == b);113    }114115    string ToString() const116    {117        if (IsNull())118            return strprintf("null");119        else120            return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);121    }122123    void print() const124    {125        printf("%s", ToString().c_str());126    }127};128129130131132class CInPoint133{134public:135    CTransaction* ptx;136    unsigned int n;137138    CInPoint() { SetNull(); }139    CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }140    void SetNull() { ptx = NULL; n = -1; }141    bool IsNull() const { return (ptx == NULL && n == -1); }142};143144145146147class COutPoint148{149public:150    uint256 hash;151    unsigned int n;152153    COutPoint() { SetNull(); }154    COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }155    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )156    void SetNull() { hash = 0; n = -1; }157    bool IsNull() const { return (hash == 0 && n == -1); }158159    friend bool operator<(const COutPoint& a, const COutPoint& b)160    {161        return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));162    }163164    friend bool operator==(const COutPoint& a, const COutPoint& b)165    {166        return (a.hash == b.hash && a.n == b.n);167    }168169    friend bool operator!=(const COutPoint& a, const COutPoint& b)170    {171        return !(a == b);172    }173174    string ToString() const175    {176        return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);177    }178179    void print() const180    {181        printf("%s\n", ToString().c_str());182    }183};184185186187188//189// An input of a transaction.  It contains the location of the previous190// transaction's output that it claims and a signature that matches the191// output's public key.192//193class CTxIn194{195public:196    COutPoint prevout;197    CScript scriptSig;198    unsigned int nSequence;199200    CTxIn()201    {202        nSequence = UINT_MAX;203    }204205    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)206    {207        prevout = prevoutIn;208        scriptSig = scriptSigIn;209        nSequence = nSequenceIn;210    }211212    CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)213    {214        prevout = COutPoint(hashPrevTx, nOut);215        scriptSig = scriptSigIn;216        nSequence = nSequenceIn;217    }218219    IMPLEMENT_SERIALIZE220    (221        READWRITE(prevout);222        READWRITE(scriptSig);223        READWRITE(nSequence);224    )225226    bool IsFinal() const227    {228        return (nSequence == UINT_MAX);229    }230231    friend bool operator==(const CTxIn& a, const CTxIn& b)232    {233        return (a.prevout   == b.prevout &&234                a.scriptSig == b.scriptSig &&235                a.nSequence == b.nSequence);236    }237238    friend bool operator!=(const CTxIn& a, const CTxIn& b)239    {240        return !(a == b);241    }242243    string ToString() const244    {245        string str;246        str += strprintf("CTxIn(");247        str += prevout.ToString();248        if (prevout.IsNull())249            str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());250        else251            str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());252        if (nSequence != UINT_MAX)253            str += strprintf(", nSequence=%u", nSequence);254        str += ")";255        return str;256    }257258    void print() const259    {260        printf("%s\n", ToString().c_str());261    }262263    bool IsMine() const;264    int64 GetDebit() const;265};266267268269270//271// An output of a transaction.  It contains the public key that the next input272// must be able to sign with to claim it.273//274class CTxOut275{276public:277    int64 nValue;278    CScript scriptPubKey;279280public:281    CTxOut()282    {283        SetNull();284    }285286    CTxOut(int64 nValueIn, CScript scriptPubKeyIn)287    {288        nValue = nValueIn;289        scriptPubKey = scriptPubKeyIn;290    }291292    IMPLEMENT_SERIALIZE293    (294        READWRITE(nValue);295        READWRITE(scriptPubKey);296    )297298    void SetNull()299    {300        nValue = -1;301        scriptPubKey.clear();302    }303304    bool IsNull()305    {306        return (nValue == -1);307    }308309    uint256 GetHash() const310    {311        return SerializeHash(*this);312    }313314    bool IsMine() const315    {316        return ::IsMine(scriptPubKey);317    }318319    int64 GetCredit() const320    {321        if (IsMine())322            return nValue;323        return 0;324    }325326    friend bool operator==(const CTxOut& a, const CTxOut& b)327    {328        return (a.nValue       == b.nValue &&329                a.scriptPubKey == b.scriptPubKey);330    }331332    friend bool operator!=(const CTxOut& a, const CTxOut& b)333    {334        return !(a == b);335    }336337    string ToString() const338    {339        if (scriptPubKey.size() < 6)340            return "CTxOut(error)";341        return strprintf("CTxOut(nValue=%I64d.%08I64d, scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());342    }343344    void print() const345    {346        printf("%s\n", ToString().c_str());347    }348};349350351352353//354// The basic transaction that is broadcasted on the network and contained in355// blocks.  A transaction can contain multiple inputs and outputs.356//357class CTransaction358{359public:360    int nVersion;361    vector<CTxIn> vin;362    vector<CTxOut> vout;363    int nLockTime;364365366    CTransaction()367    {368        SetNull();369    }370371    IMPLEMENT_SERIALIZE372    (373        READWRITE(this->nVersion);374        nVersion = this->nVersion;375        READWRITE(vin);376        READWRITE(vout);377        READWRITE(nLockTime);378    )379380    void SetNull()381    {382        nVersion = 1;383        vin.clear();384        vout.clear();385        nLockTime = 0;386    }387388    bool IsNull() const389    {390        return (vin.empty() && vout.empty());391    }392393    uint256 GetHash() const394    {395        return SerializeHash(*this);396    }397398    bool IsFinal() const399    {400        if (nLockTime == 0 || nLockTime < nBestHeight)401            return true;402        foreach(const CTxIn& txin, vin)403            if (!txin.IsFinal())404                return false;405        return true;406    }407408    bool IsNewerThan(const CTransaction& old) const409    {410        if (vin.size() != old.vin.size())411            return false;412        for (int i = 0; i < vin.size(); i++)413            if (vin[i].prevout != old.vin[i].prevout)414                return false;415416        bool fNewer = false;417        unsigned int nLowest = UINT_MAX;418        for (int i = 0; i < vin.size(); i++)419        {420            if (vin[i].nSequence != old.vin[i].nSequence)421            {422                if (vin[i].nSequence <= nLowest)423                {424                    fNewer = false;425                    nLowest = vin[i].nSequence;426                }427                if (old.vin[i].nSequence < nLowest)428                {429                    fNewer = true;430                    nLowest = old.vin[i].nSequence;431                }432            }433        }434        return fNewer;435    }436437    bool IsCoinBase() const438    {439        return (vin.size() == 1 && vin[0].prevout.IsNull());440    }441442    bool CheckTransaction() const443    {444        // Basic checks that don't depend on any context445        if (vin.empty() || vout.empty())446            return error("CTransaction::CheckTransaction() : vin or vout empty");447448        // Check for negative values449        foreach(const CTxOut& txout, vout)450            if (txout.nValue < 0)451                return error("CTransaction::CheckTransaction() : txout.nValue negative");452453        if (IsCoinBase())454        {455            if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)456                return error("CTransaction::CheckTransaction() : coinbase script size");457        }458        else459        {460            foreach(const CTxIn& txin, vin)461                if (txin.prevout.IsNull())462                    return error("CTransaction::CheckTransaction() : prevout is null");463        }464465        return true;466    }467468    bool IsMine() const469    {470        foreach(const CTxOut& txout, vout)471            if (txout.IsMine())472                return true;473        return false;474    }475476    int64 GetDebit() const477    {478        int64 nDebit = 0;479        foreach(const CTxIn& txin, vin)480            nDebit += txin.GetDebit();481        return nDebit;482    }483484    int64 GetCredit() const485    {486        int64 nCredit = 0;487        foreach(const CTxOut& txout, vout)488            nCredit += txout.GetCredit();489        return nCredit;490    }491492    int64 GetValueOut() const493    {494        int64 nValueOut = 0;495        foreach(const CTxOut& txout, vout)496        {497            if (txout.nValue < 0)498                throw runtime_error("CTransaction::GetValueOut() : negative value");499            nValueOut += txout.nValue;500        }501        return nValueOut;502    }503504    int64 GetMinFee(bool fDiscount=false) const505    {506        unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);507        if (fDiscount && nBytes < 10000)508            return 0;509        return (1 + (int64)nBytes / 1000) * CENT;510    }511512513514    bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)515    {516        CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");517        if (!filein)518            return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");519520        // Read transaction521        if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)522            return error("CTransaction::ReadFromDisk() : fseek failed");523        filein >> *this;524525        // Return file pointer526        if (pfileRet)527        {528            if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)529                return error("CTransaction::ReadFromDisk() : second fseek failed");530            *pfileRet = filein.release();531        }532        return true;533    }534535536    friend bool operator==(const CTransaction& a, const CTransaction& b)537    {538        return (a.nVersion  == b.nVersion &&539                a.vin       == b.vin &&540                a.vout      == b.vout &&541                a.nLockTime == b.nLockTime);542    }543544    friend bool operator!=(const CTransaction& a, const CTransaction& b)545    {546        return !(a == b);547    }548549550    string ToString() const551    {552        string str;553        str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",554            GetHash().ToString().substr(0,6).c_str(),555            nVersion,556            vin.size(),557            vout.size(),558            nLockTime);559        for (int i = 0; i < vin.size(); i++)560            str += "    " + vin[i].ToString() + "\n";561        for (int i = 0; i < vout.size(); i++)562            str += "    " + vout[i].ToString() + "\n";563        return str;564    }565566    void print() const567    {568        printf("%s", ToString().c_str());569    }570571572573    bool DisconnectInputs(CTxDB& txdb);574    bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);575    bool ClientConnectInputs();576577    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);578579    bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)580    {581        CTxDB txdb("r");582        return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);583    }584585protected:586    bool AddToMemoryPool();587public:588    bool RemoveFromMemoryPool();589};590591592593594595//596// A transaction with a merkle branch linking it to the block chain597//598class CMerkleTx : public CTransaction599{600public:601    uint256 hashBlock;602    vector<uint256> vMerkleBranch;603    int nIndex;604605    // memory only606    mutable bool fMerkleVerified;607608609    CMerkleTx()610    {611        Init();612    }613614    CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)615    {616        Init();617    }618619    void Init()620    {621        hashBlock = 0;622        nIndex = -1;623        fMerkleVerified = false;624    }625626    int64 GetCredit() const627    {628        // Must wait until coinbase is safely deep enough in the chain before valuing it629        if (IsCoinBase() && GetBlocksToMaturity() > 0)630            return 0;631        return CTransaction::GetCredit();632    }633634    IMPLEMENT_SERIALIZE635    (636        nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);637        nVersion = this->nVersion;638        READWRITE(hashBlock);639        READWRITE(vMerkleBranch);640        READWRITE(nIndex);641    )642643644    int SetMerkleBranch(const CBlock* pblock=NULL);645    int GetDepthInMainChain() const;646    bool IsInMainChain() const { return GetDepthInMainChain() > 0; }647    int GetBlocksToMaturity() const;648    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);649    bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }650};651652653654655//656// A transaction with a bunch of additional info that only the owner cares657// about.  It includes any unrecorded transactions needed to link it back658// to the block chain.659//660class CWalletTx : public CMerkleTx661{662public:663    vector<CMerkleTx> vtxPrev;664    map<string, string> mapValue;665    vector<pair<string, string> > vOrderForm;666    unsigned int fTimeReceivedIsTxTime;667    unsigned int nTimeReceived;  // time received by this node668    char fFromMe;669    char fSpent;670    //// probably need to sign the order info so know it came from payer671672    // memory only673    mutable unsigned int nTimeDisplayed;674675676    CWalletTx()677    {678        Init();679    }680681    CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)682    {683        Init();684    }685686    CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)687    {688        Init();689    }690691    void Init()692    {693        fTimeReceivedIsTxTime = false;694        nTimeReceived = 0;695        fFromMe = false;696        fSpent = false;697        nTimeDisplayed = 0;698    }699700    IMPLEMENT_SERIALIZE701    (702        nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);703        nVersion = this->nVersion;704        READWRITE(vtxPrev);705        READWRITE(mapValue);706        READWRITE(vOrderForm);707        READWRITE(fTimeReceivedIsTxTime);708        READWRITE(nTimeReceived);709        READWRITE(fFromMe);710        READWRITE(fSpent);711    )712713    bool WriteToDisk()714    {715        return CWalletDB().WriteTx(GetHash(), *this);716    }717718719    int64 GetTxTime() const;720721    void AddSupportingTransactions(CTxDB& txdb);722723    bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);724    bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }725726    void RelayWalletTransaction(CTxDB& txdb);727    void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }728};729730731732733//734// A txdb record that contains the disk location of a transaction and the735// locations of transactions that spend its outputs.  vSpent is really only736// used as a flag, but having the location is very helpful for debugging.737//738class CTxIndex739{740public:741    CDiskTxPos pos;742    vector<CDiskTxPos> vSpent;743744    CTxIndex()745    {746        SetNull();747    }748749    CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)750    {751        pos = posIn;752        vSpent.resize(nOutputs);753    }754755    IMPLEMENT_SERIALIZE756    (757        if (!(nType & SER_GETHASH))758            READWRITE(nVersion);759        READWRITE(pos);760        READWRITE(vSpent);761    )762763    void SetNull()764    {765        pos.SetNull();766        vSpent.clear();767    }768769    bool IsNull()770    {771        return pos.IsNull();772    }773774    friend bool operator==(const CTxIndex& a, const CTxIndex& b)775    {776        if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())777            return false;778        for (int i = 0; i < a.vSpent.size(); i++)779            if (a.vSpent[i] != b.vSpent[i])780                return false;781        return true;782    }783784    friend bool operator!=(const CTxIndex& a, const CTxIndex& b)785    {786        return !(a == b);787    }788};789790791792793794//795// Nodes collect new transactions into a block, hash them into a hash tree,796// and scan through nonce values to make the block's hash satisfy proof-of-work797// requirements.  When they solve the proof-of-work, they broadcast the block798// to everyone and the block is added to the block chain.  The first transaction799// in the block is a special one that creates a new coin owned by the creator800// of the block.801//802// Blocks are appended to blk0001.dat files on disk.  Their location on disk803// is indexed by CBlockIndex objects in memory.804//805class CBlock806{807public:808    // header809    int nVersion;810    uint256 hashPrevBlock;811    uint256 hashMerkleRoot;812    unsigned int nTime;813    unsigned int nBits;814    unsigned int nNonce;815816    // network and disk817    vector<CTransaction> vtx;818819    // memory only820    mutable vector<uint256> vMerkleTree;821822823    CBlock()824    {825        SetNull();826    }827828    IMPLEMENT_SERIALIZE829    (830        READWRITE(this->nVersion);831        nVersion = this->nVersion;832        READWRITE(hashPrevBlock);833        READWRITE(hashMerkleRoot);834        READWRITE(nTime);835        READWRITE(nBits);836        READWRITE(nNonce);837838        // ConnectBlock depends on vtx being last so it can calculate offset839        if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))840            READWRITE(vtx);841        else if (fRead)842            const_cast<CBlock*>(this)->vtx.clear();843    )844845    void SetNull()846    {847        nVersion = 1;848        hashPrevBlock = 0;849        hashMerkleRoot = 0;850        nTime = 0;851        nBits = 0;852        nNonce = 0;853        vtx.clear();854        vMerkleTree.clear();855    }856857    bool IsNull() const858    {859        return (nBits == 0);860    }861862    uint256 GetHash() const863    {864        return Hash(BEGIN(nVersion), END(nNonce));865    }866867868    uint256 BuildMerkleTree() const869    {870        vMerkleTree.clear();871        foreach(const CTransaction& tx, vtx)872            vMerkleTree.push_back(tx.GetHash());873        int j = 0;874        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)875        {876            for (int i = 0; i < nSize; i += 2)877            {878                int i2 = min(i+1, nSize-1);879                vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),880                                           BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));881            }882            j += nSize;883        }884        return (vMerkleTree.empty() ? 0 : vMerkleTree.back());885    }886887    vector<uint256> GetMerkleBranch(int nIndex) const888    {889        if (vMerkleTree.empty())890            BuildMerkleTree();891        vector<uint256> vMerkleBranch;892        int j = 0;893        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)894        {895            int i = min(nIndex^1, nSize-1);896            vMerkleBranch.push_back(vMerkleTree[j+i]);897            nIndex >>= 1;898            j += nSize;899        }900        return vMerkleBranch;901    }902903    static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)904    {905        if (nIndex == -1)906            return 0;907        foreach(const uint256& otherside, vMerkleBranch)908        {909            if (nIndex & 1)910                hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));911            else912                hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));913            nIndex >>= 1;914        }915        return hash;916    }917918919    bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)920    {921        // Open history file to append922        CAutoFile fileout = AppendBlockFile(nFileRet);923        if (!fileout)924            return error("CBlock::WriteToDisk() : AppendBlockFile failed");925        if (!fWriteTransactions)926            fileout.nType |= SER_BLOCKHEADERONLY;927928        // Write index header929        unsigned int nSize = fileout.GetSerializeSize(*this);930        fileout << FLATDATA(pchMessageStart) << nSize;931932        // Write block933        nBlockPosRet = ftell(fileout);934        if (nBlockPosRet == -1)935            return error("CBlock::WriteToDisk() : ftell failed");936        fileout << *this;937938        return true;939    }940941    bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)942    {943        SetNull();944945        // Open history file to read946        CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");947        if (!filein)948            return error("CBlock::ReadFromDisk() : OpenBlockFile failed");949        if (!fReadTransactions)950            filein.nType |= SER_BLOCKHEADERONLY;951952        // Read block953        filein >> *this;954955        // Check the header956        if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)957            return error("CBlock::ReadFromDisk() : nBits errors in block header");958        if (GetHash() > CBigNum().SetCompact(nBits).getuint256())959            return error("CBlock::ReadFromDisk() : GetHash() errors in block header");960961        return true;962    }963964965966    void print() const967    {968        printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",969            GetHash().ToString().substr(0,14).c_str(),970            nVersion,971            hashPrevBlock.ToString().substr(0,14).c_str(),972            hashMerkleRoot.ToString().substr(0,6).c_str(),973            nTime, nBits, nNonce,974            vtx.size());975        for (int i = 0; i < vtx.size(); i++)976        {977            printf("  ");978            vtx[i].print();979        }980        printf("  vMerkleTree: ");981        for (int i = 0; i < vMerkleTree.size(); i++)982            printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());983        printf("\n");984    }985986987    int64 GetBlockValue(int64 nFees) const;988    bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);989    bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);990    bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions);991    bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);992    bool CheckBlock() const;993    bool AcceptBlock();994};99599699799899910001001//1002// The block chain is a tree shaped structure starting with the1003// genesis block at the root, with each block potentially having multiple1004// candidates to be the next block.  pprev and pnext link a path through the1005// main/longest chain.  A blockindex may have multiple pprev pointing back1006// to it, but pnext will only point forward to the longest branch, or will1007// be null if the block is not part of the longest chain.1008//1009class CBlockIndex1010{1011public:1012    const uint256* phashBlock;1013    CBlockIndex* pprev;1014    CBlockIndex* pnext;1015    unsigned int nFile;1016    unsigned int nBlockPos;1017    int nHeight;10181019    // block header1020    int nVersion;1021    uint256 hashMerkleRoot;1022    unsigned int nTime;1023    unsigned int nBits;1024    unsigned int nNonce;102510261027    CBlockIndex()1028    {1029        phashBlock = NULL;1030        pprev = NULL;1031        pnext = NULL;1032        nFile = 0;1033        nBlockPos = 0;1034        nHeight = 0;10351036        nVersion       = 0;1037        hashMerkleRoot = 0;1038        nTime          = 0;1039        nBits          = 0;1040        nNonce         = 0;1041    }10421043    CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)1044    {1045        phashBlock = NULL;1046        pprev = NULL;1047        pnext = NULL;1048        nFile = nFileIn;1049        nBlockPos = nBlockPosIn;1050        nHeight = 0;10511052        nVersion       = block.nVersion;1053        hashMerkleRoot = block.hashMerkleRoot;1054        nTime          = block.nTime;1055        nBits          = block.nBits;1056        nNonce         = block.nNonce;1057    }10581059    uint256 GetBlockHash() const1060    {1061        return *phashBlock;1062    }10631064    bool IsInMainChain() const1065    {1066        return (pnext || this == pindexBest);1067    }10681069    bool EraseBlockFromDisk()1070    {1071        // Open history file1072        CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");1073        if (!fileout)1074            return false;10751076        // Overwrite with empty null block1077        CBlock block;1078        block.SetNull();1079        fileout << block;10801081        return true;1082    }10831084    enum { nMedianTimeSpan=11 };10851086    int64 GetMedianTimePast() const1087    {1088        unsigned int pmedian[nMedianTimeSpan];1089        unsigned int* pbegin = &pmedian[nMedianTimeSpan];1090        unsigned int* pend = &pmedian[nMedianTimeSpan];10911092        const CBlockIndex* pindex = this;1093        for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)1094            *(--pbegin) = pindex->nTime;10951096        sort(pbegin, pend);1097        return pbegin[(pend - pbegin)/2];1098    }10991100    int64 GetMedianTime() const1101    {1102        const CBlockIndex* pindex = this;1103        for (int i = 0; i < nMedianTimeSpan/2; i++)1104        {1105            if (!pindex->pnext)1106                return nTime;1107            pindex = pindex->pnext;1108        }1109        return pindex->GetMedianTimePast();1110    }1111111211131114    string ToString() const1115    {1116        return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",1117            pprev, pnext, nFile, nBlockPos, nHeight,1118            hashMerkleRoot.ToString().substr(0,6).c_str(),1119            GetBlockHash().ToString().substr(0,14).c_str());1120    }11211122    void print() const1123    {1124        printf("%s\n", ToString().c_str());1125    }1126};1127112811291130//1131// Used to marshal pointers into hashes for db storage.1132//1133class CDiskBlockIndex : public CBlockIndex1134{1135public:1136    uint256 hashPrev;1137    uint256 hashNext;11381139    CDiskBlockIndex()1140    {1141        hashPrev = 0;1142        hashNext = 0;1143    }11441145    explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)1146    {1147        hashPrev = (pprev ? pprev->GetBlockHash() : 0);1148        hashNext = (pnext ? pnext->GetBlockHash() : 0);1149    }11501151    IMPLEMENT_SERIALIZE1152    (1153        if (!(nType & SER_GETHASH))1154            READWRITE(nVersion);11551156        READWRITE(hashNext);1157        READWRITE(nFile);1158        READWRITE(nBlockPos);1159        READWRITE(nHeight);11601161        // block header1162        READWRITE(this->nVersion);1163        READWRITE(hashPrev);1164        READWRITE(hashMerkleRoot);1165        READWRITE(nTime);1166        READWRITE(nBits);1167        READWRITE(nNonce);1168    )11691170    uint256 GetBlockHash() const1171    {1172        CBlock block;1173        block.nVersion        = nVersion;1174        block.hashPrevBlock   = hashPrev;1175        block.hashMerkleRoot  = hashMerkleRoot;1176        block.nTime           = nTime;1177        block.nBits           = nBits;1178        block.nNonce          = nNonce;1179        return block.GetHash();1180    }118111821183    string ToString() const1184    {1185        string str = "CDiskBlockIndex(";1186        str += CBlockIndex::ToString();1187        str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",1188            GetBlockHash().ToString().c_str(),1189            hashPrev.ToString().substr(0,14).c_str(),1190            hashNext.ToString().substr(0,14).c_str());1191        return str;1192    }11931194    void print() const1195    {1196        printf("%s\n", ToString().c_str());1197    }1198};119912001201120212031204120512061207//1208// Describes a place in the block chain to another node such that if the1209// other node doesn't have the same branch, it can find a recent common trunk.1210// The further back it is, the further before the fork it may be.1211//1212class CBlockLocator1213{1214protected:1215    vector<uint256> vHave;1216public:12171218    CBlockLocator()1219    {1220    }12211222    explicit CBlockLocator(const CBlockIndex* pindex)1223    {1224        Set(pindex);1225    }12261227    explicit CBlockLocator(uint256 hashBlock)1228    {1229        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);1230        if (mi != mapBlockIndex.end())1231            Set((*mi).second);1232    }12331234    IMPLEMENT_SERIALIZE1235    (1236        if (!(nType & SER_GETHASH))1237            READWRITE(nVersion);1238        READWRITE(vHave);1239    )12401241    void Set(const CBlockIndex* pindex)1242    {1243        vHave.clear();1244        int nStep = 1;1245        while (pindex)1246        {1247            vHave.push_back(pindex->GetBlockHash());12481249            // Exponentially larger steps back1250            for (int i = 0; pindex && i < nStep; i++)1251                pindex = pindex->pprev;1252            if (vHave.size() > 10)1253                nStep *= 2;1254        }1255        vHave.push_back(hashGenesisBlock);1256    }12571258    CBlockIndex* GetBlockIndex()1259    {1260        // Find the first block the caller has in the main chain1261        foreach(const uint256& hash, vHave)1262        {1263            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1264            if (mi != mapBlockIndex.end())1265            {1266                CBlockIndex* pindex = (*mi).second;1267                if (pindex->IsInMainChain())1268                    return pindex;1269            }1270        }1271        return pindexGenesisBlock;1272    }12731274    uint256 GetBlockHash()1275    {1276        // Find the first block the caller has in the main chain1277        foreach(const uint256& hash, vHave)1278        {1279            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1280            if (mi != mapBlockIndex.end())1281            {1282                CBlockIndex* pindex = (*mi).second;1283                if (pindex->IsInMainChain())1284                    return hash;1285            }1286        }1287        return hashGenesisBlock;1288    }12891290    int GetHeight()1291    {1292        CBlockIndex* pindex = GetBlockIndex();1293        if (!pindex)1294            return 0;1295        return pindex->nHeight;1296    }1297};1298129913001301130213031304130513061307130813091310extern map<uint256, CTransaction> mapTransactions;1311extern map<uint256, CWalletTx> mapWallet;1312extern vector<pair<uint256, bool> > vWalletUpdated;1313extern CCriticalSection cs_mapWallet;1314extern map<vector<unsigned char>, CPrivKey> mapKeys;1315extern map<uint160, vector<unsigned char> > mapPubKeys;1316extern CCriticalSection cs_mapKeys;1317extern CKey keyUser;

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00