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

main.cpp

3,228 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#include "cryptopp/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;27CBigNum bnBestChainWork = 0;28CBigNum bnBestInvalidWork = 0;29uint256 hashBestChain = 0;30CBlockIndex* pindexBest = NULL;31int64 nTimeBestReceived = 0;3233map<uint256, CBlock*> mapOrphanBlocks;34multimap<uint256, CBlock*> mapOrphanBlocksByPrev;3536map<uint256, CDataStream*> mapOrphanTransactions;37multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;3839map<uint256, CWalletTx> mapWallet;40vector<uint256> vWalletUpdated;41CCriticalSection cs_mapWallet;4243map<vector<unsigned char>, CPrivKey> mapKeys;44map<uint160, vector<unsigned char> > mapPubKeys;45CCriticalSection cs_mapKeys;46CKey keyUser;4748map<uint256, int> mapRequestCount;49CCriticalSection cs_mapRequestCount;5051map<string, string> mapAddressBook;52CCriticalSection cs_mapAddressBook;5354vector<unsigned char> vchDefaultKey;5556double dHashesPerSec;57int64 nHPSTimerStart;5859// Settings60int fGenerateBitcoins = false;61int64 nTransactionFee = 0;62CAddress addrIncoming;63int fLimitProcessors = false;64int nLimitProcessors = 1;65int fMinimizeToTray = true;66int fMinimizeOnClose = true;67686970717273//////////////////////////////////////////////////////////////////////////////74//75// mapKeys76//7778bool AddKey(const CKey& key)79{80    CRITICAL_BLOCK(cs_mapKeys)81    {82        mapKeys[key.GetPubKey()] = key.GetPrivKey();83        mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();84    }85    return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());86}8788vector<unsigned char> GenerateNewKey()89{90    RandAddSeedPerfmon();91    CKey key;92    key.MakeNewKey();93    if (!AddKey(key))94        throw runtime_error("GenerateNewKey() : AddKey failed\n");95    return key.GetPubKey();96}979899100101//////////////////////////////////////////////////////////////////////////////102//103// mapWallet104//105106bool AddToWallet(const CWalletTx& wtxIn)107{108    uint256 hash = wtxIn.GetHash();109    CRITICAL_BLOCK(cs_mapWallet)110    {111        // Inserts only if not already there, returns tx inserted or tx found112        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));113        CWalletTx& wtx = (*ret.first).second;114        bool fInsertedNew = ret.second;115        if (fInsertedNew)116            wtx.nTimeReceived = GetAdjustedTime();117118        bool fUpdated = false;119        if (!fInsertedNew)120        {121            // Merge122            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)123            {124                wtx.hashBlock = wtxIn.hashBlock;125                fUpdated = true;126            }127            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))128            {129                wtx.vMerkleBranch = wtxIn.vMerkleBranch;130                wtx.nIndex = wtxIn.nIndex;131                fUpdated = true;132            }133            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)134            {135                wtx.fFromMe = wtxIn.fFromMe;136                fUpdated = true;137            }138            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)139            {140                wtx.fSpent = wtxIn.fSpent;141                fUpdated = true;142            }143        }144145        //// debug print146        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));147148        // Write to disk149        if (fInsertedNew || fUpdated)150            if (!wtx.WriteToDisk())151                return false;152153        // If default receiving address gets used, replace it with a new one154        CScript scriptDefaultKey;155        scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);156        foreach(const CTxOut& txout, wtx.vout)157        {158            if (txout.scriptPubKey == scriptDefaultKey)159            {160                CWalletDB walletdb;161                walletdb.WriteDefaultKey(GenerateNewKey());162                walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");163            }164        }165166        // Notify UI167        vWalletUpdated.push_back(hash);168    }169170    // Refresh UI171    MainFrameRepaint();172    return true;173}174175bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)176{177    if (tx.IsMine() || mapWallet.count(tx.GetHash()))178    {179        CWalletTx wtx(tx);180        // Get merkle branch if transaction was found in a block181        if (pblock)182            wtx.SetMerkleBranch(pblock);183        return AddToWallet(wtx);184    }185    return true;186}187188bool EraseFromWallet(uint256 hash)189{190    CRITICAL_BLOCK(cs_mapWallet)191    {192        if (mapWallet.erase(hash))193            CWalletDB().EraseTx(hash);194    }195    return true;196}197198void WalletUpdateSpent(const COutPoint& prevout)199{200    // Anytime a signature is successfully verified, it's proof the outpoint is spent.201    // Update the wallet spent flag if it doesn't know due to wallet.dat being202    // restored from backup or the user making copies of wallet.dat.203    CRITICAL_BLOCK(cs_mapWallet)204    {205        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);206        if (mi != mapWallet.end())207        {208            CWalletTx& wtx = (*mi).second;209            if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())210            {211                printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());212                wtx.fSpent = true;213                wtx.WriteToDisk();214                vWalletUpdated.push_back(prevout.hash);215            }216        }217    }218}219220221222223224225226227//////////////////////////////////////////////////////////////////////////////228//229// mapOrphanTransactions230//231232void AddOrphanTx(const CDataStream& vMsg)233{234    CTransaction tx;235    CDataStream(vMsg) >> tx;236    uint256 hash = tx.GetHash();237    if (mapOrphanTransactions.count(hash))238        return;239    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);240    foreach(const CTxIn& txin, tx.vin)241        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));242}243244void EraseOrphanTx(uint256 hash)245{246    if (!mapOrphanTransactions.count(hash))247        return;248    const CDataStream* pvMsg = mapOrphanTransactions[hash];249    CTransaction tx;250    CDataStream(*pvMsg) >> tx;251    foreach(const CTxIn& txin, tx.vin)252    {253        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);254             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)255        {256            if ((*mi).second == pvMsg)257                mapOrphanTransactionsByPrev.erase(mi++);258            else259                mi++;260        }261    }262    delete pvMsg;263    mapOrphanTransactions.erase(hash);264}265266267268269270271272273//////////////////////////////////////////////////////////////////////////////274//275// CTransaction276//277278bool CTxIn::IsMine() const279{280    CRITICAL_BLOCK(cs_mapWallet)281    {282        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);283        if (mi != mapWallet.end())284        {285            const CWalletTx& prev = (*mi).second;286            if (prevout.n < prev.vout.size())287                if (prev.vout[prevout.n].IsMine())288                    return true;289        }290    }291    return false;292}293294int64 CTxIn::GetDebit() const295{296    CRITICAL_BLOCK(cs_mapWallet)297    {298        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);299        if (mi != mapWallet.end())300        {301            const CWalletTx& prev = (*mi).second;302            if (prevout.n < prev.vout.size())303                if (prev.vout[prevout.n].IsMine())304                    return prev.vout[prevout.n].nValue;305        }306    }307    return 0;308}309310int64 CWalletTx::GetTxTime() const311{312    if (!fTimeReceivedIsTxTime && hashBlock != 0)313    {314        // If we did not receive the transaction directly, we rely on the block's315        // time to figure out when it happened.  We use the median over a range316        // of blocks to try to filter out inaccurate block times.317        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);318        if (mi != mapBlockIndex.end())319        {320            CBlockIndex* pindex = (*mi).second;321            if (pindex)322                return pindex->GetMedianTime();323        }324    }325    return nTimeReceived;326}327328int CWalletTx::GetRequestCount() const329{330    // Returns -1 if it wasn't being tracked331    int nRequests = -1;332    CRITICAL_BLOCK(cs_mapRequestCount)333    {334        if (IsCoinBase())335        {336            // Generated block337            if (hashBlock != 0)338            {339                map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);340                if (mi != mapRequestCount.end())341                    nRequests = (*mi).second;342            }343        }344        else345        {346            // Did anyone request this transaction?347            map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());348            if (mi != mapRequestCount.end())349            {350                nRequests = (*mi).second;351352                // How about the block it's in?353                if (nRequests == 0 && hashBlock != 0)354                {355                    map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);356                    if (mi != mapRequestCount.end())357                        nRequests = (*mi).second;358                    else359                        nRequests = 1; // If it's in someone else's block it must have got out360                }361            }362        }363    }364    return nRequests;365}366367368369370int CMerkleTx::SetMerkleBranch(const CBlock* pblock)371{372    if (fClient)373    {374        if (hashBlock == 0)375            return 0;376    }377    else378    {379        CBlock blockTmp;380        if (pblock == NULL)381        {382            // Load the block this tx is in383            CTxIndex txindex;384            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))385                return 0;386            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))387                return 0;388            pblock = &blockTmp;389        }390391        // Update the tx's hashBlock392        hashBlock = pblock->GetHash();393394        // Locate the transaction395        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)396            if (pblock->vtx[nIndex] == *(CTransaction*)this)397                break;398        if (nIndex == pblock->vtx.size())399        {400            vMerkleBranch.clear();401            nIndex = -1;402            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");403            return 0;404        }405406        // Fill in merkle branch407        vMerkleBranch = pblock->GetMerkleBranch(nIndex);408    }409410    // Is the tx in a block that's in the main chain411    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);412    if (mi == mapBlockIndex.end())413        return 0;414    CBlockIndex* pindex = (*mi).second;415    if (!pindex || !pindex->IsInMainChain())416        return 0;417418    return pindexBest->nHeight - pindex->nHeight + 1;419}420421422423void CWalletTx::AddSupportingTransactions(CTxDB& txdb)424{425    vtxPrev.clear();426427    const int COPY_DEPTH = 3;428    if (SetMerkleBranch() < COPY_DEPTH)429    {430        vector<uint256> vWorkQueue;431        foreach(const CTxIn& txin, vin)432            vWorkQueue.push_back(txin.prevout.hash);433434        // This critsect is OK because txdb is already open435        CRITICAL_BLOCK(cs_mapWallet)436        {437            map<uint256, const CMerkleTx*> mapWalletPrev;438            set<uint256> setAlreadyDone;439            for (int i = 0; i < vWorkQueue.size(); i++)440            {441                uint256 hash = vWorkQueue[i];442                if (setAlreadyDone.count(hash))443                    continue;444                setAlreadyDone.insert(hash);445446                CMerkleTx tx;447                if (mapWallet.count(hash))448                {449                    tx = mapWallet[hash];450                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)451                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;452                }453                else if (mapWalletPrev.count(hash))454                {455                    tx = *mapWalletPrev[hash];456                }457                else if (!fClient && txdb.ReadDiskTx(hash, tx))458                {459                    ;460                }461                else462                {463                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");464                    continue;465                }466467                int nDepth = tx.SetMerkleBranch();468                vtxPrev.push_back(tx);469470                if (nDepth < COPY_DEPTH)471                    foreach(const CTxIn& txin, tx.vin)472                        vWorkQueue.push_back(txin.prevout.hash);473            }474        }475    }476477    reverse(vtxPrev.begin(), vtxPrev.end());478}479480481482483484485486487488489490bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)491{492    if (pfMissingInputs)493        *pfMissingInputs = false;494495    // Coinbase is only valid in a block, not as a loose transaction496    if (IsCoinBase())497        return error("AcceptTransaction() : coinbase as individual tx");498499    if (!CheckTransaction())500        return error("AcceptTransaction() : CheckTransaction failed");501502    // To help v0.1.5 clients who would see it as a negative number503    if (nLockTime > INT_MAX)504        return error("AcceptTransaction() : not accepting nLockTime beyond 2038");505506    // Do we already have it?507    uint256 hash = GetHash();508    CRITICAL_BLOCK(cs_mapTransactions)509        if (mapTransactions.count(hash))510            return false;511    if (fCheckInputs)512        if (txdb.ContainsTx(hash))513            return false;514515    // Check for conflicts with in-memory transactions516    CTransaction* ptxOld = NULL;517    for (int i = 0; i < vin.size(); i++)518    {519        COutPoint outpoint = vin[i].prevout;520        if (mapNextTx.count(outpoint))521        {522            // Allow replacing with a newer version of the same transaction523            if (i != 0)524                return false;525            ptxOld = mapNextTx[outpoint].ptx;526            if (!IsNewerThan(*ptxOld))527                return false;528            for (int i = 0; i < vin.size(); i++)529            {530                COutPoint outpoint = vin[i].prevout;531                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)532                    return false;533            }534            break;535        }536    }537538    // Check against previous transactions539    map<uint256, CTxIndex> mapUnused;540    int64 nFees = 0;541    if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))542    {543        if (pfMissingInputs)544            *pfMissingInputs = true;545        return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());546    }547548    // Store transaction in memory549    CRITICAL_BLOCK(cs_mapTransactions)550    {551        if (ptxOld)552        {553            printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());554            mapTransactions.erase(ptxOld->GetHash());555        }556        AddToMemoryPool();557    }558559    ///// are we sure this is ok when loading transactions or restoring block txes560    // If updated, erase old tx from wallet561    if (ptxOld)562        EraseFromWallet(ptxOld->GetHash());563564    printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());565    return true;566}567568569bool CTransaction::AddToMemoryPool()570{571    // Add to memory pool without checking anything.  Don't call this directly,572    // call AcceptTransaction to properly check the transaction first.573    CRITICAL_BLOCK(cs_mapTransactions)574    {575        uint256 hash = GetHash();576        mapTransactions[hash] = *this;577        for (int i = 0; i < vin.size(); i++)578            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);579        nTransactionsUpdated++;580    }581    return true;582}583584585bool CTransaction::RemoveFromMemoryPool()586{587    // Remove transaction from memory pool588    CRITICAL_BLOCK(cs_mapTransactions)589    {590        foreach(const CTxIn& txin, vin)591            mapNextTx.erase(txin.prevout);592        mapTransactions.erase(GetHash());593        nTransactionsUpdated++;594    }595    return true;596}597598599600601602603int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const604{605    if (hashBlock == 0 || nIndex == -1)606        return 0;607608    // Find the block it claims to be in609    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);610    if (mi == mapBlockIndex.end())611        return 0;612    CBlockIndex* pindex = (*mi).second;613    if (!pindex || !pindex->IsInMainChain())614        return 0;615616    // Make sure the merkle branch connects to this block617    if (!fMerkleVerified)618    {619        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)620            return 0;621        fMerkleVerified = true;622    }623624    nHeightRet = pindex->nHeight;625    return pindexBest->nHeight - pindex->nHeight + 1;626}627628629int CMerkleTx::GetBlocksToMaturity() const630{631    if (!IsCoinBase())632        return 0;633    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());634}635636637bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)638{639    if (fClient)640    {641        if (!IsInMainChain() && !ClientConnectInputs())642            return false;643        return CTransaction::AcceptTransaction(txdb, false);644    }645    else646    {647        return CTransaction::AcceptTransaction(txdb, fCheckInputs);648    }649}650651652653bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)654{655    CRITICAL_BLOCK(cs_mapTransactions)656    {657        foreach(CMerkleTx& tx, vtxPrev)658        {659            if (!tx.IsCoinBase())660            {661                uint256 hash = tx.GetHash();662                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))663                    tx.AcceptTransaction(txdb, fCheckInputs);664            }665        }666        if (!IsCoinBase())667            return AcceptTransaction(txdb, fCheckInputs);668    }669    return true;670}671672void ReacceptWalletTransactions()673{674    CTxDB txdb("r");675    CRITICAL_BLOCK(cs_mapWallet)676    {677        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)678        {679            CWalletTx& wtx = item.second;680            if (wtx.fSpent && wtx.IsCoinBase())681                continue;682683            CTxIndex txindex;684            if (txdb.ReadTxIndex(wtx.GetHash(), txindex))685            {686                // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat687                if (!wtx.fSpent)688                {689                    if (txindex.vSpent.size() != wtx.vout.size())690                    {691                        printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());692                        continue;693                    }694                    for (int i = 0; i < txindex.vSpent.size(); i++)695                    {696                        if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())697                        {698                            printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());699                            wtx.fSpent = true;700                            wtx.WriteToDisk();701                            break;702                        }703                    }704                }705            }706            else707            {708                // Reaccept any txes of ours that aren't already in a block709                if (!wtx.IsCoinBase())710                    wtx.AcceptWalletTransaction(txdb, false);711            }712        }713    }714}715716717void CWalletTx::RelayWalletTransaction(CTxDB& txdb)718{719    foreach(const CMerkleTx& tx, vtxPrev)720    {721        if (!tx.IsCoinBase())722        {723            uint256 hash = tx.GetHash();724            if (!txdb.ContainsTx(hash))725                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);726        }727    }728    if (!IsCoinBase())729    {730        uint256 hash = GetHash();731        if (!txdb.ContainsTx(hash))732        {733            printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());734            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);735        }736    }737}738739void ResendWalletTransactions()740{741    // Do this infrequently and randomly to avoid giving away742    // that these are our transactions.743    static int64 nNextTime;744    if (GetTime() < nNextTime)745        return;746    bool fFirst = (nNextTime == 0);747    nNextTime = GetTime() + GetRand(30 * 60);748    if (fFirst)749        return;750751    // Rebroadcast any of our txes that aren't in a block yet752    printf("ResendWalletTransactions()\n");753    CTxDB txdb("r");754    CRITICAL_BLOCK(cs_mapWallet)755    {756        // Sort them in chronological order757        multimap<unsigned int, CWalletTx*> mapSorted;758        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)759        {760            CWalletTx& wtx = item.second;761            // Don't rebroadcast until it's had plenty of time that762            // it should have gotten in already by now.763            if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)764                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));765        }766        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)767        {768            CWalletTx& wtx = *item.second;769            wtx.RelayWalletTransaction(txdb);770        }771    }772}773774775776777778779780781782783//////////////////////////////////////////////////////////////////////////////784//785// CBlock and CBlockIndex786//787788bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)789{790    return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);791}792793uint256 GetOrphanRoot(const CBlock* pblock)794{795    // Work back to the first block in the orphan chain796    while (mapOrphanBlocks.count(pblock->hashPrevBlock))797        pblock = mapOrphanBlocks[pblock->hashPrevBlock];798    return pblock->GetHash();799}800801int64 CBlock::GetBlockValue(int nHeight, int64 nFees) const802{803    int64 nSubsidy = 50 * COIN;804805    // Subsidy is cut in half every 4 years806    nSubsidy >>= (nHeight / 210000);807808    return nSubsidy + nFees;809}810811unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)812{813    const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks814    const int64 nTargetSpacing = 10 * 60;815    const int64 nInterval = nTargetTimespan / nTargetSpacing;816817    // Genesis block818    if (pindexLast == NULL)819        return bnProofOfWorkLimit.GetCompact();820821    // Only change once per interval822    if ((pindexLast->nHeight+1) % nInterval != 0)823        return pindexLast->nBits;824825    // Go back by what we want to be 14 days worth of blocks826    const CBlockIndex* pindexFirst = pindexLast;827    for (int i = 0; pindexFirst && i < nInterval-1; i++)828        pindexFirst = pindexFirst->pprev;829    assert(pindexFirst);830831    // Limit adjustment step832    int64 nActualTimespan = (int64)pindexLast->nTime - (int64)pindexFirst->nTime;833    printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);834    if (nActualTimespan < nTargetTimespan/4)835        nActualTimespan = nTargetTimespan/4;836    if (nActualTimespan > nTargetTimespan*4)837        nActualTimespan = nTargetTimespan*4;838839    // Retarget840    CBigNum bnNew;841    bnNew.SetCompact(pindexLast->nBits);842    bnNew *= nActualTimespan;843    bnNew /= nTargetTimespan;844845    if (bnNew > bnProofOfWorkLimit)846        bnNew = bnProofOfWorkLimit;847848    /// debug print849    printf("GetNextWorkRequired RETARGET\n");850    printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);851    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());852    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());853854    return bnNew.GetCompact();855}856857bool IsInitialBlockDownload()858{859    if (pindexBest == NULL)860        return true;861    static int64 nLastUpdate;862    static CBlockIndex* pindexLastBest;863    if (pindexBest != pindexLastBest)864    {865        pindexLastBest = pindexBest;866        nLastUpdate = GetTime();867    }868    return (GetTime() - nLastUpdate < 10 &&869            pindexBest->nTime < GetTime() - 24 * 60 * 60);870}871872bool IsLockdown()873{874    if (!pindexBest)875        return false;876    return (bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6);877}878879void Lockdown(CBlockIndex* pindexNew)880{881    if (pindexNew->bnChainWork > bnBestInvalidWork)882    {883        bnBestInvalidWork = pindexNew->bnChainWork;884        CTxDB().WriteBestInvalidWork(bnBestInvalidWork);885        MainFrameRepaint();886    }887    printf("Lockdown: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,22).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());888    printf("Lockdown:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());889    printf("Lockdown: IsLockdown()=%d\n", (IsLockdown() ? 1 : 0));890    if (IsLockdown())891        printf("Lockdown: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");892}893894895896897898899900901bool CTransaction::DisconnectInputs(CTxDB& txdb)902{903    // Relinquish previous transactions' spent pointers904    if (!IsCoinBase())905    {906        foreach(const CTxIn& txin, vin)907        {908            COutPoint prevout = txin.prevout;909910            // Get prev txindex from disk911            CTxIndex txindex;912            if (!txdb.ReadTxIndex(prevout.hash, txindex))913                return error("DisconnectInputs() : ReadTxIndex failed");914915            if (prevout.n >= txindex.vSpent.size())916                return error("DisconnectInputs() : prevout.n out of range");917918            // Mark outpoint as not spent919            txindex.vSpent[prevout.n].SetNull();920921            // Write back922            txdb.UpdateTxIndex(prevout.hash, txindex);923        }924    }925926    // Remove transaction from index927    if (!txdb.EraseTxIndex(*this))928        return error("DisconnectInputs() : EraseTxPos failed");929930    return true;931}932933934bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,935                                 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)936{937    // Take over previous transactions' spent pointers938    if (!IsCoinBase())939    {940        int64 nValueIn = 0;941        for (int i = 0; i < vin.size(); i++)942        {943            COutPoint prevout = vin[i].prevout;944945            // Read txindex946            CTxIndex txindex;947            bool fFound = true;948            if (fMiner && mapTestPool.count(prevout.hash))949            {950                // Get txindex from current proposed changes951                txindex = mapTestPool[prevout.hash];952            }953            else954            {955                // Read txindex from txdb956                fFound = txdb.ReadTxIndex(prevout.hash, txindex);957            }958            if (!fFound && (fBlock || fMiner))959                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());960961            // Read txPrev962            CTransaction txPrev;963            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))964            {965                // Get prev tx from single transactions in memory966                CRITICAL_BLOCK(cs_mapTransactions)967                {968                    if (!mapTransactions.count(prevout.hash))969                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());970                    txPrev = mapTransactions[prevout.hash];971                }972                if (!fFound)973                    txindex.vSpent.resize(txPrev.vout.size());974            }975            else976            {977                // Get prev tx from disk978                if (!txPrev.ReadFromDisk(txindex.pos))979                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(),  prevout.hash.ToString().substr(0,6).c_str());980            }981982            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())983                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());984985            // If prev is coinbase, check that it's matured986            if (txPrev.IsCoinBase())987                for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)988                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)989                        return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);990991            // Verify signature992            if (!VerifySignature(txPrev, *this, i))993                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());994995            // Check for conflicts996            if (!txindex.vSpent[prevout.n].IsNull())997                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());998999            // Mark outpoints as spent1000            txindex.vSpent[prevout.n] = posThisTx;10011002            // Write back1003            if (fBlock)1004                txdb.UpdateTxIndex(prevout.hash, txindex);1005            else if (fMiner)1006                mapTestPool[prevout.hash] = txindex;10071008            nValueIn += txPrev.vout[prevout.n].nValue;10091010            // Check for negative or overflow input values1011            if (txPrev.vout[prevout.n].nValue < 0)1012                return error("ConnectInputs() : txin.nValue negative");1013            if (txPrev.vout[prevout.n].nValue > MAX_MONEY)1014                return error("ConnectInputs() : txin.nValue too high");1015            if (nValueIn > MAX_MONEY)1016                return error("ConnectInputs() : txin total too high");1017        }10181019        // Tally transaction fees1020        int64 nTxFee = nValueIn - GetValueOut();1021        if (nTxFee < 0)1022            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());1023        if (nTxFee < nMinFee)1024            return false;1025        nFees += nTxFee;1026    }10271028    if (fBlock)1029    {1030        // Add transaction to disk index1031        if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))1032            return error("ConnectInputs() : AddTxPos failed");1033    }1034    else if (fMiner)1035    {1036        // Add transaction to test pool1037        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());1038    }10391040    return true;1041}104210431044bool CTransaction::ClientConnectInputs()1045{1046    if (IsCoinBase())1047        return false;10481049    // Take over previous transactions' spent pointers1050    CRITICAL_BLOCK(cs_mapTransactions)1051    {1052        int64 nValueIn = 0;1053        for (int i = 0; i < vin.size(); i++)1054        {1055            // Get prev tx from single transactions in memory1056            COutPoint prevout = vin[i].prevout;1057            if (!mapTransactions.count(prevout.hash))1058                return false;1059            CTransaction& txPrev = mapTransactions[prevout.hash];10601061            if (prevout.n >= txPrev.vout.size())1062                return false;10631064            // Verify signature1065            if (!VerifySignature(txPrev, *this, i))1066                return error("ConnectInputs() : VerifySignature failed");10671068            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of1069            ///// this has to go away now that posNext is gone1070            // // Check for conflicts1071            // if (!txPrev.vout[prevout.n].posNext.IsNull())1072            //     return error("ConnectInputs() : prev tx already used");1073            //1074            // // Flag outpoints as used1075            // txPrev.vout[prevout.n].posNext = posThisTx;10761077            nValueIn += txPrev.vout[prevout.n].nValue;1078        }1079        if (GetValueOut() > nValueIn)1080            return false;1081    }10821083    return true;1084}10851086108710881089bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)1090{1091    // Disconnect in reverse order1092    for (int i = vtx.size()-1; i >= 0; i--)1093        if (!vtx[i].DisconnectInputs(txdb))1094            return false;10951096    // Update block index on disk without changing it in memory.1097    // The memory index structure will be changed after the db commits.1098    if (pindex->pprev)1099    {1100        CDiskBlockIndex blockindexPrev(pindex->pprev);1101        blockindexPrev.hashNext = 0;1102        txdb.WriteBlockIndex(blockindexPrev);1103    }11041105    return true;1106}11071108bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)1109{1110    //// issue here: it doesn't know the version1111    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());11121113    map<uint256, CTxIndex> mapUnused;1114    int64 nFees = 0;1115    foreach(CTransaction& tx, vtx)1116    {1117        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);1118        nTxPos += ::GetSerializeSize(tx, SER_DISK);11191120        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))1121            return false;1122    }11231124    if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))1125        return false;11261127    // Update block index on disk without changing it in memory.1128    // The memory index structure will be changed after the db commits.1129    if (pindex->pprev)1130    {1131        CDiskBlockIndex blockindexPrev(pindex->pprev);1132        blockindexPrev.hashNext = pindex->GetBlockHash();1133        txdb.WriteBlockIndex(blockindexPrev);1134    }11351136    // Watch for transactions paying to me1137    foreach(CTransaction& tx, vtx)1138        AddToWalletIfMine(tx, this);11391140    return true;1141}1142114311441145bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)1146{1147    printf("REORGANIZE\n");11481149    // Find the fork1150    CBlockIndex* pfork = pindexBest;1151    CBlockIndex* plonger = pindexNew;1152    while (pfork != plonger)1153    {1154        while (plonger->nHeight > pfork->nHeight)1155            if (!(plonger = plonger->pprev))1156                return error("Reorganize() : plonger->pprev is null");1157        if (pfork == plonger)1158            break;1159        if (!(pfork = pfork->pprev))1160            return error("Reorganize() : pfork->pprev is null");1161    }11621163    // List of what to disconnect1164    vector<CBlockIndex*> vDisconnect;1165    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)1166        vDisconnect.push_back(pindex);11671168    // List of what to connect1169    vector<CBlockIndex*> vConnect;1170    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)1171        vConnect.push_back(pindex);1172    reverse(vConnect.begin(), vConnect.end());11731174    // Disconnect shorter branch1175    vector<CTransaction> vResurrect;1176    foreach(CBlockIndex* pindex, vDisconnect)1177    {1178        CBlock block;1179        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1180            return error("Reorganize() : ReadFromDisk for disconnect failed");1181        if (!block.DisconnectBlock(txdb, pindex))1182            return error("Reorganize() : DisconnectBlock failed");11831184        // Queue memory transactions to resurrect1185        foreach(const CTransaction& tx, block.vtx)1186            if (!tx.IsCoinBase())1187                vResurrect.push_back(tx);1188    }11891190    // Connect longer branch1191    vector<CTransaction> vDelete;1192    for (int i = 0; i < vConnect.size(); i++)1193    {1194        CBlockIndex* pindex = vConnect[i];1195        CBlock block;1196        if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))1197            return error("Reorganize() : ReadFromDisk for connect failed");1198        if (!block.ConnectBlock(txdb, pindex))1199        {1200            // Invalid block1201            txdb.TxnAbort();1202            return error("Reorganize() : ConnectBlock failed");1203        }12041205        // Queue memory transactions to delete1206        foreach(const CTransaction& tx, block.vtx)1207            vDelete.push_back(tx);1208    }1209    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1210        return error("Reorganize() : WriteHashBestChain failed");12111212    // Commit now because resurrecting could take some time1213    txdb.TxnCommit();12141215    // Disconnect shorter branch1216    foreach(CBlockIndex* pindex, vDisconnect)1217        if (pindex->pprev)1218            pindex->pprev->pnext = NULL;12191220    // Connect longer branch1221    foreach(CBlockIndex* pindex, vConnect)1222        if (pindex->pprev)1223            pindex->pprev->pnext = pindex;12241225    // Resurrect memory transactions that were in the disconnected branch1226    foreach(CTransaction& tx, vResurrect)1227        tx.AcceptTransaction(txdb, false);12281229    // Delete redundant memory transactions that are in the connected branch1230    foreach(CTransaction& tx, vDelete)1231        tx.RemoveFromMemoryPool();12321233    return true;1234}123512361237bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1238{1239    // Check for duplicate1240    uint256 hash = GetHash();1241    if (mapBlockIndex.count(hash))1242        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());12431244    // Construct new block index object1245    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1246    if (!pindexNew)1247        return error("AddToBlockIndex() : new CBlockIndex failed");1248    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1249    pindexNew->phashBlock = &((*mi).first);1250    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1251    if (miPrev != mapBlockIndex.end())1252    {1253        pindexNew->pprev = (*miPrev).second;1254        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1255    }1256    pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();12571258    CTxDB txdb;1259    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));12601261    // New best1262    if (pindexNew->bnChainWork > bnBestChainWork)1263    {1264        txdb.TxnBegin();1265        if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1266        {1267            pindexGenesisBlock = pindexNew;1268            txdb.WriteHashBestChain(hash);1269        }1270        else if (hashPrevBlock == hashBestChain)1271        {1272            // Adding to current best branch1273            if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1274            {1275                txdb.TxnAbort();1276                Lockdown(pindexNew);1277                return error("AddToBlockIndex() : ConnectBlock failed");1278            }1279            txdb.TxnCommit();1280            pindexNew->pprev->pnext = pindexNew;12811282            // Delete redundant memory transactions1283            foreach(CTransaction& tx, vtx)1284                tx.RemoveFromMemoryPool();1285        }1286        else1287        {1288            // New best branch1289            if (!Reorganize(txdb, pindexNew))1290            {1291                txdb.TxnAbort();1292                Lockdown(pindexNew);1293                return error("AddToBlockIndex() : Reorganize failed");1294            }1295        }1296        txdb.TxnCommit();12971298        // New best block1299        hashBestChain = hash;1300        pindexBest = pindexNew;1301        nBestHeight = pindexBest->nHeight;1302        bnBestChainWork = pindexNew->bnChainWork;1303        nTimeBestReceived = GetTime();1304        nTransactionsUpdated++;1305        printf("AddToBlockIndex: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,22).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());1306    }13071308    txdb.Close();13091310    if (pindexNew == pindexBest)1311    {1312        // Notify UI to display prev block's coinbase if it was ours1313        static uint256 hashPrevBestCoinBase;1314        CRITICAL_BLOCK(cs_mapWallet)1315            vWalletUpdated.push_back(hashPrevBestCoinBase);1316        hashPrevBestCoinBase = vtx[0].GetHash();1317    }13181319    MainFrameRepaint();1320    return true;1321}13221323132413251326bool CBlock::CheckBlock() const1327{1328    // These are checks that are independent of context1329    // that can be verified before saving an orphan block.13301331    // Size limits1332    if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)1333        return error("CheckBlock() : size limits failed");13341335    // Check timestamp1336    if (nTime > GetAdjustedTime() + 2 * 60 * 60)1337        return error("CheckBlock() : block timestamp too far in the future");13381339    // First transaction must be coinbase, the rest must not be1340    if (vtx.empty() || !vtx[0].IsCoinBase())1341        return error("CheckBlock() : first tx is not coinbase");1342    for (int i = 1; i < vtx.size(); i++)1343        if (vtx[i].IsCoinBase())1344            return error("CheckBlock() : more than one coinbase");13451346    // Check transactions1347    foreach(const CTransaction& tx, vtx)1348        if (!tx.CheckTransaction())1349            return error("CheckBlock() : CheckTransaction failed");13501351    // Check proof of work matches claimed amount1352    if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)1353        return error("CheckBlock() : nBits below minimum work");1354    if (GetHash() > CBigNum().SetCompact(nBits).getuint256())1355        return error("CheckBlock() : hash doesn't match nBits");13561357    // Check merkleroot1358    if (hashMerkleRoot != BuildMerkleTree())1359        return error("CheckBlock() : hashMerkleRoot mismatch");13601361    return true;1362}13631364bool CBlock::AcceptBlock()1365{1366    // Check for duplicate1367    uint256 hash = GetHash();1368    if (mapBlockIndex.count(hash))1369        return error("AcceptBlock() : block already in mapBlockIndex");13701371    // Get prev block index1372    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1373    if (mi == mapBlockIndex.end())1374        return error("AcceptBlock() : prev block not found");1375    CBlockIndex* pindexPrev = (*mi).second;13761377    // Check timestamp against prev1378    if (nTime <= pindexPrev->GetMedianTimePast())1379        return error("AcceptBlock() : block's timestamp is too early");13801381    // Check that all transactions are finalized1382    foreach(const CTransaction& tx, vtx)1383        if (!tx.IsFinal(pindexPrev->nHeight+1, nTime))1384            return error("AcceptBlock() : contains a non-final transaction");13851386    // Check proof of work1387    if (nBits != GetNextWorkRequired(pindexPrev))1388        return error("AcceptBlock() : incorrect proof of work");13891390    // Check that the block chain matches the known block chain up to a checkpoint1391    if ((pindexPrev->nHeight+1 == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||1392        (pindexPrev->nHeight+1 == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||1393        (pindexPrev->nHeight+1 == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||1394        (pindexPrev->nHeight+1 == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||1395        (pindexPrev->nHeight+1 == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))1396        return error("AcceptBlock() : rejected by checkpoint lockin at %d", pindexPrev->nHeight+1);13971398    // Scanback checkpoint lockin1399    for (CBlockIndex* pindex = pindexPrev; pindex->nHeight >= 74000; pindex = pindex->pprev)1400    {1401        if (pindex->nHeight == 74000 && pindex->GetBlockHash() != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))1402            return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);1403        if (pindex->nHeight == 74638 && pindex->GetBlockHash() == uint256("0x0000000000790ab3f22ec756ad43b6ab569abf0bddeb97c67a6f7b1470a7ec1c"))1404            return error("AcceptBlock() : rejected by scanback lockin at %d", pindex->nHeight);1405    }14061407    // Write block to history file1408    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))1409        return error("AcceptBlock() : out of disk space");1410    unsigned int nFile;1411    unsigned int nBlockPos;1412    if (!WriteToDisk(!fClient, nFile, nBlockPos))1413        return error("AcceptBlock() : WriteToDisk failed");1414    if (!AddToBlockIndex(nFile, nBlockPos))1415        return error("AcceptBlock() : AddToBlockIndex failed");14161417    // Relay inventory, but don't relay old inventory during initial block download1418    if (hashBestChain == hash)1419        CRITICAL_BLOCK(cs_vNodes)1420            foreach(CNode* pnode, vNodes)1421                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))1422                    pnode->PushInventory(CInv(MSG_BLOCK, hash));14231424    return true;1425}14261427bool ProcessBlock(CNode* pfrom, CBlock* pblock)1428{1429    // Check for duplicate1430    uint256 hash = pblock->GetHash();1431    if (mapBlockIndex.count(hash))1432        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());1433    if (mapOrphanBlocks.count(hash))1434        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());14351436    // Preliminary checks1437    if (!pblock->CheckBlock())1438    {1439        delete pblock;1440        return error("ProcessBlock() : CheckBlock FAILED");1441    }14421443    // If don't already have its previous block, shunt it off to holding area until we get it1444    if (!mapBlockIndex.count(pblock->hashPrevBlock))1445    {1446        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());1447        mapOrphanBlocks.insert(make_pair(hash, pblock));1448        mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));14491450        // Ask this guy to fill in what we're missing1451        if (pfrom)1452            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));1453        return true;1454    }14551456    // Store to disk1457    if (!pblock->AcceptBlock())1458    {1459        delete pblock;1460        return error("ProcessBlock() : AcceptBlock FAILED");1461    }1462    delete pblock;14631464    // Recursively process any orphan blocks that depended on this one1465    vector<uint256> vWorkQueue;1466    vWorkQueue.push_back(hash);1467    for (int i = 0; i < vWorkQueue.size(); i++)1468    {1469        uint256 hashPrev = vWorkQueue[i];1470        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1471             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1472             ++mi)1473        {1474            CBlock* pblockOrphan = (*mi).second;1475            if (pblockOrphan->AcceptBlock())1476                vWorkQueue.push_back(pblockOrphan->GetHash());1477            mapOrphanBlocks.erase(pblockOrphan->GetHash());1478            delete pblockOrphan;1479        }1480        mapOrphanBlocksByPrev.erase(hashPrev);1481    }14821483    printf("ProcessBlock: ACCEPTED\n");1484    return true;1485}148614871488148914901491149214931494template<typename Stream>1495bool ScanMessageStart(Stream& s)1496{1497    // Scan ahead to the next pchMessageStart, which should normally be immediately1498    // at the file pointer.  Leaves file pointer at end of pchMessageStart.1499    s.clear(0);1500    short prevmask = s.exceptions(0);1501    const char* p = BEGIN(pchMessageStart);1502    try1503    {1504        loop1505        {1506            char c;1507            s.read(&c, 1);1508            if (s.fail())1509            {1510                s.clear(0);1511                s.exceptions(prevmask);1512                return false;1513            }1514            if (*p != c)1515                p = BEGIN(pchMessageStart);1516            if (*p == c)1517            {1518                if (++p == END(pchMessageStart))1519                {1520                    s.clear(0);1521                    s.exceptions(prevmask);1522                    return true;1523                }1524            }1525        }1526    }1527    catch (...)1528    {1529        s.clear(0);1530        s.exceptions(prevmask);1531        return false;1532    }1533}15341535bool CheckDiskSpace(int64 nAdditionalBytes)1536{1537    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;15381539    // Check for 15MB because database could create another 10MB log file at any time1540    if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)1541    {1542        fShutdown = true;1543        printf("***  %s***\n", _("Warning: Disk space is low  "));1544#ifdef GUI1545        ThreadSafeMessageBox(_("Warning: Disk space is low  "), "Bitcoin", wxOK | wxICON_EXCLAMATION);1546#endif1547        CreateThread(Shutdown, NULL);1548        return false;1549    }1550    return true;1551}15521553FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1554{1555    if (nFile == -1)1556        return NULL;1557    FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);1558    if (!file)1559        return NULL;1560    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1561    {1562        if (fseek(file, nBlockPos, SEEK_SET) != 0)1563        {1564            fclose(file);1565            return NULL;1566        }1567    }1568    return file;1569}15701571static unsigned int nCurrentBlockFile = 1;15721573FILE* AppendBlockFile(unsigned int& nFileRet)1574{1575    nFileRet = 0;1576    loop1577    {1578        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1579        if (!file)1580            return NULL;1581        if (fseek(file, 0, SEEK_END) != 0)1582            return NULL;1583        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1584        if (ftell(file) < 0x7F000000 - MAX_SIZE)1585        {1586            nFileRet = nCurrentBlockFile;1587            return file;1588        }1589        fclose(file);1590        nCurrentBlockFile++;1591    }1592}15931594bool LoadBlockIndex(bool fAllowNew)1595{1596    //1597    // Load block index1598    //1599    CTxDB txdb("cr");1600    if (!txdb.LoadBlockIndex())1601        return false;1602    txdb.Close();16031604    //1605    // Init with genesis block1606    //1607    if (mapBlockIndex.empty())1608    {1609        if (!fAllowNew)1610            return false;161116121613        // Genesis Block:1614        // GetHash()      = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f1615        // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b1616        // txNew.vin[0].scriptSig     = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D6954206568541617        // txNew.vout[0].nValue       = 50000000001618        // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG1619        // block.nVersion = 11620        // block.nTime    = 12310065051621        // block.nBits    = 0x1d00ffff1622        // block.nNonce   = 20832368931623        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1624        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1625        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1626        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1627        //   vMerkleTree: 4a5e1e16281629        // Genesis block1630        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1631        CTransaction txNew;1632        txNew.vin.resize(1);1633        txNew.vout.resize(1);1634        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));1635        txNew.vout[0].nValue = 50 * COIN;1636        CBigNum bnPubKey;1637        bnPubKey.SetHex("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704");1638        txNew.vout[0].scriptPubKey = CScript() << bnPubKey << OP_CHECKSIG;1639        CBlock block;1640        block.vtx.push_back(txNew);1641        block.hashPrevBlock = 0;1642        block.hashMerkleRoot = block.BuildMerkleTree();1643        block.nVersion = 1;1644        block.nTime    = 1231006505;1645        block.nBits    = 0x1d00ffff;1646        block.nNonce   = 2083236893;16471648            //// debug print1649            printf("%s\n", block.GetHash().ToString().c_str());1650            printf("%s\n", block.hashMerkleRoot.ToString().c_str());1651            printf("%s\n", hashGenesisBlock.ToString().c_str());1652            txNew.vout[0].scriptPubKey.print();1653            block.print();1654            assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));16551656        assert(block.GetHash() == hashGenesisBlock);16571658        // Start new block file1659        unsigned int nFile;1660        unsigned int nBlockPos;1661        if (!block.WriteToDisk(!fClient, nFile, nBlockPos))1662            return error("LoadBlockIndex() : writing genesis block to disk failed");1663        if (!block.AddToBlockIndex(nFile, nBlockPos))1664            return error("LoadBlockIndex() : genesis block not accepted");1665    }16661667    return true;1668}1669167016711672void PrintBlockTree()1673{1674    // precompute tree structure1675    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1676    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1677    {1678        CBlockIndex* pindex = (*mi).second;1679        mapNext[pindex->pprev].push_back(pindex);1680        // test1681        //while (rand() % 3 == 0)1682        //    mapNext[pindex->pprev].push_back(pindex);1683    }16841685    vector<pair<int, CBlockIndex*> > vStack;1686    vStack.push_back(make_pair(0, pindexGenesisBlock));16871688    int nPrevCol = 0;1689    while (!vStack.empty())1690    {1691        int nCol = vStack.back().first;1692        CBlockIndex* pindex = vStack.back().second;1693        vStack.pop_back();16941695        // print split or gap1696        if (nCol > nPrevCol)1697        {1698            for (int i = 0; i < nCol-1; i++)1699                printf("| ");1700            printf("|\\\n");1701        }1702        else if (nCol < nPrevCol)1703        {1704            for (int i = 0; i < nCol; i++)1705                printf("| ");1706            printf("|\n");1707        }1708        nPrevCol = nCol;17091710        // print columns1711        for (int i = 0; i < nCol; i++)1712            printf("| ");17131714        // print item1715        CBlock block;1716        block.ReadFromDisk(pindex);1717        printf("%d (%u,%u) %s  %s  tx %d",1718            pindex->nHeight,1719            pindex->nFile,1720            pindex->nBlockPos,1721            block.GetHash().ToString().substr(0,16).c_str(),1722            DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),1723            block.vtx.size());17241725        CRITICAL_BLOCK(cs_mapWallet)1726        {1727            if (mapWallet.count(block.vtx[0].GetHash()))1728            {1729                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1730                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1731            }1732        }1733        printf("\n");173417351736        // put the main timechain first1737        vector<CBlockIndex*>& vNext = mapNext[pindex];1738        for (int i = 0; i < vNext.size(); i++)1739        {1740            if (vNext[i]->pnext)1741            {1742                swap(vNext[0], vNext[i]);1743                break;1744            }1745        }17461747        // iterate children1748        for (int i = 0; i < vNext.size(); i++)1749            vStack.push_back(make_pair(nCol+i, vNext[i]));1750    }1751}17521753175417551756175717581759176017611762//////////////////////////////////////////////////////////////////////////////1763//1764// Messages1765//176617671768bool AlreadyHave(CTxDB& txdb, const CInv& inv)1769{1770    switch (inv.type)1771    {1772    case MSG_TX:    return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);1773    case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);1774    }1775    // Don't know what it is, just say we already got one1776    return true;1777}17781779178017811782178317841785bool ProcessMessages(CNode* pfrom)1786{1787    CDataStream& vRecv = pfrom->vRecv;1788    if (vRecv.empty())1789        return true;1790    //if (fDebug)1791    //    printf("ProcessMessages(%d bytes)\n", vRecv.size());17921793    //1794    // Message format1795    //  (4) message start1796    //  (12) command1797    //  (4) size1798    //  (4) checksum1799    //  (x) data1800    //18011802    loop1803    {1804        // Scan for message start1805        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));1806        int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());1807        if (vRecv.end() - pstart < nHeaderSize)1808        {1809            if (vRecv.size() > nHeaderSize)1810            {1811                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");1812                vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);1813            }1814            break;1815        }1816        if (pstart - vRecv.begin() > 0)1817            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());1818        vRecv.erase(vRecv.begin(), pstart);18191820        // Read header1821        vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);1822        CMessageHeader hdr;1823        vRecv >> hdr;1824        if (!hdr.IsValid())1825        {1826            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());1827            continue;1828        }1829        string strCommand = hdr.GetCommand();18301831        // Message size1832        unsigned int nMessageSize = hdr.nMessageSize;1833        if (nMessageSize > vRecv.size())1834        {1835            // Rewind and wait for rest of message1836            ///// need a mechanism to give up waiting for overlong message size error1837            vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());1838            break;1839        }18401841        // Copy message to its own buffer1842        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);1843        vRecv.ignore(nMessageSize);18441845        // Checksum1846        if (vRecv.GetVersion() >= 209)1847        {1848            uint256 hash = Hash(vMsg.begin(), vMsg.end());1849            unsigned int nChecksum = 0;1850            memcpy(&nChecksum, &hash, sizeof(nChecksum));1851            if (nChecksum != hdr.nChecksum)1852            {1853                printf("ProcessMessage(%s, %d bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",1854                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);1855                continue;1856            }1857        }18581859        // Process message1860        bool fRet = false;1861        try1862        {1863            CRITICAL_BLOCK(cs_main)1864                fRet = ProcessMessage(pfrom, strCommand, vMsg);1865            if (fShutdown)1866                return true;1867        }1868        catch (std::ios_base::failure& e)1869        {1870            if (strstr(e.what(), "CDataStream::read() : end of data"))1871            {1872                // Allow exceptions from underlength message on vRecv1873                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());1874            }1875            else if (strstr(e.what(), ": size too large"))1876            {1877                // Allow exceptions from overlong size1878                printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());1879            }1880            else1881            {1882                PrintException(&e, "ProcessMessage()");1883            }1884        }1885        catch (std::exception& e) {1886            PrintException(&e, "ProcessMessage()");1887        } catch (...) {1888            PrintException(NULL, "ProcessMessage()");1889        }18901891        if (!fRet)1892            printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);1893    }18941895    vRecv.Compact();1896    return true;1897}18981899190019011902bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)1903{1904    static map<unsigned int, vector<unsigned char> > mapReuseKey;1905    RandAddSeedPerfmon();1906    if (fDebug)1907        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());1908    printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());1909    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)1910    {1911        printf("dropmessagestest DROPPING RECV MESSAGE\n");1912        return true;1913    }191419151916191719181919    if (strCommand == "version")1920    {1921        // Each connection can only send one version message1922        if (pfrom->nVersion != 0)1923            return false;19241925        int64 nTime;1926        CAddress addrMe;1927        CAddress addrFrom;1928        uint64 nNonce = 1;1929        string strSubVer;1930        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;1931        if (pfrom->nVersion == 10300)1932            pfrom->nVersion = 300;1933        if (pfrom->nVersion >= 106 && !vRecv.empty())1934            vRecv >> addrFrom >> nNonce;1935        if (pfrom->nVersion >= 106 && !vRecv.empty())1936            vRecv >> strSubVer;1937        if (pfrom->nVersion >= 209 && !vRecv.empty())1938            vRecv >> pfrom->nStartingHeight;19391940        if (pfrom->nVersion == 0)1941            return false;19421943        // Disconnect if we connected to ourself1944        if (nNonce == nLocalHostNonce && nNonce > 1)1945        {1946            pfrom->fDisconnect = true;1947            return true;1948        }19491950        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);1951        if (pfrom->fClient)1952        {1953            pfrom->vSend.nType |= SER_BLOCKHEADERONLY;1954            pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;1955        }19561957        AddTimeData(pfrom->addr.ip, nTime);19581959        // Change version1960        if (pfrom->nVersion >= 209)1961            pfrom->PushMessage("verack");1962        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));1963        if (pfrom->nVersion < 209)1964            pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));19651966        // Ask the first connected node for block updates1967        static int nAskedForBlocks;1968        if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))1969        {1970            nAskedForBlocks++;1971            pfrom->PushGetBlocks(pindexBest, uint256(0));1972        }19731974        pfrom->fSuccessfullyConnected = true;19751976        printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);1977    }197819791980    else if (pfrom->nVersion == 0)1981    {1982        // Must have a version message before anything else1983        return false;1984    }198519861987    else if (strCommand == "verack")1988    {1989        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));1990    }199119921993    else if (strCommand == "addr")1994    {1995        vector<CAddress> vAddr;1996        vRecv >> vAddr;1997        if (pfrom->nVersion < 200) // don't want addresses from 0.1.51998            return true;1999        if (pfrom->nVersion < 209 && mapAddresses.size() > 1000) // don't want addr from 0.2.0 unless seeding2000            return true;2001        if (vAddr.size() > 1000)2002            return error("message addr size() = %d", vAddr.size());20032004        // Store the new addresses2005        foreach(CAddress& addr, vAddr)2006        {2007            if (fShutdown)2008                return true;2009            // ignore IPv6 for now, since it isn't implemented anyway2010            if (!addr.IsIPv4())2011                continue;2012            addr.nTime = GetAdjustedTime() - 2 * 60 * 60;2013            if (pfrom->fGetAddr || vAddr.size() > 10)2014                addr.nTime -= 5 * 24 * 60 * 60;2015            AddAddress(addr);2016            pfrom->AddAddressKnown(addr);2017            if (!pfrom->fGetAddr && addr.IsRoutable())2018            {2019                // Relay to a limited number of other nodes2020                CRITICAL_BLOCK(cs_vNodes)2021                {2022                    // Use deterministic randomness to send to2023                    // the same places for 12 hours at a time2024                    static uint256 hashSalt;2025                    if (hashSalt == 0)2026                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));2027                    uint256 hashRand = addr.ip ^ ((GetTime()+addr.ip)/(12*60*60)) ^ hashSalt;2028                    multimap<uint256, CNode*> mapMix;2029                    foreach(CNode* pnode, vNodes)2030                        mapMix.insert(make_pair(hashRand = Hash(BEGIN(hashRand), END(hashRand)), pnode));2031                    int nRelayNodes = 4;2032                    for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)2033                        ((*mi).second)->PushAddress(addr);2034                }2035            }2036        }2037        if (vAddr.size() < 1000)2038            pfrom->fGetAddr = false;2039    }204020412042    else if (strCommand == "inv")2043    {2044        vector<CInv> vInv;2045        vRecv >> vInv;2046        if (vInv.size() > 50000)2047            return error("message inv size() = %d", vInv.size());20482049        CTxDB txdb("r");2050        foreach(const CInv& inv, vInv)2051        {2052            if (fShutdown)2053                return true;2054            pfrom->AddInventoryKnown(inv);20552056            bool fAlreadyHave = AlreadyHave(txdb, inv);2057            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");20582059            if (!fAlreadyHave)2060                pfrom->AskFor(inv);2061            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))2062                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));20632064            // Track requests for our stuff2065            CRITICAL_BLOCK(cs_mapRequestCount)2066            {2067                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);2068                if (mi != mapRequestCount.end())2069                    (*mi).second++;2070            }2071        }2072    }207320742075    else if (strCommand == "getdata")2076    {2077        vector<CInv> vInv;2078        vRecv >> vInv;2079        if (vInv.size() > 50000)2080            return error("message getdata size() = %d", vInv.size());20812082        foreach(const CInv& inv, vInv)2083        {2084            if (fShutdown)2085                return true;2086            printf("received getdata for: %s\n", inv.ToString().c_str());20872088            if (inv.type == MSG_BLOCK)2089            {2090                // Send block from disk2091                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);2092                if (mi != mapBlockIndex.end())2093                {2094                    //// could optimize this to send header straight from blockindex for client2095                    CBlock block;2096                    block.ReadFromDisk((*mi).second, !pfrom->fClient);2097                    pfrom->PushMessage("block", block);20982099                    // Trigger them to send a getblocks request for the next batch of inventory2100                    if (inv.hash == pfrom->hashContinue)2101                    {2102                        // Bypass PushInventory, this must send even if redundant,2103                        // and we want it right after the last block so they don't2104                        // wait for other stuff first.2105                        vector<CInv> vInv;2106                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));2107                        pfrom->PushMessage("inv", vInv);2108                        pfrom->hashContinue = 0;2109                    }2110                }2111            }2112            else if (inv.IsKnownType())2113            {2114                // Send stream from relay memory2115                CRITICAL_BLOCK(cs_mapRelay)2116                {2117                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);2118                    if (mi != mapRelay.end())2119                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);2120                }2121            }21222123            // Track requests for our stuff2124            CRITICAL_BLOCK(cs_mapRequestCount)2125            {2126                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);2127                if (mi != mapRequestCount.end())2128                    (*mi).second++;2129            }2130        }2131    }213221332134    else if (strCommand == "getblocks")2135    {2136        CBlockLocator locator;2137        uint256 hashStop;2138        vRecv >> locator >> hashStop;21392140        // Find the first block the caller has in the main chain2141        CBlockIndex* pindex = locator.GetBlockIndex();21422143        // Send the rest of the chain2144        if (pindex)2145            pindex = pindex->pnext;2146        int nLimit = 500 + locator.GetDistanceBack();2147        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);2148        for (; pindex; pindex = pindex->pnext)2149        {2150            if (pindex->GetBlockHash() == hashStop)2151            {2152                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());2153                break;2154            }2155            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));2156            if (--nLimit <= 0)2157            {2158                // When this block is requested, we'll send an inv that'll make them2159                // getblocks the next batch of inventory.2160                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());2161                pfrom->hashContinue = pindex->GetBlockHash();2162                break;2163            }2164        }2165    }216621672168    else if (strCommand == "tx")2169    {2170        vector<uint256> vWorkQueue;2171        CDataStream vMsg(vRecv);2172        CTransaction tx;2173        vRecv >> tx;21742175        CInv inv(MSG_TX, tx.GetHash());2176        pfrom->AddInventoryKnown(inv);21772178        bool fMissingInputs = false;2179        if (tx.AcceptTransaction(true, &fMissingInputs))2180        {2181            AddToWalletIfMine(tx, NULL);2182            RelayMessage(inv, vMsg);2183            mapAlreadyAskedFor.erase(inv);2184            vWorkQueue.push_back(inv.hash);21852186            // Recursively process any orphan transactions that depended on this one2187            for (int i = 0; i < vWorkQueue.size(); i++)2188            {2189                uint256 hashPrev = vWorkQueue[i];2190                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);2191                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);2192                     ++mi)2193                {2194                    const CDataStream& vMsg = *((*mi).second);2195                    CTransaction tx;2196                    CDataStream(vMsg) >> tx;2197                    CInv inv(MSG_TX, tx.GetHash());21982199                    if (tx.AcceptTransaction(true))2200                    {2201                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2202                        AddToWalletIfMine(tx, NULL);2203                        RelayMessage(inv, vMsg);2204                        mapAlreadyAskedFor.erase(inv);2205                        vWorkQueue.push_back(inv.hash);2206                    }2207                }2208            }22092210            foreach(uint256 hash, vWorkQueue)2211                EraseOrphanTx(hash);2212        }2213        else if (fMissingInputs)2214        {2215            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());2216            AddOrphanTx(vMsg);2217        }2218    }221922202221    else if (strCommand == "block")2222    {2223        auto_ptr<CBlock> pblock(new CBlock);2224        vRecv >> *pblock;22252226        //// debug print2227        printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());2228        // pblock->print();22292230        CInv inv(MSG_BLOCK, pblock->GetHash());2231        pfrom->AddInventoryKnown(inv);22322233        if (ProcessBlock(pfrom, pblock.release()))2234            mapAlreadyAskedFor.erase(inv);2235    }223622372238    else if (strCommand == "getaddr")2239    {2240        // This includes all nodes that are currently online,2241        // since they rebroadcast an addr every 24 hours2242        pfrom->vAddrToSend.clear();2243        int64 nSince = GetAdjustedTime() - 12 * 60 * 60; // in the last 12 hours2244        CRITICAL_BLOCK(cs_mapAddresses)2245        {2246            unsigned int nSize = mapAddresses.size();2247            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)2248            {2249                if (fShutdown)2250                    return true;2251                const CAddress& addr = item.second;2252                if (addr.nTime > nSince)2253                    pfrom->PushAddress(addr);2254            }2255        }2256    }225722582259    else if (strCommand == "checkorder")2260    {2261        uint256 hashReply;2262        CWalletTx order;2263        vRecv >> hashReply >> order;22642265        /// we have a chance to check the order here22662267        // Keep giving the same key to the same ip until they use it2268        if (!mapReuseKey.count(pfrom->addr.ip))2269            mapReuseKey[pfrom->addr.ip] = GenerateNewKey();22702271        // Send back approval of order and pubkey to use2272        CScript scriptPubKey;2273        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;2274        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);2275    }227622772278    else if (strCommand == "submitorder")2279    {2280        uint256 hashReply;2281        CWalletTx wtxNew;2282        vRecv >> hashReply >> wtxNew;2283        wtxNew.fFromMe = false;22842285        // Broadcast2286        if (!wtxNew.AcceptWalletTransaction())2287        {2288            pfrom->PushMessage("reply", hashReply, (int)1);2289            return error("submitorder AcceptWalletTransaction() failed, returning error 1");2290        }2291        wtxNew.fTimeReceivedIsTxTime = true;2292        AddToWallet(wtxNew);2293        wtxNew.RelayWalletTransaction();2294        mapReuseKey.erase(pfrom->addr.ip);22952296        // Send back confirmation2297        pfrom->PushMessage("reply", hashReply, (int)0);2298    }229923002301    else if (strCommand == "reply")2302    {2303        uint256 hashReply;2304        vRecv >> hashReply;23052306        CRequestTracker tracker;2307        CRITICAL_BLOCK(pfrom->cs_mapRequests)2308        {2309            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2310            if (mi != pfrom->mapRequests.end())2311            {2312                tracker = (*mi).second;2313                pfrom->mapRequests.erase(mi);2314            }2315        }2316        if (!tracker.IsNull())2317            tracker.fn(tracker.param1, vRecv);2318    }231923202321    else if (strCommand == "ping")2322    {2323    }232423252326    else2327    {2328        // Ignore unknown commands for extensibility2329    }233023312332    // Update the last seen time for this node's address2333    if (pfrom->fNetworkNode)2334        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")2335            AddressCurrentlyConnected(pfrom->addr);233623372338    return true;2339}2340234123422343234423452346234723482349bool SendMessages(CNode* pto, bool fSendTrickle)2350{2351    CRITICAL_BLOCK(cs_main)2352    {2353        // Don't send anything until we get their version message2354        if (pto->nVersion == 0)2355            return true;23562357        // Keep-alive ping2358        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())2359            pto->PushMessage("ping");23602361        // Address refresh broadcast2362        static int64 nLastRebroadcast;2363        if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours2364        {2365            nLastRebroadcast = GetTime();2366            CRITICAL_BLOCK(cs_vNodes)2367            {2368                foreach(CNode* pnode, vNodes)2369                {2370                    // Periodically clear setAddrKnown to allow refresh broadcasts2371                    pnode->setAddrKnown.clear();23722373                    // Rebroadcast our address2374                    if (addrLocalHost.IsRoutable() && !fUseProxy)2375                        pnode->PushAddress(addrLocalHost);2376                }2377            }2378        }23792380        // Resend wallet transactions that haven't gotten in a block yet2381        ResendWalletTransactions();238223832384        //2385        // Message: addr2386        //2387        if (fSendTrickle)2388        {2389            vector<CAddress> vAddr;2390            vAddr.reserve(pto->vAddrToSend.size());2391            foreach(const CAddress& addr, pto->vAddrToSend)2392            {2393                // returns true if wasn't already contained in the set2394                if (pto->setAddrKnown.insert(addr).second)2395                {2396                    vAddr.push_back(addr);2397                    // receiver rejects addr messages larger than 10002398                    if (vAddr.size() >= 1000)2399                    {2400                        pto->PushMessage("addr", vAddr);2401                        vAddr.clear();2402                    }2403                }2404            }2405            pto->vAddrToSend.clear();2406            if (!vAddr.empty())2407                pto->PushMessage("addr", vAddr);2408        }240924102411        //2412        // Message: inventory2413        //2414        vector<CInv> vInv;2415        vector<CInv> vInvWait;2416        CRITICAL_BLOCK(pto->cs_inventory)2417        {2418            vInv.reserve(pto->vInventoryToSend.size());2419            vInvWait.reserve(pto->vInventoryToSend.size());2420            foreach(const CInv& inv, pto->vInventoryToSend)2421            {2422                if (pto->setInventoryKnown.count(inv))2423                    continue;24242425                // trickle out tx inv to protect privacy2426                if (inv.type == MSG_TX && !fSendTrickle)2427                {2428                    // 1/4 of tx invs blast to all immediately2429                    static uint256 hashSalt;2430                    if (hashSalt == 0)2431                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));2432                    uint256 hashRand = inv.hash ^ hashSalt;2433                    hashRand = Hash(BEGIN(hashRand), END(hashRand));2434                    bool fTrickleWait = ((hashRand & 3) != 0);24352436                    // always trickle our own transactions2437                    if (!fTrickleWait)2438                    {2439                        TRY_CRITICAL_BLOCK(cs_mapWallet)2440                        {2441                            map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);2442                            if (mi != mapWallet.end())2443                            {2444                                CWalletTx& wtx = (*mi).second;2445                                if (wtx.fFromMe)2446                                    fTrickleWait = true;2447                            }2448                        }2449                    }24502451                    if (fTrickleWait)2452                    {2453                        vInvWait.push_back(inv);2454                        continue;2455                    }2456                }24572458                // returns true if wasn't already contained in the set2459                if (pto->setInventoryKnown.insert(inv).second)2460                {2461                    vInv.push_back(inv);2462                    if (vInv.size() >= 1000)2463                    {2464                        pto->PushMessage("inv", vInv);2465                        vInv.clear();2466                    }2467                }2468            }2469            pto->vInventoryToSend = vInvWait;2470        }2471        if (!vInv.empty())2472            pto->PushMessage("inv", vInv);247324742475        //2476        // Message: getdata2477        //2478        vector<CInv> vGetData;2479        int64 nNow = GetTime() * 1000000;2480        CTxDB txdb("r");2481        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2482        {2483            const CInv& inv = (*pto->mapAskFor.begin()).second;2484            if (!AlreadyHave(txdb, inv))2485            {2486                printf("sending getdata: %s\n", inv.ToString().c_str());2487                vGetData.push_back(inv);2488                if (vGetData.size() >= 1000)2489                {2490                    pto->PushMessage("getdata", vGetData);2491                    vGetData.clear();2492                }2493            }2494            pto->mapAskFor.erase(pto->mapAskFor.begin());2495        }2496        if (!vGetData.empty())2497            pto->PushMessage("getdata", vGetData);24982499    }2500    return true;2501}250225032504250525062507250825092510251125122513251425152516//////////////////////////////////////////////////////////////////////////////2517//2518// BitcoinMiner2519//25202521void GenerateBitcoins(bool fGenerate)2522{2523    if (fGenerateBitcoins != fGenerate)2524    {2525        fGenerateBitcoins = fGenerate;2526        CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);2527        MainFrameRepaint();2528    }2529    if (fGenerateBitcoins)2530    {2531        int nProcessors = boost::thread::hardware_concurrency();2532        printf("%d processors\n", nProcessors);2533        if (nProcessors < 1)2534            nProcessors = 1;2535        if (fLimitProcessors && nProcessors > nLimitProcessors)2536            nProcessors = nLimitProcessors;2537        int nAddThreads = nProcessors - vnThreadsRunning[3];2538        printf("Starting %d BitcoinMiner threads\n", nAddThreads);2539        for (int i = 0; i < nAddThreads; i++)2540        {2541            if (!CreateThread(ThreadBitcoinMiner, NULL))2542                printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");2543            Sleep(10);2544        }2545    }2546}25472548void ThreadBitcoinMiner(void* parg)2549{2550    try2551    {2552        vnThreadsRunning[3]++;2553        BitcoinMiner();2554        vnThreadsRunning[3]--;2555    }2556    catch (std::exception& e) {2557        vnThreadsRunning[3]--;2558        PrintException(&e, "ThreadBitcoinMiner()");2559    } catch (...) {2560        vnThreadsRunning[3]--;2561        PrintException(NULL, "ThreadBitcoinMiner()");2562    }2563    UIThreadCall(bind(CalledSetStatusBar, "", 0));2564    nHPSTimerStart = 0;2565    if (vnThreadsRunning[3] == 0)2566        dHashesPerSec = 0;2567    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);2568}25692570int FormatHashBlocks(void* pbuffer, unsigned int len)2571{2572    unsigned char* pdata = (unsigned char*)pbuffer;2573    unsigned int blocks = 1 + ((len + 8) / 64);2574    unsigned char* pend = pdata + 64 * blocks;2575    memset(pdata + len, 0, 64 * blocks - len);2576    pdata[len] = 0x80;2577    unsigned int bits = len * 8;2578    pend[-1] = (bits >> 0) & 0xff;2579    pend[-2] = (bits >> 8) & 0xff;2580    pend[-3] = (bits >> 16) & 0xff;2581    pend[-4] = (bits >> 24) & 0xff;2582    return blocks;2583}25842585using CryptoPP::ByteReverse;25862587static const unsigned int pSHA256InitState[8] =2588{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};25892590inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)2591{2592    memcpy(pstate, pinit, 32);2593    CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);2594}25952596static const int NPAR = 32;2597extern void Double_BlockSHA256(const void* pin, void* pout, const void* pinit, unsigned int hash[8][NPAR], const void* init2);25982599260026012602void BitcoinMiner()2603{2604    printf("BitcoinMiner started\n");2605    SetThreadPriority(THREAD_PRIORITY_LOWEST);26062607    CKey key;2608    key.MakeNewKey();2609    CBigNum bnExtraNonce = 0;2610    while (fGenerateBitcoins)2611    {2612        Sleep(50);2613        if (fShutdown)2614            return;2615        while (vNodes.empty() || IsInitialBlockDownload())2616        {2617            Sleep(1000);2618            if (fShutdown)2619                return;2620            if (!fGenerateBitcoins)2621                return;2622        }26232624        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;2625        CBlockIndex* pindexPrev = pindexBest;2626        unsigned int nBits = GetNextWorkRequired(pindexPrev);262726282629        //2630        // Create coinbase tx2631        //2632        CTransaction txNew;2633        txNew.vin.resize(1);2634        txNew.vin[0].prevout.SetNull();2635        txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;2636        txNew.vout.resize(1);2637        txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;263826392640        //2641        // Create new block2642        //2643        auto_ptr<CBlock> pblock(new CBlock());2644        if (!pblock.get())2645            return;26462647        // Add our coinbase tx as first transaction2648        pblock->vtx.push_back(txNew);26492650        // Collect the latest transactions into the block2651        int64 nFees = 0;2652        CRITICAL_BLOCK(cs_main)2653        CRITICAL_BLOCK(cs_mapTransactions)2654        {2655            CTxDB txdb("r");2656            map<uint256, CTxIndex> mapTestPool;2657            vector<char> vfAlreadyAdded(mapTransactions.size());2658            bool fFoundSomething = true;2659            unsigned int nBlockSize = 0;2660            while (fFoundSomething && nBlockSize < MAX_SIZE/2)2661            {2662                fFoundSomething = false;2663                unsigned int n = 0;2664                for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)2665                {2666                    if (vfAlreadyAdded[n])2667                        continue;2668                    CTransaction& tx = (*mi).second;2669                    if (tx.IsCoinBase() || !tx.IsFinal())2670                        continue;2671                    unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);2672                    if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE - 10000)2673                        continue;26742675                    // Transaction fee based on block size2676                    int64 nMinFee = tx.GetMinFee(nBlockSize);26772678                    map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);2679                    if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))2680                        continue;2681                    swap(mapTestPool, mapTestPoolTmp);26822683                    pblock->vtx.push_back(tx);2684                    nBlockSize += nTxSize;2685                    vfAlreadyAdded[n] = true;2686                    fFoundSomething = true;2687                }2688            }2689        }2690        pblock->nBits = nBits;2691        pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(pindexPrev->nHeight+1, nFees);2692        printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());269326942695        //2696        // Prebuild hash buffer2697        //2698        struct tmpworkspace2699        {2700            struct unnamed22701            {2702                int nVersion;2703                uint256 hashPrevBlock;2704                uint256 hashMerkleRoot;2705                unsigned int nTime;2706                unsigned int nBits;2707                unsigned int nNonce;2708            }2709            block;2710            unsigned char pchPadding0[64];2711            uint256 hash1;2712            unsigned char pchPadding1[64];2713        };2714        char tmpbuf[sizeof(tmpworkspace)+16];2715        tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);27162717        tmp.block.nVersion       = pblock->nVersion;2718        tmp.block.hashPrevBlock  = pblock->hashPrevBlock  = (pindexPrev ? pindexPrev->GetBlockHash() : 0);2719        tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();2720        tmp.block.nTime          = pblock->nTime          = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());2721        tmp.block.nBits          = pblock->nBits          = nBits;2722        tmp.block.nNonce         = pblock->nNonce         = 0;27232724        unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));2725        unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));27262727        // Byte swap all the input buffer2728        for (int i = 0; i < sizeof(tmp)/4; i++)2729            ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);27302731        // Precalc the first half of the first hash, which stays constant2732        uint256 midstatebuf[2];2733        uint256& midstate = *alignup<16>(midstatebuf);2734        SHA256Transform(&midstate, &tmp.block, pSHA256InitState);273527362737        //2738        // Search2739        //2740        bool f4WaySSE2 = mapArgs.count("-4way");2741        int64 nStart = GetTime();2742        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();2743        uint256 hashbuf[2];2744        uint256& hash = *alignup<16>(hashbuf);2745        loop2746        {2747#ifdef FOURWAYSSE22748            if (f4WaySSE2)2749            {2750                // tcatm's 4-way SSE2 SHA-2562751                tmp.block.nNonce += NPAR;2752                unsigned int thashbuf[9][NPAR];2753                unsigned int (&thash)[9][NPAR] = *alignup<16>(&thashbuf);2754                Double_BlockSHA256((char*)&tmp.block + 64, &tmp.hash1, &midstate, thash, pSHA256InitState);2755                ((unsigned short*)&hash)[14] = 0xffff;2756                for (int j = 0; j < NPAR; j++)2757                {2758                    if (thash[7][j] == 0)2759                    {2760                        for (int i = 0; i < sizeof(hash)/4; i++)2761                            ((unsigned int*)&hash)[i] = thash[i][j];2762                        pblock->nNonce = ByteReverse(tmp.block.nNonce + j);2763                    }2764                }2765            }2766            else2767#endif2768            {2769                // Crypto++ SHA-2562770                tmp.block.nNonce++;2771                SHA256Transform(&tmp.hash1, (char*)&tmp.block + 64, &midstate);2772                SHA256Transform(&hash, &tmp.hash1, pSHA256InitState);2773            }27742775            if (((unsigned short*)&hash)[14] == 0)2776            {2777                // Byte swap the result after preliminary check2778                for (int i = 0; i < sizeof(hash)/4; i++)2779                    ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);27802781                if (hash <= hashTarget)2782                {2783#ifdef FOURWAYSSE22784                    if (!f4WaySSE2)2785#endif2786                        pblock->nNonce = ByteReverse(tmp.block.nNonce);2787                    assert(hash == pblock->GetHash());27882789                        //// debug print2790                        printf("BitcoinMiner:\n");2791                        printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());2792                        pblock->print();2793                        printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());2794                        printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());27952796                    SetThreadPriority(THREAD_PRIORITY_NORMAL);2797                    CRITICAL_BLOCK(cs_main)2798                    {2799                        if (pindexPrev == pindexBest)2800                        {2801                            // Save key2802                            if (!AddKey(key))2803                                return;2804                            key.MakeNewKey();28052806                            // Track how many getdata requests this block gets2807                            CRITICAL_BLOCK(cs_mapRequestCount)2808                                mapRequestCount[pblock->GetHash()] = 0;28092810                            // Process this block the same as if we had received it from another node2811                            if (!ProcessBlock(NULL, pblock.release()))2812                                printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");2813                        }2814                    }2815                    SetThreadPriority(THREAD_PRIORITY_LOWEST);28162817                    Sleep(500);2818                    break;2819                }2820            }28212822            // Update nTime every few seconds2823            const unsigned int nMask = 0xffff;2824            const int nHashesPerCycle = (nMask+1);2825            if ((tmp.block.nNonce & nMask) == 0)2826            {2827                // Meter hashes/sec2828                static int nCycleCounter;2829                if (nHPSTimerStart == 0)2830                {2831                    nHPSTimerStart = GetTimeMillis();2832                    nCycleCounter = 0;2833                }2834                else2835                    nCycleCounter++;2836                if (GetTimeMillis() - nHPSTimerStart > 4000)2837                {2838                    static CCriticalSection cs;2839                    CRITICAL_BLOCK(cs)2840                    {2841                        if (GetTimeMillis() - nHPSTimerStart > 4000)2842                        {2843                            dHashesPerSec = 1000.0 * nHashesPerCycle * nCycleCounter / (GetTimeMillis() - nHPSTimerStart);2844                            nHPSTimerStart = GetTimeMillis();2845                            nCycleCounter = 0;2846                            string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);2847                            UIThreadCall(bind(CalledSetStatusBar, strStatus, 0));2848                            static int64 nLogTime;2849                            if (GetTime() - nLogTime > 30 * 60)2850                            {2851                                nLogTime = GetTime();2852                                printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());2853                                printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);2854                            }2855                        }2856                    }2857                }28582859                // Check for stop or if block needs to be rebuilt2860                if (fShutdown)2861                    return;2862                if (!fGenerateBitcoins)2863                    return;2864                if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)2865                    return;2866                if (vNodes.empty())2867                    break;2868                if (tmp.block.nNonce == 0)2869                    break;2870                if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)2871                    break;2872                if (pindexPrev != pindexBest)2873                    break;28742875                pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());2876                tmp.block.nTime = ByteReverse(pblock->nTime);2877            }2878        }2879    }2880}2881288228832884288528862887288828892890289128922893289428952896289728982899//////////////////////////////////////////////////////////////////////////////2900//2901// Actions2902//290329042905int64 GetBalance()2906{2907    int64 nStart = GetTimeMillis();29082909    int64 nTotal = 0;2910    CRITICAL_BLOCK(cs_mapWallet)2911    {2912        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2913        {2914            CWalletTx* pcoin = &(*it).second;2915            if (!pcoin->IsFinal() || pcoin->fSpent)2916                continue;2917            nTotal += pcoin->GetCredit(true);2918        }2919    }29202921    //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);2922    return nTotal;2923}292429252926int GetRandInt(int nMax)2927{2928    return GetRand(nMax);2929}29302931bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)2932{2933    setCoinsRet.clear();29342935    // List of values less than target2936    int64 nLowestLarger = INT64_MAX;2937    CWalletTx* pcoinLowestLarger = NULL;2938    vector<pair<int64, CWalletTx*> > vValue;2939    int64 nTotalLower = 0;29402941    CRITICAL_BLOCK(cs_mapWallet)2942    {2943       vector<CWalletTx*> vCoins;2944       vCoins.reserve(mapWallet.size());2945       for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)2946           vCoins.push_back(&(*it).second);2947       random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);29482949       foreach(CWalletTx* pcoin, vCoins)2950       {2951            if (!pcoin->IsFinal() || pcoin->fSpent)2952                continue;2953            int64 n = pcoin->GetCredit();2954            if (n <= 0)2955                continue;2956            if (n < nTargetValue)2957            {2958                vValue.push_back(make_pair(n, pcoin));2959                nTotalLower += n;2960            }2961            else if (n == nTargetValue)2962            {2963                setCoinsRet.insert(pcoin);2964                return true;2965            }2966            else if (n < nLowestLarger)2967            {2968                nLowestLarger = n;2969                pcoinLowestLarger = pcoin;2970            }2971        }2972    }29732974    if (nTotalLower < nTargetValue)2975    {2976        if (pcoinLowestLarger == NULL)2977            return false;2978        setCoinsRet.insert(pcoinLowestLarger);2979        return true;2980    }29812982    // Solve subset sum by stochastic approximation2983    sort(vValue.rbegin(), vValue.rend());2984    vector<char> vfIncluded;2985    vector<char> vfBest(vValue.size(), true);2986    int64 nBest = nTotalLower;29872988    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)2989    {2990        vfIncluded.assign(vValue.size(), false);2991        int64 nTotal = 0;2992        bool fReachedTarget = false;2993        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)2994        {2995            for (int i = 0; i < vValue.size(); i++)2996            {2997                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])2998                {2999                    nTotal += vValue[i].first;3000                    vfIncluded[i] = true;3001                    if (nTotal >= nTargetValue)3002                    {3003                        fReachedTarget = true;3004                        if (nTotal < nBest)3005                        {3006                            nBest = nTotal;3007                            vfBest = vfIncluded;3008                        }3009                        nTotal -= vValue[i].first;3010                        vfIncluded[i] = false;3011                    }3012                }3013            }3014        }3015    }30163017    // If the next larger is still closer, return it3018    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)3019        setCoinsRet.insert(pcoinLowestLarger);3020    else3021    {3022        for (int i = 0; i < vValue.size(); i++)3023            if (vfBest[i])3024                setCoinsRet.insert(vValue[i].second);30253026        //// debug print3027        printf("SelectCoins() best subset: ");3028        for (int i = 0; i < vValue.size(); i++)3029            if (vfBest[i])3030                printf("%s ", FormatMoney(vValue[i].first).c_str());3031        printf("total %s\n", FormatMoney(nBest).c_str());3032    }30333034    return true;3035}30363037303830393040bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)3041{3042    nFeeRequiredRet = 0;3043    CRITICAL_BLOCK(cs_main)3044    {3045        // txdb must be opened before the mapWallet lock3046        CTxDB txdb("r");3047        CRITICAL_BLOCK(cs_mapWallet)3048        {3049            int64 nFee = nTransactionFee;3050            loop3051            {3052                wtxNew.vin.clear();3053                wtxNew.vout.clear();3054                wtxNew.fFromMe = true;3055                if (nValue < 0)3056                    return false;3057                int64 nValueOut = nValue;3058                int64 nTotalValue = nValue + nFee;30593060                // Choose coins to use3061                set<CWalletTx*> setCoins;3062                if (!SelectCoins(nTotalValue, setCoins))3063                    return false;3064                int64 nValueIn = 0;3065                foreach(CWalletTx* pcoin, setCoins)3066                    nValueIn += pcoin->GetCredit();30673068                // Fill a vout to the payee3069                bool fChangeFirst = GetRand(2);3070                if (!fChangeFirst)3071                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));30723073                // Fill a vout back to self with any change3074                if (nValueIn > nTotalValue)3075                {3076                    // Note: We use a new key here to keep it from being obvious which side is the change.3077                    //  The drawback is that by not reusing a previous key, the change may be lost if a3078                    //  backup is restored, if the backup doesn't have the new private key for the change.3079                    //  If we reused the old key, it would be possible to add code to look for and3080                    //  rediscover unknown transactions that were written with keys of ours to recover3081                    //  post-backup change.30823083                    // New private key3084                    if (keyRet.IsNull())3085                        keyRet.MakeNewKey();30863087                    // Fill a vout to ourself, using same address type as the payment3088                    CScript scriptChange;3089                    if (scriptPubKey.GetBitcoinAddressHash160() != 0)3090                        scriptChange.SetBitcoinAddress(keyRet.GetPubKey());3091                    else3092                        scriptChange << keyRet.GetPubKey() << OP_CHECKSIG;3093                    wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptChange));3094                }30953096                // Fill a vout to the payee3097                if (fChangeFirst)3098                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));30993100                // Fill vin3101                foreach(CWalletTx* pcoin, setCoins)3102                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)3103                        if (pcoin->vout[nOut].IsMine())3104                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));31053106                // Sign3107                int nIn = 0;3108                foreach(CWalletTx* pcoin, setCoins)3109                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)3110                        if (pcoin->vout[nOut].IsMine())3111                            if (!SignSignature(*pcoin, wtxNew, nIn++))3112                                return false;31133114                // Check that enough fee is included3115                if (nFee < wtxNew.GetMinFee())3116                {3117                    nFee = nFeeRequiredRet = wtxNew.GetMinFee();3118                    continue;3119                }31203121                // Fill vtxPrev by copying from previous transactions vtxPrev3122                wtxNew.AddSupportingTransactions(txdb);3123                wtxNew.fTimeReceivedIsTxTime = true;31243125                break;3126            }3127        }3128    }3129    return true;3130}31313132// Call after CreateTransaction unless you want to abort3133bool CommitTransaction(CWalletTx& wtxNew, const CKey& key)3134{3135    CRITICAL_BLOCK(cs_main)3136    {3137        printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());3138        CRITICAL_BLOCK(cs_mapWallet)3139        {3140            // This is only to keep the database open to defeat the auto-flush for the3141            // duration of this scope.  This is the only place where this optimization3142            // maybe makes sense; please don't do it anywhere else.3143            CWalletDB walletdb("r");31443145            // Add the change's private key to wallet3146            if (!key.IsNull() && !AddKey(key))3147                throw runtime_error("CommitTransaction() : AddKey failed\n");31483149            // Add tx to wallet, because if it has change it's also ours,3150            // otherwise just for transaction history.3151            AddToWallet(wtxNew);31523153            // Mark old coins as spent3154            set<CWalletTx*> setCoins;3155            foreach(const CTxIn& txin, wtxNew.vin)3156                setCoins.insert(&mapWallet[txin.prevout.hash]);3157            foreach(CWalletTx* pcoin, setCoins)3158            {3159                pcoin->fSpent = true;3160                pcoin->WriteToDisk();3161                vWalletUpdated.push_back(pcoin->GetHash());3162            }3163        }31643165        // Track how many getdata requests our transaction gets3166        CRITICAL_BLOCK(cs_mapRequestCount)3167            mapRequestCount[wtxNew.GetHash()] = 0;31683169        // Broadcast3170        if (!wtxNew.AcceptTransaction())3171        {3172            // This must not fail. The transaction has already been signed and recorded.3173            printf("CommitTransaction() : Error: Transaction not valid");3174            return false;3175        }3176        wtxNew.RelayWalletTransaction();3177    }3178    MainFrameRepaint();3179    return true;3180}31813182318331843185string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3186{3187    CRITICAL_BLOCK(cs_main)3188    {3189        CKey key;3190        int64 nFeeRequired;3191        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))3192        {3193            string strError;3194            if (nValue + nFeeRequired > GetBalance())3195                strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());3196            else3197                strError = _("Error: Transaction creation failed  ");3198            printf("SendMoney() : %s", strError.c_str());3199            return strError;3200        }32013202        if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))3203            return "ABORTED";32043205        if (!CommitTransaction(wtxNew, key))3206            return _("Error: The transaction was rejected.  This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");3207    }3208    MainFrameRepaint();3209    return "";3210}3211321232133214string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3215{3216    // Check amount3217    if (nValue <= 0)3218        return _("Invalid amount");3219    if (nValue + nTransactionFee > GetBalance())3220        return _("Insufficient funds");32213222    // Parse bitcoin address3223    CScript scriptPubKey;3224    if (!scriptPubKey.SetBitcoinAddress(strAddress))3225        return _("Invalid bitcoin address");32263227    return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);3228}

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