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.2.0 · 2009-12-16

main.cpp

2,917 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.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;2930map<uint256, CBlock*> mapOrphanBlocks;31multimap<uint256, CBlock*> mapOrphanBlocksByPrev;3233map<uint256, CDataStream*> mapOrphanTransactions;34multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;3536map<uint256, CWalletTx> mapWallet;37vector<uint256> vWalletUpdated;38CCriticalSection cs_mapWallet;3940map<vector<unsigned char>, CPrivKey> mapKeys;41map<uint160, vector<unsigned char> > mapPubKeys;42CCriticalSection cs_mapKeys;43CKey keyUser;4445map<uint256, int> mapRequestCount;46CCriticalSection cs_mapRequestCount;4748// Settings49int fGenerateBitcoins = false;50int64 nTransactionFee = 0;51CAddress addrIncoming;52int fLimitProcessors = false;53int nLimitProcessors = 1;54555657585960//////////////////////////////////////////////////////////////////////////////61//62// mapKeys63//6465bool AddKey(const CKey& key)66{67    CRITICAL_BLOCK(cs_mapKeys)68    {69        mapKeys[key.GetPubKey()] = key.GetPrivKey();70        mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();71    }72    return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());73}7475vector<unsigned char> GenerateNewKey()76{77    CKey key;78    key.MakeNewKey();79    if (!AddKey(key))80        throw runtime_error("GenerateNewKey() : AddKey failed\n");81    return key.GetPubKey();82}8384858687//////////////////////////////////////////////////////////////////////////////88//89// mapWallet90//9192bool AddToWallet(const CWalletTx& wtxIn)93{94    uint256 hash = wtxIn.GetHash();95    CRITICAL_BLOCK(cs_mapWallet)96    {97        // Inserts only if not already there, returns tx inserted or tx found98        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));99        CWalletTx& wtx = (*ret.first).second;100        bool fInsertedNew = ret.second;101        if (fInsertedNew)102            wtx.nTimeReceived = GetAdjustedTime();103104        bool fUpdated = false;105        if (!fInsertedNew)106        {107            // Merge108            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)109            {110                wtx.hashBlock = wtxIn.hashBlock;111                fUpdated = true;112            }113            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))114            {115                wtx.vMerkleBranch = wtxIn.vMerkleBranch;116                wtx.nIndex = wtxIn.nIndex;117                fUpdated = true;118            }119            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)120            {121                wtx.fFromMe = wtxIn.fFromMe;122                fUpdated = true;123            }124            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)125            {126                wtx.fSpent = wtxIn.fSpent;127                fUpdated = true;128            }129        }130131        //// debug print132        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));133134        // Write to disk135        if (fInsertedNew || fUpdated)136            if (!wtx.WriteToDisk())137                return false;138139        // Notify UI140        vWalletUpdated.push_back(hash);141    }142143    // Refresh UI144    MainFrameRepaint();145    return true;146}147148bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)149{150    if (tx.IsMine() || mapWallet.count(tx.GetHash()))151    {152        CWalletTx wtx(tx);153        // Get merkle branch if transaction was found in a block154        if (pblock)155            wtx.SetMerkleBranch(pblock);156        return AddToWallet(wtx);157    }158    return true;159}160161bool EraseFromWallet(uint256 hash)162{163    CRITICAL_BLOCK(cs_mapWallet)164    {165        if (mapWallet.erase(hash))166            CWalletDB().EraseTx(hash);167    }168    return true;169}170171172173174175176177178179//////////////////////////////////////////////////////////////////////////////180//181// mapOrphanTransactions182//183184void AddOrphanTx(const CDataStream& vMsg)185{186    CTransaction tx;187    CDataStream(vMsg) >> tx;188    uint256 hash = tx.GetHash();189    if (mapOrphanTransactions.count(hash))190        return;191    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);192    foreach(const CTxIn& txin, tx.vin)193        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));194}195196void EraseOrphanTx(uint256 hash)197{198    if (!mapOrphanTransactions.count(hash))199        return;200    const CDataStream* pvMsg = mapOrphanTransactions[hash];201    CTransaction tx;202    CDataStream(*pvMsg) >> tx;203    foreach(const CTxIn& txin, tx.vin)204    {205        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);206             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)207        {208            if ((*mi).second == pvMsg)209                mapOrphanTransactionsByPrev.erase(mi++);210            else211                mi++;212        }213    }214    delete pvMsg;215    mapOrphanTransactions.erase(hash);216}217218219220221222223224225//////////////////////////////////////////////////////////////////////////////226//227// CTransaction228//229230bool CTxIn::IsMine() const231{232    CRITICAL_BLOCK(cs_mapWallet)233    {234        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);235        if (mi != mapWallet.end())236        {237            const CWalletTx& prev = (*mi).second;238            if (prevout.n < prev.vout.size())239                if (prev.vout[prevout.n].IsMine())240                    return true;241        }242    }243    return false;244}245246int64 CTxIn::GetDebit() const247{248    CRITICAL_BLOCK(cs_mapWallet)249    {250        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);251        if (mi != mapWallet.end())252        {253            const CWalletTx& prev = (*mi).second;254            if (prevout.n < prev.vout.size())255                if (prev.vout[prevout.n].IsMine())256                    return prev.vout[prevout.n].nValue;257        }258    }259    return 0;260}261262int64 CWalletTx::GetTxTime() const263{264    if (!fTimeReceivedIsTxTime && hashBlock != 0)265    {266        // If we did not receive the transaction directly, we rely on the block's267        // time to figure out when it happened.  We use the median over a range268        // of blocks to try to filter out inaccurate block times.269        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);270        if (mi != mapBlockIndex.end())271        {272            CBlockIndex* pindex = (*mi).second;273            if (pindex)274                return pindex->GetMedianTime();275        }276    }277    return nTimeReceived;278}279280int CWalletTx::GetRequestCount() const281{282    // Returns -1 if it wasn't being tracked283    int nRequests = -1;284    CRITICAL_BLOCK(cs_mapRequestCount)285    {286        if (IsCoinBase())287        {288            // Generated block289            if (hashBlock != 0)290            {291                map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);292                if (mi != mapRequestCount.end())293                    nRequests = (*mi).second;294            }295        }296        else297        {298            // Did anyone request this transaction?299            map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());300            if (mi != mapRequestCount.end())301            {302                nRequests = (*mi).second;303304                // How about the block it's in?305                if (nRequests == 0 && hashBlock != 0)306                {307                    map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);308                    if (mi != mapRequestCount.end())309                        nRequests = (*mi).second;310                    else311                        nRequests = 1; // If it's in someone else's block it must have got out312                }313            }314        }315    }316    return nRequests;317}318319320321322int CMerkleTx::SetMerkleBranch(const CBlock* pblock)323{324    if (fClient)325    {326        if (hashBlock == 0)327            return 0;328    }329    else330    {331        CBlock blockTmp;332        if (pblock == NULL)333        {334            // Load the block this tx is in335            CTxIndex txindex;336            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))337                return 0;338            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))339                return 0;340            pblock = &blockTmp;341        }342343        // Update the tx's hashBlock344        hashBlock = pblock->GetHash();345346        // Locate the transaction347        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)348            if (pblock->vtx[nIndex] == *(CTransaction*)this)349                break;350        if (nIndex == pblock->vtx.size())351        {352            vMerkleBranch.clear();353            nIndex = -1;354            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");355            return 0;356        }357358        // Fill in merkle branch359        vMerkleBranch = pblock->GetMerkleBranch(nIndex);360    }361362    // Is the tx in a block that's in the main chain363    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);364    if (mi == mapBlockIndex.end())365        return 0;366    CBlockIndex* pindex = (*mi).second;367    if (!pindex || !pindex->IsInMainChain())368        return 0;369370    return pindexBest->nHeight - pindex->nHeight + 1;371}372373374375void CWalletTx::AddSupportingTransactions(CTxDB& txdb)376{377    vtxPrev.clear();378379    const int COPY_DEPTH = 3;380    if (SetMerkleBranch() < COPY_DEPTH)381    {382        vector<uint256> vWorkQueue;383        foreach(const CTxIn& txin, vin)384            vWorkQueue.push_back(txin.prevout.hash);385386        // This critsect is OK because txdb is already open387        CRITICAL_BLOCK(cs_mapWallet)388        {389            map<uint256, const CMerkleTx*> mapWalletPrev;390            set<uint256> setAlreadyDone;391            for (int i = 0; i < vWorkQueue.size(); i++)392            {393                uint256 hash = vWorkQueue[i];394                if (setAlreadyDone.count(hash))395                    continue;396                setAlreadyDone.insert(hash);397398                CMerkleTx tx;399                if (mapWallet.count(hash))400                {401                    tx = mapWallet[hash];402                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)403                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;404                }405                else if (mapWalletPrev.count(hash))406                {407                    tx = *mapWalletPrev[hash];408                }409                else if (!fClient && txdb.ReadDiskTx(hash, tx))410                {411                    ;412                }413                else414                {415                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");416                    continue;417                }418419                int nDepth = tx.SetMerkleBranch();420                vtxPrev.push_back(tx);421422                if (nDepth < COPY_DEPTH)423                    foreach(const CTxIn& txin, tx.vin)424                        vWorkQueue.push_back(txin.prevout.hash);425            }426        }427    }428429    reverse(vtxPrev.begin(), vtxPrev.end());430}431432433434435436437438439440441442bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)443{444    if (pfMissingInputs)445        *pfMissingInputs = false;446447    // Coinbase is only valid in a block, not as a loose transaction448    if (IsCoinBase())449        return error("AcceptTransaction() : coinbase as individual tx");450451    if (!CheckTransaction())452        return error("AcceptTransaction() : CheckTransaction failed");453454    // To help v0.1.5 clients who would see it as negative number. please delete this later.455    if (nLockTime > INT_MAX)456        return error("AcceptTransaction() : not accepting nLockTime beyond 2038");457458    // Do we already have it?459    uint256 hash = GetHash();460    CRITICAL_BLOCK(cs_mapTransactions)461        if (mapTransactions.count(hash))462            return false;463    if (fCheckInputs)464        if (txdb.ContainsTx(hash))465            return false;466467    // Check for conflicts with in-memory transactions468    CTransaction* ptxOld = NULL;469    for (int i = 0; i < vin.size(); i++)470    {471        COutPoint outpoint = vin[i].prevout;472        if (mapNextTx.count(outpoint))473        {474            // Allow replacing with a newer version of the same transaction475            if (i != 0)476                return false;477            ptxOld = mapNextTx[outpoint].ptx;478            if (!IsNewerThan(*ptxOld))479                return false;480            for (int i = 0; i < vin.size(); i++)481            {482                COutPoint outpoint = vin[i].prevout;483                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)484                    return false;485            }486            break;487        }488    }489490    // Check against previous transactions491    map<uint256, CTxIndex> mapUnused;492    int64 nFees = 0;493    if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))494    {495        if (pfMissingInputs)496            *pfMissingInputs = true;497        return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());498    }499500    // Store transaction in memory501    CRITICAL_BLOCK(cs_mapTransactions)502    {503        if (ptxOld)504        {505            printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());506            mapTransactions.erase(ptxOld->GetHash());507        }508        AddToMemoryPool();509    }510511    ///// are we sure this is ok when loading transactions or restoring block txes512    // If updated, erase old tx from wallet513    if (ptxOld)514        EraseFromWallet(ptxOld->GetHash());515516    printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());517    return true;518}519520521bool CTransaction::AddToMemoryPool()522{523    // Add to memory pool without checking anything.  Don't call this directly,524    // call AcceptTransaction to properly check the transaction first.525    CRITICAL_BLOCK(cs_mapTransactions)526    {527        uint256 hash = GetHash();528        mapTransactions[hash] = *this;529        for (int i = 0; i < vin.size(); i++)530            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);531        nTransactionsUpdated++;532    }533    return true;534}535536537bool CTransaction::RemoveFromMemoryPool()538{539    // Remove transaction from memory pool540    CRITICAL_BLOCK(cs_mapTransactions)541    {542        foreach(const CTxIn& txin, vin)543            mapNextTx.erase(txin.prevout);544        mapTransactions.erase(GetHash());545        nTransactionsUpdated++;546    }547    return true;548}549550551552553554555int CMerkleTx::GetDepthInMainChain() const556{557    if (hashBlock == 0 || nIndex == -1)558        return 0;559560    // Find the block it claims to be in561    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);562    if (mi == mapBlockIndex.end())563        return 0;564    CBlockIndex* pindex = (*mi).second;565    if (!pindex || !pindex->IsInMainChain())566        return 0;567568    // Make sure the merkle branch connects to this block569    if (!fMerkleVerified)570    {571        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)572            return 0;573        fMerkleVerified = true;574    }575576    return pindexBest->nHeight - pindex->nHeight + 1;577}578579580int CMerkleTx::GetBlocksToMaturity() const581{582    if (!IsCoinBase())583        return 0;584    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());585}586587588bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)589{590    if (fClient)591    {592        if (!IsInMainChain() && !ClientConnectInputs())593            return false;594        return CTransaction::AcceptTransaction(txdb, false);595    }596    else597    {598        return CTransaction::AcceptTransaction(txdb, fCheckInputs);599    }600}601602603604bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)605{606    CRITICAL_BLOCK(cs_mapTransactions)607    {608        foreach(CMerkleTx& tx, vtxPrev)609        {610            if (!tx.IsCoinBase())611            {612                uint256 hash = tx.GetHash();613                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))614                    tx.AcceptTransaction(txdb, fCheckInputs);615            }616        }617        if (!IsCoinBase())618            return AcceptTransaction(txdb, fCheckInputs);619    }620    return true;621}622623void ReacceptWalletTransactions()624{625    // Reaccept any txes of ours that aren't already in a block626    CTxDB txdb("r");627    CRITICAL_BLOCK(cs_mapWallet)628    {629        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)630        {631            CWalletTx& wtx = item.second;632            if (!wtx.IsCoinBase() && !txdb.ContainsTx(wtx.GetHash()))633                wtx.AcceptWalletTransaction(txdb, false);634        }635    }636}637638639void CWalletTx::RelayWalletTransaction(CTxDB& txdb)640{641    foreach(const CMerkleTx& tx, vtxPrev)642    {643        if (!tx.IsCoinBase())644        {645            uint256 hash = tx.GetHash();646            if (!txdb.ContainsTx(hash))647                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);648        }649    }650    if (!IsCoinBase())651    {652        uint256 hash = GetHash();653        if (!txdb.ContainsTx(hash))654        {655            printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());656            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);657        }658    }659}660661void RelayWalletTransactions()662{663    static int64 nLastTime;664    if (GetTime() - nLastTime < 10 * 60)665        return;666    nLastTime = GetTime();667668    // Rebroadcast any of our txes that aren't in a block yet669    printf("RelayWalletTransactions()\n");670    CTxDB txdb("r");671    CRITICAL_BLOCK(cs_mapWallet)672    {673        // Sort them in chronological order674        multimap<unsigned int, CWalletTx*> mapSorted;675        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)676        {677            CWalletTx& wtx = item.second;678            mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));679        }680        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)681        {682            CWalletTx& wtx = *item.second;683            wtx.RelayWalletTransaction(txdb);684        }685    }686}687688689690691692693694695696697//////////////////////////////////////////////////////////////////////////////698//699// CBlock and CBlockIndex700//701702bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)703{704    return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);705}706707uint256 GetOrphanRoot(const CBlock* pblock)708{709    // Work back to the first block in the orphan chain710    while (mapOrphanBlocks.count(pblock->hashPrevBlock))711        pblock = mapOrphanBlocks[pblock->hashPrevBlock];712    return pblock->GetHash();713}714715int64 CBlock::GetBlockValue(int64 nFees) const716{717    int64 nSubsidy = 50 * COIN;718719    // Subsidy is cut in half every 4 years720    nSubsidy >>= (nBestHeight / 210000);721722    return nSubsidy + nFees;723}724725unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)726{727    const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks728    const unsigned int nTargetSpacing = 10 * 60;729    const unsigned int nInterval = nTargetTimespan / nTargetSpacing;730731    // Genesis block732    if (pindexLast == NULL)733        return bnProofOfWorkLimit.GetCompact();734735    // Only change once per interval736    if ((pindexLast->nHeight+1) % nInterval != 0)737        return pindexLast->nBits;738739    // Go back by what we want to be 14 days worth of blocks740    const CBlockIndex* pindexFirst = pindexLast;741    for (int i = 0; pindexFirst && i < nInterval-1; i++)742        pindexFirst = pindexFirst->pprev;743    assert(pindexFirst);744745    // Limit adjustment step746    unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;747    printf("  nActualTimespan = %d  before bounds\n", nActualTimespan);748    if (nActualTimespan < nTargetTimespan/4)749        nActualTimespan = nTargetTimespan/4;750    if (nActualTimespan > nTargetTimespan*4)751        nActualTimespan = nTargetTimespan*4;752753    // Retarget754    CBigNum bnNew;755    bnNew.SetCompact(pindexLast->nBits);756    bnNew *= nActualTimespan;757    bnNew /= nTargetTimespan;758759    if (bnNew > bnProofOfWorkLimit)760        bnNew = bnProofOfWorkLimit;761762    /// debug print763    printf("GetNextWorkRequired RETARGET\n");764    printf("nTargetTimespan = %d    nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);765    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());766    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());767768    return bnNew.GetCompact();769}770771772773774775776777778779bool CTransaction::DisconnectInputs(CTxDB& txdb)780{781    // Relinquish previous transactions' spent pointers782    if (!IsCoinBase())783    {784        foreach(const CTxIn& txin, vin)785        {786            COutPoint prevout = txin.prevout;787788            // Get prev txindex from disk789            CTxIndex txindex;790            if (!txdb.ReadTxIndex(prevout.hash, txindex))791                return error("DisconnectInputs() : ReadTxIndex failed");792793            if (prevout.n >= txindex.vSpent.size())794                return error("DisconnectInputs() : prevout.n out of range");795796            // Mark outpoint as not spent797            txindex.vSpent[prevout.n].SetNull();798799            // Write back800            txdb.UpdateTxIndex(prevout.hash, txindex);801        }802    }803804    // Remove transaction from index805    if (!txdb.EraseTxIndex(*this))806        return error("DisconnectInputs() : EraseTxPos failed");807808    return true;809}810811812bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)813{814    // Take over previous transactions' spent pointers815    if (!IsCoinBase())816    {817        int64 nValueIn = 0;818        for (int i = 0; i < vin.size(); i++)819        {820            COutPoint prevout = vin[i].prevout;821822            // Read txindex823            CTxIndex txindex;824            bool fFound = true;825            if (fMiner && mapTestPool.count(prevout.hash))826            {827                // Get txindex from current proposed changes828                txindex = mapTestPool[prevout.hash];829            }830            else831            {832                // Read txindex from txdb833                fFound = txdb.ReadTxIndex(prevout.hash, txindex);834            }835            if (!fFound && (fBlock || fMiner))836                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());837838            // Read txPrev839            CTransaction txPrev;840            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))841            {842                // Get prev tx from single transactions in memory843                CRITICAL_BLOCK(cs_mapTransactions)844                {845                    if (!mapTransactions.count(prevout.hash))846                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());847                    txPrev = mapTransactions[prevout.hash];848                }849                if (!fFound)850                    txindex.vSpent.resize(txPrev.vout.size());851            }852            else853            {854                // Get prev tx from disk855                if (!txPrev.ReadFromDisk(txindex.pos))856                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());857            }858859            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())860                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());861862            // If prev is coinbase, check that it's matured863            if (txPrev.IsCoinBase())864                for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)865                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)866                        return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);867868            // Verify signature869            if (!VerifySignature(txPrev, *this, i))870                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());871872            // Check for conflicts873            if (!txindex.vSpent[prevout.n].IsNull())874                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());875876            // Mark outpoints as spent877            txindex.vSpent[prevout.n] = posThisTx;878879            // Write back880            if (fBlock)881                txdb.UpdateTxIndex(prevout.hash, txindex);882            else if (fMiner)883                mapTestPool[prevout.hash] = txindex;884885            nValueIn += txPrev.vout[prevout.n].nValue;886        }887888        // Tally transaction fees889        int64 nTxFee = nValueIn - GetValueOut();890        if (nTxFee < 0)891            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());892        if (nTxFee < nMinFee)893            return false;894        nFees += nTxFee;895    }896897    if (fBlock)898    {899        // Add transaction to disk index900        if (!txdb.AddTxIndex(*this, posThisTx, nHeight))901            return error("ConnectInputs() : AddTxPos failed");902    }903    else if (fMiner)904    {905        // Add transaction to test pool906        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());907    }908909    return true;910}911912913bool CTransaction::ClientConnectInputs()914{915    if (IsCoinBase())916        return false;917918    // Take over previous transactions' spent pointers919    CRITICAL_BLOCK(cs_mapTransactions)920    {921        int64 nValueIn = 0;922        for (int i = 0; i < vin.size(); i++)923        {924            // Get prev tx from single transactions in memory925            COutPoint prevout = vin[i].prevout;926            if (!mapTransactions.count(prevout.hash))927                return false;928            CTransaction& txPrev = mapTransactions[prevout.hash];929930            if (prevout.n >= txPrev.vout.size())931                return false;932933            // Verify signature934            if (!VerifySignature(txPrev, *this, i))935                return error("ConnectInputs() : VerifySignature failed");936937            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of938            ///// this has to go away now that posNext is gone939            // // Check for conflicts940            // if (!txPrev.vout[prevout.n].posNext.IsNull())941            //     return error("ConnectInputs() : prev tx already used");942            //943            // // Flag outpoints as used944            // txPrev.vout[prevout.n].posNext = posThisTx;945946            nValueIn += txPrev.vout[prevout.n].nValue;947        }948        if (GetValueOut() > nValueIn)949            return false;950    }951952    return true;953}954955956957958bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)959{960    // Disconnect in reverse order961    for (int i = vtx.size()-1; i >= 0; i--)962        if (!vtx[i].DisconnectInputs(txdb))963            return false;964965    // Update block index on disk without changing it in memory.966    // The memory index structure will be changed after the db commits.967    if (pindex->pprev)968    {969        CDiskBlockIndex blockindexPrev(pindex->pprev);970        blockindexPrev.hashNext = 0;971        txdb.WriteBlockIndex(blockindexPrev);972    }973974    return true;975}976977bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)978{979    //// issue here: it doesn't know the version980    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());981982    map<uint256, CTxIndex> mapUnused;983    int64 nFees = 0;984    foreach(CTransaction& tx, vtx)985    {986        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);987        nTxPos += ::GetSerializeSize(tx, SER_DISK);988989        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))990            return false;991    }992993    if (vtx[0].GetValueOut() > GetBlockValue(nFees))994        return false;995996    // Update block index on disk without changing it in memory.997    // The memory index structure will be changed after the db commits.998    if (pindex->pprev)999    {1000        CDiskBlockIndex blockindexPrev(pindex->pprev);1001        blockindexPrev.hashNext = pindex->GetBlockHash();1002        txdb.WriteBlockIndex(blockindexPrev);1003    }10041005    // Watch for transactions paying to me1006    foreach(CTransaction& tx, vtx)1007        AddToWalletIfMine(tx, this);10081009    return true;1010}1011101210131014bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)1015{1016    printf("REORGANIZE\n");10171018    // Find the fork1019    CBlockIndex* pfork = pindexBest;1020    CBlockIndex* plonger = pindexNew;1021    while (pfork != plonger)1022    {1023        if (!(pfork = pfork->pprev))1024            return error("Reorganize() : pfork->pprev is null");1025        while (plonger->nHeight > pfork->nHeight)1026            if (!(plonger = plonger->pprev))1027                return error("Reorganize() : plonger->pprev is null");1028    }10291030    // List of what to disconnect1031    vector<CBlockIndex*> vDisconnect;1032    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)1033        vDisconnect.push_back(pindex);10341035    // List of what to connect1036    vector<CBlockIndex*> vConnect;1037    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)1038        vConnect.push_back(pindex);1039    reverse(vConnect.begin(), vConnect.end());10401041    // Disconnect shorter branch1042    vector<CTransaction> vResurrect;1043    foreach(CBlockIndex* pindex, vDisconnect)1044    {1045        CBlock block;1046        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1047            return error("Reorganize() : ReadFromDisk for disconnect failed");1048        if (!block.DisconnectBlock(txdb, pindex))1049            return error("Reorganize() : DisconnectBlock failed");10501051        // Queue memory transactions to resurrect1052        foreach(const CTransaction& tx, block.vtx)1053            if (!tx.IsCoinBase())1054                vResurrect.push_back(tx);1055    }10561057    // Connect longer branch1058    vector<CTransaction> vDelete;1059    for (int i = 0; i < vConnect.size(); i++)1060    {1061        CBlockIndex* pindex = vConnect[i];1062        CBlock block;1063        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1064            return error("Reorganize() : ReadFromDisk for connect failed");1065        if (!block.ConnectBlock(txdb, pindex))1066        {1067            // Invalid block, delete the rest of this branch1068            txdb.TxnAbort();1069            for (int j = i; j < vConnect.size(); j++)1070            {1071                CBlockIndex* pindex = vConnect[j];1072                pindex->EraseBlockFromDisk();1073                txdb.EraseBlockIndex(pindex->GetBlockHash());1074                mapBlockIndex.erase(pindex->GetBlockHash());1075                delete pindex;1076            }1077            return error("Reorganize() : ConnectBlock failed");1078        }10791080        // Queue memory transactions to delete1081        foreach(const CTransaction& tx, block.vtx)1082            vDelete.push_back(tx);1083    }1084    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1085        return error("Reorganize() : WriteHashBestChain failed");10861087    // Commit now because resurrecting could take some time1088    txdb.TxnCommit();10891090    // Disconnect shorter branch1091    foreach(CBlockIndex* pindex, vDisconnect)1092        if (pindex->pprev)1093            pindex->pprev->pnext = NULL;10941095    // Connect longer branch1096    foreach(CBlockIndex* pindex, vConnect)1097        if (pindex->pprev)1098            pindex->pprev->pnext = pindex;10991100    // Resurrect memory transactions that were in the disconnected branch1101    foreach(CTransaction& tx, vResurrect)1102        tx.AcceptTransaction(txdb, false);11031104    // Delete redundant memory transactions that are in the connected branch1105    foreach(CTransaction& tx, vDelete)1106        tx.RemoveFromMemoryPool();11071108    return true;1109}111011111112bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1113{1114    // Check for duplicate1115    uint256 hash = GetHash();1116    if (mapBlockIndex.count(hash))1117        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());11181119    // Construct new block index object1120    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1121    if (!pindexNew)1122        return error("AddToBlockIndex() : new CBlockIndex failed");1123    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1124    pindexNew->phashBlock = &((*mi).first);1125    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1126    if (miPrev != mapBlockIndex.end())1127    {1128        pindexNew->pprev = (*miPrev).second;1129        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1130    }11311132    CTxDB txdb;1133    txdb.TxnBegin();1134    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));11351136    // New best1137    if (pindexNew->nHeight > nBestHeight)1138    {1139        if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1140        {1141            pindexGenesisBlock = pindexNew;1142            txdb.WriteHashBestChain(hash);1143        }1144        else if (hashPrevBlock == hashBestChain)1145        {1146            // Adding to current best branch1147            if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1148            {1149                txdb.TxnAbort();1150                pindexNew->EraseBlockFromDisk();1151                mapBlockIndex.erase(pindexNew->GetBlockHash());1152                delete pindexNew;1153                return error("AddToBlockIndex() : ConnectBlock failed");1154            }1155            txdb.TxnCommit();1156            pindexNew->pprev->pnext = pindexNew;11571158            // Delete redundant memory transactions1159            foreach(CTransaction& tx, vtx)1160                tx.RemoveFromMemoryPool();1161        }1162        else1163        {1164            // New best branch1165            if (!Reorganize(txdb, pindexNew))1166            {1167                txdb.TxnAbort();1168                return error("AddToBlockIndex() : Reorganize failed");1169            }1170        }11711172        // New best link1173        hashBestChain = hash;1174        pindexBest = pindexNew;1175        nBestHeight = pindexBest->nHeight;1176        nTransactionsUpdated++;1177        printf("AddToBlockIndex: new best=%s  height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);1178    }11791180    txdb.TxnCommit();1181    txdb.Close();11821183    if (pindexNew == pindexBest)1184    {1185        // Relay wallet transactions that haven't gotten in yet1186        RelayWalletTransactions();11871188        // Notify UI to display prev block's coinbase if it was ours1189        static uint256 hashPrevBestCoinBase;1190        CRITICAL_BLOCK(cs_mapWallet)1191            vWalletUpdated.push_back(hashPrevBestCoinBase);1192        hashPrevBestCoinBase = vtx[0].GetHash();1193    }11941195    MainFrameRepaint();1196    return true;1197}11981199120012011202bool CBlock::CheckBlock() const1203{1204    // These are checks that are independent of context1205    // that can be verified before saving an orphan block.12061207    // Size limits1208    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)1209        return error("CheckBlock() : size limits failed");12101211    // Check timestamp1212    if (nTime > GetAdjustedTime() + 2 * 60 * 60)1213        return error("CheckBlock() : block timestamp too far in the future");12141215    // First transaction must be coinbase, the rest must not be1216    if (vtx.empty() || !vtx[0].IsCoinBase())1217        return error("CheckBlock() : first tx is not coinbase");1218    for (int i = 1; i < vtx.size(); i++)1219        if (vtx[i].IsCoinBase())1220            return error("CheckBlock() : more than one coinbase");12211222    // Check transactions1223    foreach(const CTransaction& tx, vtx)1224        if (!tx.CheckTransaction())1225            return error("CheckBlock() : CheckTransaction failed");12261227    // Check proof of work matches claimed amount1228    if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1229        return error("CheckBlock() : nBits below minimum work");1230    if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1231        return error("CheckBlock() : hash doesn't match nBits");12321233    // Check merkleroot1234    if (hashMerkleRoot != BuildMerkleTree())1235        return error("CheckBlock() : hashMerkleRoot mismatch");12361237    return true;1238}12391240bool CBlock::AcceptBlock()1241{1242    // Check for duplicate1243    uint256 hash = GetHash();1244    if (mapBlockIndex.count(hash))1245        return error("AcceptBlock() : block already in mapBlockIndex");12461247    // Get prev block index1248    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1249    if (mi == mapBlockIndex.end())1250        return error("AcceptBlock() : prev block not found");1251    CBlockIndex* pindexPrev = (*mi).second;12521253    // Check timestamp against prev1254    if (nTime <= pindexPrev->GetMedianTimePast())1255        return error("AcceptBlock() : block's timestamp is too early");12561257    // Check that all transactions are finalized (starting around Mar 2010)1258    if (nBestHeight > 36000)1259        foreach(const CTransaction& tx, vtx)1260            if (!tx.IsFinal(nTime))1261                return error("AcceptBlock() : contains a non-final transaction");12621263    // Check proof of work1264    if (nBits != GetNextWorkRequired(pindexPrev))1265        return error("AcceptBlock() : incorrect proof of work");12661267    // Write block to history file1268    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))1269        return error("AcceptBlock() : out of disk space");1270    unsigned int nFile;1271    unsigned int nBlockPos;1272    if (!WriteToDisk(!fClient, nFile, nBlockPos))1273        return error("AcceptBlock() : WriteToDisk failed");1274    if (!AddToBlockIndex(nFile, nBlockPos))1275        return error("AcceptBlock() : AddToBlockIndex failed");12761277    if (hashBestChain == hash && nBestHeight > 28000)1278        RelayInventory(CInv(MSG_BLOCK, hash));12791280    // // Add atoms to user reviews for coins created1281    // vector<unsigned char> vchPubKey;1282    // if (ExtractPubKey(vtx[0].vout[0].scriptPubKey, false, vchPubKey))1283    // {1284    //     unsigned short nAtom = GetRand(USHRT_MAX - 100) + 100;1285    //     vector<unsigned short> vAtoms(1, nAtom);1286    //     AddAtomsAndPropagate(Hash(vchPubKey.begin(), vchPubKey.end()), vAtoms, true);1287    // }12881289    return true;1290}12911292bool ProcessBlock(CNode* pfrom, CBlock* pblock)1293{1294    // Check for duplicate1295    uint256 hash = pblock->GetHash();1296    if (mapBlockIndex.count(hash))1297        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());1298    if (mapOrphanBlocks.count(hash))1299        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());13001301    // Preliminary checks1302    if (!pblock->CheckBlock())1303    {1304        delete pblock;1305        return error("ProcessBlock() : CheckBlock FAILED");1306    }13071308    // If don't already have its previous block, shunt it off to holding area until we get it1309    if (!mapBlockIndex.count(pblock->hashPrevBlock))1310    {1311        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());1312        mapOrphanBlocks.insert(make_pair(hash, pblock));1313        mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));13141315        // Ask this guy to fill in what we're missing1316        if (pfrom)1317            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));1318        return true;1319    }13201321    // Store to disk1322    if (!pblock->AcceptBlock())1323    {1324        delete pblock;1325        return error("ProcessBlock() : AcceptBlock FAILED");1326    }1327    delete pblock;13281329    // Recursively process any orphan blocks that depended on this one1330    vector<uint256> vWorkQueue;1331    vWorkQueue.push_back(hash);1332    for (int i = 0; i < vWorkQueue.size(); i++)1333    {1334        uint256 hashPrev = vWorkQueue[i];1335        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1336             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1337             ++mi)1338        {1339            CBlock* pblockOrphan = (*mi).second;1340            if (pblockOrphan->AcceptBlock())1341                vWorkQueue.push_back(pblockOrphan->GetHash());1342            mapOrphanBlocks.erase(pblockOrphan->GetHash());1343            delete pblockOrphan;1344        }1345        mapOrphanBlocksByPrev.erase(hashPrev);1346    }13471348    printf("ProcessBlock: ACCEPTED\n");1349    return true;1350}135113521353135413551356135713581359template<typename Stream>1360bool ScanMessageStart(Stream& s)1361{1362    // Scan ahead to the next pchMessageStart, which should normally be immediately1363    // at the file pointer.  Leaves file pointer at end of pchMessageStart.1364    s.clear(0);1365    short prevmask = s.exceptions(0);1366    const char* p = BEGIN(pchMessageStart);1367    try1368    {1369        loop1370        {1371            char c;1372            s.read(&c, 1);1373            if (s.fail())1374            {1375                s.clear(0);1376                s.exceptions(prevmask);1377                return false;1378            }1379            if (*p != c)1380                p = BEGIN(pchMessageStart);1381            if (*p == c)1382            {1383                if (++p == END(pchMessageStart))1384                {1385                    s.clear(0);1386                    s.exceptions(prevmask);1387                    return true;1388                }1389            }1390        }1391    }1392    catch (...)1393    {1394        s.clear(0);1395        s.exceptions(prevmask);1396        return false;1397    }1398}13991400bool CheckDiskSpace(int64 nAdditionalBytes)1401{1402#ifdef __WXMSW__1403    uint64 nFreeBytesAvailable = 0;     // bytes available to caller1404    uint64 nTotalNumberOfBytes = 0;     // bytes on disk1405    uint64 nTotalNumberOfFreeBytes = 0; // free bytes on disk1406    if (!GetDiskFreeSpaceEx(GetDataDir().c_str(),1407            (PULARGE_INTEGER)&nFreeBytesAvailable,1408            (PULARGE_INTEGER)&nTotalNumberOfBytes,1409            (PULARGE_INTEGER)&nTotalNumberOfFreeBytes))1410    {1411        printf("ERROR: GetDiskFreeSpaceEx() failed\n");1412        return true;1413    }1414#else1415    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;1416#endif14171418    // Check for 15MB because database could create another 10MB log file at any time1419    if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)1420    {1421        fShutdown = true;1422        ThreadSafeMessageBox("Warning: Your disk space is low  ", "Bitcoin", wxOK | wxICON_EXCLAMATION);1423        CreateThread(Shutdown, NULL);1424        return false;1425    }1426    return true;1427}14281429FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1430{1431    if (nFile == -1)1432        return NULL;1433    FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);1434    if (!file)1435        return NULL;1436    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1437    {1438        if (fseek(file, nBlockPos, SEEK_SET) != 0)1439        {1440            fclose(file);1441            return NULL;1442        }1443    }1444    return file;1445}14461447static unsigned int nCurrentBlockFile = 1;14481449FILE* AppendBlockFile(unsigned int& nFileRet)1450{1451    nFileRet = 0;1452    loop1453    {1454        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1455        if (!file)1456            return NULL;1457        if (fseek(file, 0, SEEK_END) != 0)1458            return NULL;1459        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1460        if (ftell(file) < 0x7F000000 - MAX_SIZE)1461        {1462            nFileRet = nCurrentBlockFile;1463            return file;1464        }1465        fclose(file);1466        nCurrentBlockFile++;1467    }1468}14691470bool LoadBlockIndex(bool fAllowNew)1471{1472    //1473    // Load block index1474    //1475    CTxDB txdb("cr");1476    if (!txdb.LoadBlockIndex())1477        return false;1478    txdb.Close();14791480    //1481    // Init with genesis block1482    //1483    if (mapBlockIndex.empty())1484    {1485        if (!fAllowNew)1486            return false;148714881489        // Genesis Block:1490        // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f1491        // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b1492        // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D6954206568541493        // txNew.vout[0].nValue       = 50000000001494        // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG1495        // block.nVersion = 11496        // block.nTime    = 12310065051497        // block.nBits    = 0x1d00ffff1498        // block.nNonce   = 20832368931499        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1500        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1501        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1502        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1503        //   vMerkleTree: 4a5e1e15041505        // Genesis block1506        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1507        CTransaction txNew;1508        txNew.vin.resize(1);1509        txNew.vout.resize(1);1510        txNew.vin[0].scriptSig     = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));1511        txNew.vout[0].nValue       = 50 * COIN;1512        txNew.vout[0].scriptPubKey = CScript() << CBigNum("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704") << OP_CHECKSIG;1513        CBlock block;1514        block.vtx.push_back(txNew);1515        block.hashPrevBlock = 0;1516        block.hashMerkleRoot = block.BuildMerkleTree();1517        block.nVersion = 1;1518        block.nTime    = 1231006505;1519        block.nBits    = 0x1d00ffff;1520        block.nNonce   = 2083236893;15211522            //// debug print1523            printf("%s\n", block.GetHash().ToString().c_str());1524            printf("%s\n", block.hashMerkleRoot.ToString().c_str());1525            printf("%s\n", hashGenesisBlock.ToString().c_str());1526            txNew.vout[0].scriptPubKey.print();1527            block.print();1528            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));15291530        assert(block.GetHash() == hashGenesisBlock);15311532        // Start new block file1533        unsigned int nFile;1534        unsigned int nBlockPos;1535        if (!block.WriteToDisk(!fClient, nFile, nBlockPos))1536            return error("LoadBlockIndex() : writing genesis block to disk failed");1537        if (!block.AddToBlockIndex(nFile, nBlockPos))1538            return error("LoadBlockIndex() : genesis block not accepted");1539    }15401541    return true;1542}1543154415451546void PrintBlockTree()1547{1548    // precompute tree structure1549    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1550    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1551    {1552        CBlockIndex* pindex = (*mi).second;1553        mapNext[pindex->pprev].push_back(pindex);1554        // test1555        //while (rand() % 3 == 0)1556        //    mapNext[pindex->pprev].push_back(pindex);1557    }15581559    vector<pair<int, CBlockIndex*> > vStack;1560    vStack.push_back(make_pair(0, pindexGenesisBlock));15611562    int nPrevCol = 0;1563    while (!vStack.empty())1564    {1565        int nCol = vStack.back().first;1566        CBlockIndex* pindex = vStack.back().second;1567        vStack.pop_back();15681569        // print split or gap1570        if (nCol > nPrevCol)1571        {1572            for (int i = 0; i < nCol-1; i++)1573                printf("| ");1574            printf("|\\\n");1575        }1576        else if (nCol < nPrevCol)1577        {1578            for (int i = 0; i < nCol; i++)1579                printf("| ");1580            printf("|\n");1581        }1582        nPrevCol = nCol;15831584        // print columns1585        for (int i = 0; i < nCol; i++)1586            printf("| ");15871588        // print item1589        CBlock block;1590        block.ReadFromDisk(pindex);1591        printf("%d (%u,%u) %s  %s  tx %d",1592            pindex->nHeight,1593            pindex->nFile,1594            pindex->nBlockPos,1595            block.GetHash().ToString().substr(0,16).c_str(),1596            DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),1597            block.vtx.size());15981599        CRITICAL_BLOCK(cs_mapWallet)1600        {1601            if (mapWallet.count(block.vtx[0].GetHash()))1602            {1603                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1604                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1605            }1606        }1607        printf("\n");160816091610        // put the main timechain first1611        vector<CBlockIndex*>& vNext = mapNext[pindex];1612        for (int i = 0; i < vNext.size(); i++)1613        {1614            if (vNext[i]->pnext)1615            {1616                swap(vNext[0], vNext[i]);1617                break;1618            }1619        }16201621        // iterate children1622        for (int i = 0; i < vNext.size(); i++)1623            vStack.push_back(make_pair(nCol+i, vNext[i]));1624    }1625}16261627162816291630163116321633163416351636//////////////////////////////////////////////////////////////////////////////1637//1638// Messages1639//164016411642bool AlreadyHave(CTxDB& txdb, const CInv& inv)1643{1644    switch (inv.type)1645    {1646    case MSG_TX:        return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);1647    case MSG_BLOCK:     return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);1648    case MSG_REVIEW:    return true;1649    case MSG_PRODUCT:   return mapProducts.count(inv.hash);1650    }1651    // Don't know what it is, just say we already got one1652    return true;1653}16541655165616571658165916601661bool ProcessMessages(CNode* pfrom)1662{1663    CDataStream& vRecv = pfrom->vRecv;1664    if (vRecv.empty())1665        return true;1666    //if (fDebug)1667    //    printf("ProcessMessages(%d bytes)\n", vRecv.size());16681669    //1670    // Message format1671    //  (4) message start1672    //  (12) command1673    //  (4) size1674    //  (x) data1675    //16761677    loop1678    {1679        // Scan for message start1680        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1681        if (vRecv.end() - pstart < sizeof(CMessageHeader))1682        {1683            if (vRecv.size() > sizeof(CMessageHeader))1684            {1685                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1686                vRecv.erase(vRecv.begin(), vRecv.end() - sizeof(CMessageHeader));1687            }1688            break;1689        }1690        if (pstart - vRecv.begin() > 0)1691            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1692        vRecv.erase(vRecv.begin(), pstart);16931694        // Read header1695        CMessageHeader hdr;1696        vRecv >> hdr;1697        if (!hdr.IsValid())1698        {1699            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1700            continue;1701        }1702        string strCommand = hdr.GetCommand();17031704        // Message size1705        unsigned int nMessageSize = hdr.nMessageSize;1706        if (nMessageSize > vRecv.size())1707        {1708            // Rewind and wait for rest of message1709            ///// need a mechanism to give up waiting for overlong message size error1710            //if (fDebug)1711            //    printf("message-break\n");1712            vRecv.insert(vRecv.begin(), BEGIN(hdr), END(hdr));1713            Sleep(100);1714            break;1715        }17161717        // Copy message to its own buffer1718        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1719        vRecv.ignore(nMessageSize);17201721        // Process message1722        bool fRet = false;1723        try1724        {1725            CRITICAL_BLOCK(cs_main)1726                fRet = ProcessMessage(pfrom, strCommand, vMsg);1727            if (fShutdown)1728                return true;1729        }1730        catch (std::ios_base::failure& e)1731        {1732            if (strstr(e.what(), "CDataStream::read() : end of data"))1733            {1734                // Allow exceptions from underlength message on vRecv1735                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());1736            }1737            else1738            {1739                PrintException(&e, "ProcessMessage()");1740            }1741        }1742        catch (std::exception& e) {1743            PrintException(&e, "ProcessMessage()");1744        } catch (...) {1745            PrintException(NULL, "ProcessMessage()");1746        }17471748        if (!fRet)1749            printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);1750    }17511752    vRecv.Compact();1753    return true;1754}17551756175717581759bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1760{1761    static map<unsigned int, vector<unsigned char> > mapReuseKey;1762    RandAddSeedPerfmon();1763    if (fDebug)1764        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());1765    printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());1766    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)1767    {1768        printf("dropmessagestest DROPPING RECV MESSAGE\n");1769        return true;1770    }177117721773177417751776    if (strCommand == "version")1777    {1778        // Each connection can only send one version message1779        if (pfrom->nVersion != 0)1780            return false;17811782        int64 nTime;1783        CAddress addrMe;1784        CAddress addrFrom;1785        uint64 nNonce = 1;1786        string strSubVer;1787        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;1788        if (pfrom->nVersion >= 106 && !vRecv.empty())1789            vRecv >> addrFrom >> nNonce;1790        if (pfrom->nVersion >= 106 && !vRecv.empty())1791            vRecv >> strSubVer;1792        if (pfrom->nVersion == 0)1793            return false;17941795        // Disconnect if we connected to ourself1796        if (nNonce == nLocalHostNonce && nNonce > 1)1797        {1798            pfrom->fDisconnect = true;1799            return true;1800        }18011802        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));1803        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));18041805        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);1806        if (pfrom->fClient)1807        {1808            pfrom->vSend.nType |= SER_BLOCKHEADERONLY;1809            pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;1810        }18111812        AddTimeData(pfrom->addr.ip, nTime);18131814        // Ask the first connected node for block updates1815        static bool fAskedForBlocks;1816        if (!fAskedForBlocks && !pfrom->fClient)1817        {1818            fAskedForBlocks = true;1819            pfrom->PushGetBlocks(pindexBest, uint256(0));1820        }18211822        pfrom->fSuccessfullyConnected = true;18231824        printf("version message: version %d\n", pfrom->nVersion);1825    }182618271828    else if (pfrom->nVersion == 0)1829    {1830        // Must have a version message before anything else1831        return false;1832    }183318341835    else if (strCommand == "addr")1836    {1837        vector<CAddress> vAddr;1838        vRecv >> vAddr;1839        if (vAddr.size() > 50000) // lower this to 1000 later1840            return error("message addr size() = %d", vAddr.size());18411842        // Store the new addresses1843        CAddrDB addrdb;1844        foreach(CAddress& addr, vAddr)1845        {1846            if (fShutdown)1847                return true;1848            addr.nTime = GetAdjustedTime() - 2 * 60 * 60;1849            if (pfrom->fGetAddr)1850                addr.nTime -= 5 * 24 * 60 * 60;1851            AddAddress(addrdb, addr, false);1852            pfrom->AddAddressKnown(addr);1853            if (!pfrom->fGetAddr && addr.IsRoutable())1854            {1855                // Put on lists to send to other nodes1856                CRITICAL_BLOCK(cs_vNodes)1857                    foreach(CNode* pnode, vNodes)1858                        pnode->PushAddress(addr);1859            }1860        }1861        pfrom->fGetAddr = false;1862    }186318641865    else if (strCommand == "inv")1866    {1867        vector<CInv> vInv;1868        vRecv >> vInv;1869        if (vInv.size() > 50000)1870            return error("message inv size() = %d", vInv.size());18711872        CTxDB txdb("r");1873        foreach(const CInv& inv, vInv)1874        {1875            if (fShutdown)1876                return true;1877            pfrom->AddInventoryKnown(inv);18781879            bool fAlreadyHave = AlreadyHave(txdb, inv);1880            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");18811882            if (!fAlreadyHave)1883                pfrom->AskFor(inv);1884            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))1885                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));18861887            // Track requests for our stuff1888            CRITICAL_BLOCK(cs_mapRequestCount)1889            {1890                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);1891                if (mi != mapRequestCount.end())1892                    (*mi).second++;1893            }1894        }1895    }189618971898    else if (strCommand == "getdata")1899    {1900        vector<CInv> vInv;1901        vRecv >> vInv;1902        if (vInv.size() > 50000)1903            return error("message getdata size() = %d", vInv.size());19041905        foreach(const CInv& inv, vInv)1906        {1907            if (fShutdown)1908                return true;1909            printf("received getdata for: %s\n", inv.ToString().c_str());19101911            if (inv.type == MSG_BLOCK)1912            {1913                // Send block from disk1914                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);1915                if (mi != mapBlockIndex.end())1916                {1917                    //// could optimize this to send header straight from blockindex for client1918                    CBlock block;1919                    block.ReadFromDisk((*mi).second, !pfrom->fClient);1920                    pfrom->PushMessage("block", block);19211922                    // Trigger them to send a getblocks request for the next batch of inventory1923                    if (inv.hash == pfrom->hashContinue)1924                    {1925                        // Bypass PushInventory, this must send even if redundant,1926                        // and we want it right after the last block so they don't1927                        // wait for other stuff first.1928                        vector<CInv> vInv;1929                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));1930                        pfrom->PushMessage("inv", vInv);1931                        pfrom->hashContinue = 0;1932                    }1933                }1934            }1935            else if (inv.IsKnownType())1936            {1937                // Send stream from relay memory1938                CRITICAL_BLOCK(cs_mapRelay)1939                {1940                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);1941                    if (mi != mapRelay.end())1942                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);1943                }1944            }19451946            // Track requests for our stuff1947            CRITICAL_BLOCK(cs_mapRequestCount)1948            {1949                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);1950                if (mi != mapRequestCount.end())1951                    (*mi).second++;1952            }1953        }1954    }195519561957    else if (strCommand == "getblocks")1958    {1959        CBlockLocator locator;1960        uint256 hashStop;1961        vRecv >> locator >> hashStop;19621963        // Find the first block the caller has in the main chain1964        CBlockIndex* pindex = locator.GetBlockIndex();19651966        // Send the rest of the chain1967        if (pindex)1968            pindex = pindex->pnext;1969        int nLimit = 500 + locator.GetDistanceBack();1970        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);1971        for (; pindex; pindex = pindex->pnext)1972        {1973            if (pindex->GetBlockHash() == hashStop)1974            {1975                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());1976                break;1977            }1978            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));1979            if (--nLimit <= 0)1980            {1981                // When this block is requested, we'll send an inv that'll make them1982                // getblocks the next batch of inventory.1983                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());1984                pfrom->hashContinue = pindex->GetBlockHash();1985                break;1986            }1987        }1988    }198919901991    else if (strCommand == "tx")1992    {1993        vector<uint256> vWorkQueue;1994        CDataStream vMsg(vRecv);1995        CTransaction tx;1996        vRecv >> tx;19971998        CInv inv(MSG_TX, tx.GetHash());1999        pfrom->AddInventoryKnown(inv);20002001        bool fMissingInputs = false;2002        if (tx.AcceptTransaction(true, &fMissingInputs))2003        {2004            AddToWalletIfMine(tx, NULL);2005            RelayMessage(inv, vMsg);2006            mapAlreadyAskedFor.erase(inv);2007            vWorkQueue.push_back(inv.hash);20082009            // Recursively process any orphan transactions that depended on this one2010            for (int i = 0; i < vWorkQueue.size(); i++)2011            {2012                uint256 hashPrev = vWorkQueue[i];2013                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);2014                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);2015                     ++mi)2016                {2017                    const CDataStream& vMsg = *((*mi).second);2018                    CTransaction tx;2019                    CDataStream(vMsg) >> tx;2020                    CInv inv(MSG_TX, tx.GetHash());20212022                    if (tx.AcceptTransaction(true))2023                    {2024                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2025                        AddToWalletIfMine(tx, NULL);2026                        RelayMessage(inv, vMsg);2027                        mapAlreadyAskedFor.erase(inv);2028                        vWorkQueue.push_back(inv.hash);2029                    }2030                }2031            }20322033            foreach(uint256 hash, vWorkQueue)2034                EraseOrphanTx(hash);2035        }2036        else if (fMissingInputs)2037        {2038            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2039            AddOrphanTx(vMsg);2040        }2041    }204220432044    else if (strCommand == "review")2045    {2046        CDataStream vMsg(vRecv);2047        CReview review;2048        vRecv >> review;20492050        CInv inv(MSG_REVIEW, review.GetHash());2051        pfrom->AddInventoryKnown(inv);20522053        if (review.AcceptReview())2054        {2055            // Relay the original message as-is in case it's a higher version than we know how to parse2056            RelayMessage(inv, vMsg);2057            mapAlreadyAskedFor.erase(inv);2058        }2059    }206020612062    else if (strCommand == "block")2063    {2064        auto_ptr<CBlock> pblock(new CBlock);2065        vRecv >> *pblock;20662067        //// debug print2068        // printf("received block:\n");2069        // pblock->print();2070        printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());20712072        CInv inv(MSG_BLOCK, pblock->GetHash());2073        pfrom->AddInventoryKnown(inv);20742075        if (ProcessBlock(pfrom, pblock.release()))2076            mapAlreadyAskedFor.erase(inv);2077    }207820792080    else if (strCommand == "getaddr")2081    {2082        pfrom->vAddrToSend.clear();2083        int64 nSince = GetAdjustedTime() - 5 * 24 * 60 * 60; // in the last 5 days2084        CRITICAL_BLOCK(cs_mapAddresses)2085        {2086            unsigned int nSize = mapAddresses.size();2087            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)2088            {2089                if (fShutdown)2090                    return true;2091                const CAddress& addr = item.second;2092                if (addr.nTime > nSince)2093                    pfrom->PushAddress(addr);2094            }2095        }2096    }209720982099    else if (strCommand == "checkorder")2100    {2101        uint256 hashReply;2102        CWalletTx order;2103        vRecv >> hashReply >> order;21042105        /// we have a chance to check the order here21062107        // Keep giving the same key to the same ip until they use it2108        if (!mapReuseKey.count(pfrom->addr.ip))2109            mapReuseKey[pfrom->addr.ip] = GenerateNewKey();21102111        // Send back approval of order and pubkey to use2112        CScript scriptPubKey;2113        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;2114        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);2115    }211621172118    else if (strCommand == "submitorder")2119    {2120        uint256 hashReply;2121        CWalletTx wtxNew;2122        vRecv >> hashReply >> wtxNew;21232124        // Broadcast2125        if (!wtxNew.AcceptWalletTransaction())2126        {2127            pfrom->PushMessage("reply", hashReply, (int)1);2128            return error("submitorder AcceptWalletTransaction() failed, returning error 1");2129        }2130        wtxNew.fTimeReceivedIsTxTime = true;2131        AddToWallet(wtxNew);2132        wtxNew.RelayWalletTransaction();2133        mapReuseKey.erase(pfrom->addr.ip);21342135        // Send back confirmation2136        pfrom->PushMessage("reply", hashReply, (int)0);2137    }213821392140    else if (strCommand == "reply")2141    {2142        uint256 hashReply;2143        vRecv >> hashReply;21442145        CRequestTracker tracker;2146        CRITICAL_BLOCK(pfrom->cs_mapRequests)2147        {2148            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2149            if (mi != pfrom->mapRequests.end())2150            {2151                tracker = (*mi).second;2152                pfrom->mapRequests.erase(mi);2153            }2154        }2155        if (!tracker.IsNull())2156            tracker.fn(tracker.param1, vRecv);2157    }215821592160    else if (strCommand == "ping")2161    {2162    }216321642165    else2166    {2167        // Ignore unknown commands for extensibility2168    }216921702171    // Update the last seen time for this node's address2172    if (pfrom->fNetworkNode)2173        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")2174            AddressCurrentlyConnected(pfrom->addr);217521762177    return true;2178}2179218021812182218321842185218621872188bool SendMessages(CNode* pto)2189{2190    CRITICAL_BLOCK(cs_main)2191    {2192        // Don't send anything until we get their version message2193        if (pto->nVersion == 0)2194            return true;21952196        // Keep-alive ping2197        if (pto->nLastSend && GetTime() - pto->nLastSend > 12 * 60 && pto->vSend.empty())2198            pto->PushMessage("ping");21992200        // Address refresh broadcast2201        static int64 nLastRebroadcast;2202        if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours2203        {2204            nLastRebroadcast = GetTime();2205            CRITICAL_BLOCK(cs_vNodes)2206            {2207                foreach(CNode* pnode, vNodes)2208                {2209                    // Periodically clear setAddrKnown to allow refresh broadcasts2210                    pnode->setAddrKnown.clear();22112212                    // Rebroadcast our address2213                    if (addrLocalHost.IsRoutable() && !fUseProxy)2214                        pnode->PushAddress(addrLocalHost);2215                }2216            }2217        }221822192220        //2221        // Message: addr2222        //2223        vector<CAddress> vAddrToSend;2224        vAddrToSend.reserve(pto->vAddrToSend.size());2225        foreach(const CAddress& addr, pto->vAddrToSend)2226        {2227            // returns true if wasn't already contained in the set2228            if (pto->setAddrKnown.insert(addr).second)2229            {2230                vAddrToSend.push_back(addr);2231                if (vAddrToSend.size() >= 1000)2232                {2233                    pto->PushMessage("addr", vAddrToSend);2234                    vAddrToSend.clear();2235                }2236            }2237        }2238        pto->vAddrToSend.clear();2239        if (!vAddrToSend.empty())2240            pto->PushMessage("addr", vAddrToSend);224122422243        //2244        // Message: inventory2245        //2246        vector<CInv> vInventoryToSend;2247        CRITICAL_BLOCK(pto->cs_inventory)2248        {2249            vInventoryToSend.reserve(pto->vInventoryToSend.size());2250            foreach(const CInv& inv, pto->vInventoryToSend)2251            {2252                // returns true if wasn't already contained in the set2253                if (pto->setInventoryKnown.insert(inv).second)2254                {2255                    vInventoryToSend.push_back(inv);2256                    if (vInventoryToSend.size() >= 1000)2257                    {2258                        pto->PushMessage("inv", vInventoryToSend);2259                        vInventoryToSend.clear();2260                    }2261                }2262            }2263            pto->vInventoryToSend.clear();2264        }2265        if (!vInventoryToSend.empty())2266            pto->PushMessage("inv", vInventoryToSend);226722682269        //2270        // Message: getdata2271        //2272        vector<CInv> vAskFor;2273        int64 nNow = GetTime() * 1000000;2274        CTxDB txdb("r");2275        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2276        {2277            const CInv& inv = (*pto->mapAskFor.begin()).second;2278            if (!AlreadyHave(txdb, inv))2279            {2280                printf("sending getdata: %s\n", inv.ToString().c_str());2281                vAskFor.push_back(inv);2282                if (vAskFor.size() >= 1000)2283                {2284                    pto->PushMessage("getdata", vAskFor);2285                    vAskFor.clear();2286                }2287            }2288            pto->mapAskFor.erase(pto->mapAskFor.begin());2289        }2290        if (!vAskFor.empty())2291            pto->PushMessage("getdata", vAskFor);22922293    }2294    return true;2295}229622972298229923002301230223032304230523062307230823092310//////////////////////////////////////////////////////////////////////////////2311//2312// BitcoinMiner2313//23142315void GenerateBitcoins(bool fGenerate)2316{2317    if (fGenerateBitcoins != fGenerate)2318    {2319        fGenerateBitcoins = fGenerate;2320        CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);2321        MainFrameRepaint();2322    }2323    if (fGenerateBitcoins)2324    {2325        int nProcessors = wxThread::GetCPUCount();2326        printf("%d processors\n", nProcessors);2327        if (nProcessors < 1)2328            nProcessors = 1;2329        if (fLimitProcessors && nProcessors > nLimitProcessors)2330            nProcessors = nLimitProcessors;2331        int nAddThreads = nProcessors - vnThreadsRunning[3];2332        printf("Starting %d BitcoinMiner threads\n", nAddThreads);2333        for (int i = 0; i < nAddThreads; i++)2334            if (!CreateThread(ThreadBitcoinMiner, NULL))2335                printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");2336    }2337}23382339void ThreadBitcoinMiner(void* parg)2340{2341    try2342    {2343        vnThreadsRunning[3]++;2344        BitcoinMiner();2345        vnThreadsRunning[3]--;2346    }2347    catch (std::exception& e) {2348        vnThreadsRunning[3]--;2349        PrintException(&e, "ThreadBitcoinMiner()");2350    } catch (...) {2351        vnThreadsRunning[3]--;2352        PrintException(NULL, "ThreadBitcoinMiner()");2353    }23542355    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);2356}23572358int FormatHashBlocks(void* pbuffer, unsigned int len)2359{2360    unsigned char* pdata = (unsigned char*)pbuffer;2361    unsigned int blocks = 1 + ((len + 8) / 64);2362    unsigned char* pend = pdata + 64 * blocks;2363    memset(pdata + len, 0, 64 * blocks - len);2364    pdata[len] = 0x80;2365    unsigned int bits = len * 8;2366    pend[-1] = (bits >> 0) & 0xff;2367    pend[-2] = (bits >> 8) & 0xff;2368    pend[-3] = (bits >> 16) & 0xff;2369    pend[-4] = (bits >> 24) & 0xff;2370    return blocks;2371}23722373using CryptoPP::ByteReverse;2374static int detectlittleendian = 1;23752376void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)2377{2378    unsigned int* pinput = (unsigned int*)pin;2379    unsigned int* pstate = (unsigned int*)pout;23802381    CryptoPP::SHA256::InitState(pstate);23822383    if (*(char*)&detectlittleendian != 0)2384    {2385        for (int n = 0; n < nBlocks; n++)2386        {2387            unsigned int pbuf[16];2388            for (int i = 0; i < 16; i++)2389                pbuf[i] = ByteReverse(pinput[n * 16 + i]);2390            CryptoPP::SHA256::Transform(pstate, pbuf);2391        }2392        for (int i = 0; i < 8; i++)2393            pstate[i] = ByteReverse(pstate[i]);2394    }2395    else2396    {2397        for (int n = 0; n < nBlocks; n++)2398            CryptoPP::SHA256::Transform(pstate, pinput + n * 16);2399    }2400}240124022403void BitcoinMiner()2404{2405    printf("BitcoinMiner started\n");24062407    CKey key;2408    key.MakeNewKey();2409    CBigNum bnExtraNonce = 0;2410    while (fGenerateBitcoins)2411    {2412        SetThreadPriority(THREAD_PRIORITY_LOWEST);2413        Sleep(50);2414        if (fShutdown)2415            return;2416        while (vNodes.empty())2417        {2418            Sleep(1000);2419            if (fShutdown)2420                return;2421            if (!fGenerateBitcoins)2422                return;2423        }24242425        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;2426        CBlockIndex* pindexPrev = pindexBest;2427        unsigned int nBits = GetNextWorkRequired(pindexPrev);242824292430        //2431        // Create coinbase tx2432        //2433        CTransaction txNew;2434        txNew.vin.resize(1);2435        txNew.vin[0].prevout.SetNull();2436        txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;2437        txNew.vout.resize(1);2438        txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;243924402441        //2442        // Create new block2443        //2444        auto_ptr<CBlock> pblock(new CBlock());2445        if (!pblock.get())2446            return;24472448        // Add our coinbase tx as first transaction2449        pblock->vtx.push_back(txNew);24502451        // Collect the latest transactions into the block2452        int64 nFees = 0;2453        CRITICAL_BLOCK(cs_main)2454        CRITICAL_BLOCK(cs_mapTransactions)2455        {2456            CTxDB txdb("r");2457            map<uint256, CTxIndex> mapTestPool;2458            vector<char> vfAlreadyAdded(mapTransactions.size());2459            bool fFoundSomething = true;2460            unsigned int nBlockSize = 0;2461            while (fFoundSomething && nBlockSize < MAX_SIZE/2)2462            {2463                fFoundSomething = false;2464                unsigned int n = 0;2465                for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)2466                {2467                    if (vfAlreadyAdded[n])2468                        continue;2469                    CTransaction& tx = (*mi).second;2470                    if (tx.IsCoinBase() || !tx.IsFinal())2471                        continue;24722473                    // Transaction fee based on block size2474                    int64 nMinFee = tx.GetMinFee(nBlockSize);24752476                    map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);2477                    if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))2478                        continue;2479                    swap(mapTestPool, mapTestPoolTmp);24802481                    pblock->vtx.push_back(tx);2482                    nBlockSize += ::GetSerializeSize(tx, SER_NETWORK);2483                    vfAlreadyAdded[n] = true;2484                    fFoundSomething = true;2485                }2486            }2487        }2488        pblock->nBits = nBits;2489        pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);2490        printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());249124922493        //2494        // Prebuild hash buffer2495        //2496        struct unnamed12497        {2498            struct unnamed22499            {2500                int nVersion;2501                uint256 hashPrevBlock;2502                uint256 hashMerkleRoot;2503                unsigned int nTime;2504                unsigned int nBits;2505                unsigned int nNonce;2506            }2507            block;2508            unsigned char pchPadding0[64];2509            uint256 hash1;2510            unsigned char pchPadding1[64];2511        }2512        tmp;25132514        tmp.block.nVersion       = pblock->nVersion;2515        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);2516        tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();2517        tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());2518        tmp.block.nBits          = pblock->nBits          = nBits;2519        tmp.block.nNonce         = pblock->nNonce         = 1;25202521        unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));2522        unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));252325242525        //2526        // Search2527        //2528        int64 nStart = GetTime();2529        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();2530        uint256 hash;2531        loop2532        {2533            BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);2534            BlockSHA256(&tmp.hash1, nBlocks1, &hash);25352536            if (hash <= hashTarget)2537            {2538                pblock->nNonce = tmp.block.nNonce;2539                assert(hash == pblock->GetHash());25402541                    //// debug print2542                    printf("BitcoinMiner:\n");2543                    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());2544                    pblock->print();25452546                SetThreadPriority(THREAD_PRIORITY_NORMAL);2547                CRITICAL_BLOCK(cs_main)2548                {2549                    if (pindexPrev == pindexBest)2550                    {2551                        // Save key2552                        if (!AddKey(key))2553                            return;2554                        key.MakeNewKey();25552556                        // Track how many getdata requests this block gets2557                        CRITICAL_BLOCK(cs_mapRequestCount)2558                            mapRequestCount[pblock->GetHash()] = 0;25592560                        // Process this block the same as if we had received it from another node2561                        if (!ProcessBlock(NULL, pblock.release()))2562                            printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");2563                    }2564                }2565                SetThreadPriority(THREAD_PRIORITY_LOWEST);25662567                Sleep(500);2568                break;2569            }25702571            // Update nTime every few seconds2572            if ((++tmp.block.nNonce & 0xffff) == 0)2573            {2574                if (fShutdown)2575                    return;2576                if (!fGenerateBitcoins)2577                    return;2578                if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)2579                    return;2580                if (vNodes.empty())2581                    break;2582                if (tmp.block.nNonce == 0)2583                    break;2584                if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)2585                    break;2586                if (pindexPrev != pindexBest)2587                {2588                    // Pause generating during initial download2589                    if (GetTime() - nStart < 20)2590                    {2591                        CBlockIndex* pindexTmp;2592                        do2593                        {2594                            pindexTmp = pindexBest;2595                            Sleep(10000);2596                        }2597                        while (pindexTmp != pindexBest);2598                    }2599                    break;2600                }2601                tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());2602            }2603        }2604    }2605}2606260726082609261026112612261326142615261626172618261926202621262226232624//////////////////////////////////////////////////////////////////////////////2625//2626// Actions2627//262826292630int64 GetBalance()2631{2632    int64 nStart = GetTimeMillis();26332634    int64 nTotal = 0;2635    CRITICAL_BLOCK(cs_mapWallet)2636    {2637        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2638        {2639            CWalletTx* pcoin = &(*it).second;2640            if (!pcoin->IsFinal() || pcoin->fSpent)2641                continue;2642            nTotal += pcoin->GetCredit(true);2643        }2644    }26452646    //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);2647    return nTotal;2648}2649265026512652bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)2653{2654    setCoinsRet.clear();26552656    // List of values less than target2657    int64 nLowestLarger = INT64_MAX;2658    CWalletTx* pcoinLowestLarger = NULL;2659    vector<pair<int64, CWalletTx*> > vValue;2660    int64 nTotalLower = 0;26612662    CRITICAL_BLOCK(cs_mapWallet)2663    {2664        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2665        {2666            CWalletTx* pcoin = &(*it).second;2667            if (!pcoin->IsFinal() || pcoin->fSpent)2668                continue;2669            int64 n = pcoin->GetCredit();2670            if (n <= 0)2671                continue;2672            if (n < nTargetValue)2673            {2674                vValue.push_back(make_pair(n, pcoin));2675                nTotalLower += n;2676            }2677            else if (n == nTargetValue)2678            {2679                setCoinsRet.insert(pcoin);2680                return true;2681            }2682            else if (n < nLowestLarger)2683            {2684                nLowestLarger = n;2685                pcoinLowestLarger = pcoin;2686            }2687        }2688    }26892690    if (nTotalLower < nTargetValue)2691    {2692        if (pcoinLowestLarger == NULL)2693            return false;2694        setCoinsRet.insert(pcoinLowestLarger);2695        return true;2696    }26972698    // Solve subset sum by stochastic approximation2699    sort(vValue.rbegin(), vValue.rend());2700    vector<char> vfIncluded;2701    vector<char> vfBest(vValue.size(), true);2702    int64 nBest = nTotalLower;27032704    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)2705    {2706        vfIncluded.assign(vValue.size(), false);2707        int64 nTotal = 0;2708        bool fReachedTarget = false;2709        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)2710        {2711            for (int i = 0; i < vValue.size(); i++)2712            {2713                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])2714                {2715                    nTotal += vValue[i].first;2716                    vfIncluded[i] = true;2717                    if (nTotal >= nTargetValue)2718                    {2719                        fReachedTarget = true;2720                        if (nTotal < nBest)2721                        {2722                            nBest = nTotal;2723                            vfBest = vfIncluded;2724                        }2725                        nTotal -= vValue[i].first;2726                        vfIncluded[i] = false;2727                    }2728                }2729            }2730        }2731    }27322733    // If the next larger is still closer, return it2734    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)2735        setCoinsRet.insert(pcoinLowestLarger);2736    else2737    {2738        for (int i = 0; i < vValue.size(); i++)2739            if (vfBest[i])2740                setCoinsRet.insert(vValue[i].second);27412742        //// debug print2743        printf("SelectCoins() best subset: ");2744        for (int i = 0; i < vValue.size(); i++)2745            if (vfBest[i])2746                printf("%s ", FormatMoney(vValue[i].first).c_str());2747        printf("total %s\n", FormatMoney(nBest).c_str());2748    }27492750    return true;2751}27522753275427552756bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)2757{2758    nFeeRequiredRet = 0;2759    CRITICAL_BLOCK(cs_main)2760    {2761        // txdb must be opened before the mapWallet lock2762        CTxDB txdb("r");2763        CRITICAL_BLOCK(cs_mapWallet)2764        {2765            int64 nFee = nTransactionFee;2766            loop2767            {2768                wtxNew.vin.clear();2769                wtxNew.vout.clear();2770                if (nValue < 0)2771                    return false;2772                int64 nValueOut = nValue;2773                int64 nTotalValue = nValue + nFee;27742775                // Choose coins to use2776                set<CWalletTx*> setCoins;2777                if (!SelectCoins(nTotalValue, setCoins))2778                    return false;2779                int64 nValueIn = 0;2780                foreach(CWalletTx* pcoin, setCoins)2781                    nValueIn += pcoin->GetCredit();27822783                // Fill a vout to the payee2784                bool fChangeFirst = GetRand(2);2785                if (!fChangeFirst)2786                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));27872788                // Fill a vout back to self with any change2789                if (nValueIn > nTotalValue)2790                {2791                    // New private key2792                    if (keyRet.IsNull())2793                        keyRet.MakeNewKey();27942795                    // Fill a vout to ourself2796                    CScript scriptPubKey;2797                    scriptPubKey << keyRet.GetPubKey() << OP_CHECKSIG;2798                    wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptPubKey));2799                }28002801                // Fill a vout to the payee2802                if (fChangeFirst)2803                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));28042805                // Fill vin2806                foreach(CWalletTx* pcoin, setCoins)2807                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2808                        if (pcoin->vout[nOut].IsMine())2809                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));28102811                // Sign2812                int nIn = 0;2813                foreach(CWalletTx* pcoin, setCoins)2814                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2815                        if (pcoin->vout[nOut].IsMine())2816                            SignSignature(*pcoin, wtxNew, nIn++);28172818                // Check that enough fee is included2819                if (nFee < wtxNew.GetMinFee())2820                {2821                    nFee = nFeeRequiredRet = wtxNew.GetMinFee();2822                    continue;2823                }28242825                // Fill vtxPrev by copying from previous transactions vtxPrev2826                wtxNew.AddSupportingTransactions(txdb);2827                wtxNew.fTimeReceivedIsTxTime = true;28282829                break;2830            }2831        }2832    }2833    return true;2834}28352836// Call after CreateTransaction unless you want to abort2837bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key)2838{2839    CRITICAL_BLOCK(cs_main)2840    CRITICAL_BLOCK(cs_mapWallet)2841    {2842        //// todo: eventually should make this transactional, never want to add a2843        ////  transaction without marking spent transactions, although the risk of2844        ////  interruption during this step is remote.28452846        // This is only to keep the database open to defeat the auto-flush for the2847        // duration of this scope.  This is the only place where this optimization2848        // maybe makes sense; please don't do it anywhere else.2849        CWalletDB walletdb("r");28502851        // Add the change's private key to wallet2852        if (!key.IsNull() && !AddKey(key))2853            throw runtime_error("CommitTransactionSpent() : AddKey failed\n");28542855        // Add tx to wallet, because if it has change it's also ours,2856        // otherwise just for transaction history.2857        AddToWallet(wtxNew);28582859        // Mark old coins as spent2860        set<CWalletTx*> setCoins;2861        foreach(const CTxIn& txin, wtxNew.vin)2862            setCoins.insert(&mapWallet[txin.prevout.hash]);2863        foreach(CWalletTx* pcoin, setCoins)2864        {2865            pcoin->fSpent = true;2866            pcoin->WriteToDisk();2867            vWalletUpdated.push_back(pcoin->GetHash());2868        }2869    }2870    MainFrameRepaint();2871    return true;2872}28732874287528762877bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)2878{2879    CRITICAL_BLOCK(cs_main)2880    {2881        CKey key;2882        int64 nFeeRequired;2883        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))2884        {2885            string strError;2886            if (nValue + nFeeRequired > GetBalance())2887                strError = strprintf("Error: This is an oversized transaction that requires a transaction fee of %s  ", FormatMoney(nFeeRequired).c_str());2888            else2889                strError = "Error: Transaction creation failed  ";2890            wxMessageBox(strError, "Sending...");2891            return error("SendMoney() : %s", strError.c_str());2892        }2893        if (!CommitTransactionSpent(wtxNew, key))2894        {2895            wxMessageBox("Error finalizing transaction  ", "Sending...");2896            return error("SendMoney() : Error finalizing transaction");2897        }28982899        // Track how many getdata requests our transaction gets2900        CRITICAL_BLOCK(cs_mapRequestCount)2901            mapRequestCount[wtxNew.GetHash()] = 0;29022903        printf("SendMoney: %s\n", wtxNew.GetHash().ToString().substr(0,6).c_str());29042905        // Broadcast2906        if (!wtxNew.AcceptTransaction())2907        {2908            // This must not fail. The transaction has already been signed and recorded.2909            throw runtime_error("SendMoney() : wtxNew.AcceptTransaction() failed\n");2910            wxMessageBox("Error: Transaction not valid  ", "Sending...");2911            return error("SendMoney() : Error: Transaction not valid");2912        }2913        wtxNew.RelayWalletTransaction();2914    }2915    MainFrameRepaint();2916    return true;2917}

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