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.0 · 2010-07-06

main.h

1,423 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 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 map<uint256, int> mapRequestCount;38extern CCriticalSection cs_mapRequestCount;39extern map<string, string> mapAddressBook;40extern CCriticalSection cs_mapAddressBook;41extern vector<unsigned char> vchDefaultKey;4243// Settings44extern int fGenerateBitcoins;45extern int64 nTransactionFee;46extern CAddress addrIncoming;47extern int fLimitProcessors;48extern int nLimitProcessors;49extern int fMinimizeToTray;50extern int fMinimizeOnClose;5152535455565758bool CheckDiskSpace(int64 nAdditionalBytes=0);59FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");60FILE* AppendBlockFile(unsigned int& nFileRet);61bool AddKey(const CKey& key);62vector<unsigned char> GenerateNewKey();63bool AddToWallet(const CWalletTx& wtxIn);64void WalletUpdateSpent(const COutPoint& prevout);65void ReacceptWalletTransactions();66bool LoadBlockIndex(bool fAllowNew=true);67void PrintBlockTree();68bool ProcessMessages(CNode* pfrom);69bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);70bool SendMessages(CNode* pto, bool fSendTrickle);71int64 GetBalance();72bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet);73bool CommitTransaction(CWalletTx& wtxNew, const CKey& key);74bool BroadcastTransaction(CWalletTx& wtxNew);75string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);76string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);77void GenerateBitcoins(bool fGenerate);78void ThreadBitcoinMiner(void* parg);79void BitcoinMiner();80818283848586878889909192class CDiskTxPos93{94public:95    unsigned int nFile;96    unsigned int nBlockPos;97    unsigned int nTxPos;9899    CDiskTxPos()100    {101        SetNull();102    }103104    CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)105    {106        nFile = nFileIn;107        nBlockPos = nBlockPosIn;108        nTxPos = nTxPosIn;109    }110111    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )112    void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }113    bool IsNull() const { return (nFile == -1); }114115    friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)116    {117        return (a.nFile     == b.nFile &&118                a.nBlockPos == b.nBlockPos &&119                a.nTxPos    == b.nTxPos);120    }121122    friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)123    {124        return !(a == b);125    }126127    string ToString() const128    {129        if (IsNull())130            return strprintf("null");131        else132            return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);133    }134135    void print() const136    {137        printf("%s", ToString().c_str());138    }139};140141142143144class CInPoint145{146public:147    CTransaction* ptx;148    unsigned int n;149150    CInPoint() { SetNull(); }151    CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }152    void SetNull() { ptx = NULL; n = -1; }153    bool IsNull() const { return (ptx == NULL && n == -1); }154};155156157158159class COutPoint160{161public:162    uint256 hash;163    unsigned int n;164165    COutPoint() { SetNull(); }166    COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }167    IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )168    void SetNull() { hash = 0; n = -1; }169    bool IsNull() const { return (hash == 0 && n == -1); }170171    friend bool operator<(const COutPoint& a, const COutPoint& b)172    {173        return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));174    }175176    friend bool operator==(const COutPoint& a, const COutPoint& b)177    {178        return (a.hash == b.hash && a.n == b.n);179    }180181    friend bool operator!=(const COutPoint& a, const COutPoint& b)182    {183        return !(a == b);184    }185186    string ToString() const187    {188        return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,6).c_str(), n);189    }190191    void print() const192    {193        printf("%s\n", ToString().c_str());194    }195};196197198199200//201// An input of a transaction.  It contains the location of the previous202// transaction's output that it claims and a signature that matches the203// output's public key.204//205class CTxIn206{207public:208    COutPoint prevout;209    CScript scriptSig;210    unsigned int nSequence;211212    CTxIn()213    {214        nSequence = UINT_MAX;215    }216217    explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)218    {219        prevout = prevoutIn;220        scriptSig = scriptSigIn;221        nSequence = nSequenceIn;222    }223224    CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)225    {226        prevout = COutPoint(hashPrevTx, nOut);227        scriptSig = scriptSigIn;228        nSequence = nSequenceIn;229    }230231    IMPLEMENT_SERIALIZE232    (233        READWRITE(prevout);234        READWRITE(scriptSig);235        READWRITE(nSequence);236    )237238    bool IsFinal() const239    {240        return (nSequence == UINT_MAX);241    }242243    friend bool operator==(const CTxIn& a, const CTxIn& b)244    {245        return (a.prevout   == b.prevout &&246                a.scriptSig == b.scriptSig &&247                a.nSequence == b.nSequence);248    }249250    friend bool operator!=(const CTxIn& a, const CTxIn& b)251    {252        return !(a == b);253    }254255    string ToString() const256    {257        string str;258        str += strprintf("CTxIn(");259        str += prevout.ToString();260        if (prevout.IsNull())261            str += strprintf(", coinbase %s", HexStr(scriptSig.begin(), scriptSig.end(), false).c_str());262        else263            str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());264        if (nSequence != UINT_MAX)265            str += strprintf(", nSequence=%u", nSequence);266        str += ")";267        return str;268    }269270    void print() const271    {272        printf("%s\n", ToString().c_str());273    }274275    bool IsMine() const;276    int64 GetDebit() const;277};278279280281282//283// An output of a transaction.  It contains the public key that the next input284// must be able to sign with to claim it.285//286class CTxOut287{288public:289    int64 nValue;290    CScript scriptPubKey;291292public:293    CTxOut()294    {295        SetNull();296    }297298    CTxOut(int64 nValueIn, CScript scriptPubKeyIn)299    {300        nValue = nValueIn;301        scriptPubKey = scriptPubKeyIn;302    }303304    IMPLEMENT_SERIALIZE305    (306        READWRITE(nValue);307        READWRITE(scriptPubKey);308    )309310    void SetNull()311    {312        nValue = -1;313        scriptPubKey.clear();314    }315316    bool IsNull()317    {318        return (nValue == -1);319    }320321    uint256 GetHash() const322    {323        return SerializeHash(*this);324    }325326    bool IsMine() const327    {328        return ::IsMine(scriptPubKey);329    }330331    int64 GetCredit() const332    {333        if (IsMine())334            return nValue;335        return 0;336    }337338    friend bool operator==(const CTxOut& a, const CTxOut& b)339    {340        return (a.nValue       == b.nValue &&341                a.scriptPubKey == b.scriptPubKey);342    }343344    friend bool operator!=(const CTxOut& a, const CTxOut& b)345    {346        return !(a == b);347    }348349    string ToString() const350    {351        if (scriptPubKey.size() < 6)352            return "CTxOut(error)";353        return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,24).c_str());354    }355356    void print() const357    {358        printf("%s\n", ToString().c_str());359    }360};361362363364365//366// The basic transaction that is broadcasted on the network and contained in367// blocks.  A transaction can contain multiple inputs and outputs.368//369class CTransaction370{371public:372    int nVersion;373    vector<CTxIn> vin;374    vector<CTxOut> vout;375    unsigned int nLockTime;376377378    CTransaction()379    {380        SetNull();381    }382383    IMPLEMENT_SERIALIZE384    (385        READWRITE(this->nVersion);386        nVersion = this->nVersion;387        READWRITE(vin);388        READWRITE(vout);389        READWRITE(nLockTime);390    )391392    void SetNull()393    {394        nVersion = 1;395        vin.clear();396        vout.clear();397        nLockTime = 0;398    }399400    bool IsNull() const401    {402        return (vin.empty() && vout.empty());403    }404405    uint256 GetHash() const406    {407        return SerializeHash(*this);408    }409410    bool IsFinal(int64 nBlockTime=0) const411    {412        // Time based nLockTime implemented in 0.1.6,413        // do not use time based until most 0.1.5 nodes have upgraded.414        if (nLockTime == 0)415            return true;416        if (nBlockTime == 0)417            nBlockTime = GetAdjustedTime();418        if (nLockTime < (nLockTime < 500000000 ? nBestHeight : nBlockTime))419            return true;420        foreach(const CTxIn& txin, vin)421            if (!txin.IsFinal())422                return false;423        return true;424    }425426    bool IsNewerThan(const CTransaction& old) const427    {428        if (vin.size() != old.vin.size())429            return false;430        for (int i = 0; i < vin.size(); i++)431            if (vin[i].prevout != old.vin[i].prevout)432                return false;433434        bool fNewer = false;435        unsigned int nLowest = UINT_MAX;436        for (int i = 0; i < vin.size(); i++)437        {438            if (vin[i].nSequence != old.vin[i].nSequence)439            {440                if (vin[i].nSequence <= nLowest)441                {442                    fNewer = false;443                    nLowest = vin[i].nSequence;444                }445                if (old.vin[i].nSequence < nLowest)446                {447                    fNewer = true;448                    nLowest = old.vin[i].nSequence;449                }450            }451        }452        return fNewer;453    }454455    bool IsCoinBase() const456    {457        return (vin.size() == 1 && vin[0].prevout.IsNull());458    }459460    bool CheckTransaction() const461    {462        // Basic checks that don't depend on any context463        if (vin.empty() || vout.empty())464            return error("CTransaction::CheckTransaction() : vin or vout empty");465466        // Check for negative values467        foreach(const CTxOut& txout, vout)468            if (txout.nValue < 0)469                return error("CTransaction::CheckTransaction() : txout.nValue negative");470471        if (IsCoinBase())472        {473            if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)474                return error("CTransaction::CheckTransaction() : coinbase script size");475        }476        else477        {478            foreach(const CTxIn& txin, vin)479                if (txin.prevout.IsNull())480                    return error("CTransaction::CheckTransaction() : prevout is null");481        }482483        return true;484    }485486    bool IsMine() const487    {488        foreach(const CTxOut& txout, vout)489            if (txout.IsMine())490                return true;491        return false;492    }493494    int64 GetDebit() const495    {496        int64 nDebit = 0;497        foreach(const CTxIn& txin, vin)498            nDebit += txin.GetDebit();499        return nDebit;500    }501502    int64 GetCredit() const503    {504        int64 nCredit = 0;505        foreach(const CTxOut& txout, vout)506            nCredit += txout.GetCredit();507        return nCredit;508    }509510    int64 GetValueOut() const511    {512        int64 nValueOut = 0;513        foreach(const CTxOut& txout, vout)514        {515            if (txout.nValue < 0)516                throw runtime_error("CTransaction::GetValueOut() : negative value");517            nValueOut += txout.nValue;518        }519        return nValueOut;520    }521522    int64 GetMinFee(unsigned int nBlockSize=1) const523    {524        // Base fee is 1 cent per kilobyte525        unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);526        int64 nMinFee = (1 + (int64)nBytes / 1000) * CENT;527528        // Transactions under 60K are free as long as block size is under 80K529        // (about 27,000bc if made of 50bc inputs)530        if (nBytes < 60000 && nBlockSize < 80000)531            nMinFee = 0;532533        // Transactions under 3K are free as long as block size is under 200K534        if (nBytes < 3000 && nBlockSize < 200000)535            nMinFee = 0;536537        // To limit dust spam, require a 0.01 fee if any output is less than 0.01538        if (nMinFee < CENT)539            foreach(const CTxOut& txout, vout)540                if (txout.nValue < CENT)541                    nMinFee = CENT;542543        return nMinFee;544    }545546547548    bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)549    {550        CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");551        if (!filein)552            return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");553554        // Read transaction555        if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)556            return error("CTransaction::ReadFromDisk() : fseek failed");557        filein >> *this;558559        // Return file pointer560        if (pfileRet)561        {562            if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)563                return error("CTransaction::ReadFromDisk() : second fseek failed");564            *pfileRet = filein.release();565        }566        return true;567    }568569570    friend bool operator==(const CTransaction& a, const CTransaction& b)571    {572        return (a.nVersion  == b.nVersion &&573                a.vin       == b.vin &&574                a.vout      == b.vout &&575                a.nLockTime == b.nLockTime);576    }577578    friend bool operator!=(const CTransaction& a, const CTransaction& b)579    {580        return !(a == b);581    }582583584    string ToString() const585    {586        string str;587        str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",588            GetHash().ToString().substr(0,6).c_str(),589            nVersion,590            vin.size(),591            vout.size(),592            nLockTime);593        for (int i = 0; i < vin.size(); i++)594            str += "    " + vin[i].ToString() + "\n";595        for (int i = 0; i < vout.size(); i++)596            str += "    " + vout[i].ToString() + "\n";597        return str;598    }599600    void print() const601    {602        printf("%s", ToString().c_str());603    }604605606607    bool DisconnectInputs(CTxDB& txdb);608    bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);609    bool ClientConnectInputs();610611    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);612613    bool AcceptTransaction(bool fCheckInputs=true, bool* pfMissingInputs=NULL)614    {615        CTxDB txdb("r");616        return AcceptTransaction(txdb, fCheckInputs, pfMissingInputs);617    }618619protected:620    bool AddToMemoryPool();621public:622    bool RemoveFromMemoryPool();623};624625626627628629//630// A transaction with a merkle branch linking it to the block chain631//632class CMerkleTx : public CTransaction633{634public:635    uint256 hashBlock;636    vector<uint256> vMerkleBranch;637    int nIndex;638639    // memory only640    mutable bool fMerkleVerified;641    mutable bool fGetCreditCached;642    mutable int64 nGetCreditCached;643644645    CMerkleTx()646    {647        Init();648    }649650    CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)651    {652        Init();653    }654655    void Init()656    {657        hashBlock = 0;658        nIndex = -1;659        fMerkleVerified = false;660        fGetCreditCached = false;661        nGetCreditCached = 0;662    }663664    IMPLEMENT_SERIALIZE665    (666        nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);667        nVersion = this->nVersion;668        READWRITE(hashBlock);669        READWRITE(vMerkleBranch);670        READWRITE(nIndex);671    )672673    int64 GetCredit(bool fUseCache=false) const674    {675        // Must wait until coinbase is safely deep enough in the chain before valuing it676        if (IsCoinBase() && GetBlocksToMaturity() > 0)677            return 0;678679        // GetBalance can assume transactions in mapWallet won't change680        if (fUseCache && fGetCreditCached)681            return nGetCreditCached;682        nGetCreditCached = CTransaction::GetCredit();683        fGetCreditCached = true;684        return nGetCreditCached;685    }686687688    int SetMerkleBranch(const CBlock* pblock=NULL);689    int GetDepthInMainChain(int& nHeightRet) const;690    int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }691    bool IsInMainChain() const { return GetDepthInMainChain() > 0; }692    int GetBlocksToMaturity() const;693    bool AcceptTransaction(CTxDB& txdb, bool fCheckInputs=true);694    bool AcceptTransaction() { CTxDB txdb("r"); return AcceptTransaction(txdb); }695};696697698699700//701// A transaction with a bunch of additional info that only the owner cares702// about.  It includes any unrecorded transactions needed to link it back703// to the block chain.704//705class CWalletTx : public CMerkleTx706{707public:708    vector<CMerkleTx> vtxPrev;709    map<string, string> mapValue;710    vector<pair<string, string> > vOrderForm;711    unsigned int fTimeReceivedIsTxTime;712    unsigned int nTimeReceived;  // time received by this node713    char fFromMe;714    char fSpent;715    //// probably need to sign the order info so know it came from payer716717    // memory only UI hints718    mutable unsigned int nTimeDisplayed;719    mutable int nLinesDisplayed;720721722    CWalletTx()723    {724        Init();725    }726727    CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)728    {729        Init();730    }731732    CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)733    {734        Init();735    }736737    void Init()738    {739        fTimeReceivedIsTxTime = false;740        nTimeReceived = 0;741        fFromMe = false;742        fSpent = false;743        nTimeDisplayed = 0;744        nLinesDisplayed = 0;745    }746747    IMPLEMENT_SERIALIZE748    (749        nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion, ser_action);750        nVersion = this->nVersion;751        READWRITE(vtxPrev);752        READWRITE(mapValue);753        READWRITE(vOrderForm);754        READWRITE(fTimeReceivedIsTxTime);755        READWRITE(nTimeReceived);756        READWRITE(fFromMe);757        READWRITE(fSpent);758    )759760    bool WriteToDisk()761    {762        return CWalletDB().WriteTx(GetHash(), *this);763    }764765766    int64 GetTxTime() const;767    int GetRequestCount() const;768769    void AddSupportingTransactions(CTxDB& txdb);770771    bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);772    bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }773774    void RelayWalletTransaction(CTxDB& txdb);775    void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }776};777778779780781//782// A txdb record that contains the disk location of a transaction and the783// locations of transactions that spend its outputs.  vSpent is really only784// used as a flag, but having the location is very helpful for debugging.785//786class CTxIndex787{788public:789    CDiskTxPos pos;790    vector<CDiskTxPos> vSpent;791792    CTxIndex()793    {794        SetNull();795    }796797    CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)798    {799        pos = posIn;800        vSpent.resize(nOutputs);801    }802803    IMPLEMENT_SERIALIZE804    (805        if (!(nType & SER_GETHASH))806            READWRITE(nVersion);807        READWRITE(pos);808        READWRITE(vSpent);809    )810811    void SetNull()812    {813        pos.SetNull();814        vSpent.clear();815    }816817    bool IsNull()818    {819        return pos.IsNull();820    }821822    friend bool operator==(const CTxIndex& a, const CTxIndex& b)823    {824        if (a.pos != b.pos || a.vSpent.size() != b.vSpent.size())825            return false;826        for (int i = 0; i < a.vSpent.size(); i++)827            if (a.vSpent[i] != b.vSpent[i])828                return false;829        return true;830    }831832    friend bool operator!=(const CTxIndex& a, const CTxIndex& b)833    {834        return !(a == b);835    }836};837838839840841842//843// Nodes collect new transactions into a block, hash them into a hash tree,844// and scan through nonce values to make the block's hash satisfy proof-of-work845// requirements.  When they solve the proof-of-work, they broadcast the block846// to everyone and the block is added to the block chain.  The first transaction847// in the block is a special one that creates a new coin owned by the creator848// of the block.849//850// Blocks are appended to blk0001.dat files on disk.  Their location on disk851// is indexed by CBlockIndex objects in memory.852//853class CBlock854{855public:856    // header857    int nVersion;858    uint256 hashPrevBlock;859    uint256 hashMerkleRoot;860    unsigned int nTime;861    unsigned int nBits;862    unsigned int nNonce;863864    // network and disk865    vector<CTransaction> vtx;866867    // memory only868    mutable vector<uint256> vMerkleTree;869870871    CBlock()872    {873        SetNull();874    }875876    IMPLEMENT_SERIALIZE877    (878        READWRITE(this->nVersion);879        nVersion = this->nVersion;880        READWRITE(hashPrevBlock);881        READWRITE(hashMerkleRoot);882        READWRITE(nTime);883        READWRITE(nBits);884        READWRITE(nNonce);885886        // ConnectBlock depends on vtx being last so it can calculate offset887        if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))888            READWRITE(vtx);889        else if (fRead)890            const_cast<CBlock*>(this)->vtx.clear();891    )892893    void SetNull()894    {895        nVersion = 1;896        hashPrevBlock = 0;897        hashMerkleRoot = 0;898        nTime = 0;899        nBits = 0;900        nNonce = 0;901        vtx.clear();902        vMerkleTree.clear();903    }904905    bool IsNull() const906    {907        return (nBits == 0);908    }909910    uint256 GetHash() const911    {912        return Hash(BEGIN(nVersion), END(nNonce));913    }914915916    uint256 BuildMerkleTree() const917    {918        vMerkleTree.clear();919        foreach(const CTransaction& tx, vtx)920            vMerkleTree.push_back(tx.GetHash());921        int j = 0;922        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)923        {924            for (int i = 0; i < nSize; i += 2)925            {926                int i2 = min(i+1, nSize-1);927                vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),928                                           BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));929            }930            j += nSize;931        }932        return (vMerkleTree.empty() ? 0 : vMerkleTree.back());933    }934935    vector<uint256> GetMerkleBranch(int nIndex) const936    {937        if (vMerkleTree.empty())938            BuildMerkleTree();939        vector<uint256> vMerkleBranch;940        int j = 0;941        for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)942        {943            int i = min(nIndex^1, nSize-1);944            vMerkleBranch.push_back(vMerkleTree[j+i]);945            nIndex >>= 1;946            j += nSize;947        }948        return vMerkleBranch;949    }950951    static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)952    {953        if (nIndex == -1)954            return 0;955        foreach(const uint256& otherside, vMerkleBranch)956        {957            if (nIndex & 1)958                hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));959            else960                hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));961            nIndex >>= 1;962        }963        return hash;964    }965966967    bool WriteToDisk(bool fWriteTransactions, unsigned int& nFileRet, unsigned int& nBlockPosRet)968    {969        // Open history file to append970        CAutoFile fileout = AppendBlockFile(nFileRet);971        if (!fileout)972            return error("CBlock::WriteToDisk() : AppendBlockFile failed");973        if (!fWriteTransactions)974            fileout.nType |= SER_BLOCKHEADERONLY;975976        // Write index header977        unsigned int nSize = fileout.GetSerializeSize(*this);978        fileout << FLATDATA(pchMessageStart) << nSize;979980        // Write block981        nBlockPosRet = ftell(fileout);982        if (nBlockPosRet == -1)983            return error("CBlock::WriteToDisk() : ftell failed");984        fileout << *this;985986        // Flush stdio buffers and commit to disk before returning987        fflush(fileout);988#ifdef __WXMSW__989        _commit(_fileno(fileout));990#else991        fsync(fileno(fileout));992#endif993994        return true;995    }996997    bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)998    {999        SetNull();10001001        // Open history file to read1002        CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");1003        if (!filein)1004            return error("CBlock::ReadFromDisk() : OpenBlockFile failed");1005        if (!fReadTransactions)1006            filein.nType |= SER_BLOCKHEADERONLY;10071008        // Read block1009        filein >> *this;10101011        // Check the header1012        if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1013            return error("CBlock::ReadFromDisk() : nBits errors in block header");1014        if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1015            return error("CBlock::ReadFromDisk() : GetHash() errors in block header");10161017        return true;1018    }1019102010211022    void print() const1023    {1024        printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",1025            GetHash().ToString().substr(0,16).c_str(),1026            nVersion,1027            hashPrevBlock.ToString().substr(0,16).c_str(),1028            hashMerkleRoot.ToString().substr(0,6).c_str(),1029            nTime, nBits, nNonce,1030            vtx.size());1031        for (int i = 0; i < vtx.size(); i++)1032        {1033            printf("  ");1034            vtx[i].print();1035        }1036        printf("  vMerkleTree: ");1037        for (int i = 0; i < vMerkleTree.size(); i++)1038            printf("%s ", vMerkleTree[i].ToString().substr(0,6).c_str());1039        printf("\n");1040    }104110421043    int64 GetBlockValue(int64 nFees) const;1044    bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);1045    bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);1046    bool ReadFromDisk(const CBlockIndex* blockindex, bool fReadTransactions=true);1047    bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);1048    bool CheckBlock() const;1049    bool AcceptBlock();1050};1051105210531054105510561057//1058// The block chain is a tree shaped structure starting with the1059// genesis block at the root, with each block potentially having multiple1060// candidates to be the next block.  pprev and pnext link a path through the1061// main/longest chain.  A blockindex may have multiple pprev pointing back1062// to it, but pnext will only point forward to the longest branch, or will1063// be null if the block is not part of the longest chain.1064//1065class CBlockIndex1066{1067public:1068    const uint256* phashBlock;1069    CBlockIndex* pprev;1070    CBlockIndex* pnext;1071    unsigned int nFile;1072    unsigned int nBlockPos;1073    int nHeight;10741075    // block header1076    int nVersion;1077    uint256 hashMerkleRoot;1078    unsigned int nTime;1079    unsigned int nBits;1080    unsigned int nNonce;108110821083    CBlockIndex()1084    {1085        phashBlock = NULL;1086        pprev = NULL;1087        pnext = NULL;1088        nFile = 0;1089        nBlockPos = 0;1090        nHeight = 0;10911092        nVersion       = 0;1093        hashMerkleRoot = 0;1094        nTime          = 0;1095        nBits          = 0;1096        nNonce         = 0;1097    }10981099    CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)1100    {1101        phashBlock = NULL;1102        pprev = NULL;1103        pnext = NULL;1104        nFile = nFileIn;1105        nBlockPos = nBlockPosIn;1106        nHeight = 0;11071108        nVersion       = block.nVersion;1109        hashMerkleRoot = block.hashMerkleRoot;1110        nTime          = block.nTime;1111        nBits          = block.nBits;1112        nNonce         = block.nNonce;1113    }11141115    uint256 GetBlockHash() const1116    {1117        return *phashBlock;1118    }11191120    bool IsInMainChain() const1121    {1122        return (pnext || this == pindexBest);1123    }11241125    bool EraseBlockFromDisk()1126    {1127        // Open history file1128        CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");1129        if (!fileout)1130            return false;11311132        // Overwrite with empty null block1133        CBlock block;1134        block.SetNull();1135        fileout << block;11361137        return true;1138    }11391140    enum { nMedianTimeSpan=11 };11411142    int64 GetMedianTimePast() const1143    {1144        unsigned int pmedian[nMedianTimeSpan];1145        unsigned int* pbegin = &pmedian[nMedianTimeSpan];1146        unsigned int* pend = &pmedian[nMedianTimeSpan];11471148        const CBlockIndex* pindex = this;1149        for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)1150            *(--pbegin) = pindex->nTime;11511152        sort(pbegin, pend);1153        return pbegin[(pend - pbegin)/2];1154    }11551156    int64 GetMedianTime() const1157    {1158        const CBlockIndex* pindex = this;1159        for (int i = 0; i < nMedianTimeSpan/2; i++)1160        {1161            if (!pindex->pnext)1162                return nTime;1163            pindex = pindex->pnext;1164        }1165        return pindex->GetMedianTimePast();1166    }1167116811691170    string ToString() const1171    {1172        return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",1173            pprev, pnext, nFile, nBlockPos, nHeight,1174            hashMerkleRoot.ToString().substr(0,6).c_str(),1175            GetBlockHash().ToString().substr(0,16).c_str());1176    }11771178    void print() const1179    {1180        printf("%s\n", ToString().c_str());1181    }1182};1183118411851186//1187// Used to marshal pointers into hashes for db storage.1188//1189class CDiskBlockIndex : public CBlockIndex1190{1191public:1192    uint256 hashPrev;1193    uint256 hashNext;11941195    CDiskBlockIndex()1196    {1197        hashPrev = 0;1198        hashNext = 0;1199    }12001201    explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)1202    {1203        hashPrev = (pprev ? pprev->GetBlockHash() : 0);1204        hashNext = (pnext ? pnext->GetBlockHash() : 0);1205    }12061207    IMPLEMENT_SERIALIZE1208    (1209        if (!(nType & SER_GETHASH))1210            READWRITE(nVersion);12111212        READWRITE(hashNext);1213        READWRITE(nFile);1214        READWRITE(nBlockPos);1215        READWRITE(nHeight);12161217        // block header1218        READWRITE(this->nVersion);1219        READWRITE(hashPrev);1220        READWRITE(hashMerkleRoot);1221        READWRITE(nTime);1222        READWRITE(nBits);1223        READWRITE(nNonce);1224    )12251226    uint256 GetBlockHash() const1227    {1228        CBlock block;1229        block.nVersion        = nVersion;1230        block.hashPrevBlock   = hashPrev;1231        block.hashMerkleRoot  = hashMerkleRoot;1232        block.nTime           = nTime;1233        block.nBits           = nBits;1234        block.nNonce          = nNonce;1235        return block.GetHash();1236    }123712381239    string ToString() const1240    {1241        string str = "CDiskBlockIndex(";1242        str += CBlockIndex::ToString();1243        str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",1244            GetBlockHash().ToString().c_str(),1245            hashPrev.ToString().substr(0,16).c_str(),1246            hashNext.ToString().substr(0,16).c_str());1247        return str;1248    }12491250    void print() const1251    {1252        printf("%s\n", ToString().c_str());1253    }1254};125512561257125812591260126112621263//1264// Describes a place in the block chain to another node such that if the1265// other node doesn't have the same branch, it can find a recent common trunk.1266// The further back it is, the further before the fork it may be.1267//1268class CBlockLocator1269{1270protected:1271    vector<uint256> vHave;1272public:12731274    CBlockLocator()1275    {1276    }12771278    explicit CBlockLocator(const CBlockIndex* pindex)1279    {1280        Set(pindex);1281    }12821283    explicit CBlockLocator(uint256 hashBlock)1284    {1285        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);1286        if (mi != mapBlockIndex.end())1287            Set((*mi).second);1288    }12891290    IMPLEMENT_SERIALIZE1291    (1292        if (!(nType & SER_GETHASH))1293            READWRITE(nVersion);1294        READWRITE(vHave);1295    )12961297    void Set(const CBlockIndex* pindex)1298    {1299        vHave.clear();1300        int nStep = 1;1301        while (pindex)1302        {1303            vHave.push_back(pindex->GetBlockHash());13041305            // Exponentially larger steps back1306            for (int i = 0; pindex && i < nStep; i++)1307                pindex = pindex->pprev;1308            if (vHave.size() > 10)1309                nStep *= 2;1310        }1311        vHave.push_back(hashGenesisBlock);1312    }13131314    int GetDistanceBack()1315    {1316        // Retrace how far back it was in the sender's branch1317        int nDistance = 0;1318        int nStep = 1;1319        foreach(const uint256& hash, vHave)1320        {1321            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1322            if (mi != mapBlockIndex.end())1323            {1324                CBlockIndex* pindex = (*mi).second;1325                if (pindex->IsInMainChain())1326                    return nDistance;1327            }1328            nDistance += nStep;1329            if (nDistance > 10)1330                nStep *= 2;1331        }1332        return nDistance;1333    }13341335    CBlockIndex* GetBlockIndex()1336    {1337        // Find the first block the caller has in the main chain1338        foreach(const uint256& hash, vHave)1339        {1340            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1341            if (mi != mapBlockIndex.end())1342            {1343                CBlockIndex* pindex = (*mi).second;1344                if (pindex->IsInMainChain())1345                    return pindex;1346            }1347        }1348        return pindexGenesisBlock;1349    }13501351    uint256 GetBlockHash()1352    {1353        // Find the first block the caller has in the main chain1354        foreach(const uint256& hash, vHave)1355        {1356            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);1357            if (mi != mapBlockIndex.end())1358            {1359                CBlockIndex* pindex = (*mi).second;1360                if (pindex->IsInMainChain())1361                    return hash;1362            }1363        }1364        return hashGenesisBlock;1365    }13661367    int GetHeight()1368    {1369        CBlockIndex* pindex = GetBlockIndex();1370        if (!pindex)1371            return 0;1372        return pindex->nHeight;1373    }1374};1375137613771378137913801381//1382// Private key that includes an expiration date in case it never gets used.1383//1384class CWalletKey1385{1386public:1387    CPrivKey vchPrivKey;1388    int64 nTimeCreated;1389    int64 nTimeExpires;1390    string strComment;1391    //// todo: add something to note what created it (user, getnewaddress, change)1392    ////   maybe should have a map<string, string> property map13931394    CWalletKey(int64 nTimeExpiresIn=0)1395    {1396        nTimeCreated = (nTimeExpiresIn ? GetTime() : 0);1397        nTimeExpires = nTimeExpiresIn;1398    }13991400    IMPLEMENT_SERIALIZE1401    (1402        if (!(nType & SER_GETHASH))1403            READWRITE(nVersion);1404        READWRITE(vchPrivKey);1405        READWRITE(nTimeCreated);1406        READWRITE(nTimeExpires);1407        READWRITE(strComment);1408    )1409};1410141114121413141414151416extern map<uint256, CTransaction> mapTransactions;1417extern map<uint256, CWalletTx> mapWallet;1418extern vector<uint256> vWalletUpdated;1419extern CCriticalSection cs_mapWallet;1420extern map<vector<unsigned char>, CPrivKey> mapKeys;1421extern map<uint160, vector<unsigned char> > mapPubKeys;1422extern CCriticalSection cs_mapKeys;1423extern 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