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.3.10 · 2010-08-15

main.h

1,452 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 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 unsigned int MAX_BLOCK_SIZE = 1000000;19static const int64 COIN = 100000000;20static const int64 CENT = 1000000;21static const int64 MAX_MONEY = 21000000 * COIN;22static const int COINBASE_MATURITY = 100;2324static const CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);25262728293031extern CCriticalSection cs_main;32extern map<uint256, CBlockIndex*> mapBlockIndex;33extern const uint256 hashGenesisBlock;34extern CBlockIndex* pindexGenesisBlock;35extern int nBestHeight;36extern CBigNum bnBestChainWork;37extern CBigNum bnBestInvalidWork;38extern uint256 hashBestChain;39extern CBlockIndex* pindexBest;40extern unsigned int nTransactionsUpdated;41extern map<uint256, int> mapRequestCount;42extern CCriticalSection cs_mapRequestCount;43extern map<string, string> mapAddressBook;44extern CCriticalSection cs_mapAddressBook;45extern vector<unsigned char> vchDefaultKey;46extern double dHashesPerSec;47extern int64 nHPSTimerStart;4849// Settings50extern int fGenerateBitcoins;51extern int64 nTransactionFee;52extern CAddress addrIncoming;53extern int fLimitProcessors;54extern int nLimitProcessors;55extern int fMinimizeToTray;56extern int fMinimizeOnClose;5758596061626364bool CheckDiskSpace(int64 nAdditionalBytes=0);65FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");66FILE* AppendBlockFile(unsigned int& nFileRet);67bool AddKey(const CKey& key);68vector<unsigned char> GenerateNewKey();69bool AddToWallet(const CWalletTx& wtxIn);70void WalletUpdateSpent(const COutPoint& prevout);71void ReacceptWalletTransactions();72bool LoadBlockIndex(bool fAllowNew=true);73void PrintBlockTree();74bool ProcessMessages(CNode* pfrom);75bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);76bool SendMessages(CNode* pto, bool fSendTrickle);77int64 GetBalance();78bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);79bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);80bool BroadcastTransaction(CWalletTx& wtxNew);81string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);82string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);83void GenerateBitcoins(bool fGenerate);84void ThreadBitcoinMiner(void* parg);85void BitcoinMiner();86bool IsInitialBlockDownload();87bool IsLockdown();888990919293949596979899100class CDiskTxPos101{102public:103    unsigned int nFile;104    unsigned int nBlockPos;105    unsigned int nTxPos;106107    CDiskTxPos()108    {109        SetNull();110    }111112    CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)113    {114        nFile = nFileIn;115        nBlockPos = nBlockPosIn;116        nTxPos = nTxPosIn;117    }118119    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )120    void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }121    bool IsNull() const { return (nFile == -1); }122123    friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)124    {125        return (a.nFile     == b.nFile &&126                a.nBlockPos == b.nBlockPos &&127                a.nTxPos    == b.nTxPos);128    }129130    friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)131    {132        return !(a == b);133    }134135    string ToString() const136    {137        if (IsNull())138            return strprintf("null");139        else140            return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);141    }142143    void print() const144    {145        printf("%s", ToString().c_str());146    }147};148149150151152class CInPoint153{154public:155    CTransaction* ptx;156    unsigned int n;157158    CInPoint() { SetNull(); }159    CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }160    void SetNull() { ptx = NULL; n = -1; }161    bool IsNull() const { return (ptx == NULL && n == -1); }162};163164165166167class COutPoint168{169public:170    uint256 hash;171    unsigned int n;172173    COutPoint() { SetNull(); }174    COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }175    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )176    void SetNull() { hash = 0; n = -1; }177    bool IsNull() const { return (hash == 0 && n == -1); }178179    friend bool operator<(const COutPoint& a, const COutPoint& b)180    {181        return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));182    }183184    friend bool operator==(const COutPoint& a, const COutPoint& b)185    {186        return (a.hash == b.hash && a.n == b.n);187    }188189    friend bool operator!=(const COutPoint& a, const COutPoint& b)190    {191        return !(a == b);192    }193194    string ToString() const195    {196        return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);197    }198199    void print() const200    {201        printf("%s\n", ToString().c_str());202    }203};204205206207208//209// An input of a transaction.  It contains the location of the previous210// transaction's output that it claims and a signature that matches the211// output's public key.212//213class CTxIn214{215public:216    COutPoint prevout;217    CScript scriptSig;218    unsigned int nSequence;219220    CTxIn()221    {222        nSequence = UINT_MAX;223    }224225    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)226    {227        prevout = prevoutIn;228        scriptSig = scriptSigIn;229        nSequence = nSequenceIn;230    }231232    CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)233    {234        prevout = COutPoint(hashPrevTx, nOut);235        scriptSig = scriptSigIn;236        nSequence = nSequenceIn;237    }238239    IMPLEMENT_SERIALIZE240    (241        READWRITE(prevout);242        READWRITE(scriptSig);243        READWRITE(nSequence);244    )245246    bool IsFinal() const247    {248        return (nSequence == UINT_MAX);249    }250251    friend bool operator==(const CTxIn& a, const CTxIn& b)252    {253        return (a.prevout   == b.prevout &&254                a.scriptSig == b.scriptSig &&255                a.nSequence == b.nSequence);256    }257258    friend bool operator!=(const CTxIn& a, const CTxIn& b)259    {260        return !(a == b);261    }262263    string ToString() const264    {265        string str;266        str += strprintf("CTxIn(");267        str += prevout.ToString();268        if (prevout.IsNull())269            str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());270        else271            str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());272        if (nSequence != UINT_MAX)273            str += strprintf(", nSequence=%u", nSequence);274        str += ")";275        return str;276    }277278    void print() const279    {280        printf("%s\n", ToString().c_str());281    }282283    bool IsMine() const;284    int64 GetDebit() const;285};286287288289290//291// An output of a transaction.  It contains the public key that the next input292// must be able to sign with to claim it.293//294class CTxOut295{296public:297    int64 nValue;298    CScript scriptPubKey;299300public:301    CTxOut()302    {303        SetNull();304    }305306    CTxOut(int64 nValueIn, CScript scriptPubKeyIn)307    {308        nValue = nValueIn;309        scriptPubKey = scriptPubKeyIn;310    }311312    IMPLEMENT_SERIALIZE313    (314        READWRITE(nValue);315        READWRITE(scriptPubKey);316    )317318    void SetNull()319    {320        nValue = -1;321        scriptPubKey.clear();322    }323324    bool IsNull()325    {326        return (nValue == -1);327    }328329    uint256 GetHash() const330    {331        return SerializeHash(*this);332    }333334    bool IsMine() const335    {336        return ::IsMine(scriptPubKey);337    }338339    int64 GetCredit() const340    {341        if (IsMine())342            return nValue;343        return 0;344    }345346    friend bool operator==(const CTxOut& a, const CTxOut& b)347    {348        return (a.nValue       == b.nValue &&349                a.scriptPubKey == b.scriptPubKey);350    }351352    friend bool operator!=(const CTxOut& a, const CTxOut& b)353    {354        return !(a == b);355    }356357    string ToString() const358    {359        if (scriptPubKey.size() < 6)360            return "CTxOut(error)";361        return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());362    }363364    void print() const365    {366        printf("%s\n", ToString().c_str());367    }368};369370371372373//374// The basic transaction that is broadcasted on the network and contained in375// blocks.  A transaction can contain multiple inputs and outputs.376//377class CTransaction378{379public:380    int nVersion;381    vector<CTxIn> vin;382    vector<CTxOut> vout;383    unsigned int nLockTime;384385386    CTransaction()387    {388        SetNull();389    }390391    IMPLEMENT_SERIALIZE392    (393        READWRITE(this->nVersion);394        nVersion = this->nVersion;395        READWRITE(vin);396        READWRITE(vout);397        READWRITE(nLockTime);398    )399400    void SetNull()401    {402        nVersion = 1;403        vin.clear();404        vout.clear();405        nLockTime = 0;406    }407408    bool IsNull() const409    {410        return (vin.empty() && vout.empty());411    }412413    uint256 GetHash() const414    {415        return SerializeHash(*this);416    }417418    bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const419    {420        // Time based nLockTime implemented in 0.1.6421        if (nLockTime == 0)422            return true;423        if (nBlockHeight == 0)424            nBlockHeight = nBestHeight;425        if (nBlockTime == 0)426            nBlockTime = GetAdjustedTime();427        if (nLockTime < (nLockTime < 500000000 ? nBlockHeight : nBlockTime))428            return true;429        foreach(const CTxIn& txin, vin)430            if (!txin.IsFinal())431                return false;432        return true;433    }434435    bool IsNewerThan(const CTransaction& old) const436    {437        if (vin.size() != old.vin.size())438            return false;439        for (int i = 0; i < vin.size(); i++)440            if (vin[i].prevout != old.vin[i].prevout)441                return false;442443        bool fNewer = false;444        unsigned int nLowest = UINT_MAX;445        for (int i = 0; i < vin.size(); i++)446        {447            if (vin[i].nSequence != old.vin[i].nSequence)448            {449                if (vin[i].nSequence <= nLowest)450                {451                    fNewer = false;452                    nLowest = vin[i].nSequence;453                }454                if (old.vin[i].nSequence < nLowest)455                {456                    fNewer = true;457                    nLowest = old.vin[i].nSequence;458                }459            }460        }461        return fNewer;462    }463464    bool IsCoinBase() const465    {466        return (vin.size() == 1 && vin[0].prevout.IsNull());467    }468469    bool CheckTransaction() const470    {471        // Basic checks that don't depend on any context472        if (vin.empty() || vout.empty())473            return error("CTransaction::CheckTransaction() : vin or vout empty");474475        // Check for negative or overflow output values476        int64 nValueOut = 0;477        foreach(const CTxOut& txout, vout)478        {479            if (txout.nValue < 0)480                return error("CTransaction::CheckTransaction() : txout.nValue negative");481            if (txout.nValue > MAX_MONEY)482                return error("CTransaction::CheckTransaction() : txout.nValue too high");483            nValueOut += txout.nValue;484            if (nValueOut > MAX_MONEY)485                return error("CTransaction::CheckTransaction() : txout total too high");486        }487488        if (IsCoinBase())489        {490            if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)491                return error("CTransaction::CheckTransaction() : coinbase script size");492        }493        else494        {495            foreach(const CTxIn& txin, vin)496                if (txin.prevout.IsNull())497                    return error("CTransaction::CheckTransaction() : prevout is null");498        }499500        return true;501    }502503    bool IsMine() const504    {505        foreach(const CTxOut& txout, vout)506            if (txout.IsMine())507                return true;508        return false;509    }510511    int64 GetDebit() const512    {513        int64 nDebit = 0;514        foreach(const CTxIn& txin, vin)515            nDebit += txin.GetDebit();516        return nDebit;517    }518519    int64 GetCredit() const520    {521        int64 nCredit = 0;522        foreach(const CTxOut& txout, vout)523            nCredit += txout.GetCredit();524        return nCredit;525    }526527    int64 GetValueOut() const528    {529        int64 nValueOut = 0;530        foreach(const CTxOut& txout, vout)531        {532            if (txout.nValue < 0)533                throw runtime_error("CTransaction::GetValueOut() : negative value");534            nValueOut += txout.nValue;535        }536        return nValueOut;537    }538539    int64 GetMinFee(unsigned int nBlockSize=1) const540    {541        // Base fee is 1 cent per kilobyte542        unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);543        int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;544545        // Transactions under 60K are free as long as block size is under 80K546        // (about 27,000bc if made of 50bc inputs)547        if (nBytes < 60000 && nBlockSize < 80000)548            nMinFee = 0;549550        // Transactions under 3K are free as long as block size is under 200K551        if (nBytes < 3000 && nBlockSize < 200000)552            nMinFee = 0;553554        // To limit dust spam, require a 0.01 fee if any output is less than 0.01555        if (nMinFee < CENT)556            foreach(const CTxOut& txout, vout)557                if (txout.nValue < CENT)558                    nMinFee = CENT;559560        return nMinFee;561    }562563564565    bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)566    {567        CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");568        if (!filein)569            return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");570571        // Read transaction572        if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)573            return error("CTransaction::ReadFromDisk() : fseek failed");574        filein >> *this;575576        // Return file pointer577        if (pfileRet)578        {579            if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)580                return error("CTransaction::ReadFromDisk() : second fseek failed");581            *pfileRet = filein.release();582        }583        return true;584    }585586587    friend bool operator==(const CTransaction& a, const CTransaction& b)588    {589        return (a.nVersion  == b.nVersion &&590                a.vin       == b.vin &&591                a.vout      == b.vout &&592                a.nLockTime == b.nLockTime);593    }594595    friend bool operator!=(const CTransaction& a, const CTransaction& b)596    {597        return !(a == b);598    }599600601    string ToString() const602    {603        string str;604        str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",605            GetHash().ToString().substr(0,6).c_str(),606            nVersion,607            vin.size(),608            vout.size(),609            nLockTime);610        for (int i = 0; i < vin.size(); i++)611            str += "    " + vin[i].ToString() + "\n";612        for (int i = 0; i < vout.size(); i++)613            str += "    " + vout[i].ToString() + "\n";614        return str;615    }616617    void print() const618    {619        printf("%s", ToString().c_str());620    }621622623624    bool DisconnectInputs(CTxDB& txdb);625    bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,626                       CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);627    bool ClientConnectInputs();628629    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);630631    bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)632    {633        CTxDB txdb("r");634        return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);635    }636637protected:638    bool AddToMemoryPool();639public:640    bool RemoveFromMemoryPool();641};642643644645646647//648// A transaction with a merkle branch linking it to the block chain649//650class CMerkleTx : public CTransaction651{652public:653    uint256 hashBlock;654    vector<uint256> vMerkleBranch;655    int nIndex;656657    // memory only658    mutable bool fMerkleVerified;659    mutable bool fGetCreditCached;660    mutable int64 nGetCreditCached;661662663    CMerkleTx()664    {665        Init();666    }667668    CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)669    {670        Init();671    }672673    void Init()674    {675        hashBlock = 0;676        nIndex = -1;677        fMerkleVerified = false;678        fGetCreditCached = false;679        nGetCreditCached = 0;680    }681682    IMPLEMENT_SERIALIZE683    (684        nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);685        nVersion = this->nVersion;686        READWRITE(hashBlock);687        READWRITE(vMerkleBranch);688        READWRITE(nIndex);689    )690691    int64 GetCredit(bool fUseCache=false) const692    {693        // Must wait until coinbase is safely deep enough in the chain before valuing it694        if (IsCoinBase() && GetBlocksToMaturity() > 0)695            return 0;696697        // GetBalance can assume transactions in mapWallet won't change698        if (fUseCache && fGetCreditCached)699            return nGetCreditCached;700        nGetCreditCached = CTransaction::GetCredit();701        fGetCreditCached = true;702        return nGetCreditCached;703    }704705706    int SetMerkleBranch(const CBlock* pblock=NULL);707    int GetDepthInMainChain(int& nHeightRet) const;708    int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }709    bool IsInMainChain() const { return GetDepthInMainChain() > 0; }710    int GetBlocksToMaturity() const;711    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);712    bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }713};714715716717718//719// A transaction with a bunch of additional info that only the owner cares720// about.  It includes any unrecorded transactions needed to link it back721// to the block chain.722//723class CWalletTx : public CMerkleTx724{725public:726    vector<CMerkleTx> vtxPrev;727    map<string, string> mapValue;728    vector<pair<string, string> > vOrderForm;729    unsigned int fTimeReceivedIsTxTime;730    unsigned int nTimeReceived;  // time received by this node731    char fFromMe;732    char fSpent;733    //// probably need to sign the order info so know it came from payer734735    // memory only UI hints736    mutable unsigned int nTimeDisplayed;737    mutable int nLinesDisplayed;738739740    CWalletTx()741    {742        Init();743    }744745    CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)746    {747        Init();748    }749750    CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)751    {752        Init();753    }754755    void Init()756    {757        fTimeReceivedIsTxTime = false;758        nTimeReceived = 0;759        fFromMe = false;760        fSpent = false;761        nTimeDisplayed = 0;762        nLinesDisplayed = 0;763    }764765    IMPLEMENT_SERIALIZE766    (767        nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);768        nVersion = this->nVersion;769        READWRITE(vtxPrev);770        READWRITE(mapValue);771        READWRITE(vOrderForm);772        READWRITE(fTimeReceivedIsTxTime);773        READWRITE(nTimeReceived);774        READWRITE(fFromMe);775        READWRITE(fSpent);776    )777778    bool WriteToDisk()779    {780        return CWalletDB().WriteTx(GetHash(), *this);781    }782783784    int64 GetTxTime() const;785    int GetRequestCount() const;786787    void AddSupportingTransactions(CTxDB& txdb);788789    bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);790    bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }791792    void RelayWalletTransaction(CTxDB& txdb);793    void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }794};795796797798799//800// A txdb record that contains the disk location of a transaction and the801// locations of transactions that spend its outputs.  vSpent is really only802// used as a flag, but having the location is very helpful for debugging.803//804class CTxIndex805{806public:807    CDiskTxPos pos;808    vector<CDiskTxPos> vSpent;809810    CTxIndex()811    {812        SetNull();813    }814815    CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)816    {817        pos = posIn;818        vSpent.resize(nOutputs);819    }820821    IMPLEMENT_SERIALIZE822    (823        if (!(nType & SER_GETHASH))824            READWRITE(nVersion);825        READWRITE(pos);826        READWRITE(vSpent);827    )828829    void SetNull()830    {831        pos.SetNull();832        vSpent.clear();833    }834835    bool IsNull()836    {837        return pos.IsNull();838    }839840    friend bool operator==(const CTxIndex& a, const CTxIndex& b)841    {842        if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())843            return false;844        for (int i = 0; i < a.vSpent.size(); i++)845            if (a.vSpent[i] != b.vSpent[i])846                return false;847        return true;848    }849850    friend bool operator!=(const CTxIndex& a, const CTxIndex& b)851    {852        return !(a == b);853    }854};855856857858859860//861// Nodes collect new transactions into a block, hash them into a hash tree,862// and scan through nonce values to make the block's hash satisfy proof-of-work863// requirements.  When they solve the proof-of-work, they broadcast the block864// to everyone and the block is added to the block chain.  The first transaction865// in the block is a special one that creates a new coin owned by the creator866// of the block.867//868// Blocks are appended to blk0001.dat files on disk.  Their location on disk869// is indexed by CBlockIndex objects in memory.870//871class CBlock872{873public:874    // header875    int nVersion;876    uint256 hashPrevBlock;877    uint256 hashMerkleRoot;878    unsigned int nTime;879    unsigned int nBits;880    unsigned int nNonce;881882    // network and disk883    vector<CTransaction> vtx;884885    // memory only886    mutable vector<uint256> vMerkleTree;887888889    CBlock()890    {891        SetNull();892    }893894    IMPLEMENT_SERIALIZE895    (896        READWRITE(this->nVersion);897        nVersion = this->nVersion;898        READWRITE(hashPrevBlock);899        READWRITE(hashMerkleRoot);900        READWRITE(nTime);901        READWRITE(nBits);902        READWRITE(nNonce);903904        // ConnectBlock depends on vtx being last so it can calculate offset905        if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))906            READWRITE(vtx);907        else if (fRead)908            const_cast<CBlock*>(this)->vtx.clear();909    )910911    void SetNull()912    {913        nVersion = 1;914        hashPrevBlock = 0;915        hashMerkleRoot = 0;916        nTime = 0;917        nBits = 0;918        nNonce = 0;919        vtx.clear();920        vMerkleTree.clear();921    }922923    bool IsNull() const924    {925        return (nBits == 0);926    }927928    uint256 GetHash() const929    {930        return Hash(BEGIN(nVersion), END(nNonce));931    }932933934    uint256 BuildMerkleTree() const935    {936        vMerkleTree.clear();937        foreach(const CTransaction& tx, vtx)938            vMerkleTree.push_back(tx.GetHash());939        int j = 0;940        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)941        {942            for (int i = 0; i < nSize; i += 2)943            {944                int i2 = min(i+1, nSize-1);945                vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),946                                           BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));947            }948            j += nSize;949        }950        return (vMerkleTree.empty() ? 0 : vMerkleTree.back());951    }952953    vector<uint256> GetMerkleBranch(int nIndex) const954    {955        if (vMerkleTree.empty())956            BuildMerkleTree();957        vector<uint256> vMerkleBranch;958        int j = 0;959        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)960        {961            int i = min(nIndex^1, nSize-1);962            vMerkleBranch.push_back(vMerkleTree[j+i]);963            nIndex >>= 1;964            j += nSize;965        }966        return vMerkleBranch;967    }968969    static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)970    {971        if (nIndex == -1)972            return 0;973        foreach(const uint256& otherside, vMerkleBranch)974        {975            if (nIndex & 1)976                hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));977            else978                hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));979            nIndex >>= 1;980        }981        return hash;982    }983984985    bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)986    {987        // Open history file to append988        CAutoFile fileout = AppendBlockFile(nFileRet);989        if (!fileout)990            return error("CBlock::WriteToDisk() : AppendBlockFile failed");991        if (!fWriteTransactions)992            fileout.nType |= SER_BLOCKHEADERONLY;993994        // Write index header995        unsigned int nSize = fileout.GetSerializeSize(*this);996        fileout << FLATDATA(pchMessageStart) << nSize;997998        // Write block999        nBlockPosRet = ftell(fileout);1000        if (nBlockPosRet == -1)1001            return error("CBlock::WriteToDisk() : ftell failed");1002        fileout << *this;10031004        // Flush stdio buffers and commit to disk before returning1005        fflush(fileout);1006        if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)1007        {1008#ifdef __WXMSW__1009            _commit(_fileno(fileout));1010#else1011            fsync(fileno(fileout));1012#endif1013        }10141015        return true;1016    }10171018    bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)1019    {1020        SetNull();10211022        // Open history file to read1023        CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");1024        if (!filein)1025            return error("CBlock::ReadFromDisk() : OpenBlockFile failed");1026        if (!fReadTransactions)1027            filein.nType |= SER_BLOCKHEADERONLY;10281029        // Read block1030        filein >> *this;10311032        // Check the header1033        if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1034            return error("CBlock::ReadFromDisk() : nBits errors in block header");1035        if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1036            return error("CBlock::ReadFromDisk() : GetHash() errors in block header");10371038        return true;1039    }1040104110421043    void print() const1044    {1045        printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",1046            GetHash().ToString().substr(0,16).c_str(),1047            nVersion,1048            hashPrevBlock.ToString().substr(0,16).c_str(),1049            hashMerkleRoot.ToString().substr(0,6).c_str(),1050            nTime, nBits, nNonce,1051            vtx.size());1052        for (int i = 0; i < vtx.size(); i++)1053        {1054            printf("  ");1055            vtx[i].print();1056        }1057        printf("  vMerkleTree: ");1058        for (int i = 0; i < vMerkleTree.size(); i++)1059            printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());1060        printf("\n");1061    }106210631064    int64 GetBlockValue(int nHeight, int64 nFees) const;1065    bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);1066    bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);1067    bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);1068    bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);1069    bool CheckBlock() const;1070    bool AcceptBlock();1071};1072107310741075107610771078//1079// The block chain is a tree shaped structure starting with the1080// genesis block at the root, with each block potentially having multiple1081// candidates to be the next block.  pprev and pnext link a path through the1082// main/longest chain.  A blockindex may have multiple pprev pointing back1083// to it, but pnext will only point forward to the longest branch, or will1084// be null if the block is not part of the longest chain.1085//1086class CBlockIndex1087{1088public:1089    const uint256* phashBlock;1090    CBlockIndex* pprev;1091    CBlockIndex* pnext;1092    unsigned int nFile;1093    unsigned int nBlockPos;1094    int nHeight;1095    CBigNum bnChainWork;10961097    // block header1098    int nVersion;1099    uint256 hashMerkleRoot;1100    unsigned int nTime;1101    unsigned int nBits;1102    unsigned int nNonce;110311041105    CBlockIndex()1106    {1107        phashBlock = NULL;1108        pprev = NULL;1109        pnext = NULL;1110        nFile = 0;1111        nBlockPos = 0;1112        nHeight = 0;1113        bnChainWork = 0;11141115        nVersion       = 0;1116        hashMerkleRoot = 0;1117        nTime          = 0;1118        nBits          = 0;1119        nNonce         = 0;1120    }11211122    CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)1123    {1124        phashBlock = NULL;1125        pprev = NULL;1126        pnext = NULL;1127        nFile = nFileIn;1128        nBlockPos = nBlockPosIn;1129        nHeight = 0;1130        bnChainWork = 0;11311132        nVersion       = block.nVersion;1133        hashMerkleRoot = block.hashMerkleRoot;1134        nTime          = block.nTime;1135        nBits          = block.nBits;1136        nNonce         = block.nNonce;1137    }11381139    uint256 GetBlockHash() const1140    {1141        return *phashBlock;1142    }11431144    CBigNum GetBlockWork() const1145    {1146        return (CBigNum(1)<<256) / (CBigNum().SetCompact(nBits)+1);1147    }11481149    bool IsInMainChain() const1150    {1151        return (pnext || this == pindexBest);1152    }11531154    bool EraseBlockFromDisk()1155    {1156        // Open history file1157        CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");1158        if (!fileout)1159            return false;11601161        // Overwrite with empty null block1162        CBlock block;1163        block.SetNull();1164        fileout << block;11651166        return true;1167    }11681169    enum { nMedianTimeSpan=11 };11701171    int64 GetMedianTimePast() const1172    {1173        unsigned int pmedian[nMedianTimeSpan];1174        unsigned int* pbegin = &pmedian[nMedianTimeSpan];1175        unsigned int* pend = &pmedian[nMedianTimeSpan];11761177        const CBlockIndex* pindex = this;1178        for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)1179            *(--pbegin) = pindex->nTime;11801181        sort(pbegin, pend);1182        return pbegin[(pend - pbegin)/2];1183    }11841185    int64 GetMedianTime() const1186    {1187        const CBlockIndex* pindex = this;1188        for (int i = 0; i < nMedianTimeSpan/2; i++)1189        {1190            if (!pindex->pnext)1191                return nTime;1192            pindex = pindex->pnext;1193        }1194        return pindex->GetMedianTimePast();1195    }1196119711981199    string ToString() const1200    {1201        return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",1202            pprev, pnext, nFile, nBlockPos, nHeight,1203            hashMerkleRoot.ToString().substr(0,6).c_str(),1204            GetBlockHash().ToString().substr(0,16).c_str());1205    }12061207    void print() const1208    {1209        printf("%s\n", ToString().c_str());1210    }1211};1212121312141215//1216// Used to marshal pointers into hashes for db storage.1217//1218class CDiskBlockIndex : public CBlockIndex1219{1220public:1221    uint256 hashPrev;1222    uint256 hashNext;12231224    CDiskBlockIndex()1225    {1226        hashPrev = 0;1227        hashNext = 0;1228    }12291230    explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)1231    {1232        hashPrev = (pprev ? pprev->GetBlockHash() : 0);1233        hashNext = (pnext ? pnext->GetBlockHash() : 0);1234    }12351236    IMPLEMENT_SERIALIZE1237    (1238        if (!(nType & SER_GETHASH))1239            READWRITE(nVersion);12401241        READWRITE(hashNext);1242        READWRITE(nFile);1243        READWRITE(nBlockPos);1244        READWRITE(nHeight);12451246        // block header1247        READWRITE(this->nVersion);1248        READWRITE(hashPrev);1249        READWRITE(hashMerkleRoot);1250        READWRITE(nTime);1251        READWRITE(nBits);1252        READWRITE(nNonce);1253    )12541255    uint256 GetBlockHash() const1256    {1257        CBlock block;1258        block.nVersion        = nVersion;1259        block.hashPrevBlock   = hashPrev;1260        block.hashMerkleRoot  = hashMerkleRoot;1261        block.nTime           = nTime;1262        block.nBits           = nBits;1263        block.nNonce          = nNonce;1264        return block.GetHash();1265    }126612671268    string ToString() const1269    {1270        string str = "CDiskBlockIndex(";1271        str += CBlockIndex::ToString();1272        str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",1273            GetBlockHash().ToString().c_str(),1274            hashPrev.ToString().substr(0,16).c_str(),1275            hashNext.ToString().substr(0,16).c_str());1276        return str;1277    }12781279    void print() const1280    {1281        printf("%s\n", ToString().c_str());1282    }1283};128412851286128712881289129012911292//1293// Describes a place in the block chain to another node such that if the1294// other node doesn't have the same branch, it can find a recent common trunk.1295// The further back it is, the further before the fork it may be.1296//1297class CBlockLocator1298{1299protected:1300    vector<uint256> vHave;1301public:13021303    CBlockLocator()1304    {1305    }13061307    explicit CBlockLocator(const CBlockIndex* pindex)1308    {1309        Set(pindex);1310    }13111312    explicit CBlockLocator(uint256 hashBlock)1313    {1314        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);1315        if (mi != mapBlockIndex.end())1316            Set((*mi).second);1317    }13181319    IMPLEMENT_SERIALIZE1320    (1321        if (!(nType & SER_GETHASH))1322            READWRITE(nVersion);1323        READWRITE(vHave);1324    )13251326    void Set(const CBlockIndex* pindex)1327    {1328        vHave.clear();1329        int nStep = 1;1330        while (pindex)1331        {1332            vHave.push_back(pindex->GetBlockHash());13331334            // Exponentially larger steps back1335            for (int i = 0; pindex && i < nStep; i++)1336                pindex = pindex->pprev;1337            if (vHave.size() > 10)1338                nStep *= 2;1339        }1340        vHave.push_back(hashGenesisBlock);1341    }13421343    int GetDistanceBack()1344    {1345        // Retrace how far back it was in the sender's branch1346        int nDistance = 0;1347        int nStep = 1;1348        foreach(const uint256& hash, vHave)1349        {1350            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1351            if (mi != mapBlockIndex.end())1352            {1353                CBlockIndex* pindex = (*mi).second;1354                if (pindex->IsInMainChain())1355                    return nDistance;1356            }1357            nDistance += nStep;1358            if (nDistance > 10)1359                nStep *= 2;1360        }1361        return nDistance;1362    }13631364    CBlockIndex* GetBlockIndex()1365    {1366        // Find the first block the caller has in the main chain1367        foreach(const uint256& hash, vHave)1368        {1369            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1370            if (mi != mapBlockIndex.end())1371            {1372                CBlockIndex* pindex = (*mi).second;1373                if (pindex->IsInMainChain())1374                    return pindex;1375            }1376        }1377        return pindexGenesisBlock;1378    }13791380    uint256 GetBlockHash()1381    {1382        // Find the first block the caller has in the main chain1383        foreach(const uint256& hash, vHave)1384        {1385            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1386            if (mi != mapBlockIndex.end())1387            {1388                CBlockIndex* pindex = (*mi).second;1389                if (pindex->IsInMainChain())1390                    return hash;1391            }1392        }1393        return hashGenesisBlock;1394    }13951396    int GetHeight()1397    {1398        CBlockIndex* pindex = GetBlockIndex();1399        if (!pindex)1400            return 0;1401        return pindex->nHeight;1402    }1403};1404140514061407140814091410//1411// Private key that includes an expiration date in case it never gets used.1412//1413class CWalletKey1414{1415public:1416    CPrivKey vchPrivKey;1417    int64 nTimeCreated;1418    int64 nTimeExpires;1419    string strComment;1420    //// todo: add something to note what created it (user, getnewaddress, change)1421    ////   maybe should have a map<string, string> property map14221423    CWalletKey(int64 nTimeExpiresIn=0)1424    {1425        nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);1426        nTimeExpires = nTimeExpiresIn;1427    }14281429    IMPLEMENT_SERIALIZE1430    (1431        if (!(nType & SER_GETHASH))1432            READWRITE(nVersion);1433        READWRITE(vchPrivKey);1434        READWRITE(nTimeCreated);1435        READWRITE(nTimeExpires);1436        READWRITE(strComment);1437    )1438};1439144014411442144314441445extern map<uint256, CTransaction> mapTransactions;1446extern map<uint256, CWalletTx> mapWallet;1447extern vector<uint256> vWalletUpdated;1448extern CCriticalSection cs_mapWallet;1449extern map<vector<unsigned char>, CPrivKey> mapKeys;1450extern map<uint160, vector<unsigned char> > mapPubKeys;1451extern CCriticalSection cs_mapKeys;1452extern 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