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

main.cpp

2,692 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<pair<uint256, bool> > vWalletUpdated;38CCriticalSection cs_mapWallet;3940map<vector<unsigned char>, CPrivKey> mapKeys;41map<uint160, vector<unsigned char> > mapPubKeys;42CCriticalSection cs_mapKeys;43CKey keyUser;4445string strSetDataDir;46int nDropMessagesTest = 0;4748// Settings49int fGenerateBitcoins;50int64 nTransactionFee = 0;51CAddress addrIncoming;525354555657585960//////////////////////////////////////////////////////////////////////////////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        //// debug print105        printf("AddToWallet %s  %s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), fInsertedNew ? "new" : "update");106107        if (!fInsertedNew)108        {109            // Merge110            bool fUpdated = false;111            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)112            {113                wtx.hashBlock = wtxIn.hashBlock;114                fUpdated = true;115            }116            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))117            {118                wtx.vMerkleBranch = wtxIn.vMerkleBranch;119                wtx.nIndex = wtxIn.nIndex;120                fUpdated = true;121            }122            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)123            {124                wtx.fFromMe = wtxIn.fFromMe;125                fUpdated = true;126            }127            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)128            {129                wtx.fSpent = wtxIn.fSpent;130                fUpdated = true;131            }132            if (!fUpdated)133                return true;134        }135136        // Write to disk137        if (!wtx.WriteToDisk())138            return false;139140        // Notify UI141        vWalletUpdated.push_back(make_pair(hash, fInsertedNew));142    }143144    // Refresh UI145    MainFrameRepaint();146    return true;147}148149bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)150{151    if (tx.IsMine() || mapWallet.count(tx.GetHash()))152    {153        CWalletTx wtx(tx);154        // Get merkle branch if transaction was found in a block155        if (pblock)156            wtx.SetMerkleBranch(pblock);157        return AddToWallet(wtx);158    }159    return true;160}161162bool EraseFromWallet(uint256 hash)163{164    CRITICAL_BLOCK(cs_mapWallet)165    {166        if (mapWallet.erase(hash))167            CWalletDB().EraseTx(hash);168    }169    return true;170}171172173174175176177178179180//////////////////////////////////////////////////////////////////////////////181//182// mapOrphanTransactions183//184185void AddOrphanTx(const CDataStream& vMsg)186{187    CTransaction tx;188    CDataStream(vMsg) >> tx;189    uint256 hash = tx.GetHash();190    if (mapOrphanTransactions.count(hash))191        return;192    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);193    foreach(const CTxIn& txin, tx.vin)194        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));195}196197void EraseOrphanTx(uint256 hash)198{199    if (!mapOrphanTransactions.count(hash))200        return;201    const CDataStream* pvMsg = mapOrphanTransactions[hash];202    CTransaction tx;203    CDataStream(*pvMsg) >> tx;204    foreach(const CTxIn& txin, tx.vin)205    {206        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);207             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)208        {209            if ((*mi).second == pvMsg)210                mapOrphanTransactionsByPrev.erase(mi++);211            else212                mi++;213        }214    }215    delete pvMsg;216    mapOrphanTransactions.erase(hash);217}218219220221222223224225226//////////////////////////////////////////////////////////////////////////////227//228// CTransaction229//230231bool CTxIn::IsMine() const232{233    CRITICAL_BLOCK(cs_mapWallet)234    {235        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);236        if (mi != mapWallet.end())237        {238            const CWalletTx& prev = (*mi).second;239            if (prevout.n < prev.vout.size())240                if (prev.vout[prevout.n].IsMine())241                    return true;242        }243    }244    return false;245}246247int64 CTxIn::GetDebit() const248{249    CRITICAL_BLOCK(cs_mapWallet)250    {251        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);252        if (mi != mapWallet.end())253        {254            const CWalletTx& prev = (*mi).second;255            if (prevout.n < prev.vout.size())256                if (prev.vout[prevout.n].IsMine())257                    return prev.vout[prevout.n].nValue;258        }259    }260    return 0;261}262263int64 CWalletTx::GetTxTime() const264{265    if (!fTimeReceivedIsTxTime && hashBlock != 0)266    {267        // If we did not receive the transaction directly, we rely on the block's268        // time to figure out when it happened.  We use the median over a range269        // of blocks to try to filter out inaccurate block times.270        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);271        if (mi != mapBlockIndex.end())272        {273            CBlockIndex* pindex = (*mi).second;274            if (pindex)275                return pindex->GetMedianTime();276        }277    }278    return nTimeReceived;279}280281282283284285286int CMerkleTx::SetMerkleBranch(const CBlock* pblock)287{288    if (fClient)289    {290        if (hashBlock == 0)291            return 0;292    }293    else294    {295        CBlock blockTmp;296        if (pblock == NULL)297        {298            // Load the block this tx is in299            CTxIndex txindex;300            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))301                return 0;302            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, true))303                return 0;304            pblock = &blockTmp;305        }306307        // Update the tx's hashBlock308        hashBlock = pblock->GetHash();309310        // Locate the transaction311        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)312            if (pblock->vtx[nIndex] == *(CTransaction*)this)313                break;314        if (nIndex == pblock->vtx.size())315        {316            vMerkleBranch.clear();317            nIndex = -1;318            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");319            return 0;320        }321322        // Fill in merkle branch323        vMerkleBranch = pblock->GetMerkleBranch(nIndex);324    }325326    // Is the tx in a block that's in the main chain327    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);328    if (mi == mapBlockIndex.end())329        return 0;330    CBlockIndex* pindex = (*mi).second;331    if (!pindex || !pindex->IsInMainChain())332        return 0;333334    return pindexBest->nHeight - pindex->nHeight + 1;335}336337338339void CWalletTx::AddSupportingTransactions(CTxDB& txdb)340{341    vtxPrev.clear();342343    const int COPY_DEPTH = 3;344    if (SetMerkleBranch() < COPY_DEPTH)345    {346        vector<uint256> vWorkQueue;347        foreach(const CTxIn& txin, vin)348            vWorkQueue.push_back(txin.prevout.hash);349350        // This critsect is OK because txdb is already open351        CRITICAL_BLOCK(cs_mapWallet)352        {353            map<uint256, const CMerkleTx*> mapWalletPrev;354            set<uint256> setAlreadyDone;355            for (int i = 0; i < vWorkQueue.size(); i++)356            {357                uint256 hash = vWorkQueue[i];358                if (setAlreadyDone.count(hash))359                    continue;360                setAlreadyDone.insert(hash);361362                CMerkleTx tx;363                if (mapWallet.count(hash))364                {365                    tx = mapWallet[hash];366                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)367                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;368                }369                else if (mapWalletPrev.count(hash))370                {371                    tx = *mapWalletPrev[hash];372                }373                else if (!fClient && txdb.ReadDiskTx(hash, tx))374                {375                    ;376                }377                else378                {379                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");380                    continue;381                }382383                int nDepth = tx.SetMerkleBranch();384                vtxPrev.push_back(tx);385386                if (nDepth < COPY_DEPTH)387                    foreach(const CTxIn& txin, tx.vin)388                        vWorkQueue.push_back(txin.prevout.hash);389            }390        }391    }392393    reverse(vtxPrev.begin(), vtxPrev.end());394}395396397398399400401402403404405406bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)407{408    if (pfMissingInputs)409        *pfMissingInputs = false;410411    // Coinbase is only valid in a block, not as a loose transaction412    if (IsCoinBase())413        return error("AcceptTransaction() : coinbase as individual tx");414415    if (!CheckTransaction())416        return error("AcceptTransaction() : CheckTransaction failed");417418    // Do we already have it?419    uint256 hash = GetHash();420    CRITICAL_BLOCK(cs_mapTransactions)421        if (mapTransactions.count(hash))422            return false;423    if (fCheckInputs)424        if (txdb.ContainsTx(hash))425            return false;426427    // Check for conflicts with in-memory transactions428    CTransaction* ptxOld = NULL;429    for (int i = 0; i < vin.size(); i++)430    {431        COutPoint outpoint = vin[i].prevout;432        if (mapNextTx.count(outpoint))433        {434            // Allow replacing with a newer version of the same transaction435            if (i != 0)436                return false;437            ptxOld = mapNextTx[outpoint].ptx;438            if (!IsNewerThan(*ptxOld))439                return false;440            for (int i = 0; i < vin.size(); i++)441            {442                COutPoint outpoint = vin[i].prevout;443                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)444                    return false;445            }446            break;447        }448    }449450    // Check against previous transactions451    map<uint256, CTxIndex> mapUnused;452    int64 nFees = 0;453    if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))454    {455        if (pfMissingInputs)456            *pfMissingInputs = true;457        return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());458    }459460    // Store transaction in memory461    CRITICAL_BLOCK(cs_mapTransactions)462    {463        if (ptxOld)464        {465            printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());466            mapTransactions.erase(ptxOld->GetHash());467        }468        AddToMemoryPool();469    }470471    ///// are we sure this is ok when loading transactions or restoring block txes472    // If updated, erase old tx from wallet473    if (ptxOld)474        EraseFromWallet(ptxOld->GetHash());475476    printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());477    return true;478}479480481bool CTransaction::AddToMemoryPool()482{483    // Add to memory pool without checking anything.  Don't call this directly,484    // call AcceptTransaction to properly check the transaction first.485    CRITICAL_BLOCK(cs_mapTransactions)486    {487        uint256 hash = GetHash();488        mapTransactions[hash] = *this;489        for (int i = 0; i < vin.size(); i++)490            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);491        nTransactionsUpdated++;492    }493    return true;494}495496497bool CTransaction::RemoveFromMemoryPool()498{499    // Remove transaction from memory pool500    CRITICAL_BLOCK(cs_mapTransactions)501    {502        foreach(const CTxIn& txin, vin)503            mapNextTx.erase(txin.prevout);504        mapTransactions.erase(GetHash());505        nTransactionsUpdated++;506    }507    return true;508}509510511512513514515int CMerkleTx::GetDepthInMainChain() const516{517    if (hashBlock == 0 || nIndex == -1)518        return 0;519520    // Find the block it claims to be in521    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);522    if (mi == mapBlockIndex.end())523        return 0;524    CBlockIndex* pindex = (*mi).second;525    if (!pindex || !pindex->IsInMainChain())526        return 0;527528    // Make sure the merkle branch connects to this block529    if (!fMerkleVerified)530    {531        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)532            return 0;533        fMerkleVerified = true;534    }535536    return pindexBest->nHeight - pindex->nHeight + 1;537}538539540int CMerkleTx::GetBlocksToMaturity() const541{542    if (!IsCoinBase())543        return 0;544    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());545}546547548bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)549{550    if (fClient)551    {552        if (!IsInMainChain() && !ClientConnectInputs())553            return false;554        return CTransaction::AcceptTransaction(txdb, false);555    }556    else557    {558        return CTransaction::AcceptTransaction(txdb, fCheckInputs);559    }560}561562563564bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)565{566    CRITICAL_BLOCK(cs_mapTransactions)567    {568        foreach(CMerkleTx& tx, vtxPrev)569        {570            if (!tx.IsCoinBase())571            {572                uint256 hash = tx.GetHash();573                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))574                    tx.AcceptTransaction(txdb, fCheckInputs);575            }576        }577        if (!IsCoinBase())578            return AcceptTransaction(txdb, fCheckInputs);579    }580    return true;581}582583void ReacceptWalletTransactions()584{585    // Reaccept any txes of ours that aren't already in a block586    CTxDB txdb("r");587    CRITICAL_BLOCK(cs_mapWallet)588    {589        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)590        {591            CWalletTx& wtx = item.second;592            if (!wtx.IsCoinBase() && !txdb.ContainsTx(wtx.GetHash()))593                wtx.AcceptWalletTransaction(txdb, false);594        }595    }596}597598599void CWalletTx::RelayWalletTransaction(CTxDB& txdb)600{601    foreach(const CMerkleTx& tx, vtxPrev)602    {603        if (!tx.IsCoinBase())604        {605            uint256 hash = tx.GetHash();606            if (!txdb.ContainsTx(hash))607                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);608        }609    }610    if (!IsCoinBase())611    {612        uint256 hash = GetHash();613        if (!txdb.ContainsTx(hash))614        {615            printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());616            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);617        }618    }619}620621void RelayWalletTransactions()622{623    static int64 nLastTime;624    if (GetTime() - nLastTime < 10 * 60)625        return;626    nLastTime = GetTime();627628    // Rebroadcast any of our txes that aren't in a block yet629    printf("RelayWalletTransactions()\n");630    CTxDB txdb("r");631    CRITICAL_BLOCK(cs_mapWallet)632    {633        // Sort them in chronological order634        multimap<unsigned int, CWalletTx*> mapSorted;635        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)636        {637            CWalletTx& wtx = item.second;638            mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));639        }640        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)641        {642            CWalletTx& wtx = *item.second;643            wtx.RelayWalletTransaction(txdb);644        }645    }646}647648649650651652653654655656657//////////////////////////////////////////////////////////////////////////////658//659// CBlock and CBlockIndex660//661662bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)663{664    return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);665}666667uint256 GetOrphanRoot(const CBlock* pblock)668{669    // Work back to the first block in the orphan chain670    while (mapOrphanBlocks.count(pblock->hashPrevBlock))671        pblock = mapOrphanBlocks[pblock->hashPrevBlock];672    return pblock->GetHash();673}674675int64 CBlock::GetBlockValue(int64 nFees) const676{677    int64 nSubsidy = 50 * COIN;678679    // Subsidy is cut in half every 4 years680    nSubsidy >>= (nBestHeight / 210000);681682    return nSubsidy + nFees;683}684685unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)686{687    const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks688    const unsigned int nTargetSpacing = 10 * 60;689    const unsigned int nInterval = nTargetTimespan / nTargetSpacing;690691    // Genesis block692    if (pindexLast == NULL)693        return bnProofOfWorkLimit.GetCompact();694695    // Only change once per interval696    if ((pindexLast->nHeight+1) % nInterval != 0)697        return pindexLast->nBits;698699    // Go back by what we want to be 14 days worth of blocks700    const CBlockIndex* pindexFirst = pindexLast;701    for (int i = 0; pindexFirst && i < nInterval-1; i++)702        pindexFirst = pindexFirst->pprev;703    assert(pindexFirst);704705    // Limit adjustment step706    unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;707    printf("  nActualTimespan = %d  before bounds\n", nActualTimespan);708    if (nActualTimespan < nTargetTimespan/4)709        nActualTimespan = nTargetTimespan/4;710    if (nActualTimespan > nTargetTimespan*4)711        nActualTimespan = nTargetTimespan*4;712713    // Retarget714    CBigNum bnNew;715    bnNew.SetCompact(pindexLast->nBits);716    bnNew *= nActualTimespan;717    bnNew /= nTargetTimespan;718719    if (bnNew > bnProofOfWorkLimit)720        bnNew = bnProofOfWorkLimit;721722    /// debug print723    printf("\n\n\nGetNextWorkRequired RETARGET *****\n");724    printf("nTargetTimespan = %d    nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);725    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());726    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());727728    return bnNew.GetCompact();729}730731732733734735736737738739bool CTransaction::DisconnectInputs(CTxDB& txdb)740{741    // Relinquish previous transactions' spent pointers742    if (!IsCoinBase())743    {744        foreach(const CTxIn& txin, vin)745        {746            COutPoint prevout = txin.prevout;747748            // Get prev txindex from disk749            CTxIndex txindex;750            if (!txdb.ReadTxIndex(prevout.hash, txindex))751                return error("DisconnectInputs() : ReadTxIndex failed");752753            if (prevout.n >= txindex.vSpent.size())754                return error("DisconnectInputs() : prevout.n out of range");755756            // Mark outpoint as not spent757            txindex.vSpent[prevout.n].SetNull();758759            // Write back760            txdb.UpdateTxIndex(prevout.hash, txindex);761        }762    }763764    // Remove transaction from index765    if (!txdb.EraseTxIndex(*this))766        return error("DisconnectInputs() : EraseTxPos failed");767768    return true;769}770771772bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)773{774    // Take over previous transactions' spent pointers775    if (!IsCoinBase())776    {777        int64 nValueIn = 0;778        for (int i = 0; i < vin.size(); i++)779        {780            COutPoint prevout = vin[i].prevout;781782            // Read txindex783            CTxIndex txindex;784            bool fFound = true;785            if (fMiner && mapTestPool.count(prevout.hash))786            {787                // Get txindex from current proposed changes788                txindex = mapTestPool[prevout.hash];789            }790            else791            {792                // Read txindex from txdb793                fFound = txdb.ReadTxIndex(prevout.hash, txindex);794            }795            if (!fFound && (fBlock || fMiner))796                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());797798            // Read txPrev799            CTransaction txPrev;800            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))801            {802                // Get prev tx from single transactions in memory803                CRITICAL_BLOCK(cs_mapTransactions)804                {805                    if (!mapTransactions.count(prevout.hash))806                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());807                    txPrev = mapTransactions[prevout.hash];808                }809                if (!fFound)810                    txindex.vSpent.resize(txPrev.vout.size());811            }812            else813            {814                // Get prev tx from disk815                if (!txPrev.ReadFromDisk(txindex.pos))816                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());817            }818819            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())820                return error("ConnectInputs() : %s prevout.n out of range %d %d %d", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size());821822            // If prev is coinbase, check that it's matured823            if (txPrev.IsCoinBase())824                for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)825                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)826                        return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);827828            // Verify signature829            if (!VerifySignature(txPrev, *this, i))830                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());831832            // Check for conflicts833            if (!txindex.vSpent[prevout.n].IsNull())834                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());835836            // Mark outpoints as spent837            txindex.vSpent[prevout.n] = posThisTx;838839            // Write back840            if (fBlock)841                txdb.UpdateTxIndex(prevout.hash, txindex);842            else if (fMiner)843                mapTestPool[prevout.hash] = txindex;844845            nValueIn += txPrev.vout[prevout.n].nValue;846        }847848        // Tally transaction fees849        int64 nTxFee = nValueIn - GetValueOut();850        if (nTxFee < 0)851            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());852        if (nTxFee < nMinFee)853            return false;854        nFees += nTxFee;855    }856857    if (fBlock)858    {859        // Add transaction to disk index860        if (!txdb.AddTxIndex(*this, posThisTx, nHeight))861            return error("ConnectInputs() : AddTxPos failed");862    }863    else if (fMiner)864    {865        // Add transaction to test pool866        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());867    }868869    return true;870}871872873bool CTransaction::ClientConnectInputs()874{875    if (IsCoinBase())876        return false;877878    // Take over previous transactions' spent pointers879    CRITICAL_BLOCK(cs_mapTransactions)880    {881        int64 nValueIn = 0;882        for (int i = 0; i < vin.size(); i++)883        {884            // Get prev tx from single transactions in memory885            COutPoint prevout = vin[i].prevout;886            if (!mapTransactions.count(prevout.hash))887                return false;888            CTransaction& txPrev = mapTransactions[prevout.hash];889890            if (prevout.n >= txPrev.vout.size())891                return false;892893            // Verify signature894            if (!VerifySignature(txPrev, *this, i))895                return error("ConnectInputs() : VerifySignature failed");896897            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of898            ///// this has to go away now that posNext is gone899            // // Check for conflicts900            // if (!txPrev.vout[prevout.n].posNext.IsNull())901            //     return error("ConnectInputs() : prev tx already used");902            //903            // // Flag outpoints as used904            // txPrev.vout[prevout.n].posNext = posThisTx;905906            nValueIn += txPrev.vout[prevout.n].nValue;907        }908        if (GetValueOut() > nValueIn)909            return false;910    }911912    return true;913}914915916917918bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)919{920    // Disconnect in reverse order921    for (int i = vtx.size()-1; i >= 0; i--)922        if (!vtx[i].DisconnectInputs(txdb))923            return false;924925    // Update block index on disk without changing it in memory.926    // The memory index structure will be changed after the db commits.927    if (pindex->pprev)928    {929        CDiskBlockIndex blockindexPrev(pindex->pprev);930        blockindexPrev.hashNext = 0;931        txdb.WriteBlockIndex(blockindexPrev);932    }933934    return true;935}936937bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)938{939    //// issue here: it doesn't know the version940    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());941942    map<uint256, CTxIndex> mapUnused;943    int64 nFees = 0;944    foreach(CTransaction& tx, vtx)945    {946        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);947        nTxPos += ::GetSerializeSize(tx, SER_DISK);948949        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))950            return false;951    }952953    if (vtx[0].GetValueOut() > GetBlockValue(nFees))954        return false;955956    // Update block index on disk without changing it in memory.957    // The memory index structure will be changed after the db commits.958    if (pindex->pprev)959    {960        CDiskBlockIndex blockindexPrev(pindex->pprev);961        blockindexPrev.hashNext = pindex->GetBlockHash();962        txdb.WriteBlockIndex(blockindexPrev);963    }964965    // Watch for transactions paying to me966    foreach(CTransaction& tx, vtx)967        AddToWalletIfMine(tx, this);968969    return true;970}971972973974bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)975{976    printf("*** REORGANIZE ***\n");977978    // Find the fork979    CBlockIndex* pfork = pindexBest;980    CBlockIndex* plonger = pindexNew;981    while (pfork != plonger)982    {983        if (!(pfork = pfork->pprev))984            return error("Reorganize() : pfork->pprev is null");985        while (plonger->nHeight > pfork->nHeight)986            if (!(plonger = plonger->pprev))987                return error("Reorganize() : plonger->pprev is null");988    }989990    // List of what to disconnect991    vector<CBlockIndex*> vDisconnect;992    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)993        vDisconnect.push_back(pindex);994995    // List of what to connect996    vector<CBlockIndex*> vConnect;997    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)998        vConnect.push_back(pindex);999    reverse(vConnect.begin(), vConnect.end());10001001    // Disconnect shorter branch1002    vector<CTransaction> vResurrect;1003    foreach(CBlockIndex* pindex, vDisconnect)1004    {1005        CBlock block;1006        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos, true))1007            return error("Reorganize() : ReadFromDisk for disconnect failed");1008        if (!block.DisconnectBlock(txdb, pindex))1009            return error("Reorganize() : DisconnectBlock failed");10101011        // Queue memory transactions to resurrect1012        foreach(const CTransaction& tx, block.vtx)1013            if (!tx.IsCoinBase())1014                vResurrect.push_back(tx);1015    }10161017    // Connect longer branch1018    vector<CTransaction> vDelete;1019    for (int i = 0; i < vConnect.size(); i++)1020    {1021        CBlockIndex* pindex = vConnect[i];1022        CBlock block;1023        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos, true))1024            return error("Reorganize() : ReadFromDisk for connect failed");1025        if (!block.ConnectBlock(txdb, pindex))1026        {1027            // Invalid block, delete the rest of this branch1028            txdb.TxnAbort();1029            for (int j = i; j < vConnect.size(); j++)1030            {1031                CBlockIndex* pindex = vConnect[j];1032                pindex->EraseBlockFromDisk();1033                txdb.EraseBlockIndex(pindex->GetBlockHash());1034                mapBlockIndex.erase(pindex->GetBlockHash());1035                delete pindex;1036            }1037            return error("Reorganize() : ConnectBlock failed");1038        }10391040        // Queue memory transactions to delete1041        foreach(const CTransaction& tx, block.vtx)1042            vDelete.push_back(tx);1043    }1044    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1045        return error("Reorganize() : WriteHashBestChain failed");10461047    // Commit now because resurrecting could take some time1048    txdb.TxnCommit();10491050    // Disconnect shorter branch1051    foreach(CBlockIndex* pindex, vDisconnect)1052        if (pindex->pprev)1053            pindex->pprev->pnext = NULL;10541055    // Connect longer branch1056    foreach(CBlockIndex* pindex, vConnect)1057        if (pindex->pprev)1058            pindex->pprev->pnext = pindex;10591060    // Resurrect memory transactions that were in the disconnected branch1061    foreach(CTransaction& tx, vResurrect)1062        tx.AcceptTransaction(txdb, false);10631064    // Delete redundant memory transactions that are in the connected branch1065    foreach(CTransaction& tx, vDelete)1066        tx.RemoveFromMemoryPool();10671068    return true;1069}107010711072bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1073{1074    // Check for duplicate1075    uint256 hash = GetHash();1076    if (mapBlockIndex.count(hash))1077        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,14).c_str());10781079    // Construct new block index object1080    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1081    if (!pindexNew)1082        return error("AddToBlockIndex() : new CBlockIndex failed");1083    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1084    pindexNew->phashBlock = &((*mi).first);1085    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1086    if (miPrev != mapBlockIndex.end())1087    {1088        pindexNew->pprev = (*miPrev).second;1089        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1090    }10911092    CTxDB txdb;1093    txdb.TxnBegin();1094    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));10951096    // New best1097    if (pindexNew->nHeight > nBestHeight)1098    {1099        if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1100        {1101            pindexGenesisBlock = pindexNew;1102            txdb.WriteHashBestChain(hash);1103        }1104        else if (hashPrevBlock == hashBestChain)1105        {1106            // Adding to current best branch1107            if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1108            {1109                txdb.TxnAbort();1110                pindexNew->EraseBlockFromDisk();1111                mapBlockIndex.erase(pindexNew->GetBlockHash());1112                delete pindexNew;1113                return error("AddToBlockIndex() : ConnectBlock failed");1114            }1115            txdb.TxnCommit();1116            pindexNew->pprev->pnext = pindexNew;11171118            // Delete redundant memory transactions1119            foreach(CTransaction& tx, vtx)1120                tx.RemoveFromMemoryPool();1121        }1122        else1123        {1124            // New best branch1125            if (!Reorganize(txdb, pindexNew))1126            {1127                txdb.TxnAbort();1128                return error("AddToBlockIndex() : Reorganize failed");1129            }1130        }11311132        // New best link1133        hashBestChain = hash;1134        pindexBest = pindexNew;1135        nBestHeight = pindexBest->nHeight;1136        nTransactionsUpdated++;1137        printf("AddToBlockIndex: new best=%s  height=%d\n", hashBestChain.ToString().substr(0,14).c_str(), nBestHeight);1138    }11391140    txdb.TxnCommit();1141    txdb.Close();11421143    // Relay wallet transactions that haven't gotten in yet1144    if (pindexNew == pindexBest)1145        RelayWalletTransactions();11461147    MainFrameRepaint();1148    return true;1149}11501151115211531154bool CBlock::CheckBlock() const1155{1156    // These are checks that are independent of context1157    // that can be verified before saving an orphan block.11581159    // Size limits1160    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)1161        return error("CheckBlock() : size limits failed");11621163    // Check timestamp1164    if (nTime > GetAdjustedTime() + 2 * 60 * 60)1165        return error("CheckBlock() : block timestamp too far in the future");11661167    // First transaction must be coinbase, the rest must not be1168    if (vtx.empty() || !vtx[0].IsCoinBase())1169        return error("CheckBlock() : first tx is not coinbase");1170    for (int i = 1; i < vtx.size(); i++)1171        if (vtx[i].IsCoinBase())1172            return error("CheckBlock() : more than one coinbase");11731174    // Check transactions1175    foreach(const CTransaction& tx, vtx)1176        if (!tx.CheckTransaction())1177            return error("CheckBlock() : CheckTransaction failed");11781179    // Check proof of work matches claimed amount1180    if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1181        return error("CheckBlock() : nBits below minimum work");1182    if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1183        return error("CheckBlock() : hash doesn't match nBits");11841185    // Check merkleroot1186    if (hashMerkleRoot != BuildMerkleTree())1187        return error("CheckBlock() : hashMerkleRoot mismatch");11881189    return true;1190}11911192bool CBlock::AcceptBlock()1193{1194    // Check for duplicate1195    uint256 hash = GetHash();1196    if (mapBlockIndex.count(hash))1197        return error("AcceptBlock() : block already in mapBlockIndex");11981199    // Get prev block index1200    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1201    if (mi == mapBlockIndex.end())1202        return error("AcceptBlock() : prev block not found");1203    CBlockIndex* pindexPrev = (*mi).second;12041205    // Check timestamp against prev1206    if (nTime <= pindexPrev->GetMedianTimePast())1207        return error("AcceptBlock() : block's timestamp is too early");12081209    // Check proof of work1210    if (nBits != GetNextWorkRequired(pindexPrev))1211        return error("AcceptBlock() : incorrect proof of work");12121213    // Write block to history file1214    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))1215        return error("AcceptBlock() : out of disk space");1216    unsigned int nFile;1217    unsigned int nBlockPos;1218    if (!WriteToDisk(!fClient, nFile, nBlockPos))1219        return error("AcceptBlock() : WriteToDisk failed");1220    if (!AddToBlockIndex(nFile, nBlockPos))1221        return error("AcceptBlock() : AddToBlockIndex failed");12221223    if (hashBestChain == hash)1224        RelayInventory(CInv(MSG_BLOCK, hash));12251226    // // Add atoms to user reviews for coins created1227    // vector<unsigned char> vchPubKey;1228    // if (ExtractPubKey(vtx[0].vout[0].scriptPubKey, false, vchPubKey))1229    // {1230    //     unsigned short nAtom = GetRand(USHRT_MAX - 100) + 100;1231    //     vector<unsigned short> vAtoms(1, nAtom);1232    //     AddAtomsAndPropagate(Hash(vchPubKey.begin(), vchPubKey.end()), vAtoms, true);1233    // }12341235    return true;1236}12371238bool ProcessBlock(CNode* pfrom, CBlock* pblock)1239{1240    // Check for duplicate1241    uint256 hash = pblock->GetHash();1242    if (mapBlockIndex.count(hash))1243        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,14).c_str());1244    if (mapOrphanBlocks.count(hash))1245        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,14).c_str());12461247    // Preliminary checks1248    if (!pblock->CheckBlock())1249    {1250        delete pblock;1251        return error("ProcessBlock() : CheckBlock FAILED");1252    }12531254    // If don't already have its previous block, shunt it off to holding area until we get it1255    if (!mapBlockIndex.count(pblock->hashPrevBlock))1256    {1257        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,14).c_str());1258        mapOrphanBlocks.insert(make_pair(hash, pblock));1259        mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));12601261        // Ask this guy to fill in what we're missing1262        if (pfrom)1263            pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(pblock));1264        return true;1265    }12661267    // Store to disk1268    if (!pblock->AcceptBlock())1269    {1270        delete pblock;1271        return error("ProcessBlock() : AcceptBlock FAILED");1272    }1273    delete pblock;12741275    // Recursively process any orphan blocks that depended on this one1276    vector<uint256> vWorkQueue;1277    vWorkQueue.push_back(hash);1278    for (int i = 0; i < vWorkQueue.size(); i++)1279    {1280        uint256 hashPrev = vWorkQueue[i];1281        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1282             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1283             ++mi)1284        {1285            CBlock* pblockOrphan = (*mi).second;1286            if (pblockOrphan->AcceptBlock())1287                vWorkQueue.push_back(pblockOrphan->GetHash());1288            mapOrphanBlocks.erase(pblockOrphan->GetHash());1289            delete pblockOrphan;1290        }1291        mapOrphanBlocksByPrev.erase(hashPrev);1292    }12931294    printf("ProcessBlock: ACCEPTED\n");1295    return true;1296}129712981299130013011302130313041305template<typename Stream>1306bool ScanMessageStart(Stream& s)1307{1308    // Scan ahead to the next pchMessageStart, which should normally be immediately1309    // at the file pointer.  Leaves file pointer at end of pchMessageStart.1310    s.clear(0);1311    short prevmask = s.exceptions(0);1312    const char* p = BEGIN(pchMessageStart);1313    try1314    {1315        loop1316        {1317            char c;1318            s.read(&c, 1);1319            if (s.fail())1320            {1321                s.clear(0);1322                s.exceptions(prevmask);1323                return false;1324            }1325            if (*p != c)1326                p = BEGIN(pchMessageStart);1327            if (*p == c)1328            {1329                if (++p == END(pchMessageStart))1330                {1331                    s.clear(0);1332                    s.exceptions(prevmask);1333                    return true;1334                }1335            }1336        }1337    }1338    catch (...)1339    {1340        s.clear(0);1341        s.exceptions(prevmask);1342        return false;1343    }1344}13451346string GetAppDir()1347{1348    string strDir;1349    if (!strSetDataDir.empty())1350    {1351        strDir = strSetDataDir;1352    }1353    else if (getenv("APPDATA"))1354    {1355        strDir = strprintf("%s\\Bitcoin", getenv("APPDATA"));1356    }1357    else if (getenv("USERPROFILE"))1358    {1359        string strAppData = strprintf("%s\\Application Data", getenv("USERPROFILE"));1360        static bool fMkdirDone;1361        if (!fMkdirDone)1362        {1363            fMkdirDone = true;1364            _mkdir(strAppData.c_str());1365        }1366        strDir = strprintf("%s\\Bitcoin", strAppData.c_str());1367    }1368    else1369    {1370        return ".";1371    }1372    static bool fMkdirDone;1373    if (!fMkdirDone)1374    {1375        fMkdirDone = true;1376        _mkdir(strDir.c_str());1377    }1378    return strDir;1379}13801381bool CheckDiskSpace(int64 nAdditionalBytes)1382{1383    uint64 nFreeBytesAvailable = 0;     // bytes available to caller1384    uint64 nTotalNumberOfBytes = 0;     // bytes on disk1385    uint64 nTotalNumberOfFreeBytes = 0; // free bytes on disk13861387    if (!GetDiskFreeSpaceEx(GetAppDir().c_str(),1388            (PULARGE_INTEGER)&nFreeBytesAvailable,1389            (PULARGE_INTEGER)&nTotalNumberOfBytes,1390            (PULARGE_INTEGER)&nTotalNumberOfFreeBytes))1391    {1392        printf("ERROR: GetDiskFreeSpaceEx() failed\n");1393        return true;1394    }13951396    // Check for 15MB because database could create another 10MB log file at any time1397    if ((int64)nFreeBytesAvailable < 15000000 + nAdditionalBytes)1398    {1399        fShutdown = true;1400        wxMessageBox("Warning: Your disk space is low  ", "Bitcoin", wxICON_EXCLAMATION);1401        _beginthread(Shutdown, 0, NULL);1402        return false;1403    }1404    return true;1405}14061407FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1408{1409    if (nFile == -1)1410        return NULL;1411    FILE* file = fopen(strprintf("%s\\blk%04d.dat", GetAppDir().c_str(), nFile).c_str(), pszMode);1412    if (!file)1413        return NULL;1414    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1415    {1416        if (fseek(file, nBlockPos, SEEK_SET) != 0)1417        {1418            fclose(file);1419            return NULL;1420        }1421    }1422    return file;1423}14241425static unsigned int nCurrentBlockFile = 1;14261427FILE* AppendBlockFile(unsigned int& nFileRet)1428{1429    nFileRet = 0;1430    loop1431    {1432        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1433        if (!file)1434            return NULL;1435        if (fseek(file, 0, SEEK_END) != 0)1436            return NULL;1437        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1438        if (ftell(file) < 0x7F000000 - MAX_SIZE)1439        {1440            nFileRet = nCurrentBlockFile;1441            return file;1442        }1443        fclose(file);1444        nCurrentBlockFile++;1445    }1446}14471448bool LoadBlockIndex(bool fAllowNew)1449{1450    //1451    // Load block index1452    //1453    CTxDB txdb("cr");1454    if (!txdb.LoadBlockIndex())1455        return false;1456    txdb.Close();14571458    //1459    // Init with genesis block1460    //1461    if (mapBlockIndex.empty())1462    {1463        if (!fAllowNew)1464            return false;146514661467        // Genesis Block:1468        // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f1469        // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b1470        // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D6954206568541471        // txNew.vout[0].nValue       = 50000000001472        // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG1473        // block.nVersion = 11474        // block.nTime    = 12310065051475        // block.nBits    = 0x1d00ffff1476        // block.nNonce   = 20832368931477        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1478        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1479        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1480        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1481        //   vMerkleTree: 4a5e1e14821483        // Genesis block1484        char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1485        CTransaction txNew;1486        txNew.vin.resize(1);1487        txNew.vout.resize(1);1488        txNew.vin[0].scriptSig     = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((unsigned char*)pszTimestamp, (unsigned char*)pszTimestamp + strlen(pszTimestamp));1489        txNew.vout[0].nValue       = 50 * COIN;1490        txNew.vout[0].scriptPubKey = CScript() << CBigNum("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704") << OP_CHECKSIG;1491        CBlock block;1492        block.vtx.push_back(txNew);1493        block.hashPrevBlock = 0;1494        block.hashMerkleRoot = block.BuildMerkleTree();1495        block.nVersion = 1;1496        block.nTime    = 1231006505;1497        block.nBits    = 0x1d00ffff;1498        block.nNonce   = 2083236893;14991500            //// debug print, delete this later1501            printf("%s\n", block.GetHash().ToString().c_str());1502            printf("%s\n", block.hashMerkleRoot.ToString().c_str());1503            printf("%s\n", hashGenesisBlock.ToString().c_str());1504            txNew.vout[0].scriptPubKey.print();1505            block.print();1506            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));15071508        assert(block.GetHash() == hashGenesisBlock);15091510        // Start new block file1511        unsigned int nFile;1512        unsigned int nBlockPos;1513        if (!block.WriteToDisk(!fClient, nFile, nBlockPos))1514            return error("LoadBlockIndex() : writing genesis block to disk failed");1515        if (!block.AddToBlockIndex(nFile, nBlockPos))1516            return error("LoadBlockIndex() : genesis block not accepted");1517    }15181519    return true;1520}1521152215231524void PrintBlockTree()1525{1526    // precompute tree structure1527    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1528    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1529    {1530        CBlockIndex* pindex = (*mi).second;1531        mapNext[pindex->pprev].push_back(pindex);1532        // test1533        //while (rand() % 3 == 0)1534        //    mapNext[pindex->pprev].push_back(pindex);1535    }15361537    vector<pair<int, CBlockIndex*> > vStack;1538    vStack.push_back(make_pair(0, pindexGenesisBlock));15391540    int nPrevCol = 0;1541    while (!vStack.empty())1542    {1543        int nCol = vStack.back().first;1544        CBlockIndex* pindex = vStack.back().second;1545        vStack.pop_back();15461547        // print split or gap1548        if (nCol > nPrevCol)1549        {1550            for (int i = 0; i < nCol-1; i++)1551                printf("| ");1552            printf("|\\\n");1553        }1554        else if (nCol < nPrevCol)1555        {1556            for (int i = 0; i < nCol; i++)1557                printf("| ");1558            printf("|\n");1559        }1560        nPrevCol = nCol;15611562        // print columns1563        for (int i = 0; i < nCol; i++)1564            printf("| ");15651566        // print item1567        CBlock block;1568        block.ReadFromDisk(pindex, true);1569        printf("%d (%u,%u) %s  %s  tx %d",1570            pindex->nHeight,1571            pindex->nFile,1572            pindex->nBlockPos,1573            block.GetHash().ToString().substr(0,14).c_str(),1574            DateTimeStr(block.nTime).c_str(),1575            block.vtx.size());15761577        CRITICAL_BLOCK(cs_mapWallet)1578        {1579            if (mapWallet.count(block.vtx[0].GetHash()))1580            {1581                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1582                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1583            }1584        }1585        printf("\n");158615871588        // put the main timechain first1589        vector<CBlockIndex*>& vNext = mapNext[pindex];1590        for (int i = 0; i < vNext.size(); i++)1591        {1592            if (vNext[i]->pnext)1593            {1594                swap(vNext[0], vNext[i]);1595                break;1596            }1597        }15981599        // iterate children1600        for (int i = 0; i < vNext.size(); i++)1601            vStack.push_back(make_pair(nCol+i, vNext[i]));1602    }1603}16041605160616071608160916101611161216131614//////////////////////////////////////////////////////////////////////////////1615//1616// Messages1617//161816191620bool AlreadyHave(CTxDB& txdb, const CInv& inv)1621{1622    switch (inv.type)1623    {1624    case MSG_TX:        return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);1625    case MSG_BLOCK:     return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);1626    case MSG_REVIEW:    return true;1627    case MSG_PRODUCT:   return mapProducts.count(inv.hash);1628    }1629    // Don't know what it is, just say we already got one1630    return true;1631}16321633163416351636163716381639bool ProcessMessages(CNode* pfrom)1640{1641    CDataStream& vRecv = pfrom->vRecv;1642    if (vRecv.empty())1643        return true;1644    printf("ProcessMessages(%d bytes)\n", vRecv.size());16451646    //1647    // Message format1648    //  (4) message start1649    //  (12) command1650    //  (4) size1651    //  (x) data1652    //16531654    loop1655    {1656        // Scan for message start1657        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1658        if (vRecv.end() - pstart < sizeof(CMessageHeader))1659        {1660            if (vRecv.size() > sizeof(CMessageHeader))1661            {1662                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1663                vRecv.erase(vRecv.begin(), vRecv.end() - sizeof(CMessageHeader));1664            }1665            break;1666        }1667        if (pstart - vRecv.begin() > 0)1668            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1669        vRecv.erase(vRecv.begin(), pstart);16701671        // Read header1672        CMessageHeader hdr;1673        vRecv >> hdr;1674        if (!hdr.IsValid())1675        {1676            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1677            continue;1678        }1679        string strCommand = hdr.GetCommand();16801681        // Message size1682        unsigned int nMessageSize = hdr.nMessageSize;1683        if (nMessageSize > vRecv.size())1684        {1685            // Rewind and wait for rest of message1686            ///// need a mechanism to give up waiting for overlong message size error1687            printf("MESSAGE-BREAK\n");1688            vRecv.insert(vRecv.begin(), BEGIN(hdr), END(hdr));1689            Sleep(100);1690            break;1691        }16921693        // Copy message to its own buffer1694        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1695        vRecv.ignore(nMessageSize);16961697        // Process message1698        bool fRet = false;1699        try1700        {1701            CheckForShutdown(2);1702            CRITICAL_BLOCK(cs_main)1703                fRet = ProcessMessage(pfrom, strCommand, vMsg);1704            CheckForShutdown(2);1705        }1706        CATCH_PRINT_EXCEPTION("ProcessMessage()")1707        if (!fRet)1708            printf("ProcessMessage(%s, %d bytes) from %s to %s FAILED\n", strCommand.c_str(), nMessageSize, pfrom->addr.ToString().c_str(), addrLocalHost.ToString().c_str());1709    }17101711    vRecv.Compact();1712    return true;1713}17141715171617171718bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1719{1720    static map<unsigned int, vector<unsigned char> > mapReuseKey;1721    printf("received: %-12s (%d bytes)  ", strCommand.c_str(), vRecv.size());1722    for (int i = 0; i < min(vRecv.size(), (unsigned int)20); i++)1723        printf("%02x ", vRecv[i] & 0xff);1724    printf("\n");1725    if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)1726    {1727        printf("dropmessages DROPPING RECV MESSAGE\n");1728        return true;1729    }1730173117321733    if (strCommand == "version")1734    {1735        // Can only do this once1736        if (pfrom->nVersion != 0)1737            return false;17381739        int64 nTime;1740        CAddress addrMe;1741        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;1742        if (pfrom->nVersion == 0)1743            return false;17441745        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));1746        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));17471748        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);1749        if (pfrom->fClient)1750        {1751            pfrom->vSend.nType |= SER_BLOCKHEADERONLY;1752            pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;1753        }17541755        AddTimeData(pfrom->addr.ip, nTime);17561757        // Ask the first connected node for block updates1758        static bool fAskedForBlocks;1759        if (!fAskedForBlocks && !pfrom->fClient)1760        {1761            fAskedForBlocks = true;1762            pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), uint256(0));1763        }17641765        printf("version message: %s has version %d, addrMe=%s\n", pfrom->addr.ToString().c_str(), pfrom->nVersion, addrMe.ToString().c_str());1766    }176717681769    else if (pfrom->nVersion == 0)1770    {1771        // Must have a version message before anything else1772        return false;1773    }177417751776    else if (strCommand == "addr")1777    {1778        vector<CAddress> vAddr;1779        vRecv >> vAddr;17801781        // Store the new addresses1782        CAddrDB addrdb;1783        foreach(const CAddress& addr, vAddr)1784        {1785            if (fShutdown)1786                return true;1787            if (AddAddress(addrdb, addr))1788            {1789                // Put on lists to send to other nodes1790                pfrom->setAddrKnown.insert(addr);1791                CRITICAL_BLOCK(cs_vNodes)1792                    foreach(CNode* pnode, vNodes)1793                        if (!pnode->setAddrKnown.count(addr))1794                            pnode->vAddrToSend.push_back(addr);1795            }1796        }1797    }179817991800    else if (strCommand == "inv")1801    {1802        vector<CInv> vInv;1803        vRecv >> vInv;18041805        CTxDB txdb("r");1806        foreach(const CInv& inv, vInv)1807        {1808            if (fShutdown)1809                return true;1810            pfrom->AddInventoryKnown(inv);18111812            bool fAlreadyHave = AlreadyHave(txdb, inv);1813            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");18141815            if (!fAlreadyHave)1816                pfrom->AskFor(inv);1817            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))1818                pfrom->PushMessage("getblocks", CBlockLocator(pindexBest), GetOrphanRoot(mapOrphanBlocks[inv.hash]));1819        }1820    }182118221823    else if (strCommand == "getdata")1824    {1825        vector<CInv> vInv;1826        vRecv >> vInv;18271828        foreach(const CInv& inv, vInv)1829        {1830            if (fShutdown)1831                return true;1832            printf("received getdata for: %s\n", inv.ToString().c_str());18331834            if (inv.type == MSG_BLOCK)1835            {1836                // Send block from disk1837                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);1838                if (mi != mapBlockIndex.end())1839                {1840                    //// could optimize this to send header straight from blockindex for client1841                    CBlock block;1842                    block.ReadFromDisk((*mi).second, !pfrom->fClient);1843                    pfrom->PushMessage("block", block);1844                }1845            }1846            else if (inv.IsKnownType())1847            {1848                // Send stream from relay memory1849                CRITICAL_BLOCK(cs_mapRelay)1850                {1851                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);1852                    if (mi != mapRelay.end())1853                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);1854                }1855            }1856        }1857    }185818591860    else if (strCommand == "getblocks")1861    {1862        CBlockLocator locator;1863        uint256 hashStop;1864        vRecv >> locator >> hashStop;18651866        // Find the first block the caller has in the main chain1867        CBlockIndex* pindex = locator.GetBlockIndex();18681869        // Send the rest of the chain1870        if (pindex)1871            pindex = pindex->pnext;1872        printf("getblocks %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,14).c_str());1873        for (; pindex; pindex = pindex->pnext)1874        {1875            if (pindex->GetBlockHash() == hashStop)1876            {1877                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,14).c_str());1878                break;1879            }18801881            // Bypass setInventoryKnown in case an inventory message got lost1882            CRITICAL_BLOCK(pfrom->cs_inventory)1883            {1884                CInv inv(MSG_BLOCK, pindex->GetBlockHash());1885                // returns true if wasn't already contained in the set1886                if (pfrom->setInventoryKnown2.insert(inv).second)1887                {1888                    pfrom->setInventoryKnown.erase(inv);1889                    pfrom->vInventoryToSend.push_back(inv);1890                }1891            }1892        }1893    }189418951896    else if (strCommand == "tx")1897    {1898        vector<uint256> vWorkQueue;1899        CDataStream vMsg(vRecv);1900        CTransaction tx;1901        vRecv >> tx;19021903        CInv inv(MSG_TX, tx.GetHash());1904        pfrom->AddInventoryKnown(inv);19051906        bool fMissingInputs = false;1907        if (tx.AcceptTransaction(true, &fMissingInputs))1908        {1909            AddToWalletIfMine(tx, NULL);1910            RelayMessage(inv, vMsg);1911            mapAlreadyAskedFor.erase(inv);1912            vWorkQueue.push_back(inv.hash);19131914            // Recursively process any orphan transactions that depended on this one1915            for (int i = 0; i < vWorkQueue.size(); i++)1916            {1917                uint256 hashPrev = vWorkQueue[i];1918                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);1919                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);1920                     ++mi)1921                {1922                    const CDataStream& vMsg = *((*mi).second);1923                    CTransaction tx;1924                    CDataStream(vMsg) >> tx;1925                    CInv inv(MSG_TX, tx.GetHash());19261927                    if (tx.AcceptTransaction(true))1928                    {1929                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());1930                        AddToWalletIfMine(tx, NULL);1931                        RelayMessage(inv, vMsg);1932                        mapAlreadyAskedFor.erase(inv);1933                        vWorkQueue.push_back(inv.hash);1934                    }1935                }1936            }19371938            foreach(uint256 hash, vWorkQueue)1939                EraseOrphanTx(hash);1940        }1941        else if (fMissingInputs)1942        {1943            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());1944            AddOrphanTx(vMsg);1945        }1946    }194719481949    else if (strCommand == "review")1950    {1951        CDataStream vMsg(vRecv);1952        CReview review;1953        vRecv >> review;19541955        CInv inv(MSG_REVIEW, review.GetHash());1956        pfrom->AddInventoryKnown(inv);19571958        if (review.AcceptReview())1959        {1960            // Relay the original message as-is in case it's a higher version than we know how to parse1961            RelayMessage(inv, vMsg);1962            mapAlreadyAskedFor.erase(inv);1963        }1964    }196519661967    else if (strCommand == "block")1968    {1969        auto_ptr<CBlock> pblock(new CBlock);1970        vRecv >> *pblock;19711972        //// debug print1973        printf("received block:\n"); pblock->print();19741975        CInv inv(MSG_BLOCK, pblock->GetHash());1976        pfrom->AddInventoryKnown(inv);19771978        if (ProcessBlock(pfrom, pblock.release()))1979            mapAlreadyAskedFor.erase(inv);1980    }198119821983    else if (strCommand == "getaddr")1984    {1985        pfrom->vAddrToSend.clear();1986        int64 nSince = GetAdjustedTime() - 5 * 24 * 60 * 60; // in the last 5 days1987        CRITICAL_BLOCK(cs_mapAddresses)1988        {1989            unsigned int nSize = mapAddresses.size();1990            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)1991            {1992                if (fShutdown)1993                    return true;1994                const CAddress& addr = item.second;1995                //// will need this if we lose IRC1996                //if (addr.nTime > nSince || (rand() % nSize) < 500)1997                if (addr.nTime > nSince)1998                    pfrom->vAddrToSend.push_back(addr);1999            }2000        }2001    }200220032004    else if (strCommand == "checkorder")2005    {2006        uint256 hashReply;2007        CWalletTx order;2008        vRecv >> hashReply >> order;20092010        /// we have a chance to check the order here20112012        // Keep giving the same key to the same ip until they use it2013        if (!mapReuseKey.count(pfrom->addr.ip))2014            mapReuseKey[pfrom->addr.ip] = GenerateNewKey();20152016        // Send back approval of order and pubkey to use2017        CScript scriptPubKey;2018        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;2019        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);2020    }202120222023    else if (strCommand == "submitorder")2024    {2025        uint256 hashReply;2026        CWalletTx wtxNew;2027        vRecv >> hashReply >> wtxNew;20282029        // Broadcast2030        if (!wtxNew.AcceptWalletTransaction())2031        {2032            pfrom->PushMessage("reply", hashReply, (int)1);2033            return error("submitorder AcceptWalletTransaction() failed, returning error 1");2034        }2035        wtxNew.fTimeReceivedIsTxTime = true;2036        AddToWallet(wtxNew);2037        wtxNew.RelayWalletTransaction();2038        mapReuseKey.erase(pfrom->addr.ip);20392040        // Send back confirmation2041        pfrom->PushMessage("reply", hashReply, (int)0);2042    }204320442045    else if (strCommand == "reply")2046    {2047        uint256 hashReply;2048        vRecv >> hashReply;20492050        CRequestTracker tracker;2051        CRITICAL_BLOCK(pfrom->cs_mapRequests)2052        {2053            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2054            if (mi != pfrom->mapRequests.end())2055            {2056                tracker = (*mi).second;2057                pfrom->mapRequests.erase(mi);2058            }2059        }2060        if (!tracker.IsNull())2061            tracker.fn(tracker.param1, vRecv);2062    }206320642065    else2066    {2067        // Ignore unknown commands for extensibility2068        printf("ProcessMessage(%s) : Ignored unknown message\n", strCommand.c_str());2069    }207020712072    if (!vRecv.empty())2073        printf("ProcessMessage(%s) : %d extra bytes\n", strCommand.c_str(), vRecv.size());20742075    return true;2076}2077207820792080208120822083208420852086bool SendMessages(CNode* pto)2087{2088    CheckForShutdown(2);2089    CRITICAL_BLOCK(cs_main)2090    {2091        // Don't send anything until we get their version message2092        if (pto->nVersion == 0)2093            return true;209420952096        //2097        // Message: addr2098        //2099        vector<CAddress> vAddrToSend;2100        vAddrToSend.reserve(pto->vAddrToSend.size());2101        foreach(const CAddress& addr, pto->vAddrToSend)2102            if (!pto->setAddrKnown.count(addr))2103                vAddrToSend.push_back(addr);2104        pto->vAddrToSend.clear();2105        if (!vAddrToSend.empty())2106            pto->PushMessage("addr", vAddrToSend);210721082109        //2110        // Message: inventory2111        //2112        vector<CInv> vInventoryToSend;2113        CRITICAL_BLOCK(pto->cs_inventory)2114        {2115            vInventoryToSend.reserve(pto->vInventoryToSend.size());2116            foreach(const CInv& inv, pto->vInventoryToSend)2117            {2118                // returns true if wasn't already contained in the set2119                if (pto->setInventoryKnown.insert(inv).second)2120                    vInventoryToSend.push_back(inv);2121            }2122            pto->vInventoryToSend.clear();2123            pto->setInventoryKnown2.clear();2124        }2125        if (!vInventoryToSend.empty())2126            pto->PushMessage("inv", vInventoryToSend);212721282129        //2130        // Message: getdata2131        //2132        vector<CInv> vAskFor;2133        int64 nNow = GetTime() * 1000000;2134        CTxDB txdb("r");2135        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2136        {2137            const CInv& inv = (*pto->mapAskFor.begin()).second;2138            printf("sending getdata: %s\n", inv.ToString().c_str());2139            if (!AlreadyHave(txdb, inv))2140                vAskFor.push_back(inv);2141            pto->mapAskFor.erase(pto->mapAskFor.begin());2142        }2143        if (!vAskFor.empty())2144            pto->PushMessage("getdata", vAskFor);21452146    }2147    return true;2148}214921502151215221532154215521562157215821592160216121622163//////////////////////////////////////////////////////////////////////////////2164//2165// BitcoinMiner2166//21672168int FormatHashBlocks(void* pbuffer, unsigned int len)2169{2170    unsigned char* pdata = (unsigned char*)pbuffer;2171    unsigned int blocks = 1 + ((len + 8) / 64);2172    unsigned char* pend = pdata + 64 * blocks;2173    memset(pdata + len, 0, 64 * blocks - len);2174    pdata[len] = 0x80;2175    unsigned int bits = len * 8;2176    pend[-1] = (bits >> 0) & 0xff;2177    pend[-2] = (bits >> 8) & 0xff;2178    pend[-3] = (bits >> 16) & 0xff;2179    pend[-4] = (bits >> 24) & 0xff;2180    return blocks;2181}21822183using CryptoPP::ByteReverse;2184static int detectlittleendian = 1;21852186void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)2187{2188    unsigned int* pinput = (unsigned int*)pin;2189    unsigned int* pstate = (unsigned int*)pout;21902191    CryptoPP::SHA256::InitState(pstate);21922193    if (*(char*)&detectlittleendian != 0)2194    {2195        for (int n = 0; n < nBlocks; n++)2196        {2197            unsigned int pbuf[16];2198            for (int i = 0; i < 16; i++)2199                pbuf[i] = ByteReverse(pinput[n * 16 + i]);2200            CryptoPP::SHA256::Transform(pstate, pbuf);2201        }2202        for (int i = 0; i < 8; i++)2203            pstate[i] = ByteReverse(pstate[i]);2204    }2205    else2206    {2207        for (int n = 0; n < nBlocks; n++)2208            CryptoPP::SHA256::Transform(pstate, pinput + n * 16);2209    }2210}221122122213bool BitcoinMiner()2214{2215    printf("BitcoinMiner started\n");2216    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);22172218    CKey key;2219    key.MakeNewKey();2220    CBigNum bnExtraNonce = 0;2221    while (fGenerateBitcoins)2222    {2223        Sleep(50);2224        CheckForShutdown(3);2225        while (vNodes.empty())2226        {2227            Sleep(1000);2228            CheckForShutdown(3);2229        }22302231        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;2232        CBlockIndex* pindexPrev = pindexBest;2233        unsigned int nBits = GetNextWorkRequired(pindexPrev);223422352236        //2237        // Create coinbase tx2238        //2239        CTransaction txNew;2240        txNew.vin.resize(1);2241        txNew.vin[0].prevout.SetNull();2242        txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;2243        txNew.vout.resize(1);2244        txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;224522462247        //2248        // Create new block2249        //2250        auto_ptr<CBlock> pblock(new CBlock());2251        if (!pblock.get())2252            return false;22532254        // Add our coinbase tx as first transaction2255        pblock->vtx.push_back(txNew);22562257        // Collect the latest transactions into the block2258        int64 nFees = 0;2259        CRITICAL_BLOCK(cs_main)2260        CRITICAL_BLOCK(cs_mapTransactions)2261        {2262            CTxDB txdb("r");2263            map<uint256, CTxIndex> mapTestPool;2264            vector<char> vfAlreadyAdded(mapTransactions.size());2265            bool fFoundSomething = true;2266            unsigned int nBlockSize = 0;2267            while (fFoundSomething && nBlockSize < MAX_SIZE/2)2268            {2269                fFoundSomething = false;2270                unsigned int n = 0;2271                for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)2272                {2273                    if (vfAlreadyAdded[n])2274                        continue;2275                    CTransaction& tx = (*mi).second;2276                    if (tx.IsCoinBase() || !tx.IsFinal())2277                        continue;22782279                    // Transaction fee requirements, mainly only needed for flood control2280                    // Under 10K (about 80 inputs) is free for first 100 transactions2281                    // Base rate is 0.01 per KB2282                    int64 nMinFee = tx.GetMinFee(pblock->vtx.size() < 100);22832284                    map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);2285                    if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))2286                        continue;2287                    swap(mapTestPool, mapTestPoolTmp);22882289                    pblock->vtx.push_back(tx);2290                    nBlockSize += ::GetSerializeSize(tx, SER_NETWORK);2291                    vfAlreadyAdded[n] = true;2292                    fFoundSomething = true;2293                }2294            }2295        }2296        pblock->nBits = nBits;2297        pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);2298        printf("\n\nRunning BitcoinMiner with %d transactions in block\n", pblock->vtx.size());229923002301        //2302        // Prebuild hash buffer2303        //2304        struct unnamed12305        {2306            struct unnamed22307            {2308                int nVersion;2309                uint256 hashPrevBlock;2310                uint256 hashMerkleRoot;2311                unsigned int nTime;2312                unsigned int nBits;2313                unsigned int nNonce;2314            }2315            block;2316            unsigned char pchPadding0[64];2317            uint256 hash1;2318            unsigned char pchPadding1[64];2319        }2320        tmp;23212322        tmp.block.nVersion       = pblock->nVersion;2323        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);2324        tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();2325        tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());2326        tmp.block.nBits          = pblock->nBits          = nBits;2327        tmp.block.nNonce         = pblock->nNonce         = 1;23282329        unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));2330        unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));233123322333        //2334        // Search2335        //2336        unsigned int nStart = GetTime();2337        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();2338        uint256 hash;2339        loop2340        {2341            BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);2342            BlockSHA256(&tmp.hash1, nBlocks1, &hash);234323442345            if (hash <= hashTarget)2346            {2347                pblock->nNonce = tmp.block.nNonce;2348                assert(hash == pblock->GetHash());23492350                    //// debug print2351                    printf("BitcoinMiner:\n");2352                    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());2353                    pblock->print();23542355                SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);2356                CRITICAL_BLOCK(cs_main)2357                {2358                    // Save key2359                    if (!AddKey(key))2360                        return false;2361                    key.MakeNewKey();23622363                    // Process this block the same as if we had received it from another node2364                    if (!ProcessBlock(NULL, pblock.release()))2365                        printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");2366                }2367                SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);23682369                Sleep(500);2370                break;2371            }23722373            // Update nTime every few seconds2374            if ((++tmp.block.nNonce & 0x3ffff) == 0)2375            {2376                CheckForShutdown(3);2377                if (tmp.block.nNonce == 0)2378                    break;2379                if (pindexPrev != pindexBest)2380                    break;2381                if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)2382                    break;2383                if (!fGenerateBitcoins)2384                    break;2385                tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());2386            }2387        }2388    }23892390    return true;2391}2392239323942395239623972398239924002401240224032404240524062407240824092410//////////////////////////////////////////////////////////////////////////////2411//2412// Actions2413//241424152416int64 GetBalance()2417{2418    int64 nStart, nEnd;2419    QueryPerformanceCounter((LARGE_INTEGER*)&nStart);24202421    int64 nTotal = 0;2422    CRITICAL_BLOCK(cs_mapWallet)2423    {2424        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2425        {2426            CWalletTx* pcoin = &(*it).second;2427            if (!pcoin->IsFinal() || pcoin->fSpent)2428                continue;2429            nTotal += pcoin->GetCredit();2430        }2431    }24322433    QueryPerformanceCounter((LARGE_INTEGER*)&nEnd);2434    ///printf(" GetBalance() time = %16I64d\n", nEnd - nStart);2435    return nTotal;2436}2437243824392440bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)2441{2442    setCoinsRet.clear();24432444    // List of values less than target2445    int64 nLowestLarger = _I64_MAX;2446    CWalletTx* pcoinLowestLarger = NULL;2447    vector<pair<int64, CWalletTx*> > vValue;2448    int64 nTotalLower = 0;24492450    CRITICAL_BLOCK(cs_mapWallet)2451    {2452        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2453        {2454            CWalletTx* pcoin = &(*it).second;2455            if (!pcoin->IsFinal() || pcoin->fSpent)2456                continue;2457            int64 n = pcoin->GetCredit();2458            if (n <= 0)2459                continue;2460            if (n < nTargetValue)2461            {2462                vValue.push_back(make_pair(n, pcoin));2463                nTotalLower += n;2464            }2465            else if (n == nTargetValue)2466            {2467                setCoinsRet.insert(pcoin);2468                return true;2469            }2470            else if (n < nLowestLarger)2471            {2472                nLowestLarger = n;2473                pcoinLowestLarger = pcoin;2474            }2475        }2476    }24772478    if (nTotalLower < nTargetValue)2479    {2480        if (pcoinLowestLarger == NULL)2481            return false;2482        setCoinsRet.insert(pcoinLowestLarger);2483        return true;2484    }24852486    // Solve subset sum by stochastic approximation2487    sort(vValue.rbegin(), vValue.rend());2488    vector<char> vfIncluded;2489    vector<char> vfBest(vValue.size(), true);2490    int64 nBest = nTotalLower;24912492    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)2493    {2494        vfIncluded.assign(vValue.size(), false);2495        int64 nTotal = 0;2496        bool fReachedTarget = false;2497        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)2498        {2499            for (int i = 0; i < vValue.size(); i++)2500            {2501                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])2502                {2503                    nTotal += vValue[i].first;2504                    vfIncluded[i] = true;2505                    if (nTotal >= nTargetValue)2506                    {2507                        fReachedTarget = true;2508                        if (nTotal < nBest)2509                        {2510                            nBest = nTotal;2511                            vfBest = vfIncluded;2512                        }2513                        nTotal -= vValue[i].first;2514                        vfIncluded[i] = false;2515                    }2516                }2517            }2518        }2519    }25202521    // If the next larger is still closer, return it2522    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)2523        setCoinsRet.insert(pcoinLowestLarger);2524    else2525    {2526        for (int i = 0; i < vValue.size(); i++)2527            if (vfBest[i])2528                setCoinsRet.insert(vValue[i].second);25292530        //// debug print2531        printf("SelectCoins() best subset: ");2532        for (int i = 0; i < vValue.size(); i++)2533            if (vfBest[i])2534                printf("%s ", FormatMoney(vValue[i].first).c_str());2535        printf("total %s\n", FormatMoney(nBest).c_str());2536    }25372538    return true;2539}25402541254225432544bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, int64& nFeeRequiredRet)2545{2546    nFeeRequiredRet = 0;2547    CRITICAL_BLOCK(cs_main)2548    {2549        // txdb must be opened before the mapWallet lock2550        CTxDB txdb("r");2551        CRITICAL_BLOCK(cs_mapWallet)2552        {2553            int64 nFee = nTransactionFee;2554            loop2555            {2556                wtxNew.vin.clear();2557                wtxNew.vout.clear();2558                if (nValue < 0)2559                    return false;2560                int64 nValueOut = nValue;2561                nValue += nFee;25622563                // Choose coins to use2564                set<CWalletTx*> setCoins;2565                if (!SelectCoins(nValue, setCoins))2566                    return false;2567                int64 nValueIn = 0;2568                foreach(CWalletTx* pcoin, setCoins)2569                    nValueIn += pcoin->GetCredit();25702571                // Fill vout[0] to the payee2572                wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));25732574                // Fill vout[1] back to self with any change2575                if (nValueIn > nValue)2576                {2577                    /// todo: for privacy, should randomize the order of outputs,2578                    //        would also have to use a new key for the change.2579                    // Use the same key as one of the coins2580                    vector<unsigned char> vchPubKey;2581                    CTransaction& txFirst = *(*setCoins.begin());2582                    foreach(const CTxOut& txout, txFirst.vout)2583                        if (txout.IsMine())2584                            if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))2585                                break;2586                    if (vchPubKey.empty())2587                        return false;25882589                    // Fill vout[1] to ourself2590                    CScript scriptPubKey;2591                    scriptPubKey << vchPubKey << OP_CHECKSIG;2592                    wtxNew.vout.push_back(CTxOut(nValueIn - nValue, scriptPubKey));2593                }25942595                // Fill vin2596                foreach(CWalletTx* pcoin, setCoins)2597                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2598                        if (pcoin->vout[nOut].IsMine())2599                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));26002601                // Sign2602                int nIn = 0;2603                foreach(CWalletTx* pcoin, setCoins)2604                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)2605                        if (pcoin->vout[nOut].IsMine())2606                            SignSignature(*pcoin, wtxNew, nIn++);26072608                // Check that enough fee is included2609                if (nFee < wtxNew.GetMinFee(true))2610                {2611                    nFee = nFeeRequiredRet = wtxNew.GetMinFee(true);2612                    continue;2613                }26142615                // Fill vtxPrev by copying from previous transactions vtxPrev2616                wtxNew.AddSupportingTransactions(txdb);2617                wtxNew.fTimeReceivedIsTxTime = true;26182619                break;2620            }2621        }2622    }2623    return true;2624}26252626// Call after CreateTransaction unless you want to abort2627bool CommitTransactionSpent(const CWalletTx& wtxNew)2628{2629    CRITICAL_BLOCK(cs_main)2630    CRITICAL_BLOCK(cs_mapWallet)2631    {2632        //// todo: make this transactional, never want to add a transaction2633        ////  without marking spent transactions26342635        // Add tx to wallet, because if it has change it's also ours,2636        // otherwise just for transaction history.2637        AddToWallet(wtxNew);26382639        // Mark old coins as spent2640        set<CWalletTx*> setCoins;2641        foreach(const CTxIn& txin, wtxNew.vin)2642            setCoins.insert(&mapWallet[txin.prevout.hash]);2643        foreach(CWalletTx* pcoin, setCoins)2644        {2645            pcoin->fSpent = true;2646            pcoin->WriteToDisk();2647            vWalletUpdated.push_back(make_pair(pcoin->GetHash(), false));2648        }2649    }2650    MainFrameRepaint();2651    return true;2652}26532654265526562657bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)2658{2659    CRITICAL_BLOCK(cs_main)2660    {2661        int64 nFeeRequired;2662        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, nFeeRequired))2663        {2664            string strError;2665            if (nValue + nFeeRequired > GetBalance())2666                strError = strprintf("Error: This is an oversized transaction that requires a transaction fee of %s  ", FormatMoney(nFeeRequired).c_str());2667            else2668                strError = "Error: Transaction creation failed  ";2669            wxMessageBox(strError, "Sending...");2670            return error("SendMoney() : %s\n", strError.c_str());2671        }2672        if (!CommitTransactionSpent(wtxNew))2673        {2674            wxMessageBox("Error finalizing transaction  ", "Sending...");2675            return error("SendMoney() : Error finalizing transaction");2676        }26772678        printf("SendMoney: %s\n", wtxNew.GetHash().ToString().substr(0,6).c_str());26792680        // Broadcast2681        if (!wtxNew.AcceptTransaction())2682        {2683            // This must not fail. The transaction has already been signed and recorded.2684            throw runtime_error("SendMoney() : wtxNew.AcceptTransaction() failed\n");2685            wxMessageBox("Error: Transaction not valid  ", "Sending...");2686            return error("SendMoney() : Error: Transaction not valid");2687        }2688        wtxNew.RelayWalletTransaction();2689    }2690    MainFrameRepaint();2691    return true;2692}

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