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 r202 (last Satoshi commit) · 2010-12-15

main.cpp

3,888 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;24uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");25CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);26CBlockIndex* pindexGenesisBlock = NULL;27int nBestHeight = -1;28CBigNum bnBestChainWork = 0;29CBigNum bnBestInvalidWork = 0;30uint256 hashBestChain = 0;31CBlockIndex* pindexBest = NULL;32int64 nTimeBestReceived = 0;3334map<uint256, CBlock*> mapOrphanBlocks;35multimap<uint256, CBlock*> mapOrphanBlocksByPrev;3637map<uint256, CDataStream*> mapOrphanTransactions;38multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;3940map<uint256, CWalletTx> mapWallet;41vector<uint256> vWalletUpdated;42CCriticalSection cs_mapWallet;4344map<vector<unsigned char>, CPrivKey> mapKeys;45map<uint160, vector<unsigned char> > mapPubKeys;46CCriticalSection cs_mapKeys;47CKey keyUser;4849map<uint256, int> mapRequestCount;50CCriticalSection cs_mapRequestCount;5152map<string, string> mapAddressBook;53CCriticalSection cs_mapAddressBook;5455vector<unsigned char> vchDefaultKey;5657double dHashesPerSec;58int64 nHPSTimerStart;5960// Settings61int fGenerateBitcoins = false;62int64 nTransactionFee = 0;63CAddress addrIncoming;64int fLimitProcessors = false;65int nLimitProcessors = 1;66int fMinimizeToTray = true;67int fMinimizeOnClose = true;68697071727374//////////////////////////////////////////////////////////////////////////////75//76// mapKeys77//7879bool AddKey(const CKey& key)80{81    CRITICAL_BLOCK(cs_mapKeys)82    {83        mapKeys[key.GetPubKey()] = key.GetPrivKey();84        mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();85    }86    return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());87}8889vector<unsigned char> GenerateNewKey()90{91    RandAddSeedPerfmon();92    CKey key;93    key.MakeNewKey();94    if (!AddKey(key))95        throw runtime_error("GenerateNewKey() : AddKey failed");96    return key.GetPubKey();97}9899100101102//////////////////////////////////////////////////////////////////////////////103//104// mapWallet105//106107bool AddToWallet(const CWalletTx& wtxIn)108{109    uint256 hash = wtxIn.GetHash();110    CRITICAL_BLOCK(cs_mapWallet)111    {112        // Inserts only if not already there, returns tx inserted or tx found113        pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));114        CWalletTx& wtx = (*ret.first).second;115        bool fInsertedNew = ret.second;116        if (fInsertedNew)117            wtx.nTimeReceived = GetAdjustedTime();118119        bool fUpdated = false;120        if (!fInsertedNew)121        {122            // Merge123            if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)124            {125                wtx.hashBlock = wtxIn.hashBlock;126                fUpdated = true;127            }128            if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))129            {130                wtx.vMerkleBranch = wtxIn.vMerkleBranch;131                wtx.nIndex = wtxIn.nIndex;132                fUpdated = true;133            }134            if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)135            {136                wtx.fFromMe = wtxIn.fFromMe;137                fUpdated = true;138            }139            if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)140            {141                wtx.fSpent = wtxIn.fSpent;142                fUpdated = true;143            }144        }145146        //// debug print147        printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));148149        // Write to disk150        if (fInsertedNew || fUpdated)151            if (!wtx.WriteToDisk())152                return false;153154        // If default receiving address gets used, replace it with a new one155        CScript scriptDefaultKey;156        scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);157        foreach(const CTxOut& txout, wtx.vout)158        {159            if (txout.scriptPubKey == scriptDefaultKey)160            {161                CWalletDB walletdb;162                vchDefaultKey = GetKeyFromKeyPool();163                walletdb.WriteDefaultKey(vchDefaultKey);164                walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");165            }166        }167168        // Notify UI169        vWalletUpdated.push_back(hash);170    }171172    // Refresh UI173    MainFrameRepaint();174    return true;175}176177bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)178{179    if (tx.IsMine() || mapWallet.count(tx.GetHash()))180    {181        CWalletTx wtx(tx);182        // Get merkle branch if transaction was found in a block183        if (pblock)184            wtx.SetMerkleBranch(pblock);185        return AddToWallet(wtx);186    }187    return true;188}189190bool EraseFromWallet(uint256 hash)191{192    CRITICAL_BLOCK(cs_mapWallet)193    {194        if (mapWallet.erase(hash))195            CWalletDB().EraseTx(hash);196    }197    return true;198}199200void WalletUpdateSpent(const COutPoint& prevout)201{202    // Anytime a signature is successfully verified, it's proof the outpoint is spent.203    // Update the wallet spent flag if it doesn't know due to wallet.dat being204    // restored from backup or the user making copies of wallet.dat.205    CRITICAL_BLOCK(cs_mapWallet)206    {207        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);208        if (mi != mapWallet.end())209        {210            CWalletTx& wtx = (*mi).second;211            if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())212            {213                printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());214                wtx.fSpent = true;215                wtx.WriteToDisk();216                vWalletUpdated.push_back(prevout.hash);217            }218        }219    }220}221222223224225226227228229//////////////////////////////////////////////////////////////////////////////230//231// mapOrphanTransactions232//233234void AddOrphanTx(const CDataStream& vMsg)235{236    CTransaction tx;237    CDataStream(vMsg) >> tx;238    uint256 hash = tx.GetHash();239    if (mapOrphanTransactions.count(hash))240        return;241    CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);242    foreach(const CTxIn& txin, tx.vin)243        mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));244}245246void EraseOrphanTx(uint256 hash)247{248    if (!mapOrphanTransactions.count(hash))249        return;250    const CDataStream* pvMsg = mapOrphanTransactions[hash];251    CTransaction tx;252    CDataStream(*pvMsg) >> tx;253    foreach(const CTxIn& txin, tx.vin)254    {255        for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);256             mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)257        {258            if ((*mi).second == pvMsg)259                mapOrphanTransactionsByPrev.erase(mi++);260            else261                mi++;262        }263    }264    delete pvMsg;265    mapOrphanTransactions.erase(hash);266}267268269270271272273274275//////////////////////////////////////////////////////////////////////////////276//277// CTransaction278//279280bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)281{282    SetNull();283    if (!txdb.ReadTxIndex(prevout.hash, txindexRet))284        return false;285    if (!ReadFromDisk(txindexRet.pos))286        return false;287    if (prevout.n >= vout.size())288    {289        SetNull();290        return false;291    }292    return true;293}294295bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)296{297    CTxIndex txindex;298    return ReadFromDisk(txdb, prevout, txindex);299}300301bool CTransaction::ReadFromDisk(COutPoint prevout)302{303    CTxDB txdb("r");304    CTxIndex txindex;305    return ReadFromDisk(txdb, prevout, txindex);306}307308bool CTxIn::IsMine() const309{310    CRITICAL_BLOCK(cs_mapWallet)311    {312        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);313        if (mi != mapWallet.end())314        {315            const CWalletTx& prev = (*mi).second;316            if (prevout.n < prev.vout.size())317                if (prev.vout[prevout.n].IsMine())318                    return true;319        }320    }321    return false;322}323324int64 CTxIn::GetDebit() const325{326    CRITICAL_BLOCK(cs_mapWallet)327    {328        map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);329        if (mi != mapWallet.end())330        {331            const CWalletTx& prev = (*mi).second;332            if (prevout.n < prev.vout.size())333                if (prev.vout[prevout.n].IsMine())334                    return prev.vout[prevout.n].nValue;335        }336    }337    return 0;338}339340int64 CWalletTx::GetTxTime() const341{342    if (!fTimeReceivedIsTxTime && hashBlock != 0)343    {344        // If we did not receive the transaction directly, we rely on the block's345        // time to figure out when it happened.  We use the median over a range346        // of blocks to try to filter out inaccurate block times.347        map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);348        if (mi != mapBlockIndex.end())349        {350            CBlockIndex* pindex = (*mi).second;351            if (pindex)352                return pindex->GetMedianTime();353        }354    }355    return nTimeReceived;356}357358int CWalletTx::GetRequestCount() const359{360    // Returns -1 if it wasn't being tracked361    int nRequests = -1;362    CRITICAL_BLOCK(cs_mapRequestCount)363    {364        if (IsCoinBase())365        {366            // Generated block367            if (hashBlock != 0)368            {369                map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);370                if (mi != mapRequestCount.end())371                    nRequests = (*mi).second;372            }373        }374        else375        {376            // Did anyone request this transaction?377            map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());378            if (mi != mapRequestCount.end())379            {380                nRequests = (*mi).second;381382                // How about the block it's in?383                if (nRequests == 0 && hashBlock != 0)384                {385                    map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);386                    if (mi != mapRequestCount.end())387                        nRequests = (*mi).second;388                    else389                        nRequests = 1; // If it's in someone else's block it must have got out390                }391            }392        }393    }394    return nRequests;395}396397398399400int CMerkleTx::SetMerkleBranch(const CBlock* pblock)401{402    if (fClient)403    {404        if (hashBlock == 0)405            return 0;406    }407    else408    {409        CBlock blockTmp;410        if (pblock == NULL)411        {412            // Load the block this tx is in413            CTxIndex txindex;414            if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))415                return 0;416            if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))417                return 0;418            pblock = &blockTmp;419        }420421        // Update the tx's hashBlock422        hashBlock = pblock->GetHash();423424        // Locate the transaction425        for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)426            if (pblock->vtx[nIndex] == *(CTransaction*)this)427                break;428        if (nIndex == pblock->vtx.size())429        {430            vMerkleBranch.clear();431            nIndex = -1;432            printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");433            return 0;434        }435436        // Fill in merkle branch437        vMerkleBranch = pblock->GetMerkleBranch(nIndex);438    }439440    // Is the tx in a block that's in the main chain441    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);442    if (mi == mapBlockIndex.end())443        return 0;444    CBlockIndex* pindex = (*mi).second;445    if (!pindex || !pindex->IsInMainChain())446        return 0;447448    return pindexBest->nHeight - pindex->nHeight + 1;449}450451452453void CWalletTx::AddSupportingTransactions(CTxDB& txdb)454{455    vtxPrev.clear();456457    const int COPY_DEPTH = 3;458    if (SetMerkleBranch() < COPY_DEPTH)459    {460        vector<uint256> vWorkQueue;461        foreach(const CTxIn& txin, vin)462            vWorkQueue.push_back(txin.prevout.hash);463464        // This critsect is OK because txdb is already open465        CRITICAL_BLOCK(cs_mapWallet)466        {467            map<uint256, const CMerkleTx*> mapWalletPrev;468            set<uint256> setAlreadyDone;469            for (int i = 0; i < vWorkQueue.size(); i++)470            {471                uint256 hash = vWorkQueue[i];472                if (setAlreadyDone.count(hash))473                    continue;474                setAlreadyDone.insert(hash);475476                CMerkleTx tx;477                if (mapWallet.count(hash))478                {479                    tx = mapWallet[hash];480                    foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)481                        mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;482                }483                else if (mapWalletPrev.count(hash))484                {485                    tx = *mapWalletPrev[hash];486                }487                else if (!fClient && txdb.ReadDiskTx(hash, tx))488                {489                    ;490                }491                else492                {493                    printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");494                    continue;495                }496497                int nDepth = tx.SetMerkleBranch();498                vtxPrev.push_back(tx);499500                if (nDepth < COPY_DEPTH)501                    foreach(const CTxIn& txin, tx.vin)502                        vWorkQueue.push_back(txin.prevout.hash);503            }504        }505    }506507    reverse(vtxPrev.begin(), vtxPrev.end());508}509510511512513514515516517518519520bool CTransaction::CheckTransaction() const521{522    // Basic checks that don't depend on any context523    if (vin.empty() || vout.empty())524        return error("CTransaction::CheckTransaction() : vin or vout empty");525526    // Size limits527    if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)528        return error("CTransaction::CheckTransaction() : size limits failed");529530    // Check for negative or overflow output values531    int64 nValueOut = 0;532    foreach(const CTxOut& txout, vout)533    {534        if (txout.nValue < 0)535            return error("CTransaction::CheckTransaction() : txout.nValue negative");536        if (txout.nValue > MAX_MONEY)537            return error("CTransaction::CheckTransaction() : txout.nValue too high");538        nValueOut += txout.nValue;539        if (!MoneyRange(nValueOut))540            return error("CTransaction::CheckTransaction() : txout total out of range");541    }542543    if (IsCoinBase())544    {545        if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)546            return error("CTransaction::CheckTransaction() : coinbase script size");547    }548    else549    {550        foreach(const CTxIn& txin, vin)551            if (txin.prevout.IsNull())552                return error("CTransaction::CheckTransaction() : prevout is null");553    }554555    return true;556}557558bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)559{560    if (pfMissingInputs)561        *pfMissingInputs = false;562563    if (!CheckTransaction())564        return error("AcceptToMemoryPool() : CheckTransaction failed");565566    // Coinbase is only valid in a block, not as a loose transaction567    if (IsCoinBase())568        return error("AcceptToMemoryPool() : coinbase as individual tx");569570    // To help v0.1.5 clients who would see it as a negative number571    if ((int64)nLockTime > INT_MAX)572        return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");573574    // Safety limits575    unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);576    if (GetSigOpCount() > 2 || nSize < 100)577        return error("AcceptToMemoryPool() : nonstandard transaction");578579    // Rather not work on nonstandard transactions580    if (!IsStandard())581        return error("AcceptToMemoryPool() : nonstandard transaction type");582583    // Do we already have it?584    uint256 hash = GetHash();585    CRITICAL_BLOCK(cs_mapTransactions)586        if (mapTransactions.count(hash))587            return false;588    if (fCheckInputs)589        if (txdb.ContainsTx(hash))590            return false;591592    // Check for conflicts with in-memory transactions593    CTransaction* ptxOld = NULL;594    for (int i = 0; i < vin.size(); i++)595    {596        COutPoint outpoint = vin[i].prevout;597        if (mapNextTx.count(outpoint))598        {599            // Disable replacement feature for now600            return false;601602            // Allow replacing with a newer version of the same transaction603            if (i != 0)604                return false;605            ptxOld = mapNextTx[outpoint].ptx;606            if (ptxOld->IsFinal())607                return false;608            if (!IsNewerThan(*ptxOld))609                return false;610            for (int i = 0; i < vin.size(); i++)611            {612                COutPoint outpoint = vin[i].prevout;613                if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)614                    return false;615            }616            break;617        }618    }619620    if (fCheckInputs)621    {622        // Check against previous transactions623        map<uint256, CTxIndex> mapUnused;624        int64 nFees = 0;625        if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))626        {627            if (pfMissingInputs)628                *pfMissingInputs = true;629            return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());630        }631632        // Don't accept it if it can't get into a block633        if (nFees < GetMinFee(1000))634            return error("AcceptToMemoryPool() : not enough fees");635636        // Limit free transactions per 10 minutes637        if (nFees < CENT && GetBoolArg("-limitfreerelay"))638        {639            static int64 nNextReset;640            static int64 nFreeCount;641            if (GetTime() > nNextReset)642            {643                nNextReset = GetTime() + 10 * 60;644                nFreeCount = 0;645            }646            if (nFreeCount > 150000 && !IsFromMe())647                return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");648            nFreeCount += nSize;649        }650    }651652    // Store transaction in memory653    CRITICAL_BLOCK(cs_mapTransactions)654    {655        if (ptxOld)656        {657            printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());658            ptxOld->RemoveFromMemoryPool();659        }660        AddToMemoryPoolUnchecked();661    }662663    ///// are we sure this is ok when loading transactions or restoring block txes664    // If updated, erase old tx from wallet665    if (ptxOld)666        EraseFromWallet(ptxOld->GetHash());667668    printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());669    return true;670}671672673bool CTransaction::AddToMemoryPoolUnchecked()674{675    // Add to memory pool without checking anything.  Don't call this directly,676    // call AcceptToMemoryPool to properly check the transaction first.677    CRITICAL_BLOCK(cs_mapTransactions)678    {679        uint256 hash = GetHash();680        mapTransactions[hash] = *this;681        for (int i = 0; i < vin.size(); i++)682            mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);683        nTransactionsUpdated++;684    }685    return true;686}687688689bool CTransaction::RemoveFromMemoryPool()690{691    // Remove transaction from memory pool692    CRITICAL_BLOCK(cs_mapTransactions)693    {694        foreach(const CTxIn& txin, vin)695            mapNextTx.erase(txin.prevout);696        mapTransactions.erase(GetHash());697        nTransactionsUpdated++;698    }699    return true;700}701702703704705706707int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const708{709    if (hashBlock == 0 || nIndex == -1)710        return 0;711712    // Find the block it claims to be in713    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);714    if (mi == mapBlockIndex.end())715        return 0;716    CBlockIndex* pindex = (*mi).second;717    if (!pindex || !pindex->IsInMainChain())718        return 0;719720    // Make sure the merkle branch connects to this block721    if (!fMerkleVerified)722    {723        if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)724            return 0;725        fMerkleVerified = true;726    }727728    nHeightRet = pindex->nHeight;729    return pindexBest->nHeight - pindex->nHeight + 1;730}731732733int CMerkleTx::GetBlocksToMaturity() const734{735    if (!IsCoinBase())736        return 0;737    return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());738}739740741bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)742{743    if (fClient)744    {745        if (!IsInMainChain() && !ClientConnectInputs())746            return false;747        return CTransaction::AcceptToMemoryPool(txdb, false);748    }749    else750    {751        return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);752    }753}754755756757bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)758{759    CRITICAL_BLOCK(cs_mapTransactions)760    {761        // Add previous supporting transactions first762        foreach(CMerkleTx& tx, vtxPrev)763        {764            if (!tx.IsCoinBase())765            {766                uint256 hash = tx.GetHash();767                if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))768                    tx.AcceptToMemoryPool(txdb, fCheckInputs);769            }770        }771        return AcceptToMemoryPool(txdb, fCheckInputs);772    }773    return false;774}775776void ReacceptWalletTransactions()777{778    CTxDB txdb("r");779    CRITICAL_BLOCK(cs_mapWallet)780    {781        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)782        {783            CWalletTx& wtx = item.second;784            if (wtx.fSpent && wtx.IsCoinBase())785                continue;786787            CTxIndex txindex;788            if (txdb.ReadTxIndex(wtx.GetHash(), txindex))789            {790                // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat791                if (!wtx.fSpent)792                {793                    if (txindex.vSpent.size() != wtx.vout.size())794                    {795                        printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());796                        continue;797                    }798                    for (int i = 0; i < txindex.vSpent.size(); i++)799                    {800                        if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())801                        {802                            printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());803                            wtx.fSpent = true;804                            wtx.WriteToDisk();805                            break;806                        }807                    }808                }809            }810            else811            {812                // Reaccept any txes of ours that aren't already in a block813                if (!wtx.IsCoinBase())814                    wtx.AcceptWalletTransaction(txdb, false);815            }816        }817    }818}819820821void CWalletTx::RelayWalletTransaction(CTxDB& txdb)822{823    foreach(const CMerkleTx& tx, vtxPrev)824    {825        if (!tx.IsCoinBase())826        {827            uint256 hash = tx.GetHash();828            if (!txdb.ContainsTx(hash))829                RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);830        }831    }832    if (!IsCoinBase())833    {834        uint256 hash = GetHash();835        if (!txdb.ContainsTx(hash))836        {837            printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());838            RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);839        }840    }841}842843void ResendWalletTransactions()844{845    // Do this infrequently and randomly to avoid giving away846    // that these are our transactions.847    static int64 nNextTime;848    if (GetTime() < nNextTime)849        return;850    bool fFirst = (nNextTime == 0);851    nNextTime = GetTime() + GetRand(30 * 60);852    if (fFirst)853        return;854855    // Only do it if there's been a new block since last time856    static int64 nLastTime;857    if (nTimeBestReceived < nLastTime)858        return;859    nLastTime = GetTime();860861    // Rebroadcast any of our txes that aren't in a block yet862    printf("ResendWalletTransactions()\n");863    CTxDB txdb("r");864    CRITICAL_BLOCK(cs_mapWallet)865    {866        // Sort them in chronological order867        multimap<unsigned int, CWalletTx*> mapSorted;868        foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)869        {870            CWalletTx& wtx = item.second;871            // Don't rebroadcast until it's had plenty of time that872            // it should have gotten in already by now.873            if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)874                mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));875        }876        foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)877        {878            CWalletTx& wtx = *item.second;879            wtx.RelayWalletTransaction(txdb);880        }881    }882}883884885886887888889890891892893//////////////////////////////////////////////////////////////////////////////894//895// CBlock and CBlockIndex896//897898bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)899{900    if (!fReadTransactions)901    {902        *this = pindex->GetBlockHeader();903        return true;904    }905    if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))906        return false;907    if (GetHash() != pindex->GetBlockHash())908        return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");909    return true;910}911912uint256 GetOrphanRoot(const CBlock* pblock)913{914    // Work back to the first block in the orphan chain915    while (mapOrphanBlocks.count(pblock->hashPrevBlock))916        pblock = mapOrphanBlocks[pblock->hashPrevBlock];917    return pblock->GetHash();918}919920int64 GetBlockValue(int nHeight, int64 nFees)921{922    int64 nSubsidy = 50 * COIN;923924    // Subsidy is cut in half every 4 years925    nSubsidy >>= (nHeight / 210000);926927    return nSubsidy + nFees;928}929930unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)931{932    const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks933    const int64 nTargetSpacing = 10 * 60;934    const int64 nInterval = nTargetTimespan / nTargetSpacing;935936    // Genesis block937    if (pindexLast == NULL)938        return bnProofOfWorkLimit.GetCompact();939940    // Only change once per interval941    if ((pindexLast->nHeight+1) % nInterval != 0)942        return pindexLast->nBits;943944    // Go back by what we want to be 14 days worth of blocks945    const CBlockIndex* pindexFirst = pindexLast;946    for (int i = 0; pindexFirst && i < nInterval-1; i++)947        pindexFirst = pindexFirst->pprev;948    assert(pindexFirst);949950    // Limit adjustment step951    int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();952    printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);953    if (nActualTimespan < nTargetTimespan/4)954        nActualTimespan = nTargetTimespan/4;955    if (nActualTimespan > nTargetTimespan*4)956        nActualTimespan = nTargetTimespan*4;957958    // Retarget959    CBigNum bnNew;960    bnNew.SetCompact(pindexLast->nBits);961    bnNew *= nActualTimespan;962    bnNew /= nTargetTimespan;963964    if (bnNew > bnProofOfWorkLimit)965        bnNew = bnProofOfWorkLimit;966967    /// debug print968    printf("GetNextWorkRequired RETARGET\n");969    printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);970    printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());971    printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());972973    return bnNew.GetCompact();974}975976bool CheckProofOfWork(uint256 hash, unsigned int nBits)977{978    CBigNum bnTarget;979    bnTarget.SetCompact(nBits);980981    // Check range982    if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)983        return error("CheckProofOfWork() : nBits below minimum work");984985    // Check proof of work matches claimed amount986    if (hash > bnTarget.getuint256())987        return error("CheckProofOfWork() : hash doesn't match nBits");988989    return true;990}991992bool IsInitialBlockDownload()993{994    if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))995        return true;996    static int64 nLastUpdate;997    static CBlockIndex* pindexLastBest;998    if (pindexBest != pindexLastBest)999    {1000        pindexLastBest = pindexBest;1001        nLastUpdate = GetTime();1002    }1003    return (GetTime() - nLastUpdate < 10 &&1004            pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);1005}10061007void InvalidChainFound(CBlockIndex* pindexNew)1008{1009    if (pindexNew->bnChainWork > bnBestInvalidWork)1010    {1011        bnBestInvalidWork = pindexNew->bnChainWork;1012        CTxDB().WriteBestInvalidWork(bnBestInvalidWork);1013        MainFrameRepaint();1014    }1015    printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());1016    printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());1017    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)1018        printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");1019}102010211022102310241025102610271028102910301031bool CTransaction::DisconnectInputs(CTxDB& txdb)1032{1033    // Relinquish previous transactions' spent pointers1034    if (!IsCoinBase())1035    {1036        foreach(const CTxIn& txin, vin)1037        {1038            COutPoint prevout = txin.prevout;10391040            // Get prev txindex from disk1041            CTxIndex txindex;1042            if (!txdb.ReadTxIndex(prevout.hash, txindex))1043                return error("DisconnectInputs() : ReadTxIndex failed");10441045            if (prevout.n >= txindex.vSpent.size())1046                return error("DisconnectInputs() : prevout.n out of range");10471048            // Mark outpoint as not spent1049            txindex.vSpent[prevout.n].SetNull();10501051            // Write back1052            if (!txdb.UpdateTxIndex(prevout.hash, txindex))1053                return error("DisconnectInputs() : UpdateTxIndex failed");1054        }1055    }10561057    // Remove transaction from index1058    if (!txdb.EraseTxIndex(*this))1059        return error("DisconnectInputs() : EraseTxPos failed");10601061    return true;1062}106310641065bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,1066                                 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)1067{1068    // Take over previous transactions' spent pointers1069    if (!IsCoinBase())1070    {1071        int64 nValueIn = 0;1072        for (int i = 0; i < vin.size(); i++)1073        {1074            COutPoint prevout = vin[i].prevout;10751076            // Read txindex1077            CTxIndex txindex;1078            bool fFound = true;1079            if (fMiner && mapTestPool.count(prevout.hash))1080            {1081                // Get txindex from current proposed changes1082                txindex = mapTestPool[prevout.hash];1083            }1084            else1085            {1086                // Read txindex from txdb1087                fFound = txdb.ReadTxIndex(prevout.hash, txindex);1088            }1089            if (!fFound && (fBlock || fMiner))1090                return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());10911092            // Read txPrev1093            CTransaction txPrev;1094            if (!fFound || txindex.pos == CDiskTxPos(1,1,1))1095            {1096                // Get prev tx from single transactions in memory1097                CRITICAL_BLOCK(cs_mapTransactions)1098                {1099                    if (!mapTransactions.count(prevout.hash))1100                        return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());1101                    txPrev = mapTransactions[prevout.hash];1102                }1103                if (!fFound)1104                    txindex.vSpent.resize(txPrev.vout.size());1105            }1106            else1107            {1108                // Get prev tx from disk1109                if (!txPrev.ReadFromDisk(txindex.pos))1110                    return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());1111            }11121113            if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())1114                return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());11151116            // If prev is coinbase, check that it's matured1117            if (txPrev.IsCoinBase())1118                for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)1119                    if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)1120                        return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);11211122            // Verify signature1123            if (!VerifySignature(txPrev, *this, i))1124                return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());11251126            // Check for conflicts1127            if (!txindex.vSpent[prevout.n].IsNull())1128                return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());11291130            // Check for negative or overflow input values1131            nValueIn += txPrev.vout[prevout.n].nValue;1132            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))1133                return error("ConnectInputs() : txin values out of range");11341135            // Mark outpoints as spent1136            txindex.vSpent[prevout.n] = posThisTx;11371138            // Write back1139            if (fBlock)1140            {1141                if (!txdb.UpdateTxIndex(prevout.hash, txindex))1142                    return error("ConnectInputs() : UpdateTxIndex failed");1143            }1144            else if (fMiner)1145            {1146                mapTestPool[prevout.hash] = txindex;1147            }1148        }11491150        if (nValueIn < GetValueOut())1151            return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());11521153        // Tally transaction fees1154        int64 nTxFee = nValueIn - GetValueOut();1155        if (nTxFee < 0)1156            return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());1157        if (nTxFee < nMinFee)1158            return false;1159        nFees += nTxFee;1160        if (!MoneyRange(nFees))1161            return error("ConnectInputs() : nFees out of range");1162    }11631164    if (fBlock)1165    {1166        // Add transaction to disk index1167        if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))1168            return error("ConnectInputs() : AddTxPos failed");1169    }1170    else if (fMiner)1171    {1172        // Add transaction to test pool1173        mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());1174    }11751176    return true;1177}117811791180bool CTransaction::ClientConnectInputs()1181{1182    if (IsCoinBase())1183        return false;11841185    // Take over previous transactions' spent pointers1186    CRITICAL_BLOCK(cs_mapTransactions)1187    {1188        int64 nValueIn = 0;1189        for (int i = 0; i < vin.size(); i++)1190        {1191            // Get prev tx from single transactions in memory1192            COutPoint prevout = vin[i].prevout;1193            if (!mapTransactions.count(prevout.hash))1194                return false;1195            CTransaction& txPrev = mapTransactions[prevout.hash];11961197            if (prevout.n >= txPrev.vout.size())1198                return false;11991200            // Verify signature1201            if (!VerifySignature(txPrev, *this, i))1202                return error("ConnectInputs() : VerifySignature failed");12031204            ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of1205            ///// this has to go away now that posNext is gone1206            // // Check for conflicts1207            // if (!txPrev.vout[prevout.n].posNext.IsNull())1208            //     return error("ConnectInputs() : prev tx already used");1209            //1210            // // Flag outpoints as used1211            // txPrev.vout[prevout.n].posNext = posThisTx;12121213            nValueIn += txPrev.vout[prevout.n].nValue;12141215            if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))1216                return error("ClientConnectInputs() : txin values out of range");1217        }1218        if (GetValueOut() > nValueIn)1219            return false;1220    }12211222    return true;1223}12241225122612271228bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)1229{1230    // Disconnect in reverse order1231    for (int i = vtx.size()-1; i >= 0; i--)1232        if (!vtx[i].DisconnectInputs(txdb))1233            return false;12341235    // Update block index on disk without changing it in memory.1236    // The memory index structure will be changed after the db commits.1237    if (pindex->pprev)1238    {1239        CDiskBlockIndex blockindexPrev(pindex->pprev);1240        blockindexPrev.hashNext = 0;1241        if (!txdb.WriteBlockIndex(blockindexPrev))1242            return error("DisconnectBlock() : WriteBlockIndex failed");1243    }12441245    return true;1246}12471248bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)1249{1250    // Check it again in case a previous version let a bad block in1251    if (!CheckBlock())1252        return false;12531254    //// issue here: it doesn't know the version1255    unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());12561257    map<uint256, CTxIndex> mapUnused;1258    int64 nFees = 0;1259    foreach(CTransaction& tx, vtx)1260    {1261        CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);1262        nTxPos += ::GetSerializeSize(tx, SER_DISK);12631264        if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))1265            return false;1266    }12671268    if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))1269        return false;12701271    // Update block index on disk without changing it in memory.1272    // The memory index structure will be changed after the db commits.1273    if (pindex->pprev)1274    {1275        CDiskBlockIndex blockindexPrev(pindex->pprev);1276        blockindexPrev.hashNext = pindex->GetBlockHash();1277        if (!txdb.WriteBlockIndex(blockindexPrev))1278            return error("ConnectBlock() : WriteBlockIndex failed");1279    }12801281    // Watch for transactions paying to me1282    foreach(CTransaction& tx, vtx)1283        AddToWalletIfMine(tx, this);12841285    return true;1286}1287128812891290bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)1291{1292    printf("REORGANIZE\n");12931294    // Find the fork1295    CBlockIndex* pfork = pindexBest;1296    CBlockIndex* plonger = pindexNew;1297    while (pfork != plonger)1298    {1299        while (plonger->nHeight > pfork->nHeight)1300            if (!(plonger = plonger->pprev))1301                return error("Reorganize() : plonger->pprev is null");1302        if (pfork == plonger)1303            break;1304        if (!(pfork = pfork->pprev))1305            return error("Reorganize() : pfork->pprev is null");1306    }13071308    // List of what to disconnect1309    vector<CBlockIndex*> vDisconnect;1310    for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)1311        vDisconnect.push_back(pindex);13121313    // List of what to connect1314    vector<CBlockIndex*> vConnect;1315    for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)1316        vConnect.push_back(pindex);1317    reverse(vConnect.begin(), vConnect.end());13181319    // Disconnect shorter branch1320    vector<CTransaction> vResurrect;1321    foreach(CBlockIndex* pindex, vDisconnect)1322    {1323        CBlock block;1324        if (!block.ReadFromDisk(pindex))1325            return error("Reorganize() : ReadFromDisk for disconnect failed");1326        if (!block.DisconnectBlock(txdb, pindex))1327            return error("Reorganize() : DisconnectBlock failed");13281329        // Queue memory transactions to resurrect1330        foreach(const CTransaction& tx, block.vtx)1331            if (!tx.IsCoinBase())1332                vResurrect.push_back(tx);1333    }13341335    // Connect longer branch1336    vector<CTransaction> vDelete;1337    for (int i = 0; i < vConnect.size(); i++)1338    {1339        CBlockIndex* pindex = vConnect[i];1340        CBlock block;1341        if (!block.ReadFromDisk(pindex))1342            return error("Reorganize() : ReadFromDisk for connect failed");1343        if (!block.ConnectBlock(txdb, pindex))1344        {1345            // Invalid block1346            txdb.TxnAbort();1347            return error("Reorganize() : ConnectBlock failed");1348        }13491350        // Queue memory transactions to delete1351        foreach(const CTransaction& tx, block.vtx)1352            vDelete.push_back(tx);1353    }1354    if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))1355        return error("Reorganize() : WriteHashBestChain failed");13561357    // Make sure it's successfully written to disk before changing memory structure1358    if (!txdb.TxnCommit())1359        return error("Reorganize() : TxnCommit failed");13601361    // Disconnect shorter branch1362    foreach(CBlockIndex* pindex, vDisconnect)1363        if (pindex->pprev)1364            pindex->pprev->pnext = NULL;13651366    // Connect longer branch1367    foreach(CBlockIndex* pindex, vConnect)1368        if (pindex->pprev)1369            pindex->pprev->pnext = pindex;13701371    // Resurrect memory transactions that were in the disconnected branch1372    foreach(CTransaction& tx, vResurrect)1373        tx.AcceptToMemoryPool(txdb, false);13741375    // Delete redundant memory transactions that are in the connected branch1376    foreach(CTransaction& tx, vDelete)1377        tx.RemoveFromMemoryPool();13781379    return true;1380}138113821383bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)1384{1385    uint256 hash = GetHash();13861387    txdb.TxnBegin();1388    if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)1389    {1390        txdb.WriteHashBestChain(hash);1391        if (!txdb.TxnCommit())1392            return error("SetBestChain() : TxnCommit failed");1393        pindexGenesisBlock = pindexNew;1394    }1395    else if (hashPrevBlock == hashBestChain)1396    {1397        // Adding to current best branch1398        if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))1399        {1400            txdb.TxnAbort();1401            InvalidChainFound(pindexNew);1402            return error("SetBestChain() : ConnectBlock failed");1403        }1404        if (!txdb.TxnCommit())1405            return error("SetBestChain() : TxnCommit failed");14061407        // Add to current best branch1408        pindexNew->pprev->pnext = pindexNew;14091410        // Delete redundant memory transactions1411        foreach(CTransaction& tx, vtx)1412            tx.RemoveFromMemoryPool();1413    }1414    else1415    {1416        // New best branch1417        if (!Reorganize(txdb, pindexNew))1418        {1419            txdb.TxnAbort();1420            InvalidChainFound(pindexNew);1421            return error("SetBestChain() : Reorganize failed");1422        }1423    }14241425    // New best block1426    hashBestChain = hash;1427    pindexBest = pindexNew;1428    nBestHeight = pindexBest->nHeight;1429    bnBestChainWork = pindexNew->bnChainWork;1430    nTimeBestReceived = GetTime();1431    nTransactionsUpdated++;1432    printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());14331434    return true;1435}143614371438bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)1439{1440    // Check for duplicate1441    uint256 hash = GetHash();1442    if (mapBlockIndex.count(hash))1443        return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());14441445    // Construct new block index object1446    CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);1447    if (!pindexNew)1448        return error("AddToBlockIndex() : new CBlockIndex failed");1449    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;1450    pindexNew->phashBlock = &((*mi).first);1451    map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);1452    if (miPrev != mapBlockIndex.end())1453    {1454        pindexNew->pprev = (*miPrev).second;1455        pindexNew->nHeight = pindexNew->pprev->nHeight + 1;1456    }1457    pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();14581459    CTxDB txdb;1460    txdb.TxnBegin();1461    txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));1462    if (!txdb.TxnCommit())1463        return false;14641465    // New best1466    if (pindexNew->bnChainWork > bnBestChainWork)1467        if (!SetBestChain(txdb, pindexNew))1468            return false;14691470    txdb.Close();14711472    if (pindexNew == pindexBest)1473    {1474        // Notify UI to display prev block's coinbase if it was ours1475        static uint256 hashPrevBestCoinBase;1476        CRITICAL_BLOCK(cs_mapWallet)1477            vWalletUpdated.push_back(hashPrevBestCoinBase);1478        hashPrevBestCoinBase = vtx[0].GetHash();1479    }14801481    MainFrameRepaint();1482    return true;1483}14841485148614871488bool CBlock::CheckBlock() const1489{1490    // These are checks that are independent of context1491    // that can be verified before saving an orphan block.14921493    // Size limits1494    if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)1495        return error("CheckBlock() : size limits failed");14961497    // Check proof of work matches claimed amount1498    if (!CheckProofOfWork(GetHash(), nBits))1499        return error("CheckBlock() : proof of work failed");15001501    // Check timestamp1502    if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)1503        return error("CheckBlock() : block timestamp too far in the future");15041505    // First transaction must be coinbase, the rest must not be1506    if (vtx.empty() || !vtx[0].IsCoinBase())1507        return error("CheckBlock() : first tx is not coinbase");1508    for (int i = 1; i < vtx.size(); i++)1509        if (vtx[i].IsCoinBase())1510            return error("CheckBlock() : more than one coinbase");15111512    // Check transactions1513    foreach(const CTransaction& tx, vtx)1514        if (!tx.CheckTransaction())1515            return error("CheckBlock() : CheckTransaction failed");15161517    // Check that it's not full of nonstandard transactions1518    if (GetSigOpCount() > MAX_BLOCK_SIGOPS)1519        return error("CheckBlock() : too many nonstandard transactions");15201521    // Check merkleroot1522    if (hashMerkleRoot != BuildMerkleTree())1523        return error("CheckBlock() : hashMerkleRoot mismatch");15241525    return true;1526}15271528bool CBlock::AcceptBlock()1529{1530    // Check for duplicate1531    uint256 hash = GetHash();1532    if (mapBlockIndex.count(hash))1533        return error("AcceptBlock() : block already in mapBlockIndex");15341535    // Get prev block index1536    map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);1537    if (mi == mapBlockIndex.end())1538        return error("AcceptBlock() : prev block not found");1539    CBlockIndex* pindexPrev = (*mi).second;1540    int nHeight = pindexPrev->nHeight+1;15411542    // Check proof of work1543    if (nBits != GetNextWorkRequired(pindexPrev))1544        return error("AcceptBlock() : incorrect proof of work");15451546    // Check timestamp against prev1547    if (GetBlockTime() <= pindexPrev->GetMedianTimePast())1548        return error("AcceptBlock() : block's timestamp is too early");15491550    // Check that all transactions are finalized1551    foreach(const CTransaction& tx, vtx)1552        if (!tx.IsFinal(nHeight, GetBlockTime()))1553            return error("AcceptBlock() : contains a non-final transaction");15541555    // Check that the block chain matches the known block chain up to a checkpoint1556    if (!fTestNet)1557        if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||1558            (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||1559            (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||1560            (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||1561            (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))1562            return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);15631564    // Write block to history file1565    if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))1566        return error("AcceptBlock() : out of disk space");1567    unsigned int nFile = -1;1568    unsigned int nBlockPos = 0;1569    if (!WriteToDisk(nFile, nBlockPos))1570        return error("AcceptBlock() : WriteToDisk failed");1571    if (!AddToBlockIndex(nFile, nBlockPos))1572        return error("AcceptBlock() : AddToBlockIndex failed");15731574    // Relay inventory, but don't relay old inventory during initial block download1575    if (hashBestChain == hash)1576        CRITICAL_BLOCK(cs_vNodes)1577            foreach(CNode* pnode, vNodes)1578                if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))1579                    pnode->PushInventory(CInv(MSG_BLOCK, hash));15801581    return true;1582}15831584bool ProcessBlock(CNode* pfrom, CBlock* pblock)1585{1586    // Check for duplicate1587    uint256 hash = pblock->GetHash();1588    if (mapBlockIndex.count(hash))1589        return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());1590    if (mapOrphanBlocks.count(hash))1591        return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());15921593    // Preliminary checks1594    if (!pblock->CheckBlock())1595        return error("ProcessBlock() : CheckBlock FAILED");15961597    // If don't already have its previous block, shunt it off to holding area until we get it1598    if (!mapBlockIndex.count(pblock->hashPrevBlock))1599    {1600        printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());1601        CBlock* pblock2 = new CBlock(*pblock);1602        mapOrphanBlocks.insert(make_pair(hash, pblock2));1603        mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));16041605        // Ask this guy to fill in what we're missing1606        if (pfrom)1607            pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));1608        return true;1609    }16101611    // Store to disk1612    if (!pblock->AcceptBlock())1613        return error("ProcessBlock() : AcceptBlock FAILED");16141615    // Recursively process any orphan blocks that depended on this one1616    vector<uint256> vWorkQueue;1617    vWorkQueue.push_back(hash);1618    for (int i = 0; i < vWorkQueue.size(); i++)1619    {1620        uint256 hashPrev = vWorkQueue[i];1621        for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);1622             mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);1623             ++mi)1624        {1625            CBlock* pblockOrphan = (*mi).second;1626            if (pblockOrphan->AcceptBlock())1627                vWorkQueue.push_back(pblockOrphan->GetHash());1628            mapOrphanBlocks.erase(pblockOrphan->GetHash());1629            delete pblockOrphan;1630        }1631        mapOrphanBlocksByPrev.erase(hashPrev);1632    }16331634    printf("ProcessBlock: ACCEPTED\n");1635    return true;1636}163716381639164016411642164316441645template<typename Stream>1646bool ScanMessageStart(Stream& s)1647{1648    // Scan ahead to the next pchMessageStart, which should normally be immediately1649    // at the file pointer.  Leaves file pointer at end of pchMessageStart.1650    s.clear(0);1651    short prevmask = s.exceptions(0);1652    const char* p = BEGIN(pchMessageStart);1653    try1654    {1655        loop1656        {1657            char c;1658            s.read(&c, 1);1659            if (s.fail())1660            {1661                s.clear(0);1662                s.exceptions(prevmask);1663                return false;1664            }1665            if (*p != c)1666                p = BEGIN(pchMessageStart);1667            if (*p == c)1668            {1669                if (++p == END(pchMessageStart))1670                {1671                    s.clear(0);1672                    s.exceptions(prevmask);1673                    return true;1674                }1675            }1676        }1677    }1678    catch (...)1679    {1680        s.clear(0);1681        s.exceptions(prevmask);1682        return false;1683    }1684}16851686bool CheckDiskSpace(uint64 nAdditionalBytes)1687{1688    uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;16891690    // Check for 15MB because database could create another 10MB log file at any time1691    if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)1692    {1693        fShutdown = true;1694        string strMessage = _("Warning: Disk space is low  ");1695        strMiscWarning = strMessage;1696        printf("*** %s\n", strMessage.c_str());1697        ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);1698        CreateThread(Shutdown, NULL);1699        return false;1700    }1701    return true;1702}17031704FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)1705{1706    if (nFile == -1)1707        return NULL;1708    FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);1709    if (!file)1710        return NULL;1711    if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))1712    {1713        if (fseek(file, nBlockPos, SEEK_SET) != 0)1714        {1715            fclose(file);1716            return NULL;1717        }1718    }1719    return file;1720}17211722static unsigned int nCurrentBlockFile = 1;17231724FILE* AppendBlockFile(unsigned int& nFileRet)1725{1726    nFileRet = 0;1727    loop1728    {1729        FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");1730        if (!file)1731            return NULL;1732        if (fseek(file, 0, SEEK_END) != 0)1733            return NULL;1734        // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB1735        if (ftell(file) < 0x7F000000 - MAX_SIZE)1736        {1737            nFileRet = nCurrentBlockFile;1738            return file;1739        }1740        fclose(file);1741        nCurrentBlockFile++;1742    }1743}17441745bool LoadBlockIndex(bool fAllowNew)1746{1747    if (fTestNet)1748    {1749        hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");1750        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);1751        pchMessageStart[0] = 0xfa;1752        pchMessageStart[1] = 0xbf;1753        pchMessageStart[2] = 0xb5;1754        pchMessageStart[3] = 0xda;1755    }17561757    //1758    // Load block index1759    //1760    CTxDB txdb("cr");1761    if (!txdb.LoadBlockIndex())1762        return false;1763    txdb.Close();17641765    //1766    // Init with genesis block1767    //1768    if (mapBlockIndex.empty())1769    {1770        if (!fAllowNew)1771            return false;17721773        // Genesis Block:1774        // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)1775        //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)1776        //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)1777        //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)1778        //   vMerkleTree: 4a5e1e17791780        // Genesis block1781        const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";1782        CTransaction txNew;1783        txNew.vin.resize(1);1784        txNew.vout.resize(1);1785        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));1786        txNew.vout[0].nValue = 50 * COIN;1787        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;1788        CBlock block;1789        block.vtx.push_back(txNew);1790        block.hashPrevBlock = 0;1791        block.hashMerkleRoot = block.BuildMerkleTree();1792        block.nVersion = 1;1793        block.nTime    = 1231006505;1794        block.nBits    = 0x1d00ffff;1795        block.nNonce   = 2083236893;17961797        if (fTestNet)1798        {1799            block.nTime    = 1279232055;1800            block.nBits    = 0x1d07fff8;1801            block.nNonce   = 81622180;1802        }18031804        //// debug print1805        printf("%s\n", block.GetHash().ToString().c_str());1806        printf("%s\n", hashGenesisBlock.ToString().c_str());1807        printf("%s\n", block.hashMerkleRoot.ToString().c_str());1808        assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));1809        block.print();1810        assert(block.GetHash() == hashGenesisBlock);18111812        // Start new block file1813        unsigned int nFile;1814        unsigned int nBlockPos;1815        if (!block.WriteToDisk(nFile, nBlockPos))1816            return error("LoadBlockIndex() : writing genesis block to disk failed");1817        if (!block.AddToBlockIndex(nFile, nBlockPos))1818            return error("LoadBlockIndex() : genesis block not accepted");1819    }18201821    return true;1822}1823182418251826void PrintBlockTree()1827{1828    // precompute tree structure1829    map<CBlockIndex*, vector<CBlockIndex*> > mapNext;1830    for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)1831    {1832        CBlockIndex* pindex = (*mi).second;1833        mapNext[pindex->pprev].push_back(pindex);1834        // test1835        //while (rand() % 3 == 0)1836        //    mapNext[pindex->pprev].push_back(pindex);1837    }18381839    vector<pair<int, CBlockIndex*> > vStack;1840    vStack.push_back(make_pair(0, pindexGenesisBlock));18411842    int nPrevCol = 0;1843    while (!vStack.empty())1844    {1845        int nCol = vStack.back().first;1846        CBlockIndex* pindex = vStack.back().second;1847        vStack.pop_back();18481849        // print split or gap1850        if (nCol > nPrevCol)1851        {1852            for (int i = 0; i < nCol-1; i++)1853                printf("| ");1854            printf("|\\\n");1855        }1856        else if (nCol < nPrevCol)1857        {1858            for (int i = 0; i < nCol; i++)1859                printf("| ");1860            printf("|\n");1861        }1862        nPrevCol = nCol;18631864        // print columns1865        for (int i = 0; i < nCol; i++)1866            printf("| ");18671868        // print item1869        CBlock block;1870        block.ReadFromDisk(pindex);1871        printf("%d (%u,%u) %s  %s  tx %d",1872            pindex->nHeight,1873            pindex->nFile,1874            pindex->nBlockPos,1875            block.GetHash().ToString().substr(0,20).c_str(),1876            DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),1877            block.vtx.size());18781879        CRITICAL_BLOCK(cs_mapWallet)1880        {1881            if (mapWallet.count(block.vtx[0].GetHash()))1882            {1883                CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];1884                printf("    mine:  %d  %d  %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());1885            }1886        }1887        printf("\n");188818891890        // put the main timechain first1891        vector<CBlockIndex*>& vNext = mapNext[pindex];1892        for (int i = 0; i < vNext.size(); i++)1893        {1894            if (vNext[i]->pnext)1895            {1896                swap(vNext[0], vNext[i]);1897                break;1898            }1899        }19001901        // iterate children1902        for (int i = 0; i < vNext.size(); i++)1903            vStack.push_back(make_pair(nCol+i, vNext[i]));1904    }1905}19061907190819091910191119121913191419151916//////////////////////////////////////////////////////////////////////////////1917//1918// CAlert1919//19201921map<uint256, CAlert> mapAlerts;1922CCriticalSection cs_mapAlerts;19231924string GetWarnings(string strFor)1925{1926    int nPriority = 0;1927    string strStatusBar;1928    string strRPC;1929    if (GetBoolArg("-testsafemode"))1930        strRPC = "test";19311932    // Misc warnings like out of disk space and clock is wrong1933    if (strMiscWarning != "")1934    {1935        nPriority = 1000;1936        strStatusBar = strMiscWarning;1937    }19381939    // Longer invalid proof-of-work chain1940    if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)1941    {1942        nPriority = 2000;1943        strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";1944    }19451946    // Alerts1947    CRITICAL_BLOCK(cs_mapAlerts)1948    {1949        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)1950        {1951            const CAlert& alert = item.second;1952            if (alert.AppliesToMe() && alert.nPriority > nPriority)1953            {1954                nPriority = alert.nPriority;1955                strStatusBar = alert.strStatusBar;1956            }1957        }1958    }19591960    if (strFor == "statusbar")1961        return strStatusBar;1962    else if (strFor == "rpc")1963        return strRPC;1964    assert(("GetWarnings() : invalid parameter", false));1965    return "error";1966}19671968bool CAlert::ProcessAlert()1969{1970    if (!CheckSignature())1971        return false;1972    if (!IsInEffect())1973        return false;19741975    CRITICAL_BLOCK(cs_mapAlerts)1976    {1977        // Cancel previous alerts1978        for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)1979        {1980            const CAlert& alert = (*mi).second;1981            if (Cancels(alert))1982            {1983                printf("cancelling alert %d\n", alert.nID);1984                mapAlerts.erase(mi++);1985            }1986            else if (!alert.IsInEffect())1987            {1988                printf("expiring alert %d\n", alert.nID);1989                mapAlerts.erase(mi++);1990            }1991            else1992                mi++;1993        }19941995        // Check if this alert has been cancelled1996        foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)1997        {1998            const CAlert& alert = item.second;1999            if (alert.Cancels(*this))2000            {2001                printf("alert already cancelled by %d\n", alert.nID);2002                return false;2003            }2004        }20052006        // Add to mapAlerts2007        mapAlerts.insert(make_pair(GetHash(), *this));2008    }20092010    printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());2011    MainFrameRepaint();2012    return true;2013}201420152016201720182019202020212022//////////////////////////////////////////////////////////////////////////////2023//2024// Messages2025//202620272028bool AlreadyHave(CTxDB& txdb, const CInv& inv)2029{2030    switch (inv.type)2031    {2032    case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);2033    case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);2034    }2035    // Don't know what it is, just say we already got one2036    return true;2037}20382039204020412042// The message start string is designed to be unlikely to occur in normal data.2043// The characters are rarely used upper ascii, not valid as UTF-8, and produce2044// a large 4-byte int at any alignment.2045char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };204620472048bool ProcessMessages(CNode* pfrom)2049{2050    CDataStream& vRecv = pfrom->vRecv;2051    if (vRecv.empty())2052        return true;2053    //if (fDebug)2054    //    printf("ProcessMessages(%u bytes)\n", vRecv.size());20552056    //2057    // Message format2058    //  (4) message start2059    //  (12) command2060    //  (4) size2061    //  (4) checksum2062    //  (x) data2063    //20642065    loop2066    {2067        // Scan for message start2068        CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));2069        int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());2070        if (vRecv.end() - pstart < nHeaderSize)2071        {2072            if (vRecv.size() > nHeaderSize)2073            {2074                printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");2075                vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);2076            }2077            break;2078        }2079        if (pstart - vRecv.begin() > 0)2080            printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());2081        vRecv.erase(vRecv.begin(), pstart);20822083        // Read header2084        vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);2085        CMessageHeader hdr;2086        vRecv >> hdr;2087        if (!hdr.IsValid())2088        {2089            printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());2090            continue;2091        }2092        string strCommand = hdr.GetCommand();20932094        // Message size2095        unsigned int nMessageSize = hdr.nMessageSize;2096        if (nMessageSize > MAX_SIZE)2097        {2098            printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);2099            continue;2100        }2101        if (nMessageSize > vRecv.size())2102        {2103            // Rewind and wait for rest of message2104            vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());2105            break;2106        }21072108        // Checksum2109        if (vRecv.GetVersion() >= 209)2110        {2111            uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);2112            unsigned int nChecksum = 0;2113            memcpy(&nChecksum, &hash, sizeof(nChecksum));2114            if (nChecksum != hdr.nChecksum)2115            {2116                printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",2117                       strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);2118                continue;2119            }2120        }21212122        // Copy message to its own buffer2123        CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);2124        vRecv.ignore(nMessageSize);21252126        // Process message2127        bool fRet = false;2128        try2129        {2130            CRITICAL_BLOCK(cs_main)2131                fRet = ProcessMessage(pfrom, strCommand, vMsg);2132            if (fShutdown)2133                return true;2134        }2135        catch (std::ios_base::failure& e)2136        {2137            if (strstr(e.what(), "end of data"))2138            {2139                // Allow exceptions from underlength message on vRecv2140                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());2141            }2142            else if (strstr(e.what(), "size too large"))2143            {2144                // Allow exceptions from overlong size2145                printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());2146            }2147            else2148            {2149                PrintExceptionContinue(&e, "ProcessMessage()");2150            }2151        }2152        catch (std::exception& e) {2153            PrintExceptionContinue(&e, "ProcessMessage()");2154        } catch (...) {2155            PrintExceptionContinue(NULL, "ProcessMessage()");2156        }21572158        if (!fRet)2159            printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);2160    }21612162    vRecv.Compact();2163    return true;2164}21652166216721682169bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)2170{2171    static map<unsigned int, vector<unsigned char> > mapReuseKey;2172    RandAddSeedPerfmon();2173    if (fDebug)2174        printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());2175    printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());2176    if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)2177    {2178        printf("dropmessagestest DROPPING RECV MESSAGE\n");2179        return true;2180    }218121822183218421852186    if (strCommand == "version")2187    {2188        // Each connection can only send one version message2189        if (pfrom->nVersion != 0)2190            return false;21912192        int64 nTime;2193        CAddress addrMe;2194        CAddress addrFrom;2195        uint64 nNonce = 1;2196        vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;2197        if (pfrom->nVersion == 10300)2198            pfrom->nVersion = 300;2199        if (pfrom->nVersion >= 106 && !vRecv.empty())2200            vRecv >> addrFrom >> nNonce;2201        if (pfrom->nVersion >= 106 && !vRecv.empty())2202            vRecv >> pfrom->strSubVer;2203        if (pfrom->nVersion >= 209 && !vRecv.empty())2204            vRecv >> pfrom->nStartingHeight;22052206        if (pfrom->nVersion == 0)2207            return false;22082209        // Disconnect if we connected to ourself2210        if (nNonce == nLocalHostNonce && nNonce > 1)2211        {2212            printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());2213            pfrom->fDisconnect = true;2214            return true;2215        }22162217        pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);22182219        AddTimeData(pfrom->addr.ip, nTime);22202221        // Change version2222        if (pfrom->nVersion >= 209)2223            pfrom->PushMessage("verack");2224        pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));2225        if (pfrom->nVersion < 209)2226            pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));22272228        if (!pfrom->fInbound)2229        {2230            // Advertise our address2231            if (addrLocalHost.IsRoutable() && !fUseProxy)2232            {2233                CAddress addr(addrLocalHost);2234                addr.nTime = GetAdjustedTime();2235                pfrom->PushAddress(addr);2236            }22372238            // Get recent addresses2239            if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)2240            {2241                pfrom->PushMessage("getaddr");2242                pfrom->fGetAddr = true;2243            }2244        }22452246        // Ask the first connected node for block updates2247        static int nAskedForBlocks;2248        if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))2249        {2250            nAskedForBlocks++;2251            pfrom->PushGetBlocks(pindexBest, uint256(0));2252        }22532254        // Relay alerts2255        CRITICAL_BLOCK(cs_mapAlerts)2256            foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)2257                item.second.RelayTo(pfrom);22582259        pfrom->fSuccessfullyConnected = true;22602261        printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);2262    }226322642265    else if (pfrom->nVersion == 0)2266    {2267        // Must have a version message before anything else2268        return false;2269    }227022712272    else if (strCommand == "verack")2273    {2274        pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));2275    }227622772278    else if (strCommand == "addr")2279    {2280        vector<CAddress> vAddr;2281        vRecv >> vAddr;22822283        // Don't want addr from older versions unless seeding2284        if (pfrom->nVersion < 209)2285            return true;2286        if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)2287            return true;2288        if (vAddr.size() > 1000)2289            return error("message addr size() = %d", vAddr.size());22902291        // Store the new addresses2292        int64 nNow = GetAdjustedTime();2293        int64 nSince = nNow - 10 * 60;2294        foreach(CAddress& addr, vAddr)2295        {2296            if (fShutdown)2297                return true;2298            // ignore IPv6 for now, since it isn't implemented anyway2299            if (!addr.IsIPv4())2300                continue;2301            if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)2302                addr.nTime = nNow - 5 * 24 * 60 * 60;2303            AddAddress(addr, 2 * 60 * 60);2304            pfrom->AddAddressKnown(addr);2305            if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())2306            {2307                // Relay to a limited number of other nodes2308                CRITICAL_BLOCK(cs_vNodes)2309                {2310                    // Use deterministic randomness to send to the same nodes for 24 hours2311                    // at a time so the setAddrKnowns of the chosen nodes prevent repeats2312                    static uint256 hashSalt;2313                    if (hashSalt == 0)2314                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));2315                    uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));2316                    hashRand = Hash(BEGIN(hashRand), END(hashRand));2317                    multimap<uint256, CNode*> mapMix;2318                    foreach(CNode* pnode, vNodes)2319                    {2320                        if (pnode->nVersion < 31402)2321                            continue;2322                        unsigned int nPointer;2323                        memcpy(&nPointer, &pnode, sizeof(nPointer));2324                        uint256 hashKey = hashRand ^ nPointer;2325                        hashKey = Hash(BEGIN(hashKey), END(hashKey));2326                        mapMix.insert(make_pair(hashKey, pnode));2327                    }2328                    int nRelayNodes = 2;2329                    for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)2330                        ((*mi).second)->PushAddress(addr);2331                }2332            }2333        }2334        if (vAddr.size() < 1000)2335            pfrom->fGetAddr = false;2336    }233723382339    else if (strCommand == "inv")2340    {2341        vector<CInv> vInv;2342        vRecv >> vInv;2343        if (vInv.size() > 50000)2344            return error("message inv size() = %d", vInv.size());23452346        CTxDB txdb("r");2347        foreach(const CInv& inv, vInv)2348        {2349            if (fShutdown)2350                return true;2351            pfrom->AddInventoryKnown(inv);23522353            bool fAlreadyHave = AlreadyHave(txdb, inv);2354            printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");23552356            if (!fAlreadyHave)2357                pfrom->AskFor(inv);2358            else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))2359                pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));23602361            // Track requests for our stuff2362            CRITICAL_BLOCK(cs_mapRequestCount)2363            {2364                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);2365                if (mi != mapRequestCount.end())2366                    (*mi).second++;2367            }2368        }2369    }237023712372    else if (strCommand == "getdata")2373    {2374        vector<CInv> vInv;2375        vRecv >> vInv;2376        if (vInv.size() > 50000)2377            return error("message getdata size() = %d", vInv.size());23782379        foreach(const CInv& inv, vInv)2380        {2381            if (fShutdown)2382                return true;2383            printf("received getdata for: %s\n", inv.ToString().c_str());23842385            if (inv.type == MSG_BLOCK)2386            {2387                // Send block from disk2388                map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);2389                if (mi != mapBlockIndex.end())2390                {2391                    CBlock block;2392                    block.ReadFromDisk((*mi).second);2393                    pfrom->PushMessage("block", block);23942395                    // Trigger them to send a getblocks request for the next batch of inventory2396                    if (inv.hash == pfrom->hashContinue)2397                    {2398                        // Bypass PushInventory, this must send even if redundant,2399                        // and we want it right after the last block so they don't2400                        // wait for other stuff first.2401                        vector<CInv> vInv;2402                        vInv.push_back(CInv(MSG_BLOCK, hashBestChain));2403                        pfrom->PushMessage("inv", vInv);2404                        pfrom->hashContinue = 0;2405                    }2406                }2407            }2408            else if (inv.IsKnownType())2409            {2410                // Send stream from relay memory2411                CRITICAL_BLOCK(cs_mapRelay)2412                {2413                    map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);2414                    if (mi != mapRelay.end())2415                        pfrom->PushMessage(inv.GetCommand(), (*mi).second);2416                }2417            }24182419            // Track requests for our stuff2420            CRITICAL_BLOCK(cs_mapRequestCount)2421            {2422                map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);2423                if (mi != mapRequestCount.end())2424                    (*mi).second++;2425            }2426        }2427    }242824292430    else if (strCommand == "getblocks")2431    {2432        CBlockLocator locator;2433        uint256 hashStop;2434        vRecv >> locator >> hashStop;24352436        // Find the last block the caller has in the main chain2437        CBlockIndex* pindex = locator.GetBlockIndex();24382439        // Send the rest of the chain2440        if (pindex)2441            pindex = pindex->pnext;2442        int nLimit = 500 + locator.GetDistanceBack();2443        printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);2444        for (; pindex; pindex = pindex->pnext)2445        {2446            if (pindex->GetBlockHash() == hashStop)2447            {2448                printf("  getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());2449                break;2450            }2451            pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));2452            if (--nLimit <= 0)2453            {2454                // When this block is requested, we'll send an inv that'll make them2455                // getblocks the next batch of inventory.2456                printf("  getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());2457                pfrom->hashContinue = pindex->GetBlockHash();2458                break;2459            }2460        }2461    }246224632464    else if (strCommand == "getheaders")2465    {2466        CBlockLocator locator;2467        uint256 hashStop;2468        vRecv >> locator >> hashStop;24692470        CBlockIndex* pindex = NULL;2471        if (locator.IsNull())2472        {2473            // If locator is null, return the hashStop block2474            map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);2475            if (mi == mapBlockIndex.end())2476                return true;2477            pindex = (*mi).second;2478        }2479        else2480        {2481            // Find the last block the caller has in the main chain2482            pindex = locator.GetBlockIndex();2483            if (pindex)2484                pindex = pindex->pnext;2485        }24862487        vector<CBlock> vHeaders;2488        int nLimit = 2000 + locator.GetDistanceBack();2489        printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);2490        for (; pindex; pindex = pindex->pnext)2491        {2492            vHeaders.push_back(pindex->GetBlockHeader());2493            if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)2494                break;2495        }2496        pfrom->PushMessage("headers", vHeaders);2497    }249824992500    else if (strCommand == "tx")2501    {2502        vector<uint256> vWorkQueue;2503        CDataStream vMsg(vRecv);2504        CTransaction tx;2505        vRecv >> tx;25062507        CInv inv(MSG_TX, tx.GetHash());2508        pfrom->AddInventoryKnown(inv);25092510        bool fMissingInputs = false;2511        if (tx.AcceptToMemoryPool(true, &fMissingInputs))2512        {2513            AddToWalletIfMine(tx, NULL);2514            RelayMessage(inv, vMsg);2515            mapAlreadyAskedFor.erase(inv);2516            vWorkQueue.push_back(inv.hash);25172518            // Recursively process any orphan transactions that depended on this one2519            for (int i = 0; i < vWorkQueue.size(); i++)2520            {2521                uint256 hashPrev = vWorkQueue[i];2522                for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);2523                     mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);2524                     ++mi)2525                {2526                    const CDataStream& vMsg = *((*mi).second);2527                    CTransaction tx;2528                    CDataStream(vMsg) >> tx;2529                    CInv inv(MSG_TX, tx.GetHash());25302531                    if (tx.AcceptToMemoryPool(true))2532                    {2533                        printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());2534                        AddToWalletIfMine(tx, NULL);2535                        RelayMessage(inv, vMsg);2536                        mapAlreadyAskedFor.erase(inv);2537                        vWorkQueue.push_back(inv.hash);2538                    }2539                }2540            }25412542            foreach(uint256 hash, vWorkQueue)2543                EraseOrphanTx(hash);2544        }2545        else if (fMissingInputs)2546        {2547            printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());2548            AddOrphanTx(vMsg);2549        }2550    }255125522553    else if (strCommand == "block")2554    {2555        CBlock block;2556        vRecv >> block;25572558        printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());2559        // block.print();25602561        CInv inv(MSG_BLOCK, block.GetHash());2562        pfrom->AddInventoryKnown(inv);25632564        if (ProcessBlock(pfrom, &block))2565            mapAlreadyAskedFor.erase(inv);2566    }256725682569    else if (strCommand == "getaddr")2570    {2571        // Nodes rebroadcast an addr every 24 hours2572        pfrom->vAddrToSend.clear();2573        int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours2574        CRITICAL_BLOCK(cs_mapAddresses)2575        {2576            unsigned int nCount = 0;2577            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)2578            {2579                const CAddress& addr = item.second;2580                if (addr.nTime > nSince)2581                    nCount++;2582            }2583            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)2584            {2585                const CAddress& addr = item.second;2586                if (addr.nTime > nSince && GetRand(nCount) < 2500)2587                    pfrom->PushAddress(addr);2588            }2589        }2590    }259125922593    else if (strCommand == "checkorder")2594    {2595        uint256 hashReply;2596        vRecv >> hashReply;25972598        if (!GetBoolArg("-allowreceivebyip"))2599        {2600            pfrom->PushMessage("reply", hashReply, (int)2, string(""));2601            return true;2602        }26032604        CWalletTx order;2605        vRecv >> order;26062607        /// we have a chance to check the order here26082609        // Keep giving the same key to the same ip until they use it2610        if (!mapReuseKey.count(pfrom->addr.ip))2611            mapReuseKey[pfrom->addr.ip] = GetKeyFromKeyPool();26122613        // Send back approval of order and pubkey to use2614        CScript scriptPubKey;2615        scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;2616        pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);2617    }261826192620    else if (strCommand == "submitorder")2621    {2622        uint256 hashReply;2623        vRecv >> hashReply;26242625        if (!GetBoolArg("-allowreceivebyip"))2626        {2627            pfrom->PushMessage("reply", hashReply, (int)2);2628            return true;2629        }26302631        CWalletTx wtxNew;2632        vRecv >> wtxNew;2633        wtxNew.fFromMe = false;26342635        // Broadcast2636        if (!wtxNew.AcceptWalletTransaction())2637        {2638            pfrom->PushMessage("reply", hashReply, (int)1);2639            return error("submitorder AcceptWalletTransaction() failed, returning error 1");2640        }2641        wtxNew.fTimeReceivedIsTxTime = true;2642        AddToWallet(wtxNew);2643        wtxNew.RelayWalletTransaction();2644        mapReuseKey.erase(pfrom->addr.ip);26452646        // Send back confirmation2647        pfrom->PushMessage("reply", hashReply, (int)0);2648    }264926502651    else if (strCommand == "reply")2652    {2653        uint256 hashReply;2654        vRecv >> hashReply;26552656        CRequestTracker tracker;2657        CRITICAL_BLOCK(pfrom->cs_mapRequests)2658        {2659            map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);2660            if (mi != pfrom->mapRequests.end())2661            {2662                tracker = (*mi).second;2663                pfrom->mapRequests.erase(mi);2664            }2665        }2666        if (!tracker.IsNull())2667            tracker.fn(tracker.param1, vRecv);2668    }266926702671    else if (strCommand == "ping")2672    {2673    }267426752676    else if (strCommand == "alert")2677    {2678        CAlert alert;2679        vRecv >> alert;26802681        if (alert.ProcessAlert())2682        {2683            // Relay2684            pfrom->setKnown.insert(alert.GetHash());2685            CRITICAL_BLOCK(cs_vNodes)2686                foreach(CNode* pnode, vNodes)2687                    alert.RelayTo(pnode);2688        }2689    }269026912692    else2693    {2694        // Ignore unknown commands for extensibility2695    }269626972698    // Update the last seen time for this node's address2699    if (pfrom->fNetworkNode)2700        if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")2701            AddressCurrentlyConnected(pfrom->addr);270227032704    return true;2705}2706270727082709271027112712271327142715bool SendMessages(CNode* pto, bool fSendTrickle)2716{2717    CRITICAL_BLOCK(cs_main)2718    {2719        // Don't send anything until we get their version message2720        if (pto->nVersion == 0)2721            return true;27222723        // Keep-alive ping2724        if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())2725            pto->PushMessage("ping");27262727        // Resend wallet transactions that haven't gotten in a block yet2728        ResendWalletTransactions();27292730        // Address refresh broadcast2731        static int64 nLastRebroadcast;2732        if (GetTime() - nLastRebroadcast > 24 * 60 * 60)2733        {2734            nLastRebroadcast = GetTime();2735            CRITICAL_BLOCK(cs_vNodes)2736            {2737                foreach(CNode* pnode, vNodes)2738                {2739                    // Periodically clear setAddrKnown to allow refresh broadcasts2740                    pnode->setAddrKnown.clear();27412742                    // Rebroadcast our address2743                    if (addrLocalHost.IsRoutable() && !fUseProxy)2744                    {2745                        CAddress addr(addrLocalHost);2746                        addr.nTime = GetAdjustedTime();2747                        pnode->PushAddress(addr);2748                    }2749                }2750            }2751        }27522753        // Clear out old addresses periodically so it's not too much work at once2754        static int64 nLastClear;2755        if (nLastClear == 0)2756            nLastClear = GetTime();2757        if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)2758        {2759            nLastClear = GetTime();2760            CRITICAL_BLOCK(cs_mapAddresses)2761            {2762                CAddrDB addrdb;2763                int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;2764                for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();2765                     mi != mapAddresses.end();)2766                {2767                    const CAddress& addr = (*mi).second;2768                    if (addr.nTime < nSince)2769                    {2770                        if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)2771                            break;2772                        addrdb.EraseAddress(addr);2773                        mapAddresses.erase(mi++);2774                    }2775                    else2776                        mi++;2777                }2778            }2779        }278027812782        //2783        // Message: addr2784        //2785        if (fSendTrickle)2786        {2787            vector<CAddress> vAddr;2788            vAddr.reserve(pto->vAddrToSend.size());2789            foreach(const CAddress& addr, pto->vAddrToSend)2790            {2791                // returns true if wasn't already contained in the set2792                if (pto->setAddrKnown.insert(addr).second)2793                {2794                    vAddr.push_back(addr);2795                    // receiver rejects addr messages larger than 10002796                    if (vAddr.size() >= 1000)2797                    {2798                        pto->PushMessage("addr", vAddr);2799                        vAddr.clear();2800                    }2801                }2802            }2803            pto->vAddrToSend.clear();2804            if (!vAddr.empty())2805                pto->PushMessage("addr", vAddr);2806        }280728082809        //2810        // Message: inventory2811        //2812        vector<CInv> vInv;2813        vector<CInv> vInvWait;2814        CRITICAL_BLOCK(pto->cs_inventory)2815        {2816            vInv.reserve(pto->vInventoryToSend.size());2817            vInvWait.reserve(pto->vInventoryToSend.size());2818            foreach(const CInv& inv, pto->vInventoryToSend)2819            {2820                if (pto->setInventoryKnown.count(inv))2821                    continue;28222823                // trickle out tx inv to protect privacy2824                if (inv.type == MSG_TX && !fSendTrickle)2825                {2826                    // 1/4 of tx invs blast to all immediately2827                    static uint256 hashSalt;2828                    if (hashSalt == 0)2829                        RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));2830                    uint256 hashRand = inv.hash ^ hashSalt;2831                    hashRand = Hash(BEGIN(hashRand), END(hashRand));2832                    bool fTrickleWait = ((hashRand & 3) != 0);28332834                    // always trickle our own transactions2835                    if (!fTrickleWait)2836                    {2837                        TRY_CRITICAL_BLOCK(cs_mapWallet)2838                        {2839                            map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);2840                            if (mi != mapWallet.end())2841                            {2842                                CWalletTx& wtx = (*mi).second;2843                                if (wtx.fFromMe)2844                                    fTrickleWait = true;2845                            }2846                        }2847                    }28482849                    if (fTrickleWait)2850                    {2851                        vInvWait.push_back(inv);2852                        continue;2853                    }2854                }28552856                // returns true if wasn't already contained in the set2857                if (pto->setInventoryKnown.insert(inv).second)2858                {2859                    vInv.push_back(inv);2860                    if (vInv.size() >= 1000)2861                    {2862                        pto->PushMessage("inv", vInv);2863                        vInv.clear();2864                    }2865                }2866            }2867            pto->vInventoryToSend = vInvWait;2868        }2869        if (!vInv.empty())2870            pto->PushMessage("inv", vInv);287128722873        //2874        // Message: getdata2875        //2876        vector<CInv> vGetData;2877        int64 nNow = GetTime() * 1000000;2878        CTxDB txdb("r");2879        while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)2880        {2881            const CInv& inv = (*pto->mapAskFor.begin()).second;2882            if (!AlreadyHave(txdb, inv))2883            {2884                printf("sending getdata: %s\n", inv.ToString().c_str());2885                vGetData.push_back(inv);2886                if (vGetData.size() >= 1000)2887                {2888                    pto->PushMessage("getdata", vGetData);2889                    vGetData.clear();2890                }2891            }2892            pto->mapAskFor.erase(pto->mapAskFor.begin());2893        }2894        if (!vGetData.empty())2895            pto->PushMessage("getdata", vGetData);28962897    }2898    return true;2899}290029012902290329042905290629072908290929102911291229132914//////////////////////////////////////////////////////////////////////////////2915//2916// BitcoinMiner2917//29182919void GenerateBitcoins(bool fGenerate)2920{2921    if (fGenerateBitcoins != fGenerate)2922    {2923        fGenerateBitcoins = fGenerate;2924        CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);2925        MainFrameRepaint();2926    }2927    if (fGenerateBitcoins)2928    {2929        int nProcessors = boost::thread::hardware_concurrency();2930        printf("%d processors\n", nProcessors);2931        if (nProcessors < 1)2932            nProcessors = 1;2933        if (fLimitProcessors && nProcessors > nLimitProcessors)2934            nProcessors = nLimitProcessors;2935        int nAddThreads = nProcessors - vnThreadsRunning[3];2936        printf("Starting %d BitcoinMiner threads\n", nAddThreads);2937        for (int i = 0; i < nAddThreads; i++)2938        {2939            if (!CreateThread(ThreadBitcoinMiner, NULL))2940                printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");2941            Sleep(10);2942        }2943    }2944}29452946void ThreadBitcoinMiner(void* parg)2947{2948    try2949    {2950        vnThreadsRunning[3]++;2951        BitcoinMiner();2952        vnThreadsRunning[3]--;2953    }2954    catch (std::exception& e) {2955        vnThreadsRunning[3]--;2956        PrintException(&e, "ThreadBitcoinMiner()");2957    } catch (...) {2958        vnThreadsRunning[3]--;2959        PrintException(NULL, "ThreadBitcoinMiner()");2960    }2961    UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));2962    nHPSTimerStart = 0;2963    if (vnThreadsRunning[3] == 0)2964        dHashesPerSec = 0;2965    printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);2966}29672968#if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)2969void CallCPUID(int in, int& aret, int& cret)2970{2971    int a, c;2972    asm (2973        "mov %2, %%eax; " // in into eax2974        "cpuid;"2975        "mov %%eax, %0;" // eax into a2976        "mov %%ecx, %1;" // ecx into c2977        :"=r"(a),"=r"(c) /* output */2978        :"r"(in) /* input */2979        :"%eax","%ecx" /* clobbered register */2980    );2981    aret = a;2982    cret = c;2983}29842985bool Detect128BitSSE2()2986{2987    int a, c, nBrand;2988    CallCPUID(0, a, nBrand);2989    bool fIntel = (nBrand == 0x6c65746e); // ntel2990    bool fAMD = (nBrand == 0x444d4163); // cAMD29912992    struct2993    {2994        unsigned int nStepping : 4;2995        unsigned int nModel : 4;2996        unsigned int nFamily : 4;2997        unsigned int nProcessorType : 2;2998        unsigned int nUnused : 2;2999        unsigned int nExtendedModel : 4;3000        unsigned int nExtendedFamily : 8;3001    }3002    cpu;3003    CallCPUID(1, a, c);3004    memcpy(&cpu, &a, sizeof(cpu));3005    int nFamily = cpu.nExtendedFamily + cpu.nFamily;3006    int nModel = cpu.nExtendedModel*16 + cpu.nModel;30073008    // We need Intel Nehalem or AMD K10 or better for 128bit SSE23009    // Nehalem = i3/i5/i7 and some Xeon3010    // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II3011    //  Intel Core i5  family 6, model 26 or 303012    //  Intel Core i7  family 6, model 26 or 303013    //  Intel Core i3  family 6, model 373014    //  AMD Phenom    family 16, model 103015    bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >=  60026) ||3016                     (fAMD   && nFamily * 10000 + nModel >= 160010));30173018    // AMD reports a lower model number in 64-bit mode3019    if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)3020        fUseSSE2 = true;30213022    static bool fPrinted;3023    if (!fPrinted)3024    {3025        fPrinted = true;3026        printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);3027    }3028    return fUseSSE2;3029}3030#else3031bool Detect128BitSSE2() { return false; }3032#endif30333034int FormatHashBlocks(void* pbuffer, unsigned int len)3035{3036    unsigned char* pdata = (unsigned char*)pbuffer;3037    unsigned int blocks = 1 + ((len + 8) / 64);3038    unsigned char* pend = pdata + 64 * blocks;3039    memset(pdata + len, 0, 64 * blocks - len);3040    pdata[len] = 0x80;3041    unsigned int bits = len * 8;3042    pend[-1] = (bits >> 0) & 0xff;3043    pend[-2] = (bits >> 8) & 0xff;3044    pend[-3] = (bits >> 16) & 0xff;3045    pend[-4] = (bits >> 24) & 0xff;3046    return blocks;3047}30483049using CryptoPP::ByteReverse;30503051static const unsigned int pSHA256InitState[8] =3052{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};30533054inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)3055{3056    memcpy(pstate, pinit, 32);3057    CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);3058}30593060//3061// ScanHash scans nonces looking for a hash with at least some zero bits.3062// It operates on big endian data.  Caller does the byte reversing.3063// All input buffers are 16-byte aligned.  nNonce is usually preserved3064// between calls, but periodically or if nNonce is 0xffff0000 or above,3065// the block is rebuilt and nNonce starts over at zero.3066//3067unsigned int ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)3068{3069    unsigned int& nNonce = *(unsigned int*)(pdata + 12);3070    for (;;)3071    {3072        // Crypto++ SHA-2563073        // Hash pdata using pmidstate as the starting state into3074        // preformatted buffer phash1, then hash phash1 into phash3075        nNonce++;3076        SHA256Transform(phash1, pdata, pmidstate);3077        SHA256Transform(phash, phash1, pSHA256InitState);30783079        // Return the nonce if the hash has at least some zero bits,3080        // caller will check if it has enough to reach the target3081        if (((unsigned short*)phash)[14] == 0)3082            return nNonce;30833084        // If nothing found after trying for a while, return -13085        if ((nNonce & 0xffff) == 0)3086        {3087            nHashesDone = 0xffff+1;3088            return -1;3089        }3090    }3091}30923093extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);3094309530963097class COrphan3098{3099public:3100    CTransaction* ptx;3101    set<uint256> setDependsOn;3102    double dPriority;31033104    COrphan(CTransaction* ptxIn)3105    {3106        ptx = ptxIn;3107        dPriority = 0;3108    }31093110    void print() const3111    {3112        printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);3113        foreach(uint256 hash, setDependsOn)3114            printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());3115    }3116};311731183119CBlock* CreateNewBlock(CReserveKey& reservekey)3120{3121    CBlockIndex* pindexPrev = pindexBest;31223123    // Create new block3124    auto_ptr<CBlock> pblock(new CBlock());3125    if (!pblock.get())3126        return NULL;31273128    // Create coinbase tx3129    CTransaction txNew;3130    txNew.vin.resize(1);3131    txNew.vin[0].prevout.SetNull();3132    txNew.vout.resize(1);3133    txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;31343135    // Add our coinbase tx as first transaction3136    pblock->vtx.push_back(txNew);31373138    // Collect memory pool transactions into the block3139    int64 nFees = 0;3140    CRITICAL_BLOCK(cs_main)3141    CRITICAL_BLOCK(cs_mapTransactions)3142    {3143        CTxDB txdb("r");31443145        // Priority order to process transactions3146        list<COrphan> vOrphan; // list memory doesn't move3147        map<uint256, vector<COrphan*> > mapDependers;3148        multimap<double, CTransaction*> mapPriority;3149        for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)3150        {3151            CTransaction& tx = (*mi).second;3152            if (tx.IsCoinBase() || !tx.IsFinal())3153                continue;31543155            COrphan* porphan = NULL;3156            double dPriority = 0;3157            foreach(const CTxIn& txin, tx.vin)3158            {3159                // Read prev transaction3160                CTransaction txPrev;3161                CTxIndex txindex;3162                if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))3163                {3164                    // Has to wait for dependencies3165                    if (!porphan)3166                    {3167                        // Use list for automatic deletion3168                        vOrphan.push_back(COrphan(&tx));3169                        porphan = &vOrphan.back();3170                    }3171                    mapDependers[txin.prevout.hash].push_back(porphan);3172                    porphan->setDependsOn.insert(txin.prevout.hash);3173                    continue;3174                }3175                int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;31763177                // Read block header3178                int nConf = 0;3179                CBlock block;3180                if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))3181                {3182                    map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());3183                    if (it != mapBlockIndex.end())3184                    {3185                        CBlockIndex* pindex = (*it).second;3186                        if (pindex->IsInMainChain())3187                            nConf = 1 + nBestHeight - pindex->nHeight;3188                    }3189                }31903191                dPriority += (double)nValueIn * nConf;31923193                if (fDebug && GetBoolArg("-printpriority"))3194                    printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);3195            }31963197            // Priority is sum(valuein * age) / txsize3198            dPriority /= ::GetSerializeSize(tx, SER_NETWORK);31993200            if (porphan)3201                porphan->dPriority = dPriority;3202            else3203                mapPriority.insert(make_pair(-dPriority, &(*mi).second));32043205            if (fDebug && GetBoolArg("-printpriority"))3206            {3207                printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());3208                if (porphan)3209                    porphan->print();3210                printf("\n");3211            }3212        }32133214        // Collect transactions into block3215        map<uint256, CTxIndex> mapTestPool;3216        uint64 nBlockSize = 1000;3217        int nBlockSigOps = 100;3218        while (!mapPriority.empty())3219        {3220            // Take highest priority transaction off priority queue3221            double dPriority = -(*mapPriority.begin()).first;3222            CTransaction& tx = *(*mapPriority.begin()).second;3223            mapPriority.erase(mapPriority.begin());32243225            // Size limits3226            unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);3227            if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)3228                continue;3229            int nTxSigOps = tx.GetSigOpCount();3230            if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)3231                continue;32323233            // Transaction fee required depends on block size3234            bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);3235            int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);32363237            // Connecting shouldn't fail due to dependency on other memory pool transactions3238            // because we're already processing them in order of dependency3239            map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);3240            if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))3241                continue;3242            swap(mapTestPool, mapTestPoolTmp);32433244            // Added3245            pblock->vtx.push_back(tx);3246            nBlockSize += nTxSize;3247            nBlockSigOps += nTxSigOps;32483249            // Add transactions that depend on this one to the priority queue3250            uint256 hash = tx.GetHash();3251            if (mapDependers.count(hash))3252            {3253                foreach(COrphan* porphan, mapDependers[hash])3254                {3255                    if (!porphan->setDependsOn.empty())3256                    {3257                        porphan->setDependsOn.erase(hash);3258                        if (porphan->setDependsOn.empty())3259                            mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));3260                    }3261                }3262            }3263        }3264    }3265    pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);32663267    // Fill in header3268    pblock->hashPrevBlock  = pindexPrev->GetBlockHash();3269    pblock->hashMerkleRoot = pblock->BuildMerkleTree();3270    pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());3271    pblock->nBits          = GetNextWorkRequired(pindexPrev);3272    pblock->nNonce         = 0;32733274    return pblock.release();3275}327632773278void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)3279{3280    // Update nExtraNonce3281    int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());3282    if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)3283    {3284        nExtraNonce = 1;3285        nPrevTime = nNow;3286    }3287    pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);3288    pblock->hashMerkleRoot = pblock->BuildMerkleTree();3289}329032913292void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)3293{3294    //3295    // Prebuild hash buffers3296    //3297    struct3298    {3299        struct unnamed23300        {3301            int nVersion;3302            uint256 hashPrevBlock;3303            uint256 hashMerkleRoot;3304            unsigned int nTime;3305            unsigned int nBits;3306            unsigned int nNonce;3307        }3308        block;3309        unsigned char pchPadding0[64];3310        uint256 hash1;3311        unsigned char pchPadding1[64];3312    }3313    tmp;3314    memset(&tmp, 0, sizeof(tmp));33153316    tmp.block.nVersion       = pblock->nVersion;3317    tmp.block.hashPrevBlock  = pblock->hashPrevBlock;3318    tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;3319    tmp.block.nTime          = pblock->nTime;3320    tmp.block.nBits          = pblock->nBits;3321    tmp.block.nNonce         = pblock->nNonce;33223323    FormatHashBlocks(&tmp.block, sizeof(tmp.block));3324    FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));33253326    // Byte swap all the input buffer3327    for (int i = 0; i < sizeof(tmp)/4; i++)3328        ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);33293330    // Precalc the first half of the first hash, which stays constant3331    SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);33323333    memcpy(pdata, &tmp.block, 128);3334    memcpy(phash1, &tmp.hash1, 64);3335}333633373338bool CheckWork(CBlock* pblock, CReserveKey& reservekey)3339{3340    uint256 hash = pblock->GetHash();3341    uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();33423343    if (hash > hashTarget)3344        return false;33453346    //// debug print3347    printf("BitcoinMiner:\n");3348    printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());3349    pblock->print();3350    printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());3351    printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());33523353    // Found a solution3354    CRITICAL_BLOCK(cs_main)3355    {3356        if (pblock->hashPrevBlock != hashBestChain)3357            return error("BitcoinMiner : generated block is stale");33583359        // Remove key from key pool3360        reservekey.KeepKey();33613362        // Track how many getdata requests this block gets3363        CRITICAL_BLOCK(cs_mapRequestCount)3364            mapRequestCount[pblock->GetHash()] = 0;33653366        // Process this block the same as if we had received it from another node3367        if (!ProcessBlock(NULL, pblock))3368            return error("BitcoinMiner : ProcessBlock, block not accepted");3369    }33703371    Sleep(2000);3372    return true;3373}337433753376void BitcoinMiner()3377{3378    printf("BitcoinMiner started\n");3379    SetThreadPriority(THREAD_PRIORITY_LOWEST);3380    bool f4WaySSE2 = Detect128BitSSE2();3381    if (mapArgs.count("-4way"))3382        f4WaySSE2 = GetBoolArg(mapArgs["-4way"]);33833384    // Each thread has its own key and counter3385    CReserveKey reservekey;3386    unsigned int nExtraNonce = 0;3387    int64 nPrevTime = 0;33883389    while (fGenerateBitcoins)3390    {3391        if (AffinityBugWorkaround(ThreadBitcoinMiner))3392            return;3393        if (fShutdown)3394            return;3395        while (vNodes.empty() || IsInitialBlockDownload())3396        {3397            Sleep(1000);3398            if (fShutdown)3399                return;3400            if (!fGenerateBitcoins)3401                return;3402        }340334043405        //3406        // Create new block3407        //3408        unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;3409        CBlockIndex* pindexPrev = pindexBest;34103411        auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));3412        if (!pblock.get())3413            return;3414        IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);34153416        printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());341734183419        //3420        // Prebuild hash buffers3421        //3422        char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);3423        char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);3424        char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);34253426        FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);34273428        unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);3429        unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);343034313432        //3433        // Search3434        //3435        int64 nStart = GetTime();3436        uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();3437        uint256 hashbuf[2];3438        uint256& hash = *alignup<16>(hashbuf);3439        loop3440        {3441            unsigned int nHashesDone = 0;3442            unsigned int nNonceFound;34433444#ifdef FOURWAYSSE23445            if (f4WaySSE2)3446                // tcatm's 4-way 128-bit SSE2 SHA-2563447                nNonceFound = ScanHash_4WaySSE2(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);3448            else3449#endif3450                // Crypto++ SHA-2563451                nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1, (char*)&hash, nHashesDone);34523453            // Check if something found3454            if (nNonceFound != -1)3455            {3456                for (int i = 0; i < sizeof(hash)/4; i++)3457                    ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);34583459                if (hash <= hashTarget)3460                {3461                    // Found a solution3462                    pblock->nNonce = ByteReverse(nNonceFound);3463                    assert(hash == pblock->GetHash());34643465                    SetThreadPriority(THREAD_PRIORITY_NORMAL);3466                    CheckWork(pblock.get(), reservekey);3467                    SetThreadPriority(THREAD_PRIORITY_LOWEST);3468                    break;3469                }3470            }34713472            // Meter hashes/sec3473            static int64 nHashCounter;3474            if (nHPSTimerStart == 0)3475            {3476                nHPSTimerStart = GetTimeMillis();3477                nHashCounter = 0;3478            }3479            else3480                nHashCounter += nHashesDone;3481            if (GetTimeMillis() - nHPSTimerStart > 4000)3482            {3483                static CCriticalSection cs;3484                CRITICAL_BLOCK(cs)3485                {3486                    if (GetTimeMillis() - nHPSTimerStart > 4000)3487                    {3488                        dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);3489                        nHPSTimerStart = GetTimeMillis();3490                        nHashCounter = 0;3491                        string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);3492                        UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));3493                        static int64 nLogTime;3494                        if (GetTime() - nLogTime > 30 * 60)3495                        {3496                            nLogTime = GetTime();3497                            printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());3498                            printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);3499                        }3500                    }3501                }3502            }35033504            // Check for stop or if block needs to be rebuilt3505            if (fShutdown)3506                return;3507            if (!fGenerateBitcoins)3508                return;3509            if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)3510                return;3511            if (vNodes.empty())3512                break;3513            if (nBlockNonce >= 0xffff0000)3514                break;3515            if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)3516                break;3517            if (pindexPrev != pindexBest)3518                break;35193520            // Update nTime every few seconds3521            pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());3522            nBlockTime = ByteReverse(pblock->nTime);3523        }3524    }3525}3526352735283529353035313532353335343535353635373538353935403541354235433544//////////////////////////////////////////////////////////////////////////////3545//3546// Actions3547//354835493550int64 GetBalance()3551{3552    int64 nStart = GetTimeMillis();35533554    int64 nTotal = 0;3555    CRITICAL_BLOCK(cs_mapWallet)3556    {3557        for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)3558        {3559            CWalletTx* pcoin = &(*it).second;3560            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())3561                continue;3562            nTotal += pcoin->GetCredit();3563        }3564    }35653566    //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);3567    return nTotal;3568}356935703571bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)3572{3573    setCoinsRet.clear();35743575    // List of values less than target3576    int64 nLowestLarger = INT64_MAX;3577    CWalletTx* pcoinLowestLarger = NULL;3578    vector<pair<int64, CWalletTx*> > vValue;3579    int64 nTotalLower = 0;35803581    CRITICAL_BLOCK(cs_mapWallet)3582    {3583       vector<CWalletTx*> vCoins;3584       vCoins.reserve(mapWallet.size());3585       for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)3586           vCoins.push_back(&(*it).second);3587       random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);35883589       foreach(CWalletTx* pcoin, vCoins)3590       {3591            if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())3592                continue;35933594            int nDepth = pcoin->GetDepthInMainChain();3595            if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))3596                continue;35973598            int64 n = pcoin->GetCredit();3599            if (n <= 0)3600                continue;3601            if (n < nTargetValue)3602            {3603                vValue.push_back(make_pair(n, pcoin));3604                nTotalLower += n;3605            }3606            else if (n == nTargetValue)3607            {3608                setCoinsRet.insert(pcoin);3609                return true;3610            }3611            else if (n < nLowestLarger)3612            {3613                nLowestLarger = n;3614                pcoinLowestLarger = pcoin;3615            }3616        }3617    }36183619    if (nTotalLower < nTargetValue)3620    {3621        if (pcoinLowestLarger == NULL)3622            return false;3623        setCoinsRet.insert(pcoinLowestLarger);3624        return true;3625    }36263627    // Solve subset sum by stochastic approximation3628    sort(vValue.rbegin(), vValue.rend());3629    vector<char> vfIncluded;3630    vector<char> vfBest(vValue.size(), true);3631    int64 nBest = nTotalLower;36323633    for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)3634    {3635        vfIncluded.assign(vValue.size(), false);3636        int64 nTotal = 0;3637        bool fReachedTarget = false;3638        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)3639        {3640            for (int i = 0; i < vValue.size(); i++)3641            {3642                if (nPass == 0 ? rand() % 2 : !vfIncluded[i])3643                {3644                    nTotal += vValue[i].first;3645                    vfIncluded[i] = true;3646                    if (nTotal >= nTargetValue)3647                    {3648                        fReachedTarget = true;3649                        if (nTotal < nBest)3650                        {3651                            nBest = nTotal;3652                            vfBest = vfIncluded;3653                        }3654                        nTotal -= vValue[i].first;3655                        vfIncluded[i] = false;3656                    }3657                }3658            }3659        }3660    }36613662    // If the next larger is still closer, return it3663    if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)3664        setCoinsRet.insert(pcoinLowestLarger);3665    else3666    {3667        for (int i = 0; i < vValue.size(); i++)3668            if (vfBest[i])3669                setCoinsRet.insert(vValue[i].second);36703671        //// debug print3672        printf("SelectCoins() best subset: ");3673        for (int i = 0; i < vValue.size(); i++)3674            if (vfBest[i])3675                printf("%s ", FormatMoney(vValue[i].first).c_str());3676        printf("total %s\n", FormatMoney(nBest).c_str());3677    }36783679    return true;3680}36813682bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)3683{3684    return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||3685            SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||3686            SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));3687}36883689369036913692bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)3693{3694    CRITICAL_BLOCK(cs_main)3695    {3696        // txdb must be opened before the mapWallet lock3697        CTxDB txdb("r");3698        CRITICAL_BLOCK(cs_mapWallet)3699        {3700            nFeeRet = nTransactionFee;3701            loop3702            {3703                wtxNew.vin.clear();3704                wtxNew.vout.clear();3705                wtxNew.fFromMe = true;3706                if (nValue < 0)3707                    return false;3708                int64 nValueOut = nValue;3709                int64 nTotalValue = nValue + nFeeRet;37103711                // Choose coins to use3712                set<CWalletTx*> setCoins;3713                if (!SelectCoins(nTotalValue, setCoins))3714                    return false;3715                int64 nValueIn = 0;3716                foreach(CWalletTx* pcoin, setCoins)3717                    nValueIn += pcoin->GetCredit();37183719                // Fill a vout to the payee3720                bool fChangeFirst = GetRand(2);3721                if (!fChangeFirst)3722                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));37233724                // Fill a vout back to self with any change3725                int64 nChange = nValueIn - nTotalValue;3726                if (nChange >= CENT)3727                {3728                    // Note: We use a new key here to keep it from being obvious which side is the change.3729                    //  The drawback is that by not reusing a previous key, the change may be lost if a3730                    //  backup is restored, if the backup doesn't have the new private key for the change.3731                    //  If we reused the old key, it would be possible to add code to look for and3732                    //  rediscover unknown transactions that were written with keys of ours to recover3733                    //  post-backup change.37343735                    // Reserve a new key pair from key pool3736                    vector<unsigned char> vchPubKey = reservekey.GetReservedKey();3737                    assert(mapKeys.count(vchPubKey));37383739                    // Fill a vout to ourself, using same address type as the payment3740                    CScript scriptChange;3741                    if (scriptPubKey.GetBitcoinAddressHash160() != 0)3742                        scriptChange.SetBitcoinAddress(vchPubKey);3743                    else3744                        scriptChange << vchPubKey << OP_CHECKSIG;3745                    wtxNew.vout.push_back(CTxOut(nChange, scriptChange));3746                }3747                else3748                    reservekey.ReturnKey();37493750                // Fill a vout to the payee3751                if (fChangeFirst)3752                    wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));37533754                // Fill vin3755                foreach(CWalletTx* pcoin, setCoins)3756                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)3757                        if (pcoin->vout[nOut].IsMine())3758                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));37593760                // Sign3761                int nIn = 0;3762                foreach(CWalletTx* pcoin, setCoins)3763                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)3764                        if (pcoin->vout[nOut].IsMine())3765                            if (!SignSignature(*pcoin, wtxNew, nIn++))3766                                return false;37673768                // Limit size3769                unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);3770                if (nBytes >= MAX_BLOCK_SIZE_GEN/5)3771                    return false;37723773                // Check that enough fee is included3774                int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);3775                int64 nMinFee = wtxNew.GetMinFee();3776                if (nFeeRet < max(nPayFee, nMinFee))3777                {3778                    nFeeRet = max(nPayFee, nMinFee);3779                    continue;3780                }37813782                // Fill vtxPrev by copying from previous transactions vtxPrev3783                wtxNew.AddSupportingTransactions(txdb);3784                wtxNew.fTimeReceivedIsTxTime = true;37853786                break;3787            }3788        }3789    }3790    return true;3791}37923793// Call after CreateTransaction unless you want to abort3794bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)3795{3796    CRITICAL_BLOCK(cs_main)3797    {3798        printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());3799        CRITICAL_BLOCK(cs_mapWallet)3800        {3801            // This is only to keep the database open to defeat the auto-flush for the3802            // duration of this scope.  This is the only place where this optimization3803            // maybe makes sense; please don't do it anywhere else.3804            CWalletDB walletdb("r");38053806            // Take key pair from key pool so it won't be used again3807            reservekey.KeepKey();38083809            // Add tx to wallet, because if it has change it's also ours,3810            // otherwise just for transaction history.3811            AddToWallet(wtxNew);38123813            // Mark old coins as spent3814            set<CWalletTx*> setCoins;3815            foreach(const CTxIn& txin, wtxNew.vin)3816                setCoins.insert(&mapWallet[txin.prevout.hash]);3817            foreach(CWalletTx* pcoin, setCoins)3818            {3819                pcoin->fSpent = true;3820                pcoin->WriteToDisk();3821                vWalletUpdated.push_back(pcoin->GetHash());3822            }3823        }38243825        // Track how many getdata requests our transaction gets3826        CRITICAL_BLOCK(cs_mapRequestCount)3827            mapRequestCount[wtxNew.GetHash()] = 0;38283829        // Broadcast3830        if (!wtxNew.AcceptToMemoryPool())3831        {3832            // This must not fail. The transaction has already been signed and recorded.3833            printf("CommitTransaction() : Error: Transaction not valid");3834            return false;3835        }3836        wtxNew.RelayWalletTransaction();3837    }3838    MainFrameRepaint();3839    return true;3840}38413842384338443845string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3846{3847    CRITICAL_BLOCK(cs_main)3848    {3849        CReserveKey reservekey;3850        int64 nFeeRequired;3851        if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))3852        {3853            string strError;3854            if (nValue + nFeeRequired > GetBalance())3855                strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s  "), FormatMoney(nFeeRequired).c_str());3856            else3857                strError = _("Error: Transaction creation failed  ");3858            printf("SendMoney() : %s", strError.c_str());3859            return strError;3860        }38613862        if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))3863            return "ABORTED";38643865        if (!CommitTransaction(wtxNew, reservekey))3866            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.");3867    }3868    MainFrameRepaint();3869    return "";3870}3871387238733874string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)3875{3876    // Check amount3877    if (nValue <= 0)3878        return _("Invalid amount");3879    if (nValue + nTransactionFee > GetBalance())3880        return _("Insufficient funds");38813882    // Parse bitcoin address3883    CScript scriptPubKey;3884    if (!scriptPubKey.SetBitcoinAddress(strAddress))3885        return _("Invalid bitcoin address");38863887    return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);3888}

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