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.cpp

3,114 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.45#include "headers.h"6#include "sha.h"789101112//13// Global state14//1516CCriticalSection cs_main;1718map<uint256, CTransaction> mapTransactions;19CCriticalSection cs_mapTransactions;20unsigned int nTransactionsUpdated = 0;21map<COutPoint, CInPoint> mapNextTx;2223map<uint256, CBlockIndex*> mapBlockIndex;24const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");25CBlockIndex* pindexGenesisBlock = NULL;26int nBestHeight = -1;27uint256 hashBestChain = 0;28CBlockIndex* pindexBest = NULL;29int64 nTimeBestReceived = 0;3031map<uint256, CBlock*> mapOrphanBlocks;32multimap<uint256, CBlock*> mapOrphanBlocksByPrev;3334map<uint256, CDataStream*> mapOrphanTransactions;35multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;3637map<uint256, CWalletTx> mapWallet;38vector<uint256> vWalletUpdated;39CCriticalSection cs_mapWallet;4041map<vector<unsigned char>, CPrivKey> mapKeys;42map<uint160, vector<unsigned char> > mapPubKeys;43CCriticalSection cs_mapKeys;44CKey keyUser;4546map<uint256, int> mapRequestCount;47CCriticalSection cs_mapRequestCount;4849map<string, string> mapAddressBook;50CCriticalSection cs_mapAddressBook;5152vector<unsigned char> vchDefaultKey;5354// Settings55int fGenerateBitcoins = false;56int64 nTransactionFee = 0;57CAddress addrIncoming;58int fLimitProcessors = false;59int nLimitProcessors = 1;60int fMinimizeToTray = true;61int fMinimizeOnClose = true;62636465666768//////////////////////////////////////////////////////////////////////////////69//70// mapKeys71//7273bool AddKey(const CKey& key)74{75    CRITICAL_BLOCK(cs_mapKeys)76    {77        mapKeys[key.GetPubKey()] = key.GetPrivKey();78        mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();79    }80    return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());81}8283vector<unsigned char> GenerateNewKey()84{85    CKey key;86    key.MakeNewKey();87    if (!AddKey(key))88        throw runtime_error("GenerateNewKey() : AddKey failed\n");89    return key.GetPubKey();90}9192939495//////////////////////////////////////////////////////////////////////////////96//97// mapWallet98//99100bool AddToWallet(const CWalletTx& wtxIn)101{102    uint256 hash = wtxIn.GetHash();103    CRITICAL_BLOCK(cs_mapWallet)104    {105        // Inserts only if not already there, returns tx inserted or tx found106        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));107        CWalletTx& wtx = (*ret.first).second;108        bool fInsertedNew = ret.second;109        if (fInsertedNew)110            wtx.nTimeReceived = GetAdjustedTime();111112        bool fUpdated = false;113        if (!fInsertedNew)114        {115            // Merge116            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)117            {118                wtx.hashBlock = wtxIn.hashBlock;119                fUpdated = true;120            }121            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))122            {123                wtx.vMerkleBranch = wtxIn.vMerkleBranch;124                wtx.nIndex = wtxIn.nIndex;125                fUpdated = true;126            }127            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)128            {129                wtx.fFromMe = wtxIn.fFromMe;130                fUpdated = true;131            }132            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)133            {134                wtx.fSpent = wtxIn.fSpent;135                fUpdated = true;136            }137        }138139        //// debug print140        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));141142        // Write to disk143        if (fInsertedNew || fUpdated)144            if (!wtx.WriteToDisk())145                return false;146147        // If default receiving address gets used, replace it with a new one148        CScript scriptDefaultKey;149        scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);150        foreach(const CTxOut& txout, wtx.vout)151        {152            if (txout.scriptPubKey == scriptDefaultKey)153            {154                CWalletDB walletdb;155                walletdb.WriteDefaultKey(GenerateNewKey());156                walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");157            }158        }159160        // Notify UI161        vWalletUpdated.push_back(hash);162    }163164    // Refresh UI165    MainFrameRepaint();166    return true;167}168169bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)170{171    if (tx.IsMine() || mapWallet.count(tx.GetHash()))172    {173        CWalletTx wtx(tx);174        // Get merkle branch if transaction was found in a block175        if (pblock)176            wtx.SetMerkleBranch(pblock);177        return AddToWallet(wtx);178    }179    return true;180}181182bool EraseFromWallet(uint256 hash)183{184    CRITICAL_BLOCK(cs_mapWallet)185    {186        if (mapWallet.erase(hash))187            CWalletDB().EraseTx(hash);188    }189    return true;190}191192void WalletUpdateSpent(const COutPoint& prevout)193{194    // Anytime a signature is successfully verified, it's proof the outpoint is spent.195    // Update the wallet spent flag if it doesn't know due to wallet.dat being196    // restored from backup or the user making copies of wallet.dat.197    CRITICAL_BLOCK(cs_mapWallet)198    {199        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);200        if (mi != mapWallet.end())201        {202            CWalletTx& wtx = (*mi).second;203            if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())204            {205                printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());206                wtx.fSpent = true;207                wtx.WriteToDisk();208                vWalletUpdated.push_back(prevout.hash);209            }210        }211    }212}213214215216217218219220221//////////////////////////////////////////////////////////////////////////////222//223// mapOrphanTransactions224//225226void AddOrphanTx(const CDataStream& vMsg)227{228    CTransaction tx;229    CDataStream(vMsg) >> tx;230    uint256 hash = tx.GetHash();231    if (mapOrphanTransactions.count(hash))232        return;233    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);234    foreach(const CTxIn& txin, tx.vin)235        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));236}237238void EraseOrphanTx(uint256 hash)239{240    if (!mapOrphanTransactions.count(hash))241        return;242    const CDataStream* pvMsg = mapOrphanTransactions[hash];243    CTransaction tx;244    CDataStream(*pvMsg) >> tx;245    foreach(const CTxIn& txin, tx.vin)246    {247        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);248             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)249        {250            if ((*mi).second == pvMsg)251                mapOrphanTransactionsByPrev.erase(mi++);252            else253                mi++;254        }255    }256    delete pvMsg;257    mapOrphanTransactions.erase(hash);258}259260261262263264265266267//////////////////////////////////////////////////////////////////////////////268//269// CTransaction270//271272bool CTxIn::IsMine() const273{274    CRITICAL_BLOCK(cs_mapWallet)275    {276        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);277        if (mi != mapWallet.end())278        {279            const CWalletTx& prev = (*mi).second;280            if (prevout.n < prev.vout.size())281                if (prev.vout[prevout.n].IsMine())282                    return true;283        }284    }285    return false;286}287288int64 CTxIn::GetDebit() const289{290    CRITICAL_BLOCK(cs_mapWallet)291    {292        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);293        if (mi != mapWallet.end())294        {295            const CWalletTx& prev = (*mi).second;296            if (prevout.n < prev.vout.size())297                if (prev.vout[prevout.n].IsMine())298                    return prev.vout[prevout.n].nValue;299        }300    }301    return 0;302}303304int64 CWalletTx::GetTxTime() const305{306    if (!fTimeReceivedIsTxTime && hashBlock != 0)307    {308        // If we did not receive the transaction directly, we rely on the block's309        // time to figure out when it happened.  We use the median over a range310        // of blocks to try to filter out inaccurate block times.311        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);312        if (mi != mapBlockIndex.end())313        {314            CBlockIndex* pindex = (*mi).second;315            if (pindex)316                return pindex->GetMedianTime();317        }318    }319    return nTimeReceived;320}321322int CWalletTx::GetRequestCount() const323{324    // Returns -1 if it wasn't being tracked325    int nRequests = -1;326    CRITICAL_BLOCK(cs_mapRequestCount)327    {328        if (IsCoinBase())329        {330            // Generated block331            if (hashBlock != 0)332            {333                map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);334                if (mi != mapRequestCount.end())335                    nRequests = (*mi).second;336            }337        }338        else339        {340            // Did anyone request this transaction?341            map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());342            if (mi != mapRequestCount.end())343            {344                nRequests = (*mi).second;345346                // How about the block it's in?347                if (nRequests == 0 && hashBlock != 0)348                {349                    map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);350                    if (mi != mapRequestCount.end())351                        nRequests = (*mi).second;352                    else353                        nRequests = 1; // If it's in someone else's block it must have got out354                }355            }356        }357    }358    return nRequests;359}360361362363364int CMerkleTx::SetMerkleBranch(const CBlock* pblock)365{366    if (fClient)367    {368        if (hashBlock == 0)369            return 0;370    }371    else372    {373        CBlock blockTmp;374        if (pblock == NULL)375        {376            // Load the block this tx is in377            CTxIndex txindex;378            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))379                return 0;380            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))381                return 0;382            pblock = &blockTmp;383        }384385        // Update the tx's hashBlock386        hashBlock = pblock->GetHash();387388        // Locate the transaction389        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)390            if (pblock->vtx[nIndex] == *(CTransaction*)this)391                break;392        if (nIndex == pblock->vtx.size())393        {394            vMerkleBranch.clear();395            nIndex = -1;396            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");397            return 0;398        }399400        // Fill in merkle branch401        vMerkleBranch = pblock->GetMerkleBranch(nIndex);402    }403404    // Is the tx in a block that's in the main chain405    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);406    if (mi == mapBlockIndex.end())407        return 0;408    CBlockIndex* pindex = (*mi).second;409    if (!pindex || !pindex->IsInMainChain())410        return 0;411412    return pindexBest->nHeight - pindex->nHeight + 1;413}414415416417void CWalletTx::AddSupportingTransactions(CTxDB& txdb)418{419    vtxPrev.clear();420421    const int COPY_DEPTH = 3;422    if (SetMerkleBranch() < COPY_DEPTH)423    {424        vector<uint256> vWorkQueue;425        foreach(const CTxIn& txin, vin)426            vWorkQueue.push_back(txin.prevout.hash);427428        // This critsect is OK because txdb is already open429        CRITICAL_BLOCK(cs_mapWallet)430        {431            map<uint256, const CMerkleTx*> mapWalletPrev;432            set<uint256> setAlreadyDone;433            for (int i = 0; i < vWorkQueue.size(); i++)434            {435                uint256 hash = vWorkQueue[i];436                if (setAlreadyDone.count(hash))437                    continue;438                setAlreadyDone.insert(hash);439440                CMerkleTx tx;441                if (mapWallet.count(hash))442                {443                    tx = mapWallet[hash];444                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)445                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;446                }447                else if (mapWalletPrev.count(hash))448                {449                    tx = *mapWalletPrev[hash];450                }451                else if (!fClient && txdb.ReadDiskTx(hash, tx))452                {453                    ;454                }455                else456                {457                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");458                    continue;459                }460461                int nDepth = tx.SetMerkleBranch();462                vtxPrev.push_back(tx);463464                if (nDepth < COPY_DEPTH)465                    foreach(const CTxIn& txin, tx.vin)466                        vWorkQueue.push_back(txin.prevout.hash);467            }468        }469    }470471    reverse(vtxPrev.begin(), vtxPrev.end());472}473474475476477478479480481482483484bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)485{486    if (pfMissingInputs)487        *pfMissingInputs = false;488489    // Coinbase is only valid in a block, not as a loose transaction490    if (IsCoinBase())491        return error("AcceptTransaction() : coinbase as individual tx");492493    if (!CheckTransaction())494        return error("AcceptTransaction() : CheckTransaction failed");495496    // To help v0.1.5 clients who would see it as a negative number497    if (nLockTime > INT_MAX)498        return error("AcceptTransaction() : not accepting nLockTime beyond 2038");499500    // Do we already have it?501    uint256 hash = GetHash();502    CRITICAL_BLOCK(cs_mapTransactions)503        if (mapTransactions.count(hash))504            return false;505    if (fCheckInputs)506        if (txdb.ContainsTx(hash))507            return false;508509    // Check for conflicts with in-memory transactions510    CTransaction* ptxOld = NULL;511    for (int i = 0; i < vin.size(); i++)512    {513        COutPoint outpoint = vin[i].prevout;514        if (mapNextTx.count(outpoint))515        {516            // Allow replacing with a newer version of the same transaction517            if (i != 0)518                return false;519            ptxOld = mapNextTx[outpoint].ptx;520            if (!IsNewerThan(*ptxOld))521                return false;522            for (int i = 0; i < vin.size(); i++)523            {524                COutPoint outpoint = vin[i].prevout;525                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)526                    return false;527            }528            break;529        }530    }531532    // Check against previous transactions533    map<uint256, CTxIndex> mapUnused;534    int64 nFees = 0;535    if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))536    {537        if (pfMissingInputs)538            *pfMissingInputs = true;539        return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());540    }541542    // Store transaction in memory543    CRITICAL_BLOCK(cs_mapTransactions)544    {545        if (ptxOld)546        {547            printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());548            mapTransactions.erase(ptxOld->GetHash());549        }550        AddToMemoryPool();551    }552553    ///// are we sure this is ok when loading transactions or restoring block txes554    // If updated, erase old tx from wallet555    if (ptxOld)556        EraseFromWallet(ptxOld->GetHash());557558    printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());559    return true;560}561562563bool CTransaction::AddToMemoryPool()564{565    // Add to memory pool without checking anything.  Don't call this directly,566    // call AcceptTransaction to properly check the transaction first.567    CRITICAL_BLOCK(cs_mapTransactions)568    {569        uint256 hash = GetHash();570        mapTransactions[hash] = *this;571        for (int i = 0; i < vin.size(); i++)572            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);573        nTransactionsUpdated++;574    }575    return true;576}577578579bool CTransaction::RemoveFromMemoryPool()580{581    // Remove transaction from memory pool582    CRITICAL_BLOCK(cs_mapTransactions)583    {584        foreach(const CTxIn& txin, vin)585            mapNextTx.erase(txin.prevout);586        mapTransactions.erase(GetHash());587        nTransactionsUpdated++;588    }589    return true;590}591592593594595596597int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const598{599    if (hashBlock == 0 || nIndex == -1)600        return 0;601602    // Find the block it claims to be in603    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);604    if (mi == mapBlockIndex.end())605        return 0;606    CBlockIndex* pindex = (*mi).second;607    if (!pindex || !pindex->IsInMainChain())608        return 0;609610    // Make sure the merkle branch connects to this block611    if (!fMerkleVerified)612    {613        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)614            return 0;615        fMerkleVerified = true;616    }617618    nHeightRet = pindex->nHeight;619    return pindexBest->nHeight - pindex->nHeight + 1;620}621622623int CMerkleTx::GetBlocksToMaturity() const624{625    if (!IsCoinBase())626        return 0;627    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());628}629630631bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)632{633    if (fClient)634    {635        if (!IsInMainChain() && !ClientConnectInputs())636            return false;637        return CTransaction::AcceptTransaction(txdb, false);638    }639    else640    {641        return CTransaction::AcceptTransaction(txdb, fCheckInputs);642    }643}644645646647bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)648{649    CRITICAL_BLOCK(cs_mapTransactions)650    {651        foreach(CMerkleTx& tx, vtxPrev)652        {653            if (!tx.IsCoinBase())654            {655                uint256 hash = tx.GetHash();656                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))657                    tx.AcceptTransaction(txdb, fCheckInputs);658            }659        }660        if (!IsCoinBase())661            return AcceptTransaction(txdb, fCheckInputs);662    }663    return true;664}665666void ReacceptWalletTransactions()667{668    CTxDB txdb("r");669    CRITICAL_BLOCK(cs_mapWallet)670    {671        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)672        {673            CWalletTx& wtx = item.second;674            if (wtx.fSpent && wtx.IsCoinBase())675                continue;676677            CTxIndex txindex;678            if (txdb.ReadTxIndex(wtx.GetHash(), txindex))679            {680                // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat681                if (!wtx.fSpent)682                {683                    if (txindex.vSpent.size() != wtx.vout.size())684                    {685                        printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());686                        continue;687                    }688                    for (int i = 0; i < txindex.vSpent.size(); i++)689                    {690                        if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())691                        {692                            printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());693                            wtx.fSpent = true;694                            wtx.WriteToDisk();695                            break;696                        }697                    }698                }699            }700            else701            {702                // Reaccept any txes of ours that aren't already in a block703                if (!wtx.IsCoinBase())704                    wtx.AcceptWalletTransaction(txdb, false);705            }706        }707    }708}709710711void CWalletTx::RelayWalletTransaction(CTxDB& txdb)712{713    foreach(const CMerkleTx& tx, vtxPrev)714    {715        if (!tx.IsCoinBase())716        {717            uint256 hash = tx.GetHash();718            if (!txdb.ContainsTx(hash))719                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);720        }721    }722    if (!IsCoinBase())723    {724        uint256 hash = GetHash();725        if (!txdb.ContainsTx(hash))726        {727            printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());728            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);729        }730    }731}732733void ResendWalletTransactions()734{735    // Do this infrequently and randomly to avoid giving away736    // that these are our transactions.737    static int64 nNextTime;738    if (GetTime() < nNextTime)739        return;740    bool fFirst = (nNextTime == 0);741    nNextTime = GetTime() + GetRand(120 * 60);742    if (fFirst)743        return;744745    // Rebroadcast any of our txes that aren't in a block yet746    printf("ResendWalletTransactions()\n");747    CTxDB txdb("r");748    CRITICAL_BLOCK(cs_mapWallet)749    {750        // Sort them in chronological order751        multimap<unsigned int, CWalletTx*> mapSorted;752        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)753        {754            CWalletTx& wtx = item.second;755            // Don't rebroadcast until it's had plenty of time that756            // it should have gotten in already by now.757            if (nTimeBestReceived - wtx.nTimeReceived > 60 * 60)758                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));759        }760        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)761        {762            CWalletTx& wtx = *item.second;763            wtx.RelayWalletTransaction(txdb);764        }765    }766}767768769770771772773774775776777//////////////////////////////////////////////////////////////////////////////778//779// CBlock and CBlockIndex780//781782bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)783{784    return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);785}786787uint256 GetOrphanRoot(const CBlock* pblock)788{789    // Work back to the first block in the orphan chain790    while (mapOrphanBlocks.count(pblock->hashPrevBlock))791        pblock = mapOrphanBlocks[pblock->hashPrevBlock];792    return pblock->GetHash();793}794795int64 CBlock::GetBlockValue(int64 nFees) const796{797    int64 nSubsidy = 50 * COIN;798799    // Subsidy is cut in half every 4 years800    nSubsidy >>= (nBestHeight / 210000);801802    return nSubsidy + nFees;803}804805unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)806{807    const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks808    const unsigned int nTargetSpacing = 10 * 60;809    const unsigned int nInterval = nTargetTimespan / nTargetSpacing;810811    // Genesis block812    if (pindexLast == NULL)813        return bnProofOfWorkLimit.GetCompact();814815    // Only change once per interval816    if ((pindexLast->nHeight+1) % nInterval != 0)817        return pindexLast->nBits;818819    // Go back by what we want to be 14 days worth of blocks820    const CBlockIndex* pindexFirst = pindexLast;821    for (int i = 0; pindexFirst && i < nInterval-1; i++)822        pindexFirst = pindexFirst->pprev;823    assert(pindexFirst);824825    // Limit adjustment step826    unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;827    printf("  nActualTimespan = %d  before bounds\n", nActualTimespan);828    if (nActualTimespan < nTargetTimespan/4)829        nActualTimespan = nTargetTimespan/4;830    if (nActualTimespan > nTargetTimespan*4)831        nActualTimespan = nTargetTimespan*4;832833    // Retarget834    CBigNum bnNew;835    bnNew.SetCompact(pindexLast->nBits);836    bnNew *= nActualTimespan;837    bnNew /= nTargetTimespan;838839    if (bnNew > bnProofOfWorkLimit)840        bnNew = bnProofOfWorkLimit;841842    /// debug print843    printf("GetNextWorkRequired RETARGET\n");844    printf("nTargetTimespan = %d    nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);845    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());846    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());847848    return bnNew.GetCompact();849}850851852853854855856857858859bool CTransaction::DisconnectInputs(CTxDB& txdb)860{861    // Relinquish previous transactions' spent pointers862    if (!IsCoinBase())863    {864        foreach(const CTxIn& txin, vin)865        {866            COutPoint prevout = txin.prevout;867868            // Get prev txindex from disk869            CTxIndex txindex;870            if (!txdb.ReadTxIndex(prevout.hash, txindex))871                return error("DisconnectInputs() : ReadTxIndex failed");872873            if (prevout.n >= txindex.vSpent.size())874                return error("DisconnectInputs() : prevout.n out of range");875876            // Mark outpoint as not spent877            txindex.vSpent[prevout.n].SetNull();878879            // Write back880            txdb.UpdateTxIndex(prevout.hash, txindex);881        }882    }883884    // Remove transaction from index885    if (!txdb.EraseTxIndex(*this))886        return error("DisconnectInputs() : EraseTxPos failed");887888    return true;889}890891892bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)893{894    // Take over previous transactions' spent pointers895    if (!IsCoinBase())896    {897        int64 nValueIn = 0;898        for (int i = 0; i < vin.size(); i++)899        {900            COutPoint prevout = vin[i].prevout;901902            // Read txindex903            CTxIndex txindex;904            bool fFound = true;905            if (fMiner && mapTestPool.count(prevout.hash))906            {907                // Get txindex from current proposed changes908                txindex = mapTestPool[prevout.hash];909            }910            else911            {912                // Read txindex from txdb913                fFound = txdb.ReadTxIndex(prevout.hash, txindex);914            }915            if (!fFound && (fBlock || fMiner))916                return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());917918            // Read txPrev919            CTransaction txPrev;920            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))921            {922                // Get prev tx from single transactions in memory923                CRITICAL_BLOCK(cs_mapTransactions)924                {925                    if (!mapTransactions.count(prevout.hash))926                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());927                    txPrev = mapTransactions[prevout.hash];928                }929                if (!fFound)930                    txindex.vSpent.resize(txPrev.vout.size());931            }932            else933            {934                // Get prev tx from disk935                if (!txPrev.ReadFromDisk(txindex.pos))936                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());937            }938939            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())940                return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());941942            // If prev is coinbase, check that it's matured943            if (txPrev.IsCoinBase())944                for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)945                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)946                        return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);947948            // Verify signature949            if (!VerifySignature(txPrev, *this, i))950                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());951952            // Check for conflicts953            if (!txindex.vSpent[prevout.n].IsNull())954                return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());955956            // Mark outpoints as spent957            txindex.vSpent[prevout.n] = posThisTx;958959            // Write back960            if (fBlock)961                txdb.UpdateTxIndex(prevout.hash, txindex);962            else if (fMiner)963                mapTestPool[prevout.hash] = txindex;964965            nValueIn += txPrev.vout[prevout.n].nValue;966        }967968        // Tally transaction fees969        int64 nTxFee = nValueIn - GetValueOut();970        if (nTxFee < 0)971            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());972        if (nTxFee < nMinFee)973            return false;974        nFees += nTxFee;975    }976977    if (fBlock)978    {979        // Add transaction to disk index980        if (!txdb.AddTxIndex(*this, posThisTx, nHeight))981            return error("ConnectInputs() : AddTxPos failed");982    }983    else if (fMiner)984    {985        // Add transaction to test pool986        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());987    }988989    return true;990}991992993bool CTransaction::ClientConnectInputs()994{995    if (IsCoinBase())996        return false;997998    // Take over previous transactions' spent pointers999    CRITICAL_BLOCK(cs_mapTransactions)1000    {1001        int64 nValueIn = 0;1002        for (int i = 0; i < vin.size(); i++)1003        {1004            // Get prev tx from single transactions in memory1005            COutPoint prevout = vin[i].prevout;1006            if (!mapTransactions.count(prevout.hash))1007                return false;1008            CTransaction& txPrev = mapTransactions[prevout.hash];10091010            if (prevout.n >= txPrev.vout.size())1011                return false;10121013            // Verify signature1014            if (!VerifySignature(txPrev, *this, i))1015                return error("ConnectInputs() : VerifySignature failed");10161017            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of1018            ///// this has to go away now that posNext is gone1019            // // Check for conflicts1020            // if (!txPrev.vout[prevout.n].posNext.IsNull())1021            //     return error("ConnectInputs() : prev tx already used");1022            //1023            // // Flag outpoints as used1024            // txPrev.vout[prevout.n].posNext = posThisTx;10251026            nValueIn += txPrev.vout[prevout.n].nValue;1027        }1028        if (GetValueOut() > nValueIn)1029            return false;1030    }10311032    return true;1033}10341035103610371038bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)1039{1040    // Disconnect in reverse order1041    for (int i = vtx.size()-1; i >= 0; i--)1042        if (!vtx[i].DisconnectInputs(txdb))1043            return false;10441045    // Update block index on disk without changing it in memory.1046    // The memory index structure will be changed after the db commits.1047    if (pindex->pprev)1048    {1049        CDiskBlockIndex blockindexPrev(pindex->pprev);1050        blockindexPrev.hashNext = 0;1051        txdb.WriteBlockIndex(blockindexPrev);1052    }10531054    return true;1055}10561057bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)1058{1059    //// issue here: it doesn't know the version1060    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());10611062    map<uint256, CTxIndex> mapUnused;1063    int64 nFees = 0;1064    foreach(CTransaction& tx, vtx)1065    {1066        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);1067        nTxPos += ::GetSerializeSize(tx, SER_DISK);10681069        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))1070            return false;1071    }10721073    if (vtx[0].GetValueOut() > GetBlockValue(nFees))1074        return false;10751076    // Update block index on disk without changing it in memory.1077    // The memory index structure will be changed after the db commits.1078    if (pindex->pprev)1079    {1080        CDiskBlockIndex blockindexPrev(pindex->pprev);1081        blockindexPrev.hashNext = pindex->GetBlockHash();1082        txdb.WriteBlockIndex(blockindexPrev);1083    }10841085    // Watch for transactions paying to me1086    foreach(CTransaction& tx, vtx)1087        AddToWalletIfMine(tx, this);10881089    return true;1090}1091109210931094bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)1095{1096    printf("REORGANIZE\n");10971098    // Find the fork1099    CBlockIndex* pfork = pindexBest;1100    CBlockIndex* plonger = pindexNew;1101    while (pfork != plonger)1102    {1103        if (!(pfork = pfork->pprev))1104            return error("Reorganize() : pfork->pprev is null");1105        while (plonger->nHeight > pfork->nHeight)1106            if (!(plonger = plonger->pprev))1107                return error("Reorganize() : plonger->pprev is null");1108    }11091110    // List of what to disconnect1111    vector<CBlockIndex*> vDisconnect;1112    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)1113        vDisconnect.push_back(pindex);11141115    // List of what to connect1116    vector<CBlockIndex*> vConnect;1117    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)1118        vConnect.push_back(pindex);1119    reverse(vConnect.begin(), vConnect.end());11201121    // Disconnect shorter branch1122    vector<CTransaction> vResurrect;1123    foreach(CBlockIndex* pindex, vDisconnect)1124    {1125        CBlock block;1126        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1127            return error("Reorganize() : ReadFromDisk for disconnect failed");1128        if (!block.DisconnectBlock(txdb, pindex))1129            return error("Reorganize() : DisconnectBlock failed");11301131        // Queue memory transactions to resurrect1132        foreach(const CTransaction& tx, block.vtx)1133            if (!tx.IsCoinBase())1134                vResurrect.push_back(tx);1135    }11361137    // Connect longer branch1138    vector<CTransaction> vDelete;1139    for (int i = 0; i < vConnect.size(); i++)1140    {1141        CBlockIndex* pindex = vConnect[i];1142        CBlock block;1143        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1144            return error("Reorganize() : ReadFromDisk for connect failed");1145        if (!block.ConnectBlock(txdb, pindex))1146        {1147            // Invalid block, delete the rest of this branch1148            txdb.TxnAbort();1149            for (int j = i; j < vConnect.size(); j++)1150            {1151                CBlockIndex* pindex = vConnect[j];1152                pindex->EraseBlockFromDisk();1153                txdb.EraseBlockIndex(pindex->GetBlockHash());1154                mapBlockIndex.erase(pindex->GetBlockHash());1155                delete pindex;1156            }1157            return error("Reorganize() : ConnectBlock failed");1158        }11591160        // Queue memory transactions to delete1161        foreach(const CTransaction& tx, block.vtx)1162            vDelete.push_back(tx);1163    }1164    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1165        return error("Reorganize() : WriteHashBestChain failed");11661167    // Commit now because resurrecting could take some time1168    txdb.TxnCommit();11691170    // Disconnect shorter branch1171    foreach(CBlockIndex* pindex, vDisconnect)1172        if (pindex->pprev)1173            pindex->pprev->pnext = NULL;11741175    // Connect longer branch1176    foreach(CBlockIndex* pindex, vConnect)1177        if (pindex->pprev)1178            pindex->pprev->pnext = pindex;11791180    // Resurrect memory transactions that were in the disconnected branch1181    foreach(CTransaction& tx, vResurrect)1182        tx.AcceptTransaction(txdb, false);11831184    // Delete redundant memory transactions that are in the connected branch1185    foreach(CTransaction& tx, vDelete)1186        tx.RemoveFromMemoryPool();11871188    return true;1189}119011911192bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1193{1194    // Check for duplicate1195    uint256 hash = GetHash();1196    if (mapBlockIndex.count(hash))1197        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());11981199    // Construct new block index object1200    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1201    if (!pindexNew)1202        return error("AddToBlockIndex() : new CBlockIndex failed");1203    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1204    pindexNew->phashBlock = &((*mi).first);1205    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1206    if (miPrev != mapBlockIndex.end())1207    {1208        pindexNew->pprev = (*miPrev).second;1209        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1210    }12111212    CTxDB txdb;1213    txdb.TxnBegin();1214    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));12151216    // New best1217    if (pindexNew->nHeight > nBestHeight)1218    {1219        if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1220        {1221            pindexGenesisBlock = pindexNew;1222            txdb.WriteHashBestChain(hash);1223        }1224        else if (hashPrevBlock == hashBestChain)1225        {1226            // Adding to current best branch1227            if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1228            {1229                txdb.TxnAbort();1230                pindexNew->EraseBlockFromDisk();1231                mapBlockIndex.erase(pindexNew->GetBlockHash());1232                delete pindexNew;1233                return error("AddToBlockIndex() : ConnectBlock failed");1234            }1235            txdb.TxnCommit();1236            pindexNew->pprev->pnext = pindexNew;12371238            // Delete redundant memory transactions1239            foreach(CTransaction& tx, vtx)1240                tx.RemoveFromMemoryPool();1241        }1242        else1243        {1244            // New best branch1245            if (!Reorganize(txdb, pindexNew))1246            {1247                txdb.TxnAbort();1248                return error("AddToBlockIndex() : Reorganize failed");1249            }1250        }12511252        // New best block1253        hashBestChain = hash;1254        pindexBest = pindexNew;1255        nBestHeight = pindexBest->nHeight;1256        nTimeBestReceived = GetTime();1257        nTransactionsUpdated++;1258        printf("AddToBlockIndex: new best=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);1259    }12601261    txdb.TxnCommit();1262    txdb.Close();12631264    if (pindexNew == pindexBest)1265    {1266        // Notify UI to display prev block's coinbase if it was ours1267        static uint256 hashPrevBestCoinBase;1268        CRITICAL_BLOCK(cs_mapWallet)1269            vWalletUpdated.push_back(hashPrevBestCoinBase);1270        hashPrevBestCoinBase = vtx[0].GetHash();1271    }12721273    MainFrameRepaint();1274    return true;1275}12761277127812791280bool CBlock::CheckBlock() const1281{1282    // These are checks that are independent of context1283    // that can be verified before saving an orphan block.12841285    // Size limits1286    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)1287        return error("CheckBlock() : size limits failed");12881289    // Check timestamp1290    if (nTime > GetAdjustedTime() + 2 * 60 * 60)1291        return error("CheckBlock() : block timestamp too far in the future");12921293    // First transaction must be coinbase, the rest must not be1294    if (vtx.empty() || !vtx[0].IsCoinBase())1295        return error("CheckBlock() : first tx is not coinbase");1296    for (int i = 1; i < vtx.size(); i++)1297        if (vtx[i].IsCoinBase())1298            return error("CheckBlock() : more than one coinbase");12991300    // Check transactions1301    foreach(const CTransaction& tx, vtx)1302        if (!tx.CheckTransaction())1303            return error("CheckBlock() : CheckTransaction failed");13041305    // Check proof of work matches claimed amount1306    if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1307        return error("CheckBlock() : nBits below minimum work");1308    if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1309        return error("CheckBlock() : hash doesn't match nBits");13101311    // Check merkleroot1312    if (hashMerkleRoot != BuildMerkleTree())1313        return error("CheckBlock() : hashMerkleRoot mismatch");13141315    return true;1316}13171318bool CBlock::AcceptBlock()1319{1320    // Check for duplicate1321    uint256 hash = GetHash();1322    if (mapBlockIndex.count(hash))1323        return error("AcceptBlock() : block already in mapBlockIndex");13241325    // Get prev block index1326    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1327    if (mi == mapBlockIndex.end())1328        return error("AcceptBlock() : prev block not found");1329    CBlockIndex* pindexPrev = (*mi).second;13301331    // Check timestamp against prev1332    if (nTime <= pindexPrev->GetMedianTimePast())1333        return error("AcceptBlock() : block's timestamp is too early");13341335    // Check that all transactions are finalized1336    foreach(const CTransaction& tx, vtx)1337        if (!tx.IsFinal(nTime))1338            return error("AcceptBlock() : contains a non-final transaction");13391340    // Check proof of work1341    if (nBits != GetNextWorkRequired(pindexPrev))1342        return error("AcceptBlock() : incorrect proof of work");13431344    // Write block to history file1345    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))1346        return error("AcceptBlock() : out of disk space");1347    unsigned int nFile;1348    unsigned int nBlockPos;1349    if (!WriteToDisk(!fClient, nFile, nBlockPos))1350        return error("AcceptBlock() : WriteToDisk failed");1351    if (!AddToBlockIndex(nFile, nBlockPos))1352        return error("AcceptBlock() : AddToBlockIndex failed");13531354    // Relay inventory, but don't relay old inventory during initial block download1355    if (hashBestChain == hash)1356        CRITICAL_BLOCK(cs_vNodes)1357            foreach(CNode* pnode, vNodes)1358                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))1359                    pnode->PushInventory(CInv(MSG_BLOCK, hash));13601361    return true;1362}13631364bool ProcessBlock(CNode* pfrom, CBlock* pblock)1365{1366    // Check for duplicate1367    uint256 hash = pblock->GetHash();1368    if (mapBlockIndex.count(hash))1369        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());1370    if (mapOrphanBlocks.count(hash))1371        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());13721373    // Preliminary checks1374    if (!pblock->CheckBlock())1375    {1376        delete pblock;1377        return error("ProcessBlock() : CheckBlock FAILED");1378    }13791380    // If don't already have its previous block, shunt it off to holding area until we get it1381    if (!mapBlockIndex.count(pblock->hashPrevBlock))1382    {1383        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());1384        mapOrphanBlocks.insert(make_pair(hash, pblock));1385        mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));13861387        // Ask this guy to fill in what we're missing1388        if (pfrom)1389            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));1390        return true;1391    }13921393    // Store to disk1394    if (!pblock->AcceptBlock())1395    {1396        delete pblock;1397        return error("ProcessBlock() : AcceptBlock FAILED");1398    }1399    delete pblock;14001401    // Recursively process any orphan blocks that depended on this one1402    vector<uint256> vWorkQueue;1403    vWorkQueue.push_back(hash);1404    for (int i = 0; i < vWorkQueue.size(); i++)1405    {1406        uint256 hashPrev = vWorkQueue[i];1407        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1408             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1409             ++mi)1410        {1411            CBlock* pblockOrphan = (*mi).second;1412            if (pblockOrphan->AcceptBlock())1413                vWorkQueue.push_back(pblockOrphan->GetHash());1414            mapOrphanBlocks.erase(pblockOrphan->GetHash());1415            delete pblockOrphan;1416        }1417        mapOrphanBlocksByPrev.erase(hashPrev);1418    }14191420    printf("ProcessBlock: ACCEPTED\n");1421    return true;1422}142314241425142614271428142914301431template<typename Stream>1432bool ScanMessageStart(Stream& s)1433{1434    // Scan ahead to the next pchMessageStart, which should normally be immediately1435    // at the file pointer.  Leaves file pointer at end of pchMessageStart.1436    s.clear(0);1437    short prevmask = s.exceptions(0);1438    const char* p = BEGIN(pchMessageStart);1439    try1440    {1441        loop1442        {1443            char c;1444            s.read(&c, 1);1445            if (s.fail())1446            {1447                s.clear(0);1448                s.exceptions(prevmask);1449                return false;1450            }1451            if (*p != c)1452                p = BEGIN(pchMessageStart);1453            if (*p == c)1454            {1455                if (++p == END(pchMessageStart))1456                {1457                    s.clear(0);1458                    s.exceptions(prevmask);1459                    return true;1460                }1461            }1462        }1463    }1464    catch (...)1465    {1466        s.clear(0);1467        s.exceptions(prevmask);1468        return false;1469    }1470}14711472bool CheckDiskSpace(int64 nAdditionalBytes)1473{1474    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;14751476    // Check for 15MB because database could create another 10MB log file at any time1477    if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)1478    {1479        fShutdown = true;1480        ThreadSafeMessageBox(_("Warning: Disk space is low  "), "Bitcoin", wxOK | wxICON_EXCLAMATION);1481        CreateThread(Shutdown, NULL);1482        return false;1483    }1484    return true;1485}14861487FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1488{1489    if (nFile == -1)1490        return NULL;1491    FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);1492    if (!file)1493        return NULL;1494    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1495    {1496        if (fseek(file, nBlockPos, SEEK_SET) != 0)1497        {1498            fclose(file);1499            return NULL;1500        }1501    }1502    return file;1503}15041505static unsigned int nCurrentBlockFile = 1;15061507FILE* AppendBlockFile(unsigned int& nFileRet)1508{1509    nFileRet = 0;1510    loop1511    {1512        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1513        if (!file)1514            return NULL;1515        if (fseek(file, 0, SEEK_END) != 0)1516            return NULL;1517        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1518        if (ftell(file) < 0x7F000000 - MAX_SIZE)1519        {1520            nFileRet = nCurrentBlockFile;1521            return file;1522        }1523        fclose(file);1524        nCurrentBlockFile++;1525    }1526}15271528bool LoadBlockIndex(bool fAllowNew)1529{1530    //1531    // Load block index1532    //1533    CTxDB txdb("cr");1534    if (!txdb.LoadBlockIndex())1535        return false;1536    txdb.Close();15371538    //1539    // Init with genesis block1540    //1541    if (mapBlockIndex.empty())1542    {1543        if (!fAllowNew)1544            return false;154515461547        // Genesis Block:1548        // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f1549        // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b1550        // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D6954206568541551        // txNew.vout[0].nValue       = 50000000001552        // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG1553        // block.nVersion = 11554        // block.nTime    = 12310065051555        // block.nBits    = 0x1d00ffff1556        // block.nNonce   = 20832368931557        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1558        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1559        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1560        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1561        //   vMerkleTree: 4a5e1e15621563        // Genesis block1564        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1565        CTransaction txNew;1566        txNew.vin.resize(1);1567        txNew.vout.resize(1);1568        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));1569        txNew.vout[0].nValue = 50 * COIN;1570        CBigNum bnPubKey;1571        bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");1572        txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;1573        CBlock block;1574        block.vtx.push_back(txNew);1575        block.hashPrevBlock = 0;1576        block.hashMerkleRoot = block.BuildMerkleTree();1577        block.nVersion = 1;1578        block.nTime    = 1231006505;1579        block.nBits    = 0x1d00ffff;1580        block.nNonce   = 2083236893;15811582            //// debug print1583            printf("%s\n", block.GetHash().ToString().c_str());1584            printf("%s\n", block.hashMerkleRoot.ToString().c_str());1585            printf("%s\n", hashGenesisBlock.ToString().c_str());1586            txNew.vout[0].scriptPubKey.print();1587            block.print();1588            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));15891590        assert(block.GetHash() == hashGenesisBlock);15911592        // Start new block file1593        unsigned int nFile;1594        unsigned int nBlockPos;1595        if (!block.WriteToDisk(!fClient, nFile, nBlockPos))1596            return error("LoadBlockIndex() : writing genesis block to disk failed");1597        if (!block.AddToBlockIndex(nFile, nBlockPos))1598            return error("LoadBlockIndex() : genesis block not accepted");1599    }16001601    return true;1602}1603160416051606void PrintBlockTree()1607{1608    // precompute tree structure1609    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1610    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1611    {1612        CBlockIndex* pindex = (*mi).second;1613        mapNext[pindex->pprev].push_back(pindex);1614        // test1615        //while (rand() % 3 == 0)1616        //    mapNext[pindex->pprev].push_back(pindex);1617    }16181619    vector<pair<int, CBlockIndex*> > vStack;1620    vStack.push_back(make_pair(0, pindexGenesisBlock));16211622    int nPrevCol = 0;1623    while (!vStack.empty())1624    {1625        int nCol = vStack.back().first;1626        CBlockIndex* pindex = vStack.back().second;1627        vStack.pop_back();16281629        // print split or gap1630        if (nCol > nPrevCol)1631        {1632            for (int i = 0; i < nCol-1; i++)1633                printf("| ");1634            printf("|\\\n");1635        }1636        else if (nCol < nPrevCol)1637        {1638            for (int i = 0; i < nCol; i++)1639                printf("| ");1640            printf("|\n");1641        }1642        nPrevCol = nCol;16431644        // print columns1645        for (int i = 0; i < nCol; i++)1646            printf("| ");16471648        // print item1649        CBlock block;1650        block.ReadFromDisk(pindex);1651        printf("%d (%u,%u) %s  %s  tx %d",1652            pindex->nHeight,1653            pindex->nFile,1654            pindex->nBlockPos,1655            block.GetHash().ToString().substr(0,16).c_str(),1656            DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),1657            block.vtx.size());16581659        CRITICAL_BLOCK(cs_mapWallet)1660        {1661            if (mapWallet.count(block.vtx[0].GetHash()))1662            {1663                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1664                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1665            }1666        }1667        printf("\n");166816691670        // put the main timechain first1671        vector<CBlockIndex*>& vNext = mapNext[pindex];1672        for (int i = 0; i < vNext.size(); i++)1673        {1674            if (vNext[i]->pnext)1675            {1676                swap(vNext[0], vNext[i]);1677                break;1678            }1679        }16801681        // iterate children1682        for (int i = 0; i < vNext.size(); i++)1683            vStack.push_back(make_pair(nCol+i, vNext[i]));1684    }1685}16861687168816891690169116921693169416951696//////////////////////////////////////////////////////////////////////////////1697//1698// Messages1699//170017011702bool AlreadyHave(CTxDB& txdb, const CInv& inv)1703{1704    switch (inv.type)1705    {1706    case MSG_TX:    return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);1707    case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);1708    }1709    // Don't know what it is, just say we already got one1710    return true;1711}17121713171417151716171717181719bool ProcessMessages(CNode* pfrom)1720{1721    CDataStream& vRecv = pfrom->vRecv;1722    if (vRecv.empty())1723        return true;1724    //if (fDebug)1725    //    printf("ProcessMessages(%d bytes)\n", vRecv.size());17261727    //1728    // Message format1729    //  (4) message start1730    //  (12) command1731    //  (4) size1732    //  (4) checksum1733    //  (x) data1734    //17351736    loop1737    {1738        // Scan for message start1739        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1740        int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());1741        if (vRecv.end() - pstart < nHeaderSize)1742        {1743            if (vRecv.size() > nHeaderSize)1744            {1745                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1746                vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);1747            }1748            break;1749        }1750        if (pstart - vRecv.begin() > 0)1751            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1752        vRecv.erase(vRecv.begin(), pstart);17531754        // Read header1755        vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);1756        CMessageHeader hdr;1757        vRecv >> hdr;1758        if (!hdr.IsValid())1759        {1760            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1761            continue;1762        }1763        string strCommand = hdr.GetCommand();17641765        // Message size1766        unsigned int nMessageSize = hdr.nMessageSize;1767        if (nMessageSize > vRecv.size())1768        {1769            // Rewind and wait for rest of message1770            ///// need a mechanism to give up waiting for overlong message size error1771            vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());1772            break;1773        }17741775        // Copy message to its own buffer1776        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1777        vRecv.ignore(nMessageSize);17781779        // Checksum1780        if (vRecv.GetVersion() >= 209)1781        {1782            uint256 hash = Hash(vMsg.begin(), vMsg.end());1783            unsigned int nChecksum = 0;1784            memcpy(&nChecksum, &hash, sizeof(nChecksum));1785            if (nChecksum != hdr.nChecksum)1786            {1787                printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",1788                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);1789                continue;1790            }1791        }17921793        // Process message1794        bool fRet = false;1795        try1796        {1797            CRITICAL_BLOCK(cs_main)1798                fRet = ProcessMessage(pfrom, strCommand, vMsg);1799            if (fShutdown)1800                return true;1801        }1802        catch (std::ios_base::failure& e)1803        {1804            if (strstr(e.what(), "CDataStream::read() : end of data"))1805            {1806                // Allow exceptions from underlength message on vRecv1807                printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());1808            }1809            else if (strstr(e.what(), ": size too large"))1810            {1811                // Allow exceptions from overlong size1812                printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());1813            }1814            else1815            {1816                PrintException(&e, "ProcessMessage()");1817            }1818        }1819        catch (std::exception& e) {1820            PrintException(&e, "ProcessMessage()");1821        } catch (...) {1822            PrintException(NULL, "ProcessMessage()");1823        }18241825        if (!fRet)1826            printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);1827    }18281829    vRecv.Compact();1830    return true;1831}18321833183418351836bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1837{1838    static map<unsigned int, vector<unsigned char> > mapReuseKey;1839    RandAddSeedPerfmon();1840    if (fDebug)1841        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());1842    printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());1843    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)1844    {1845        printf("dropmessagestest DROPPING RECV MESSAGE\n");1846        return true;1847    }184818491850185118521853    if (strCommand == "version")1854    {1855        // Each connection can only send one version message1856        if (pfrom->nVersion != 0)1857            return false;18581859        int64 nTime;1860        CAddress addrMe;1861        CAddress addrFrom;1862        uint64 nNonce = 1;1863        string strSubVer;1864        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;1865        if (pfrom->nVersion == 10300)1866            pfrom->nVersion = 300;1867        if (pfrom->nVersion >= 106 && !vRecv.empty())1868            vRecv >> addrFrom >> nNonce;1869        if (pfrom->nVersion >= 106 && !vRecv.empty())1870            vRecv >> strSubVer;1871        if (pfrom->nVersion >= 209 && !vRecv.empty())1872            vRecv >> pfrom->nStartingHeight;18731874        if (pfrom->nVersion == 0)1875            return false;18761877        // Disconnect if we connected to ourself1878        if (nNonce == nLocalHostNonce && nNonce > 1)1879        {1880            pfrom->fDisconnect = true;1881            return true;1882        }18831884        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);1885        if (pfrom->fClient)1886        {1887            pfrom->vSend.nType |= SER_BLOCKHEADERONLY;1888            pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;1889        }18901891        AddTimeData(pfrom->addr.ip, nTime);18921893        // Change version1894        if (pfrom->nVersion >= 209)1895            pfrom->PushMessage("verack");1896        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));1897        if (pfrom->nVersion < 209)1898            pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));18991900        // Ask the first connected node for block updates1901        static int nAskedForBlocks;1902        if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))1903        {1904            nAskedForBlocks++;1905            pfrom->PushGetBlocks(pindexBest, uint256(0));1906        }19071908        pfrom->fSuccessfullyConnected = true;19091910        printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);1911    }191219131914    else if (pfrom->nVersion == 0)1915    {1916        // Must have a version message before anything else1917        return false;1918    }191919201921    else if (strCommand == "verack")1922    {1923        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));1924    }192519261927    else if (strCommand == "addr")1928    {1929        vector<CAddress> vAddr;1930        vRecv >> vAddr;1931        if (pfrom->nVersion < 200) // don't want addresses from 0.1.51932            return true;1933        if (vAddr.size() > 1000)1934            return error("message addr size() = %d", vAddr.size());19351936        // Store the new addresses1937        foreach(CAddress& addr, vAddr)1938        {1939            if (fShutdown)1940                return true;1941            addr.nTime = GetAdjustedTime() - 2 * 60 * 60;1942            if (pfrom->fGetAddr || vAddr.size() > 10)1943                addr.nTime -= 5 * 24 * 60 * 60;1944            AddAddress(addr);1945            pfrom->AddAddressKnown(addr);1946            if (!pfrom->fGetAddr && addr.IsRoutable())1947            {1948                // Relay to a limited number of other nodes1949                CRITICAL_BLOCK(cs_vNodes)1950                {1951                    // Use deterministic randomness to send to1952                    // the same places for an hour at a time1953                    static uint256 hashSalt;1954                    if (hashSalt == 0)1955                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));1956                    uint256 hashRand = addr.ip ^ (GetTime()/3600) ^ hashSalt;1957                    multimap<uint256, CNode*> mapMix;1958                    foreach(CNode* pnode, vNodes)1959                        mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));1960                    int nRelayNodes = 10; // reduce this to 5 when the network is large1961                    for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)1962                        ((*mi).second)->PushAddress(addr);1963                }1964            }1965        }1966        if (vAddr.size() < 1000)1967            pfrom->fGetAddr = false;1968    }196919701971    else if (strCommand == "inv")1972    {1973        vector<CInv> vInv;1974        vRecv >> vInv;1975        if (vInv.size() > 50000)1976            return error("message inv size() = %d", vInv.size());19771978        CTxDB txdb("r");1979        foreach(const CInv& inv, vInv)1980        {1981            if (fShutdown)1982                return true;1983            pfrom->AddInventoryKnown(inv);19841985            bool fAlreadyHave = AlreadyHave(txdb, inv);1986            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");19871988            if (!fAlreadyHave)1989                pfrom->AskFor(inv);1990            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))1991                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));19921993            // Track requests for our stuff1994            CRITICAL_BLOCK(cs_mapRequestCount)1995            {1996                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);1997                if (mi != mapRequestCount.end())1998                    (*mi).second++;1999            }2000        }2001    }200220032004    else if (strCommand == "getdata")2005    {2006        vector<CInv> vInv;2007        vRecv >> vInv;2008        if (vInv.size() > 50000)2009            return error("message getdata size() = %d", vInv.size());20102011        foreach(const CInv& inv, vInv)2012        {2013            if (fShutdown)2014                return true;2015            printf("received getdata for: %s\n", inv.ToString().c_str());20162017            if (inv.type == MSG_BLOCK)2018            {2019                // Send block from disk2020                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);2021                if (mi != mapBlockIndex.end())2022                {2023                    //// could optimize this to send header straight from blockindex for client2024                    CBlock block;2025                    block.ReadFromDisk((*mi).second, !pfrom->fClient);2026                    pfrom->PushMessage("block", block);20272028                    // Trigger them to send a getblocks request for the next batch of inventory2029                    if (inv.hash == pfrom->hashContinue)2030                    {2031                        // Bypass PushInventory, this must send even if redundant,2032                        // and we want it right after the last block so they don't2033                        // wait for other stuff first.2034                        vector<CInv> vInv;2035                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));2036                        pfrom->PushMessage("inv", vInv);2037                        pfrom->hashContinue = 0;2038                    }2039                }2040            }2041            else if (inv.IsKnownType())2042            {2043                // Send stream from relay memory2044                CRITICAL_BLOCK(cs_mapRelay)2045                {2046                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);2047                    if (mi != mapRelay.end())2048                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);2049                }2050            }20512052            // Track requests for our stuff2053            CRITICAL_BLOCK(cs_mapRequestCount)2054            {2055                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);2056                if (mi != mapRequestCount.end())2057                    (*mi).second++;2058            }2059        }2060    }206120622063    else if (strCommand == "getblocks")2064    {2065        CBlockLocator locator;2066        uint256 hashStop;2067        vRecv >> locator >> hashStop;20682069        // Find the first block the caller has in the main chain2070        CBlockIndex* pindex = locator.GetBlockIndex();20712072        // Send the rest of the chain2073        if (pindex)2074            pindex = pindex->pnext;2075        int nLimit = 500 + locator.GetDistanceBack();2076        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);2077        for (; pindex; pindex = pindex->pnext)2078        {2079            if (pindex->GetBlockHash() == hashStop)2080            {2081                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());2082                break;2083            }2084            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));2085            if (--nLimit <= 0)2086            {2087                // When this block is requested, we'll send an inv that'll make them2088                // getblocks the next batch of inventory.2089                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());2090                pfrom->hashContinue = pindex->GetBlockHash();2091                break;2092            }2093        }2094    }209520962097    else if (strCommand == "tx")2098    {2099        vector<uint256> vWorkQueue;2100        CDataStream vMsg(vRecv);2101        CTransaction tx;2102        vRecv >> tx;21032104        CInv inv(MSG_TX, tx.GetHash());2105        pfrom->AddInventoryKnown(inv);21062107        bool fMissingInputs = false;2108        if (tx.AcceptTransaction(true, &fMissingInputs))2109        {2110            AddToWalletIfMine(tx, NULL);2111            RelayMessage(inv, vMsg);2112            mapAlreadyAskedFor.erase(inv);2113            vWorkQueue.push_back(inv.hash);21142115            // Recursively process any orphan transactions that depended on this one2116            for (int i = 0; i < vWorkQueue.size(); i++)2117            {2118                uint256 hashPrev = vWorkQueue[i];2119                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);2120                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);2121                     ++mi)2122                {2123                    const CDataStream& vMsg = *((*mi).second);2124                    CTransaction tx;2125                    CDataStream(vMsg) >> tx;2126                    CInv inv(MSG_TX, tx.GetHash());21272128                    if (tx.AcceptTransaction(true))2129                    {2130                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2131                        AddToWalletIfMine(tx, NULL);2132                        RelayMessage(inv, vMsg);2133                        mapAlreadyAskedFor.erase(inv);2134                        vWorkQueue.push_back(inv.hash);2135                    }2136                }2137            }21382139            foreach(uint256 hash, vWorkQueue)2140                EraseOrphanTx(hash);2141        }2142        else if (fMissingInputs)2143        {2144            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2145            AddOrphanTx(vMsg);2146        }2147    }214821492150    else if (strCommand == "block")2151    {2152        auto_ptr<CBlock> pblock(new CBlock);2153        vRecv >> *pblock;21542155        //// debug print2156        printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());2157        // pblock->print();21582159        CInv inv(MSG_BLOCK, pblock->GetHash());2160        pfrom->AddInventoryKnown(inv);21612162        if (ProcessBlock(pfrom, pblock.release()))2163            mapAlreadyAskedFor.erase(inv);2164    }216521662167    else if (strCommand == "getaddr")2168    {2169        // This includes all nodes that are currently online,2170        // since they rebroadcast an addr every 24 hours2171        pfrom->vAddrToSend.clear();2172        int64 nSince = GetAdjustedTime() - 24 * 60 * 60; // in the last 24 hours2173        CRITICAL_BLOCK(cs_mapAddresses)2174        {2175            unsigned int nSize = mapAddresses.size();2176            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)2177            {2178                if (fShutdown)2179                    return true;2180                const CAddress& addr = item.second;2181                if (addr.nTime > nSince)2182                    pfrom->PushAddress(addr);2183            }2184        }2185    }218621872188    else if (strCommand == "checkorder")2189    {2190        uint256 hashReply;2191        CWalletTx order;2192        vRecv >> hashReply >> order;21932194        /// we have a chance to check the order here21952196        // Keep giving the same key to the same ip until they use it2197        if (!mapReuseKey.count(pfrom->addr.ip))2198            mapReuseKey[pfrom->addr.ip] = GenerateNewKey();21992200        // Send back approval of order and pubkey to use2201        CScript scriptPubKey;2202        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;2203        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);2204    }220522062207    else if (strCommand == "submitorder")2208    {2209        uint256 hashReply;2210        CWalletTx wtxNew;2211        vRecv >> hashReply >> wtxNew;2212        wtxNew.fFromMe = false;22132214        // Broadcast2215        if (!wtxNew.AcceptWalletTransaction())2216        {2217            pfrom->PushMessage("reply", hashReply, (int)1);2218            return error("submitorder AcceptWalletTransaction() failed, returning error 1");2219        }2220        wtxNew.fTimeReceivedIsTxTime = true;2221        AddToWallet(wtxNew);2222        wtxNew.RelayWalletTransaction();2223        mapReuseKey.erase(pfrom->addr.ip);22242225        // Send back confirmation2226        pfrom->PushMessage("reply", hashReply, (int)0);2227    }222822292230    else if (strCommand == "reply")2231    {2232        uint256 hashReply;2233        vRecv >> hashReply;22342235        CRequestTracker tracker;2236        CRITICAL_BLOCK(pfrom->cs_mapRequests)2237        {2238            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2239            if (mi != pfrom->mapRequests.end())2240            {2241                tracker = (*mi).second;2242                pfrom->mapRequests.erase(mi);2243            }2244        }2245        if (!tracker.IsNull())2246            tracker.fn(tracker.param1, vRecv);2247    }224822492250    else if (strCommand == "ping")2251    {2252    }225322542255    else2256    {2257        // Ignore unknown commands for extensibility2258    }225922602261    // Update the last seen time for this node's address2262    if (pfrom->fNetworkNode)2263        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")2264            AddressCurrentlyConnected(pfrom->addr);226522662267    return true;2268}2269227022712272227322742275227622772278bool SendMessages(CNode* pto, bool fSendTrickle)2279{2280    CRITICAL_BLOCK(cs_main)2281    {2282        // Don't send anything until we get their version message2283        if (pto->nVersion == 0)2284            return true;22852286        // Keep-alive ping2287        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())2288            pto->PushMessage("ping");22892290        // Address refresh broadcast2291        static int64 nLastRebroadcast;2292        if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours2293        {2294            nLastRebroadcast = GetTime();2295            CRITICAL_BLOCK(cs_vNodes)2296            {2297                foreach(CNode* pnode, vNodes)2298                {2299                    // Periodically clear setAddrKnown to allow refresh broadcasts2300                    pnode->setAddrKnown.clear();23012302                    // Rebroadcast our address2303                    if (addrLocalHost.IsRoutable() && !fUseProxy)2304                        pnode->PushAddress(addrLocalHost);2305                }2306            }2307        }23082309        // Resend wallet transactions that haven't gotten in a block yet2310        ResendWalletTransactions();231123122313        //2314        // Message: addr2315        //2316        if (fSendTrickle)2317        {2318            vector<CAddress> vAddr;2319            vAddr.reserve(pto->vAddrToSend.size());2320            foreach(const CAddress& addr, pto->vAddrToSend)2321            {2322                // returns true if wasn't already contained in the set2323                if (pto->setAddrKnown.insert(addr).second)2324                {2325                    vAddr.push_back(addr);2326                    // receiver rejects addr messages larger than 10002327                    if (vAddr.size() >= 1000)2328                    {2329                        pto->PushMessage("addr", vAddr);2330                        vAddr.clear();2331                    }2332                }2333            }2334            pto->vAddrToSend.clear();2335            if (!vAddr.empty())2336                pto->PushMessage("addr", vAddr);2337        }233823392340        //2341        // Message: inventory2342        //2343        vector<CInv> vInv;2344        vector<CInv> vInvWait;2345        CRITICAL_BLOCK(pto->cs_inventory)2346        {2347            vInv.reserve(pto->vInventoryToSend.size());2348            vInvWait.reserve(pto->vInventoryToSend.size());2349            foreach(const CInv& inv, pto->vInventoryToSend)2350            {2351                if (pto->setInventoryKnown.count(inv))2352                    continue;23532354                // trickle out tx inv to protect privacy2355                if (inv.type == MSG_TX && !fSendTrickle)2356                {2357                    // 1/4 of tx invs blast to all immediately2358                    static uint256 hashSalt;2359                    if (hashSalt == 0)2360                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));2361                    uint256 hashRand = inv.hash ^ hashSalt;2362                    hashRand = Hash(BEGIN(hashRand), END(hashRand));2363                    bool fTrickleWait = ((hashRand & 3) != 0);23642365                    // always trickle our own transactions2366                    if (!fTrickleWait)2367                    {2368                        TRY_CRITICAL_BLOCK(cs_mapWallet)2369                        {2370                            map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);2371                            if (mi != mapWallet.end())2372                            {2373                                CWalletTx& wtx = (*mi).second;2374                                if (wtx.fFromMe)2375                                    fTrickleWait = true;2376                            }2377                        }2378                    }23792380                    if (fTrickleWait)2381                    {2382                        vInvWait.push_back(inv);2383                        continue;2384                    }2385                }23862387                // returns true if wasn't already contained in the set2388                if (pto->setInventoryKnown.insert(inv).second)2389                {2390                    vInv.push_back(inv);2391                    if (vInv.size() >= 1000)2392                    {2393                        pto->PushMessage("inv", vInv);2394                        vInv.clear();2395                    }2396                }2397            }2398            pto->vInventoryToSend = vInvWait;2399        }2400        if (!vInv.empty())2401            pto->PushMessage("inv", vInv);240224032404        //2405        // Message: getdata2406        //2407        vector<CInv> vGetData;2408        int64 nNow = GetTime() * 1000000;2409        CTxDB txdb("r");2410        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2411        {2412            const CInv& inv = (*pto->mapAskFor.begin()).second;2413            if (!AlreadyHave(txdb, inv))2414            {2415                printf("sending getdata: %s\n", inv.ToString().c_str());2416                vGetData.push_back(inv);2417                if (vGetData.size() >= 1000)2418                {2419                    pto->PushMessage("getdata", vGetData);2420                    vGetData.clear();2421                }2422            }2423            pto->mapAskFor.erase(pto->mapAskFor.begin());2424        }2425        if (!vGetData.empty())2426            pto->PushMessage("getdata", vGetData);24272428    }2429    return true;2430}243124322433243424352436243724382439244024412442244324442445//////////////////////////////////////////////////////////////////////////////2446//2447// BitcoinMiner2448//24492450void GenerateBitcoins(bool fGenerate)2451{2452    if (fGenerateBitcoins != fGenerate)2453    {2454        fGenerateBitcoins = fGenerate;2455        CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);2456        MainFrameRepaint();2457    }2458    if (fGenerateBitcoins)2459    {2460        int nProcessors = wxThread::GetCPUCount();2461        printf("%d processors\n", nProcessors);2462        if (nProcessors < 1)2463            nProcessors = 1;2464        if (fLimitProcessors && nProcessors > nLimitProcessors)2465            nProcessors = nLimitProcessors;2466        int nAddThreads = nProcessors - vnThreadsRunning[3];2467        printf("Starting %d BitcoinMiner threads\n", nAddThreads);2468        for (int i = 0; i < nAddThreads; i++)2469        {2470            if (!CreateThread(ThreadBitcoinMiner, NULL))2471                printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");2472            Sleep(10);2473        }2474    }2475}24762477void ThreadBitcoinMiner(void* parg)2478{2479    try2480    {2481        vnThreadsRunning[3]++;2482        BitcoinMiner();2483        vnThreadsRunning[3]--;2484    }2485    catch (std::exception& e) {2486        vnThreadsRunning[3]--;2487        PrintException(&e, "ThreadBitcoinMiner()");2488    } catch (...) {2489        vnThreadsRunning[3]--;2490        PrintException(NULL, "ThreadBitcoinMiner()");2491    }2492    UIThreadCall(bind(CalledSetStatusBar, "", 0));2493    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);2494}24952496int FormatHashBlocks(void* pbuffer, unsigned int len)2497{2498    unsigned char* pdata = (unsigned char*)pbuffer;2499    unsigned int blocks = 1 + ((len + 8) / 64);2500    unsigned char* pend = pdata + 64 * blocks;2501    memset(pdata + len, 0, 64 * blocks - len);2502    pdata[len] = 0x80;2503    unsigned int bits = len * 8;2504    pend[-1] = (bits >> 0) & 0xff;2505    pend[-2] = (bits >> 8) & 0xff;2506    pend[-3] = (bits >> 16) & 0xff;2507    pend[-4] = (bits >> 24) & 0xff;2508    return blocks;2509}25102511using CryptoPP::ByteReverse;2512static int detectlittleendian = 1;25132514void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)2515{2516    unsigned int* pinput = (unsigned int*)pin;2517    unsigned int* pstate = (unsigned int*)pout;25182519    CryptoPP::SHA256::InitState(pstate);25202521    if (*(char*)&detectlittleendian != 0)2522    {2523        for (int n = 0; n < nBlocks; n++)2524        {2525            unsigned int pbuf[16];2526            for (int i = 0; i < 16; i++)2527                pbuf[i] = ByteReverse(pinput[n * 16 + i]);2528            CryptoPP::SHA256::Transform(pstate, pbuf);2529        }2530        for (int i = 0; i < 8; i++)2531            pstate[i] = ByteReverse(pstate[i]);2532    }2533    else2534    {2535        for (int n = 0; n < nBlocks; n++)2536            CryptoPP::SHA256::Transform(pstate, pinput + n * 16);2537    }2538}253925402541void BitcoinMiner()2542{2543    printf("BitcoinMiner started\n");25442545    CKey key;2546    key.MakeNewKey();2547    CBigNum bnExtraNonce = 0;2548    while (fGenerateBitcoins)2549    {2550        SetThreadPriority(THREAD_PRIORITY_LOWEST);2551        Sleep(50);2552        if (fShutdown)2553            return;2554        while (vNodes.empty())2555        {2556            Sleep(1000);2557            if (fShutdown)2558                return;2559            if (!fGenerateBitcoins)2560                return;2561        }25622563        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;2564        CBlockIndex* pindexPrev = pindexBest;2565        unsigned int nBits = GetNextWorkRequired(pindexPrev);256625672568        //2569        // Create coinbase tx2570        //2571        CTransaction txNew;2572        txNew.vin.resize(1);2573        txNew.vin[0].prevout.SetNull();2574        txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;2575        txNew.vout.resize(1);2576        txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;257725782579        //2580        // Create new block2581        //2582        auto_ptr<CBlock> pblock(new CBlock());2583        if (!pblock.get())2584            return;25852586        // Add our coinbase tx as first transaction2587        pblock->vtx.push_back(txNew);25882589        // Collect the latest transactions into the block2590        int64 nFees = 0;2591        CRITICAL_BLOCK(cs_main)2592        CRITICAL_BLOCK(cs_mapTransactions)2593        {2594            CTxDB txdb("r");2595            map<uint256, CTxIndex> mapTestPool;2596            vector<char> vfAlreadyAdded(mapTransactions.size());2597            bool fFoundSomething = true;2598            unsigned int nBlockSize = 0;2599            while (fFoundSomething && nBlockSize < MAX_SIZE/2)2600            {2601                fFoundSomething = false;2602                unsigned int n = 0;2603                for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)2604                {2605                    if (vfAlreadyAdded[n])2606                        continue;2607                    CTransaction& tx = (*mi).second;2608                    if (tx.IsCoinBase() || !tx.IsFinal())2609                        continue;26102611                    // Transaction fee based on block size2612                    int64 nMinFee = tx.GetMinFee(nBlockSize);26132614                    map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);2615                    if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))2616                        continue;2617                    swap(mapTestPool, mapTestPoolTmp);26182619                    pblock->vtx.push_back(tx);2620                    nBlockSize += ::GetSerializeSize(tx, SER_NETWORK);2621                    vfAlreadyAdded[n] = true;2622                    fFoundSomething = true;2623                }2624            }2625        }2626        pblock->nBits = nBits;2627        pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);2628        printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());262926302631        //2632        // Prebuild hash buffer2633        //2634        struct unnamed12635        {2636            struct unnamed22637            {2638                int nVersion;2639                uint256 hashPrevBlock;2640                uint256 hashMerkleRoot;2641                unsigned int nTime;2642                unsigned int nBits;2643                unsigned int nNonce;2644            }2645            block;2646            unsigned char pchPadding0[64];2647            uint256 hash1;2648            unsigned char pchPadding1[64];2649        }2650        tmp;26512652        tmp.block.nVersion       = pblock->nVersion;2653        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);2654        tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();2655        tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());2656        tmp.block.nBits          = pblock->nBits          = nBits;2657        tmp.block.nNonce         = pblock->nNonce         = 1;26582659        unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));2660        unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));266126622663        //2664        // Search2665        //2666        int64 nStart = GetTime();2667        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();2668        uint256 hash;2669        loop2670        {2671            BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);2672            BlockSHA256(&tmp.hash1, nBlocks1, &hash);26732674            if (hash <= hashTarget)2675            {2676                pblock->nNonce = tmp.block.nNonce;2677                assert(hash == pblock->GetHash());26782679                    //// debug print2680                    printf("BitcoinMiner:\n");2681                    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());2682                    pblock->print();2683                    printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());2684                    printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());26852686                SetThreadPriority(THREAD_PRIORITY_NORMAL);2687                CRITICAL_BLOCK(cs_main)2688                {2689                    if (pindexPrev == pindexBest)2690                    {2691                        // Save key2692                        if (!AddKey(key))2693                            return;2694                        key.MakeNewKey();26952696                        // Track how many getdata requests this block gets2697                        CRITICAL_BLOCK(cs_mapRequestCount)2698                            mapRequestCount[pblock->GetHash()] = 0;26992700                        // Process this block the same as if we had received it from another node2701                        if (!ProcessBlock(NULL, pblock.release()))2702                            printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");2703                    }2704                }2705                SetThreadPriority(THREAD_PRIORITY_LOWEST);27062707                Sleep(500);2708                break;2709            }27102711            // Update nTime every few seconds2712            const unsigned int nMask = 0xffff;2713            if ((++tmp.block.nNonce & nMask) == 0)2714            {2715                // Meter hashes/sec2716                static int64 nHashCounter;2717                static int64 nLastTick;2718                if (nLastTick == 0)2719                    nLastTick = GetTimeMillis();2720                else2721                    nHashCounter += nMask + 1;2722                if (GetTimeMillis() - nLastTick > 4000)2723                {2724                    double dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nLastTick);2725                    nLastTick = GetTimeMillis();2726                    nHashCounter = 0;2727                    string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);2728                    UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));2729                    static int64 nLogTime;2730                    if (GetTime() - nLogTime > 30 * 60)2731                    {2732                        nLogTime = GetTime();2733                        printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());2734                        printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);2735                    }2736                }27372738                // Check for stop or if block needs to be rebuilt2739                if (fShutdown)2740                    return;2741                if (!fGenerateBitcoins)2742                    return;2743                if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)2744                    return;2745                if (vNodes.empty())2746                    break;2747                if (tmp.block.nNonce == 0)2748                    break;2749                if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)2750                    break;2751                if (pindexPrev != pindexBest)2752                {2753                    // Pause generating during initial download2754                    if (GetTime() - nStart < 20)2755                    {2756                        CBlockIndex* pindexTmp;2757                        do2758                        {2759                            pindexTmp = pindexBest;2760                            for (int i = 0; i < 10; i++)2761                            {2762                                Sleep(1000);2763                                if (fShutdown)2764                                    return;2765                            }2766                        }2767                        while (pindexTmp != pindexBest);2768                    }2769                    break;2770                }27712772                tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());2773            }2774        }2775    }2776}2777277827792780278127822783278427852786278727882789279027912792279327942795//////////////////////////////////////////////////////////////////////////////2796//2797// Actions2798//279928002801int64 GetBalance()2802{2803    int64 nStart = GetTimeMillis();28042805    int64 nTotal = 0;2806    CRITICAL_BLOCK(cs_mapWallet)2807    {2808        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2809        {2810            CWalletTx* pcoin = &(*it).second;2811            if (!pcoin->IsFinal() || pcoin->fSpent)2812                continue;2813            nTotal += pcoin->GetCredit(true);2814        }2815    }28162817    //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);2818    return nTotal;2819}2820282128222823bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)2824{2825    setCoinsRet.clear();28262827    // List of values less than target2828    int64 nLowestLarger = INT64_MAX;2829    CWalletTx* pcoinLowestLarger = NULL;2830    vector<pair<int64, CWalletTx*> > vValue;2831    int64 nTotalLower = 0;28322833    CRITICAL_BLOCK(cs_mapWallet)2834    {2835        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2836        {2837            CWalletTx* pcoin = &(*it).second;2838            if (!pcoin->IsFinal() || pcoin->fSpent)2839                continue;2840            int64 n = pcoin->GetCredit();2841            if (n <= 0)2842                continue;2843            if (n < nTargetValue)2844            {2845                vValue.push_back(make_pair(n, pcoin));2846                nTotalLower += n;2847            }2848            else if (n == nTargetValue)2849            {2850                setCoinsRet.insert(pcoin);2851                return true;2852            }2853            else if (n < nLowestLarger)2854            {2855                nLowestLarger = n;2856                pcoinLowestLarger = pcoin;2857            }2858        }2859    }28602861    if (nTotalLower < nTargetValue)2862    {2863        if (pcoinLowestLarger == NULL)2864            return false;2865        setCoinsRet.insert(pcoinLowestLarger);2866        return true;2867    }28682869    // Solve subset sum by stochastic approximation2870    sort(vValue.rbegin(), vValue.rend());2871    vector<char> vfIncluded;2872    vector<char> vfBest(vValue.size(), true);2873    int64 nBest = nTotalLower;28742875    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)2876    {2877        vfIncluded.assign(vValue.size(), false);2878        int64 nTotal = 0;2879        bool fReachedTarget = false;2880        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)2881        {2882            for (int i = 0; i < vValue.size(); i++)2883            {2884                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])2885                {2886                    nTotal += vValue[i].first;2887                    vfIncluded[i] = true;2888                    if (nTotal >= nTargetValue)2889                    {2890                        fReachedTarget = true;2891                        if (nTotal < nBest)2892                        {2893                            nBest = nTotal;2894                            vfBest = vfIncluded;2895                        }2896                        nTotal -= vValue[i].first;2897                        vfIncluded[i] = false;2898                    }2899                }2900            }2901        }2902    }29032904    // If the next larger is still closer, return it2905    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)2906        setCoinsRet.insert(pcoinLowestLarger);2907    else2908    {2909        for (int i = 0; i < vValue.size(); i++)2910            if (vfBest[i])2911                setCoinsRet.insert(vValue[i].second);29122913        //// debug print2914        printf("SelectCoins() best subset: ");2915        for (int i = 0; i < vValue.size(); i++)2916            if (vfBest[i])2917                printf("%s ", FormatMoney(vValue[i].first).c_str());2918        printf("total %s\n", FormatMoney(nBest).c_str());2919    }29202921    return true;2922}29232924292529262927bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)2928{2929    nFeeRequiredRet = 0;2930    CRITICAL_BLOCK(cs_main)2931    {2932        // txdb must be opened before the mapWallet lock2933        CTxDB txdb("r");2934        CRITICAL_BLOCK(cs_mapWallet)2935        {2936            int64 nFee = nTransactionFee;2937            loop2938            {2939                wtxNew.vin.clear();2940                wtxNew.vout.clear();2941                wtxNew.fFromMe = true;2942                if (nValue < 0)2943                    return false;2944                int64 nValueOut = nValue;2945                int64 nTotalValue = nValue + nFee;29462947                // Choose coins to use2948                set<CWalletTx*> setCoins;2949                if (!SelectCoins(nTotalValue, setCoins))2950                    return false;2951                int64 nValueIn = 0;2952                foreach(CWalletTx* pcoin, setCoins)2953                    nValueIn += pcoin->GetCredit();29542955                // Fill a vout to the payee2956                bool fChangeFirst = GetRand(2);2957                if (!fChangeFirst)2958                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));29592960                // Fill a vout back to self with any change2961                if (nValueIn > nTotalValue)2962                {2963                    // Note: We use a new key here to keep it from being obvious which side is the change.2964                    //  The drawback is that by not reusing a previous key, the change may be lost if a2965                    //  backup is restored, if the backup doesn't have the new private key for the change.2966                    //  If we reused the old key, it would be possible to add code to look for and2967                    //  rediscover unknown transactions that were written with keys of ours to recover2968                    //  post-backup change.29692970                    // New private key2971                    if (keyRet.IsNull())2972                        keyRet.MakeNewKey();29732974                    // Fill a vout to ourself, using same address type as the payment2975                    CScript scriptChange;2976                    if (scriptPubKey.GetBitcoinAddressHash160() != 0)2977                        scriptChange.SetBitcoinAddress(keyRet.GetPubKey());2978                    else2979                        scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;2980                    wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));2981                }29822983                // Fill a vout to the payee2984                if (fChangeFirst)2985                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));29862987                // Fill vin2988                foreach(CWalletTx* pcoin, setCoins)2989                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2990                        if (pcoin->vout[nOut].IsMine())2991                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));29922993                // Sign2994                int nIn = 0;2995                foreach(CWalletTx* pcoin, setCoins)2996                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2997                        if (pcoin->vout[nOut].IsMine())2998                            SignSignature(*pcoin, wtxNew, nIn++);29993000                // Check that enough fee is included3001                if (nFee < wtxNew.GetMinFee())3002                {3003                    nFee = nFeeRequiredRet = wtxNew.GetMinFee();3004                    continue;3005                }30063007                // Fill vtxPrev by copying from previous transactions vtxPrev3008                wtxNew.AddSupportingTransactions(txdb);3009                wtxNew.fTimeReceivedIsTxTime = true;30103011                break;3012            }3013        }3014    }3015    return true;3016}30173018// Call after CreateTransaction unless you want to abort3019bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)3020{3021    CRITICAL_BLOCK(cs_main)3022    {3023        printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());3024        CRITICAL_BLOCK(cs_mapWallet)3025        {3026            // This is only to keep the database open to defeat the auto-flush for the3027            // duration of this scope.  This is the only place where this optimization3028            // maybe makes sense; please don't do it anywhere else.3029            CWalletDB walletdb("r");30303031            // Add the change's private key to wallet3032            if (!key.IsNull() && !AddKey(key))3033                throw runtime_error("CommitTransaction() : AddKey failed\n");30343035            // Add tx to wallet, because if it has change it's also ours,3036            // otherwise just for transaction history.3037            AddToWallet(wtxNew);30383039            // Mark old coins as spent3040            set<CWalletTx*> setCoins;3041            foreach(const CTxIn& txin, wtxNew.vin)3042                setCoins.insert(&mapWallet[txin.prevout.hash]);3043            foreach(CWalletTx* pcoin, setCoins)3044            {3045                pcoin->fSpent = true;3046                pcoin->WriteToDisk();3047                vWalletUpdated.push_back(pcoin->GetHash());3048            }3049        }30503051        // Track how many getdata requests our transaction gets3052        CRITICAL_BLOCK(cs_mapRequestCount)3053            mapRequestCount[wtxNew.GetHash()] = 0;30543055        // Broadcast3056        if (!wtxNew.AcceptTransaction())3057        {3058            // This must not fail. The transaction has already been signed and recorded.3059            printf("CommitTransaction() : Error: Transaction not valid");3060            return false;3061        }3062        wtxNew.RelayWalletTransaction();3063    }3064    MainFrameRepaint();3065    return true;3066}30673068306930703071string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3072{3073    CRITICAL_BLOCK(cs_main)3074    {3075        CKey key;3076        int64 nFeeRequired;3077        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))3078        {3079            string strError;3080            if (nValue + nFeeRequired > GetBalance())3081                strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());3082            else3083                strError = _("Error: Transaction creation failed  ");3084            printf("SendMoney() : %s", strError.c_str());3085            return strError;3086        }30873088        if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))3089            return "ABORTED";30903091        if (!CommitTransaction(wtxNew, key))3092            return _("Error: The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");3093    }3094    MainFrameRepaint();3095    return "";3096}3097309830993100string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3101{3102    // Check amount3103    if (nValue <= 0)3104        return _("Invalid amount");3105    if (nValue + nTransactionFee > GetBalance())3106        return _("Insufficient funds");31073108    // Parse bitcoin address3109    CScript scriptPubKey;3110    if (!scriptPubKey.SetBitcoinAddress(strAddress))3111        return _("Invalid bitcoin address");31123113    return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);3114}

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