Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #include "headers.h"
0006 #include "checkpoints.h"
0007 #include "db.h"
0008 #include "net.h"
0009 #include "init.h"
0010 #include <boost/filesystem.hpp>
0011 #include <boost/filesystem/fstream.hpp>
0012 
0013 using namespace std;
0014 using namespace boost;
0015 
0016 //
0017 // Global state
0018 //
0019 
0020 CCriticalSection cs_setpwalletRegistered;
0021 set<CWallet*> setpwalletRegistered;
0022 
0023 CCriticalSection cs_main;
0024 
0025 static map<uint256, CTransaction> mapTransactions;
0026 CCriticalSection cs_mapTransactions;
0027 unsigned int nTransactionsUpdated = 0;
0028 map<COutPoint, CInPoint> mapNextTx;
0029 
0030 map<uint256, CBlockIndex*> mapBlockIndex;
0031 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
0032 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
0033 CBlockIndex* pindexGenesisBlock = NULL;
0034 int nBestHeight = -1;
0035 CBigNum bnBestChainWork = 0;
0036 CBigNum bnBestInvalidWork = 0;
0037 uint256 hashBestChain = 0;
0038 CBlockIndex* pindexBest = NULL;
0039 int64 nTimeBestReceived = 0;
0040 
0041 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
0042 
0043 map<uint256, CBlock*> mapOrphanBlocks;
0044 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
0045 
0046 map<uint256, CDataStream*> mapOrphanTransactions;
0047 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
0048 
0049 
0050 double dHashesPerSec;
0051 int64 nHPSTimerStart;
0052 
0053 // Settings
0054 int fGenerateBitcoins = false;
0055 int64 nTransactionFee = 0;
0056 int fLimitProcessors = false;
0057 int nLimitProcessors = 1;
0058 int fMinimizeToTray = true;
0059 int fMinimizeOnClose = true;
0060 
0061 
0062 //////////////////////////////////////////////////////////////////////////////
0063 //
0064 // dispatching functions
0065 //
0066 
0067 // These functions dispatch to one or all registered wallets
0068 
0069 
0070 void RegisterWallet(CWallet* pwalletIn)
0071 {
0072     CRITICAL_BLOCK(cs_setpwalletRegistered)
0073     {
0074         setpwalletRegistered.insert(pwalletIn);
0075     }
0076 }
0077 
0078 void UnregisterWallet(CWallet* pwalletIn)
0079 {
0080     CRITICAL_BLOCK(cs_setpwalletRegistered)
0081     {
0082         setpwalletRegistered.erase(pwalletIn);
0083     }
0084 }
0085 
0086 // check whether the passed transaction is from us
0087 bool static IsFromMe(CTransaction& tx)
0088 {
0089     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0090         if (pwallet->IsFromMe(tx))
0091             return true;
0092     return false;
0093 }
0094 
0095 // get the wallet transaction with the given hash (if it exists)
0096 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
0097 {
0098     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0099         if (pwallet->GetTransaction(hashTx,wtx))
0100             return true;
0101     return false;
0102 }
0103 
0104 // erases transaction with the given hash from all wallets
0105 void static EraseFromWallets(uint256 hash)
0106 {
0107     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0108         pwallet->EraseFromWallet(hash);
0109 }
0110 
0111 // make sure all wallets know about the given transaction, in the given block
0112 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
0113 {
0114     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0115         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
0116 }
0117 
0118 // notify wallets about a new best chain
0119 void static SetBestChain(const CBlockLocator& loc)
0120 {
0121     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0122         pwallet->SetBestChain(loc);
0123 }
0124 
0125 // notify wallets about an updated transaction
0126 void static UpdatedTransaction(const uint256& hashTx)
0127 {
0128     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0129         pwallet->UpdatedTransaction(hashTx);
0130 }
0131 
0132 // dump all wallets
0133 void static PrintWallets(const CBlock& block)
0134 {
0135     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0136         pwallet->PrintWallet(block);
0137 }
0138 
0139 // notify wallets about an incoming inventory (for request counts)
0140 void static Inventory(const uint256& hash)
0141 {
0142     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0143         pwallet->Inventory(hash);
0144 }
0145 
0146 // ask wallets to resend their transactions
0147 void static ResendWalletTransactions()
0148 {
0149     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0150         pwallet->ResendWalletTransactions();
0151 }
0152 
0153 
0154 
0155 
0156 
0157 
0158 
0159 //////////////////////////////////////////////////////////////////////////////
0160 //
0161 // mapOrphanTransactions
0162 //
0163 
0164 void AddOrphanTx(const CDataStream& vMsg)
0165 {
0166     CTransaction tx;
0167     CDataStream(vMsg) >> tx;
0168     uint256 hash = tx.GetHash();
0169     if (mapOrphanTransactions.count(hash))
0170         return;
0171 
0172     CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
0173     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0174         mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
0175 }
0176 
0177 void static EraseOrphanTx(uint256 hash)
0178 {
0179     if (!mapOrphanTransactions.count(hash))
0180         return;
0181     const CDataStream* pvMsg = mapOrphanTransactions[hash];
0182     CTransaction tx;
0183     CDataStream(*pvMsg) >> tx;
0184     BOOST_FOREACH(const CTxIn& txin, tx.vin)
0185     {
0186         for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
0187              mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
0188         {
0189             if ((*mi).second == pvMsg)
0190                 mapOrphanTransactionsByPrev.erase(mi++);
0191             else
0192                 mi++;
0193         }
0194     }
0195     delete pvMsg;
0196     mapOrphanTransactions.erase(hash);
0197 }
0198 
0199 int LimitOrphanTxSize(int nMaxOrphans)
0200 {
0201     int nEvicted = 0;
0202     while (mapOrphanTransactions.size() > nMaxOrphans)
0203     {
0204         // Evict a random orphan:
0205         std::vector<unsigned char> randbytes(32);
0206         RAND_bytes(&randbytes[0], 32);
0207         uint256 randomhash(randbytes);
0208         map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
0209         if (it == mapOrphanTransactions.end())
0210             it = mapOrphanTransactions.begin();
0211         EraseOrphanTx(it->first);
0212         ++nEvicted;
0213     }
0214     return nEvicted;
0215 }
0216 
0217 
0218 
0219 
0220 
0221 
0222 
0223 //////////////////////////////////////////////////////////////////////////////
0224 //
0225 // CTransaction and CTxIndex
0226 //
0227 
0228 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
0229 {
0230     SetNull();
0231     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
0232         return false;
0233     if (!ReadFromDisk(txindexRet.pos))
0234         return false;
0235     if (prevout.n >= vout.size())
0236     {
0237         SetNull();
0238         return false;
0239     }
0240     return true;
0241 }
0242 
0243 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
0244 {
0245     CTxIndex txindex;
0246     return ReadFromDisk(txdb, prevout, txindex);
0247 }
0248 
0249 bool CTransaction::ReadFromDisk(COutPoint prevout)
0250 {
0251     CTxDB txdb("r");
0252     CTxIndex txindex;
0253     return ReadFromDisk(txdb, prevout, txindex);
0254 }
0255 
0256 
0257 
0258 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
0259 {
0260     if (fClient)
0261     {
0262         if (hashBlock == 0)
0263             return 0;
0264     }
0265     else
0266     {
0267         CBlock blockTmp;
0268         if (pblock == NULL)
0269         {
0270             // Load the block this tx is in
0271             CTxIndex txindex;
0272             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
0273                 return 0;
0274             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
0275                 return 0;
0276             pblock = &blockTmp;
0277         }
0278 
0279         // Update the tx's hashBlock
0280         hashBlock = pblock->GetHash();
0281 
0282         // Locate the transaction
0283         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
0284             if (pblock->vtx[nIndex] == *(CTransaction*)this)
0285                 break;
0286         if (nIndex == pblock->vtx.size())
0287         {
0288             vMerkleBranch.clear();
0289             nIndex = -1;
0290             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
0291             return 0;
0292         }
0293 
0294         // Fill in merkle branch
0295         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
0296     }
0297 
0298     // Is the tx in a block that's in the main chain
0299     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
0300     if (mi == mapBlockIndex.end())
0301         return 0;
0302     CBlockIndex* pindex = (*mi).second;
0303     if (!pindex || !pindex->IsInMainChain())
0304         return 0;
0305 
0306     return pindexBest->nHeight - pindex->nHeight + 1;
0307 }
0308 
0309 
0310 
0311 
0312 
0313 
0314 
0315 bool CTransaction::CheckTransaction() const
0316 {
0317     // Basic checks that don't depend on any context
0318     if (vin.empty())
0319         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
0320     if (vout.empty())
0321         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
0322     // Size limits
0323     if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
0324         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
0325 
0326     // Check for negative or overflow output values
0327     int64 nValueOut = 0;
0328     BOOST_FOREACH(const CTxOut& txout, vout)
0329     {
0330         if (txout.nValue < 0)
0331             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
0332         if (txout.nValue > MAX_MONEY)
0333             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
0334         nValueOut += txout.nValue;
0335         if (!MoneyRange(nValueOut))
0336             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
0337     }
0338 
0339     // Check for duplicate inputs
0340     set<COutPoint> vInOutPoints;
0341     BOOST_FOREACH(const CTxIn& txin, vin)
0342     {
0343         if (vInOutPoints.count(txin.prevout))
0344             return false;
0345         vInOutPoints.insert(txin.prevout);
0346     }
0347 
0348     if (IsCoinBase())
0349     {
0350         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
0351             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
0352     }
0353     else
0354     {
0355         BOOST_FOREACH(const CTxIn& txin, vin)
0356             if (txin.prevout.IsNull())
0357                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
0358     }
0359 
0360     return true;
0361 }
0362 
0363 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
0364 {
0365     if (pfMissingInputs)
0366         *pfMissingInputs = false;
0367 
0368     if (!CheckTransaction())
0369         return error("AcceptToMemoryPool() : CheckTransaction failed");
0370 
0371     // Coinbase is only valid in a block, not as a loose transaction
0372     if (IsCoinBase())
0373         return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
0374 
0375     // To help v0.1.5 clients who would see it as a negative number
0376     if ((int64)nLockTime > INT_MAX)
0377         return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
0378 
0379     // Safety limits
0380     unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
0381     // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
0382     // attacks disallow transactions with more than one SigOp per 34 bytes.
0383     // 34 bytes because a TxOut is:
0384     //   20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
0385     if (GetSigOpCount() > nSize / 34 || nSize < 100)
0386         return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
0387 
0388     // Rather not work on nonstandard transactions (unless -testnet)
0389     if (!fTestNet && !IsStandard())
0390         return error("AcceptToMemoryPool() : nonstandard transaction type");
0391 
0392     // Do we already have it?
0393     uint256 hash = GetHash();
0394     CRITICAL_BLOCK(cs_mapTransactions)
0395         if (mapTransactions.count(hash))
0396             return false;
0397     if (fCheckInputs)
0398         if (txdb.ContainsTx(hash))
0399             return false;
0400 
0401     // Check for conflicts with in-memory transactions
0402     CTransaction* ptxOld = NULL;
0403     for (int i = 0; i < vin.size(); i++)
0404     {
0405         COutPoint outpoint = vin[i].prevout;
0406         if (mapNextTx.count(outpoint))
0407         {
0408             // Disable replacement feature for now
0409             return false;
0410 
0411             // Allow replacing with a newer version of the same transaction
0412             if (i != 0)
0413                 return false;
0414             ptxOld = mapNextTx[outpoint].ptx;
0415             if (ptxOld->IsFinal())
0416                 return false;
0417             if (!IsNewerThan(*ptxOld))
0418                 return false;
0419             for (int i = 0; i < vin.size(); i++)
0420             {
0421                 COutPoint outpoint = vin[i].prevout;
0422                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
0423                     return false;
0424             }
0425             break;
0426         }
0427     }
0428 
0429     if (fCheckInputs)
0430     {
0431         // Check against previous transactions
0432         map<uint256, CTxIndex> mapUnused;
0433         int64 nFees = 0;
0434         bool fInvalid = false;
0435         if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
0436         {
0437             if (fInvalid)
0438                 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
0439             return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
0440         }
0441 
0442         // Don't accept it if it can't get into a block
0443         if (nFees < GetMinFee(1000, true, true))
0444             return error("AcceptToMemoryPool() : not enough fees");
0445 
0446         // Continuously rate-limit free transactions
0447         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
0448         // be annoying or make other's transactions take longer to confirm.
0449         if (nFees < MIN_RELAY_TX_FEE)
0450         {
0451             static CCriticalSection cs;
0452             static double dFreeCount;
0453             static int64 nLastTime;
0454             int64 nNow = GetTime();
0455 
0456             CRITICAL_BLOCK(cs)
0457             {
0458                 // Use an exponentially decaying ~10-minute window:
0459                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
0460                 nLastTime = nNow;
0461                 // -limitfreerelay unit is thousand-bytes-per-minute
0462                 // At default rate it would take over a month to fill 1GB
0463                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
0464                     return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
0465                 if (fDebug)
0466                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
0467                 dFreeCount += nSize;
0468             }
0469         }
0470     }
0471 
0472     // Store transaction in memory
0473     CRITICAL_BLOCK(cs_mapTransactions)
0474     {
0475         if (ptxOld)
0476         {
0477             printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
0478             ptxOld->RemoveFromMemoryPool();
0479         }
0480         AddToMemoryPoolUnchecked();
0481     }
0482 
0483     ///// are we sure this is ok when loading transactions or restoring block txes
0484     // If updated, erase old tx from wallet
0485     if (ptxOld)
0486         EraseFromWallets(ptxOld->GetHash());
0487 
0488     printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
0489     return true;
0490 }
0491 
0492 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
0493 {
0494     CTxDB txdb("r");
0495     return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
0496 }
0497 
0498 bool CTransaction::AddToMemoryPoolUnchecked()
0499 {
0500     // Add to memory pool without checking anything.  Don't call this directly,
0501     // call AcceptToMemoryPool to properly check the transaction first.
0502     CRITICAL_BLOCK(cs_mapTransactions)
0503     {
0504         uint256 hash = GetHash();
0505         mapTransactions[hash] = *this;
0506         for (int i = 0; i < vin.size(); i++)
0507             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
0508         nTransactionsUpdated++;
0509     }
0510     return true;
0511 }
0512 
0513 
0514 bool CTransaction::RemoveFromMemoryPool()
0515 {
0516     // Remove transaction from memory pool
0517     CRITICAL_BLOCK(cs_mapTransactions)
0518     {
0519         BOOST_FOREACH(const CTxIn& txin, vin)
0520             mapNextTx.erase(txin.prevout);
0521         mapTransactions.erase(GetHash());
0522         nTransactionsUpdated++;
0523     }
0524     return true;
0525 }
0526 
0527 
0528 
0529 
0530 
0531 
0532 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
0533 {
0534     if (hashBlock == 0 || nIndex == -1)
0535         return 0;
0536 
0537     // Find the block it claims to be in
0538     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
0539     if (mi == mapBlockIndex.end())
0540         return 0;
0541     CBlockIndex* pindex = (*mi).second;
0542     if (!pindex || !pindex->IsInMainChain())
0543         return 0;
0544 
0545     // Make sure the merkle branch connects to this block
0546     if (!fMerkleVerified)
0547     {
0548         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
0549             return 0;
0550         fMerkleVerified = true;
0551     }
0552 
0553     nHeightRet = pindex->nHeight;
0554     return pindexBest->nHeight - pindex->nHeight + 1;
0555 }
0556 
0557 
0558 int CMerkleTx::GetBlocksToMaturity() const
0559 {
0560     if (!IsCoinBase())
0561         return 0;
0562     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
0563 }
0564 
0565 
0566 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
0567 {
0568     if (fClient)
0569     {
0570         if (!IsInMainChain() && !ClientConnectInputs())
0571             return false;
0572         return CTransaction::AcceptToMemoryPool(txdb, false);
0573     }
0574     else
0575     {
0576         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
0577     }
0578 }
0579 
0580 bool CMerkleTx::AcceptToMemoryPool()
0581 {
0582     CTxDB txdb("r");
0583     return AcceptToMemoryPool(txdb);
0584 }
0585 
0586 
0587 
0588 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
0589 {
0590     CRITICAL_BLOCK(cs_mapTransactions)
0591     {
0592         // Add previous supporting transactions first
0593         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
0594         {
0595             if (!tx.IsCoinBase())
0596             {
0597                 uint256 hash = tx.GetHash();
0598                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
0599                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
0600             }
0601         }
0602         return AcceptToMemoryPool(txdb, fCheckInputs);
0603     }
0604     return false;
0605 }
0606 
0607 bool CWalletTx::AcceptWalletTransaction() 
0608 {
0609     CTxDB txdb("r");
0610     return AcceptWalletTransaction(txdb);
0611 }
0612 
0613 int CTxIndex::GetDepthInMainChain() const
0614 {
0615     // Read block header
0616     CBlock block;
0617     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
0618         return 0;
0619     // Find the block in the index
0620     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
0621     if (mi == mapBlockIndex.end())
0622         return 0;
0623     CBlockIndex* pindex = (*mi).second;
0624     if (!pindex || !pindex->IsInMainChain())
0625         return 0;
0626     return 1 + nBestHeight - pindex->nHeight;
0627 }
0628 
0629 
0630 
0631 
0632 
0633 
0634 
0635 
0636 
0637 
0638 //////////////////////////////////////////////////////////////////////////////
0639 //
0640 // CBlock and CBlockIndex
0641 //
0642 
0643 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
0644 {
0645     if (!fReadTransactions)
0646     {
0647         *this = pindex->GetBlockHeader();
0648         return true;
0649     }
0650     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
0651         return false;
0652     if (GetHash() != pindex->GetBlockHash())
0653         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
0654     return true;
0655 }
0656 
0657 uint256 static GetOrphanRoot(const CBlock* pblock)
0658 {
0659     // Work back to the first block in the orphan chain
0660     while (mapOrphanBlocks.count(pblock->hashPrevBlock))
0661         pblock = mapOrphanBlocks[pblock->hashPrevBlock];
0662     return pblock->GetHash();
0663 }
0664 
0665 int64 static GetBlockValue(int nHeight, int64 nFees)
0666 {
0667     int64 nSubsidy = 50 * COIN;
0668 
0669     // Subsidy is cut in half every 4 years
0670     nSubsidy >>= (nHeight / 210000);
0671 
0672     return nSubsidy + nFees;
0673 }
0674 
0675 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
0676 static const int64 nTargetSpacing = 10 * 60;
0677 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
0678 
0679 //
0680 // minimum amount of work that could possibly be required nTime after
0681 // minimum work required was nBase
0682 //
0683 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
0684 {
0685     // Testnet has min-difficulty blocks
0686     // after nTargetSpacing*2 time between blocks:
0687     if (fTestNet && nTime > nTargetSpacing*2)
0688         return bnProofOfWorkLimit.GetCompact();
0689 
0690     CBigNum bnResult;
0691     bnResult.SetCompact(nBase);
0692     while (nTime > 0 && bnResult < bnProofOfWorkLimit)
0693     {
0694         // Maximum 400% adjustment...
0695         bnResult *= 4;
0696         // ... in best-case exactly 4-times-normal target time
0697         nTime -= nTargetTimespan*4;
0698     }
0699     if (bnResult > bnProofOfWorkLimit)
0700         bnResult = bnProofOfWorkLimit;
0701     return bnResult.GetCompact();
0702 }
0703 
0704 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
0705 {
0706     unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
0707 
0708     // Genesis block
0709     if (pindexLast == NULL)
0710         return nProofOfWorkLimit;
0711 
0712     // Only change once per interval
0713     if ((pindexLast->nHeight+1) % nInterval != 0)
0714     {
0715         // Special rules for testnet after 15 Feb 2012:
0716         if (fTestNet && pblock->nTime > 1329264000)
0717         {
0718             // If the new block's timestamp is more than 2* 10 minutes
0719             // then allow mining of a min-difficulty block.
0720             if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
0721                 return nProofOfWorkLimit;
0722             else
0723             {
0724                 // Return the last non-special-min-difficulty-rules-block
0725                 const CBlockIndex* pindex = pindexLast;
0726                 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
0727                     pindex = pindex->pprev;
0728                 return pindex->nBits;
0729             }
0730         }
0731 
0732         return pindexLast->nBits;
0733     }
0734 
0735     // Go back by what we want to be 14 days worth of blocks
0736     const CBlockIndex* pindexFirst = pindexLast;
0737     for (int i = 0; pindexFirst && i < nInterval-1; i++)
0738         pindexFirst = pindexFirst->pprev;
0739     assert(pindexFirst);
0740 
0741     // Limit adjustment step
0742     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
0743     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
0744     if (nActualTimespan < nTargetTimespan/4)
0745         nActualTimespan = nTargetTimespan/4;
0746     if (nActualTimespan > nTargetTimespan*4)
0747         nActualTimespan = nTargetTimespan*4;
0748 
0749     // Retarget
0750     CBigNum bnNew;
0751     bnNew.SetCompact(pindexLast->nBits);
0752     bnNew *= nActualTimespan;
0753     bnNew /= nTargetTimespan;
0754 
0755     if (bnNew > bnProofOfWorkLimit)
0756         bnNew = bnProofOfWorkLimit;
0757 
0758     /// debug print
0759     printf("GetNextWorkRequired RETARGET\n");
0760     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
0761     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
0762     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
0763 
0764     return bnNew.GetCompact();
0765 }
0766 
0767 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
0768 {
0769     CBigNum bnTarget;
0770     bnTarget.SetCompact(nBits);
0771 
0772     // Check range
0773     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
0774         return error("CheckProofOfWork() : nBits below minimum work");
0775 
0776     // Check proof of work matches claimed amount
0777     if (hash > bnTarget.getuint256())
0778         return error("CheckProofOfWork() : hash doesn't match nBits");
0779 
0780     return true;
0781 }
0782 
0783 // Return maximum amount of blocks that other nodes claim to have
0784 int GetNumBlocksOfPeers()
0785 {
0786     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
0787 }
0788 
0789 bool IsInitialBlockDownload()
0790 {
0791     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
0792         return true;
0793     static int64 nLastUpdate;
0794     static CBlockIndex* pindexLastBest;
0795     if (pindexBest != pindexLastBest)
0796     {
0797         pindexLastBest = pindexBest;
0798         nLastUpdate = GetTime();
0799     }
0800     return (GetTime() - nLastUpdate < 10 &&
0801             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
0802 }
0803 
0804 void static InvalidChainFound(CBlockIndex* pindexNew)
0805 {
0806     if (pindexNew->bnChainWork > bnBestInvalidWork)
0807     {
0808         bnBestInvalidWork = pindexNew->bnChainWork;
0809         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
0810         MainFrameRepaint();
0811     }
0812     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());
0813     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
0814     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
0815         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
0816 }
0817 
0818 
0819 
0820 
0821 
0822 
0823 
0824 
0825 
0826 
0827 
0828 bool CTransaction::DisconnectInputs(CTxDB& txdb)
0829 {
0830     // Relinquish previous transactions' spent pointers
0831     if (!IsCoinBase())
0832     {
0833         BOOST_FOREACH(const CTxIn& txin, vin)
0834         {
0835             COutPoint prevout = txin.prevout;
0836 
0837             // Get prev txindex from disk
0838             CTxIndex txindex;
0839             if (!txdb.ReadTxIndex(prevout.hash, txindex))
0840                 return error("DisconnectInputs() : ReadTxIndex failed");
0841 
0842             if (prevout.n >= txindex.vSpent.size())
0843                 return error("DisconnectInputs() : prevout.n out of range");
0844 
0845             // Mark outpoint as not spent
0846             txindex.vSpent[prevout.n].SetNull();
0847 
0848             // Write back
0849             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
0850                 return error("DisconnectInputs() : UpdateTxIndex failed");
0851         }
0852     }
0853 
0854     // Remove transaction from index
0855     // This can fail if a duplicate of this transaction was in a chain that got
0856     // reorganized away. This is only possible if this transaction was completely
0857     // spent, so erasing it would be a no-op anway.
0858     txdb.EraseTxIndex(*this);
0859 
0860     return true;
0861 }
0862 
0863 
0864 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
0865                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
0866                                  bool& fInvalid)
0867 {
0868     // FetchInputs can return false either because we just haven't seen some inputs
0869     // (in which case the transaction should be stored as an orphan)
0870     // or because the transaction is malformed (in which case the transaction should
0871     // be dropped).  If tx is definitely invalid, fInvalid will be set to true.
0872     fInvalid = false;
0873 
0874     // Take over previous transactions' spent pointers
0875     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
0876     // fMiner is true when called from the internal bitcoin miner
0877     // ... both are false when called from CTransaction::AcceptToMemoryPool
0878     if (!IsCoinBase())
0879     {
0880         int64 nValueIn = 0;
0881         for (int i = 0; i < vin.size(); i++)
0882         {
0883             COutPoint prevout = vin[i].prevout;
0884 
0885             // Read txindex
0886             CTxIndex txindex;
0887             bool fFound = true;
0888             if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
0889             {
0890                 // Get txindex from current proposed changes
0891                 txindex = mapTestPool[prevout.hash];
0892             }
0893             else
0894             {
0895                 // Read txindex from txdb
0896                 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
0897             }
0898             if (!fFound && (fBlock || fMiner))
0899                 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());
0900 
0901             // Read txPrev
0902             CTransaction txPrev;
0903             if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
0904             {
0905                 // Get prev tx from single transactions in memory
0906                 CRITICAL_BLOCK(cs_mapTransactions)
0907                 {
0908                     if (!mapTransactions.count(prevout.hash))
0909                         return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
0910                     txPrev = mapTransactions[prevout.hash];
0911                 }
0912                 if (!fFound)
0913                     txindex.vSpent.resize(txPrev.vout.size());
0914             }
0915             else
0916             {
0917                 // Get prev tx from disk
0918                 if (!txPrev.ReadFromDisk(txindex.pos))
0919                     return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
0920             }
0921 
0922             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
0923             {
0924                 // Revisit this if/when transaction replacement is implemented and allows
0925                 // adding inputs:
0926                 fInvalid = true;
0927                 return DoS(100, 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()));
0928             }
0929 
0930             // If prev is coinbase, check that it's matured
0931             if (txPrev.IsCoinBase())
0932                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
0933                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
0934                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
0935 
0936             // Skip ECDSA signature verification when connecting blocks (fBlock=true)
0937             // before the last blockchain checkpoint. This is safe because block merkle hashes are
0938             // still computed and checked, and any change will be caught at the next checkpoint.
0939             if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
0940                 // Verify signature
0941                 if (!VerifySignature(txPrev, *this, i))
0942                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
0943 
0944             // Check for conflicts (double-spend)
0945             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
0946             // for an attacker to attempt to split the network.
0947             if (!txindex.vSpent[prevout.n].IsNull())
0948                 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());
0949 
0950             // Check for negative or overflow input values
0951             nValueIn += txPrev.vout[prevout.n].nValue;
0952             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
0953                 return DoS(100, error("ConnectInputs() : txin values out of range"));
0954 
0955             // Mark outpoints as spent
0956             txindex.vSpent[prevout.n] = posThisTx;
0957 
0958             // Write back
0959             if (fBlock || fMiner)
0960             {
0961                 mapTestPool[prevout.hash] = txindex;
0962             }
0963         }
0964 
0965         if (nValueIn < GetValueOut())
0966             return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
0967 
0968         // Tally transaction fees
0969         int64 nTxFee = nValueIn - GetValueOut();
0970         if (nTxFee < 0)
0971             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
0972         if (nTxFee < nMinFee)
0973             return false;
0974         nFees += nTxFee;
0975         if (!MoneyRange(nFees))
0976             return DoS(100, error("ConnectInputs() : nFees out of range"));
0977     }
0978 
0979     if (fBlock)
0980     {
0981         // Add transaction to changes
0982         mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
0983     }
0984     else if (fMiner)
0985     {
0986         // Add transaction to test pool
0987         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
0988     }
0989 
0990     return true;
0991 }
0992 
0993 
0994 bool CTransaction::ClientConnectInputs()
0995 {
0996     if (IsCoinBase())
0997         return false;
0998 
0999     // Take over previous transactions' spent pointers
1000     CRITICAL_BLOCK(cs_mapTransactions)
1001     {
1002         int64 nValueIn = 0;
1003         for (int i = 0; i < vin.size(); i++)
1004         {
1005             // Get prev tx from single transactions in memory
1006             COutPoint prevout = vin[i].prevout;
1007             if (!mapTransactions.count(prevout.hash))
1008                 return false;
1009             CTransaction& txPrev = mapTransactions[prevout.hash];
1010 
1011             if (prevout.n >= txPrev.vout.size())
1012                 return false;
1013 
1014             // Verify signature
1015             if (!VerifySignature(txPrev, *this, i))
1016                 return error("ConnectInputs() : VerifySignature failed");
1017 
1018             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1019             ///// this has to go away now that posNext is gone
1020             // // Check for conflicts
1021             // if (!txPrev.vout[prevout.n].posNext.IsNull())
1022             //     return error("ConnectInputs() : prev tx already used");
1023             //
1024             // // Flag outpoints as used
1025             // txPrev.vout[prevout.n].posNext = posThisTx;
1026 
1027             nValueIn += txPrev.vout[prevout.n].nValue;
1028 
1029             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1030                 return error("ClientConnectInputs() : txin values out of range");
1031         }
1032         if (GetValueOut() > nValueIn)
1033             return false;
1034     }
1035 
1036     return true;
1037 }
1038 
1039 
1040 
1041 
1042 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1043 {
1044     // Disconnect in reverse order
1045     for (int i = vtx.size()-1; i >= 0; i--)
1046         if (!vtx[i].DisconnectInputs(txdb))
1047             return false;
1048 
1049     // Update block index on disk without changing it in memory.
1050     // The memory index structure will be changed after the db commits.
1051     if (pindex->pprev)
1052     {
1053         CDiskBlockIndex blockindexPrev(pindex->pprev);
1054         blockindexPrev.hashNext = 0;
1055         if (!txdb.WriteBlockIndex(blockindexPrev))
1056             return error("DisconnectBlock() : WriteBlockIndex failed");
1057     }
1058 
1059     return true;
1060 }
1061 
1062 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1063 {
1064     // Check it again in case a previous version let a bad block in
1065     if (!CheckBlock())
1066         return false;
1067 
1068     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1069     // unless those are already completely spent.
1070     // If such overwrites are allowed, coinbases and transactions depending upon those
1071     // can be duplicated to remove the ability to spend the first instance -- even after
1072     // being sent to another address.
1073     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1074     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1075     // already refuses previously-known transaction id's entirely.
1076     // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1077     // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1078     if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1079         BOOST_FOREACH(CTransaction& tx, vtx)
1080         {
1081             CTxIndex txindexOld;
1082             if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1083                 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1084                     if (pos.IsNull())
1085                         return false;
1086         }
1087 
1088     //// issue here: it doesn't know the version
1089     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1090 
1091     map<uint256, CTxIndex> mapQueuedChanges;
1092     int64 nFees = 0;
1093     BOOST_FOREACH(CTransaction& tx, vtx)
1094     {
1095         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1096         nTxPos += ::GetSerializeSize(tx, SER_DISK);
1097 
1098         bool fInvalid;
1099         if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
1100             return false;
1101     }
1102     // Write queued txindex changes
1103     for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1104     {
1105         if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1106             return error("ConnectBlock() : UpdateTxIndex failed");
1107     }
1108 
1109     if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1110         return false;
1111 
1112     // Update block index on disk without changing it in memory.
1113     // The memory index structure will be changed after the db commits.
1114     if (pindex->pprev)
1115     {
1116         CDiskBlockIndex blockindexPrev(pindex->pprev);
1117         blockindexPrev.hashNext = pindex->GetBlockHash();
1118         if (!txdb.WriteBlockIndex(blockindexPrev))
1119             return error("ConnectBlock() : WriteBlockIndex failed");
1120     }
1121 
1122     // Watch for transactions paying to me
1123     BOOST_FOREACH(CTransaction& tx, vtx)
1124         SyncWithWallets(tx, this, true);
1125 
1126     return true;
1127 }
1128 
1129 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1130 {
1131     printf("REORGANIZE\n");
1132 
1133     // Find the fork
1134     CBlockIndex* pfork = pindexBest;
1135     CBlockIndex* plonger = pindexNew;
1136     while (pfork != plonger)
1137     {
1138         while (plonger->nHeight > pfork->nHeight)
1139             if (!(plonger = plonger->pprev))
1140                 return error("Reorganize() : plonger->pprev is null");
1141         if (pfork == plonger)
1142             break;
1143         if (!(pfork = pfork->pprev))
1144             return error("Reorganize() : pfork->pprev is null");
1145     }
1146 
1147     // List of what to disconnect
1148     vector<CBlockIndex*> vDisconnect;
1149     for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1150         vDisconnect.push_back(pindex);
1151 
1152     // List of what to connect
1153     vector<CBlockIndex*> vConnect;
1154     for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1155         vConnect.push_back(pindex);
1156     reverse(vConnect.begin(), vConnect.end());
1157 
1158     // Disconnect shorter branch
1159     vector<CTransaction> vResurrect;
1160     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1161     {
1162         CBlock block;
1163         if (!block.ReadFromDisk(pindex))
1164             return error("Reorganize() : ReadFromDisk for disconnect failed");
1165         if (!block.DisconnectBlock(txdb, pindex))
1166             return error("Reorganize() : DisconnectBlock failed");
1167 
1168         // Queue memory transactions to resurrect
1169         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1170             if (!tx.IsCoinBase())
1171                 vResurrect.push_back(tx);
1172     }
1173 
1174     // Connect longer branch
1175     vector<CTransaction> vDelete;
1176     for (int i = 0; i < vConnect.size(); i++)
1177     {
1178         CBlockIndex* pindex = vConnect[i];
1179         CBlock block;
1180         if (!block.ReadFromDisk(pindex))
1181             return error("Reorganize() : ReadFromDisk for connect failed");
1182         if (!block.ConnectBlock(txdb, pindex))
1183         {
1184             // Invalid block
1185             txdb.TxnAbort();
1186             return error("Reorganize() : ConnectBlock failed");
1187         }
1188 
1189         // Queue memory transactions to delete
1190         BOOST_FOREACH(const CTransaction& tx, block.vtx)
1191             vDelete.push_back(tx);
1192     }
1193     if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1194         return error("Reorganize() : WriteHashBestChain failed");
1195 
1196     // Make sure it's successfully written to disk before changing memory structure
1197     if (!txdb.TxnCommit())
1198         return error("Reorganize() : TxnCommit failed");
1199 
1200     // Disconnect shorter branch
1201     BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1202         if (pindex->pprev)
1203             pindex->pprev->pnext = NULL;
1204 
1205     // Connect longer branch
1206     BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1207         if (pindex->pprev)
1208             pindex->pprev->pnext = pindex;
1209 
1210     // Resurrect memory transactions that were in the disconnected branch
1211     BOOST_FOREACH(CTransaction& tx, vResurrect)
1212         tx.AcceptToMemoryPool(txdb, false);
1213 
1214     // Delete redundant memory transactions that are in the connected branch
1215     BOOST_FOREACH(CTransaction& tx, vDelete)
1216         tx.RemoveFromMemoryPool();
1217 
1218     return true;
1219 }
1220 
1221 
1222 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1223 {
1224     uint256 hash = GetHash();
1225 
1226     txdb.TxnBegin();
1227     if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1228     {
1229         txdb.WriteHashBestChain(hash);
1230         if (!txdb.TxnCommit())
1231             return error("SetBestChain() : TxnCommit failed");
1232         pindexGenesisBlock = pindexNew;
1233     }
1234     else if (hashPrevBlock == hashBestChain)
1235     {
1236         // Adding to current best branch
1237         if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1238         {
1239             txdb.TxnAbort();
1240             InvalidChainFound(pindexNew);
1241             return error("SetBestChain() : ConnectBlock failed");
1242         }
1243         if (!txdb.TxnCommit())
1244             return error("SetBestChain() : TxnCommit failed");
1245 
1246         // Add to current best branch
1247         pindexNew->pprev->pnext = pindexNew;
1248 
1249         // Delete redundant memory transactions
1250         BOOST_FOREACH(CTransaction& tx, vtx)
1251             tx.RemoveFromMemoryPool();
1252     }
1253     else
1254     {
1255         // New best branch
1256         if (!Reorganize(txdb, pindexNew))
1257         {
1258             txdb.TxnAbort();
1259             InvalidChainFound(pindexNew);
1260             return error("SetBestChain() : Reorganize failed");
1261         }
1262     }
1263 
1264     // Update best block in wallet (so we can detect restored wallets)
1265     if (!IsInitialBlockDownload())
1266     {
1267         const CBlockLocator locator(pindexNew);
1268         ::SetBestChain(locator);
1269     }
1270 
1271     // New best block
1272     hashBestChain = hash;
1273     pindexBest = pindexNew;
1274     nBestHeight = pindexBest->nHeight;
1275     bnBestChainWork = pindexNew->bnChainWork;
1276     nTimeBestReceived = GetTime();
1277     nTransactionsUpdated++;
1278     printf("SetBestChain: new best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1279 
1280     return true;
1281 }
1282 
1283 
1284 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1285 {
1286     // Check for duplicate
1287     uint256 hash = GetHash();
1288     if (mapBlockIndex.count(hash))
1289         return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1290 
1291     // Construct new block index object
1292     CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1293     if (!pindexNew)
1294         return error("AddToBlockIndex() : new CBlockIndex failed");
1295     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1296     pindexNew->phashBlock = &((*mi).first);
1297     map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1298     if (miPrev != mapBlockIndex.end())
1299     {
1300         pindexNew->pprev = (*miPrev).second;
1301         pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1302     }
1303     pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1304 
1305     CTxDB txdb;
1306     txdb.TxnBegin();
1307     txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1308     if (!txdb.TxnCommit())
1309         return false;
1310 
1311     // New best
1312     if (pindexNew->bnChainWork > bnBestChainWork)
1313         if (!SetBestChain(txdb, pindexNew))
1314             return false;
1315 
1316     txdb.Close();
1317 
1318     if (pindexNew == pindexBest)
1319     {
1320         // Notify UI to display prev block's coinbase if it was ours
1321         static uint256 hashPrevBestCoinBase;
1322         UpdatedTransaction(hashPrevBestCoinBase);
1323         hashPrevBestCoinBase = vtx[0].GetHash();
1324     }
1325 
1326     MainFrameRepaint();
1327     return true;
1328 }
1329 
1330 
1331 
1332 
1333 bool CBlock::CheckBlock() const
1334 {
1335     // These are checks that are independent of context
1336     // that can be verified before saving an orphan block.
1337 
1338     // Size limits
1339     if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1340         return DoS(100, error("CheckBlock() : size limits failed"));
1341 
1342     // Check proof of work matches claimed amount
1343     if (!CheckProofOfWork(GetHash(), nBits))
1344         return DoS(50, error("CheckBlock() : proof of work failed"));
1345 
1346     // Check timestamp
1347     if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1348         return error("CheckBlock() : block timestamp too far in the future");
1349 
1350     // First transaction must be coinbase, the rest must not be
1351     if (vtx.empty() || !vtx[0].IsCoinBase())
1352         return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1353     for (int i = 1; i < vtx.size(); i++)
1354         if (vtx[i].IsCoinBase())
1355             return DoS(100, error("CheckBlock() : more than one coinbase"));
1356 
1357     // Check transactions
1358     BOOST_FOREACH(const CTransaction& tx, vtx)
1359         if (!tx.CheckTransaction())
1360             return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1361 
1362     // Check that it's not full of nonstandard transactions
1363     if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1364         return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1365 
1366     // Check merkleroot
1367     if (hashMerkleRoot != BuildMerkleTree())
1368         return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1369 
1370     return true;
1371 }
1372 
1373 bool CBlock::AcceptBlock()
1374 {
1375     // Check for duplicate
1376     uint256 hash = GetHash();
1377     if (mapBlockIndex.count(hash))
1378         return error("AcceptBlock() : block already in mapBlockIndex");
1379 
1380     // Get prev block index
1381     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1382     if (mi == mapBlockIndex.end())
1383         return DoS(10, error("AcceptBlock() : prev block not found"));
1384     CBlockIndex* pindexPrev = (*mi).second;
1385     int nHeight = pindexPrev->nHeight+1;
1386 
1387     // Check proof of work
1388     if (nBits != GetNextWorkRequired(pindexPrev, this))
1389         return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1390 
1391     // Check timestamp against prev
1392     if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1393         return error("AcceptBlock() : block's timestamp is too early");
1394 
1395     // Check that all transactions are finalized
1396     BOOST_FOREACH(const CTransaction& tx, vtx)
1397         if (!tx.IsFinal(nHeight, GetBlockTime()))
1398             return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1399 
1400     // Check that the block chain matches the known block chain up to a checkpoint
1401     if (!Checkpoints::CheckBlock(nHeight, hash))
1402         return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1403 
1404     // Write block to history file
1405     if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1406         return error("AcceptBlock() : out of disk space");
1407     unsigned int nFile = -1;
1408     unsigned int nBlockPos = 0;
1409     if (!WriteToDisk(nFile, nBlockPos))
1410         return error("AcceptBlock() : WriteToDisk failed");
1411     if (!AddToBlockIndex(nFile, nBlockPos))
1412         return error("AcceptBlock() : AddToBlockIndex failed");
1413 
1414     // Relay inventory, but don't relay old inventory during initial block download
1415     if (hashBestChain == hash)
1416         CRITICAL_BLOCK(cs_vNodes)
1417             BOOST_FOREACH(CNode* pnode, vNodes)
1418                 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1419                     pnode->PushInventory(CInv(MSG_BLOCK, hash));
1420 
1421     return true;
1422 }
1423 
1424 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1425 {
1426     // Check for duplicate
1427     uint256 hash = pblock->GetHash();
1428     if (mapBlockIndex.count(hash))
1429         return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1430     if (mapOrphanBlocks.count(hash))
1431         return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1432 
1433     // Preliminary checks
1434     if (!pblock->CheckBlock())
1435         return error("ProcessBlock() : CheckBlock FAILED");
1436 
1437     CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1438     if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1439     {
1440         // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1441         int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1442         if (deltaTime < 0)
1443         {
1444             if (pfrom)
1445                 pfrom->Misbehaving(100);
1446             return error("ProcessBlock() : block with timestamp before last checkpoint");
1447         }
1448         CBigNum bnNewBlock;
1449         bnNewBlock.SetCompact(pblock->nBits);
1450         CBigNum bnRequired;
1451         bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1452         if (bnNewBlock > bnRequired)
1453         {
1454             if (pfrom)
1455                 pfrom->Misbehaving(100);
1456             return error("ProcessBlock() : block with too little proof-of-work");
1457         }
1458     }
1459 
1460 
1461     // If don't already have its previous block, shunt it off to holding area until we get it
1462     if (!mapBlockIndex.count(pblock->hashPrevBlock))
1463     {
1464         printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1465         CBlock* pblock2 = new CBlock(*pblock);
1466         mapOrphanBlocks.insert(make_pair(hash, pblock2));
1467         mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1468 
1469         // Ask this guy to fill in what we're missing
1470         if (pfrom)
1471             pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1472         return true;
1473     }
1474 
1475     // Store to disk
1476     if (!pblock->AcceptBlock())
1477         return error("ProcessBlock() : AcceptBlock FAILED");
1478 
1479     // Recursively process any orphan blocks that depended on this one
1480     vector<uint256> vWorkQueue;
1481     vWorkQueue.push_back(hash);
1482     for (int i = 0; i < vWorkQueue.size(); i++)
1483     {
1484         uint256 hashPrev = vWorkQueue[i];
1485         for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1486              mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1487              ++mi)
1488         {
1489             CBlock* pblockOrphan = (*mi).second;
1490             if (pblockOrphan->AcceptBlock())
1491                 vWorkQueue.push_back(pblockOrphan->GetHash());
1492             mapOrphanBlocks.erase(pblockOrphan->GetHash());
1493             delete pblockOrphan;
1494         }
1495         mapOrphanBlocksByPrev.erase(hashPrev);
1496     }
1497 
1498     printf("ProcessBlock: ACCEPTED\n");
1499     return true;
1500 }
1501 
1502 
1503 
1504 
1505 
1506 
1507 
1508 
1509 bool CheckDiskSpace(uint64 nAdditionalBytes)
1510 {
1511     uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1512 
1513     // Check for 15MB because database could create another 10MB log file at any time
1514     if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1515     {
1516         fShutdown = true;
1517         string strMessage = _("Warning: Disk space is low  ");
1518         strMiscWarning = strMessage;
1519         printf("*** %s\n", strMessage.c_str());
1520         ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1521         CreateThread(Shutdown, NULL);
1522         return false;
1523     }
1524     return true;
1525 }
1526 
1527 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1528 {
1529     if (nFile == -1)
1530         return NULL;
1531     FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1532     if (!file)
1533         return NULL;
1534     if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1535     {
1536         if (fseek(file, nBlockPos, SEEK_SET) != 0)
1537         {
1538             fclose(file);
1539             return NULL;
1540         }
1541     }
1542     return file;
1543 }
1544 
1545 static unsigned int nCurrentBlockFile = 1;
1546 
1547 FILE* AppendBlockFile(unsigned int& nFileRet)
1548 {
1549     nFileRet = 0;
1550     loop
1551     {
1552         FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1553         if (!file)
1554             return NULL;
1555         if (fseek(file, 0, SEEK_END) != 0)
1556             return NULL;
1557         // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1558         if (ftell(file) < 0x7F000000 - MAX_SIZE)
1559         {
1560             nFileRet = nCurrentBlockFile;
1561             return file;
1562         }
1563         fclose(file);
1564         nCurrentBlockFile++;
1565     }
1566 }
1567 
1568 bool LoadBlockIndex(bool fAllowNew)
1569 {
1570     if (fTestNet)
1571     {
1572         hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1573         bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1574         pchMessageStart[0] = 0xfa;
1575         pchMessageStart[1] = 0xbf;
1576         pchMessageStart[2] = 0xb5;
1577         pchMessageStart[3] = 0xda;
1578     }
1579 
1580     //
1581     // Load block index
1582     //
1583     CTxDB txdb("cr");
1584     if (!txdb.LoadBlockIndex())
1585         return false;
1586     txdb.Close();
1587 
1588     //
1589     // Init with genesis block
1590     //
1591     if (mapBlockIndex.empty())
1592     {
1593         if (!fAllowNew)
1594             return false;
1595 
1596         // Genesis Block:
1597         // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1598         //   CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1599         //     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1600         //     CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1601         //   vMerkleTree: 4a5e1e
1602 
1603         // Genesis block
1604         const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1605         CTransaction txNew;
1606         txNew.vin.resize(1);
1607         txNew.vout.resize(1);
1608         txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1609         txNew.vout[0].nValue = 50 * COIN;
1610         txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1611         CBlock block;
1612         block.vtx.push_back(txNew);
1613         block.hashPrevBlock = 0;
1614         block.hashMerkleRoot = block.BuildMerkleTree();
1615         block.nVersion = 1;
1616         block.nTime    = 1231006505;
1617         block.nBits    = 0x1d00ffff;
1618         block.nNonce   = 2083236893;
1619 
1620         if (fTestNet)
1621         {
1622             block.nTime    = 1296688602;
1623             block.nBits    = 0x1d07fff8;
1624             block.nNonce   = 384568319;
1625         }
1626 
1627         //// debug print
1628         printf("%s\n", block.GetHash().ToString().c_str());
1629         printf("%s\n", hashGenesisBlock.ToString().c_str());
1630         printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1631         assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1632         block.print();
1633         assert(block.GetHash() == hashGenesisBlock);
1634 
1635         // Start new block file
1636         unsigned int nFile;
1637         unsigned int nBlockPos;
1638         if (!block.WriteToDisk(nFile, nBlockPos))
1639             return error("LoadBlockIndex() : writing genesis block to disk failed");
1640         if (!block.AddToBlockIndex(nFile, nBlockPos))
1641             return error("LoadBlockIndex() : genesis block not accepted");
1642     }
1643 
1644     return true;
1645 }
1646 
1647 
1648 
1649 void PrintBlockTree()
1650 {
1651     // precompute tree structure
1652     map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1653     for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1654     {
1655         CBlockIndex* pindex = (*mi).second;
1656         mapNext[pindex->pprev].push_back(pindex);
1657         // test
1658         //while (rand() % 3 == 0)
1659         //    mapNext[pindex->pprev].push_back(pindex);
1660     }
1661 
1662     vector<pair<int, CBlockIndex*> > vStack;
1663     vStack.push_back(make_pair(0, pindexGenesisBlock));
1664 
1665     int nPrevCol = 0;
1666     while (!vStack.empty())
1667     {
1668         int nCol = vStack.back().first;
1669         CBlockIndex* pindex = vStack.back().second;
1670         vStack.pop_back();
1671 
1672         // print split or gap
1673         if (nCol > nPrevCol)
1674         {
1675             for (int i = 0; i < nCol-1; i++)
1676                 printf("| ");
1677             printf("|\\\n");
1678         }
1679         else if (nCol < nPrevCol)
1680         {
1681             for (int i = 0; i < nCol; i++)
1682                 printf("| ");
1683             printf("|\n");
1684        }
1685         nPrevCol = nCol;
1686 
1687         // print columns
1688         for (int i = 0; i < nCol; i++)
1689             printf("| ");
1690 
1691         // print item
1692         CBlock block;
1693         block.ReadFromDisk(pindex);
1694         printf("%d (%u,%u) %s  %s  tx %d",
1695             pindex->nHeight,
1696             pindex->nFile,
1697             pindex->nBlockPos,
1698             block.GetHash().ToString().substr(0,20).c_str(),
1699             DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1700             block.vtx.size());
1701 
1702         PrintWallets(block);
1703 
1704         // put the main timechain first
1705         vector<CBlockIndex*>& vNext = mapNext[pindex];
1706         for (int i = 0; i < vNext.size(); i++)
1707         {
1708             if (vNext[i]->pnext)
1709             {
1710                 swap(vNext[0], vNext[i]);
1711                 break;
1712             }
1713         }
1714 
1715         // iterate children
1716         for (int i = 0; i < vNext.size(); i++)
1717             vStack.push_back(make_pair(nCol+i, vNext[i]));
1718     }
1719 }
1720 
1721 
1722 
1723 //////////////////////////////////////////////////////////////////////////////
1724 //
1725 // Warnings (was: CAlert)
1726 //
1727 
1728 string GetWarnings(string strFor)
1729 {
1730     int nPriority = 0;
1731     string strStatusBar;
1732     string strRPC;
1733     if (GetBoolArg("-testsafemode"))
1734         strRPC = "test";
1735 
1736     // Misc warnings like out of disk space and clock is wrong
1737     if (strMiscWarning != "")
1738     {
1739         nPriority = 1000;
1740         strStatusBar = strMiscWarning;
1741     }
1742 
1743     // Longer invalid proof-of-work chain
1744     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1745     {
1746         nPriority = 2000;
1747         strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.";
1748     }
1749 
1750     if (strFor == "statusbar")
1751         return strStatusBar;
1752     else if (strFor == "rpc")
1753         return strRPC;
1754     assert(!"GetWarnings() : invalid parameter");
1755     return "error";
1756 }
1757 
1758 
1759 //////////////////////////////////////////////////////////////////////////////
1760 //
1761 // Messages
1762 //
1763 
1764 
1765 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1766 {
1767     switch (inv.type)
1768     {
1769     case MSG_TX:    return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1770     case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1771     }
1772     // Don't know what it is, just say we already got one
1773     return true;
1774 }
1775 
1776 
1777 
1778 
1779 // The message start string is designed to be unlikely to occur in normal data.
1780 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1781 // a large 4-byte int at any alignment.
1782 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1783 
1784 
1785 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1786 {
1787     static map<unsigned int, vector<unsigned char> > mapReuseKey;
1788     RandAddSeedPerfmon();
1789     if (fDebug) {
1790         printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1791         printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1792     }
1793     if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1794     {
1795         printf("dropmessagestest DROPPING RECV MESSAGE\n");
1796         return true;
1797     }
1798 
1799 
1800 
1801 
1802 
1803     if (strCommand == "version")
1804     {
1805         // Each connection can only send one version message
1806         if (pfrom->nVersion != 0)
1807         {
1808             pfrom->Misbehaving(1);
1809             return false;
1810         }
1811 
1812         int64 nTime;
1813         CAddress addrMe;
1814         CAddress addrFrom;
1815         uint64 nNonce = 1;
1816         vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1817         if (pfrom->nVersion == 10300)
1818             pfrom->nVersion = 300;
1819         if (pfrom->nVersion >= 106 && !vRecv.empty())
1820             vRecv >> addrFrom >> nNonce;
1821         if (pfrom->nVersion >= 106 && !vRecv.empty())
1822             vRecv >> pfrom->strSubVer;
1823         if (pfrom->nVersion >= 209 && !vRecv.empty())
1824             vRecv >> pfrom->nStartingHeight;
1825 
1826         if (pfrom->nVersion == 0)
1827             return false;
1828 
1829         // Disconnect if we connected to ourself
1830         if (nNonce == nLocalHostNonce && nNonce > 1)
1831         {
1832             printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1833             pfrom->fDisconnect = true;
1834             return true;
1835         }
1836 
1837         // Be shy and don't send version until we hear
1838         if (pfrom->fInbound)
1839             pfrom->PushVersion();
1840 
1841         pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1842 
1843         AddTimeData(pfrom->addr.ip, nTime);
1844 
1845         // Change version
1846         if (pfrom->nVersion >= 209)
1847             pfrom->PushMessage("verack");
1848         pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
1849         if (pfrom->nVersion < 209)
1850             pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1851 
1852         if (!pfrom->fInbound)
1853         {
1854             // Advertise our address
1855             if (addrLocalHost.IsRoutable() && !fUseProxy)
1856             {
1857                 CAddress addr(addrLocalHost);
1858                 addr.nTime = GetAdjustedTime();
1859                 pfrom->PushAddress(addr);
1860             }
1861 
1862             // Get recent addresses
1863             if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
1864             {
1865                 pfrom->PushMessage("getaddr");
1866                 pfrom->fGetAddr = true;
1867             }
1868         }
1869 
1870         // Ask the first connected node for block updates
1871         static int nAskedForBlocks;
1872         if (!pfrom->fClient &&
1873             (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
1874              (nAskedForBlocks < 1 || vNodes.size() <= 1))
1875         {
1876             nAskedForBlocks++;
1877             pfrom->PushGetBlocks(pindexBest, uint256(0));
1878         }
1879 
1880         pfrom->fSuccessfullyConnected = true;
1881 
1882         printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
1883 
1884         cPeerBlockCounts.input(pfrom->nStartingHeight);
1885     }
1886 
1887 
1888     else if (pfrom->nVersion == 0)
1889     {
1890         // Must have a version message before anything else
1891         pfrom->Misbehaving(1);
1892         return false;
1893     }
1894 
1895 
1896     else if (strCommand == "verack")
1897     {
1898         pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
1899     }
1900 
1901 
1902     else if (strCommand == "addr")
1903     {
1904         vector<CAddress> vAddr;
1905         vRecv >> vAddr;
1906 
1907         // Don't want addr from older versions unless seeding
1908         if (pfrom->nVersion < 209)
1909             return true;
1910         if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
1911             return true;
1912         if (vAddr.size() > 1000)
1913         {
1914             pfrom->Misbehaving(20);
1915             return error("message addr size() = %d", vAddr.size());
1916         }
1917 
1918         // Store the new addresses
1919         CAddrDB addrDB;
1920         addrDB.TxnBegin();
1921         int64 nNow = GetAdjustedTime();
1922         int64 nSince = nNow - 10 * 60;
1923         BOOST_FOREACH(CAddress& addr, vAddr)
1924         {
1925             if (fShutdown)
1926                 return true;
1927             // ignore IPv6 for now, since it isn't implemented anyway
1928             if (!addr.IsIPv4())
1929                 continue;
1930             if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
1931                 addr.nTime = nNow - 5 * 24 * 60 * 60;
1932             AddAddress(addr, 2 * 60 * 60, &addrDB);
1933             pfrom->AddAddressKnown(addr);
1934             if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
1935             {
1936                 // Relay to a limited number of other nodes
1937                 CRITICAL_BLOCK(cs_vNodes)
1938                 {
1939                     // Use deterministic randomness to send to the same nodes for 24 hours
1940                     // at a time so the setAddrKnowns of the chosen nodes prevent repeats
1941                     static uint256 hashSalt;
1942                     if (hashSalt == 0)
1943                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
1944                     uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
1945                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
1946                     multimap<uint256, CNode*> mapMix;
1947                     BOOST_FOREACH(CNode* pnode, vNodes)
1948                     {
1949                         if (pnode->nVersion < 31402)
1950                             continue;
1951                         unsigned int nPointer;
1952                         memcpy(&nPointer, &pnode, sizeof(nPointer));
1953                         uint256 hashKey = hashRand ^ nPointer;
1954                         hashKey = Hash(BEGIN(hashKey), END(hashKey));
1955                         mapMix.insert(make_pair(hashKey, pnode));
1956                     }
1957                     int nRelayNodes = 2;
1958                     for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
1959                         ((*mi).second)->PushAddress(addr);
1960                 }
1961             }
1962         }
1963         addrDB.TxnCommit();  // Save addresses (it's ok if this fails)
1964         if (vAddr.size() < 1000)
1965             pfrom->fGetAddr = false;
1966     }
1967 
1968 
1969     else if (strCommand == "inv")
1970     {
1971         vector<CInv> vInv;
1972         vRecv >> vInv;
1973         if (vInv.size() > 50000)
1974         {
1975             pfrom->Misbehaving(20);
1976             return error("message inv size() = %d", vInv.size());
1977         }
1978 
1979         CTxDB txdb("r");
1980         BOOST_FOREACH(const CInv& inv, vInv)
1981         {
1982             if (fShutdown)
1983                 return true;
1984             pfrom->AddInventoryKnown(inv);
1985 
1986             bool fAlreadyHave = AlreadyHave(txdb, inv);
1987             if (fDebug)
1988                 printf("  got inventory: %s  %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
1989 
1990             if (!fAlreadyHave)
1991                 pfrom->AskFor(inv);
1992             else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
1993                 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
1994 
1995             // Track requests for our stuff
1996             Inventory(inv.hash);
1997         }
1998     }
1999 
2000 
2001     else if (strCommand == "getdata")
2002     {
2003         vector<CInv> vInv;
2004         vRecv >> vInv;
2005         if (vInv.size() > 50000)
2006         {
2007             pfrom->Misbehaving(20);
2008             return error("message getdata size() = %d", vInv.size());
2009         }
2010 
2011         BOOST_FOREACH(const CInv& inv, vInv)
2012         {
2013             if (fShutdown)
2014                 return true;
2015             printf("received getdata for: %s\n", inv.ToString().c_str());
2016 
2017             if (inv.type == MSG_BLOCK)
2018             {
2019                 // Send block from disk
2020                 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2021                 if (mi != mapBlockIndex.end())
2022                 {
2023                     CBlock block;
2024                     block.ReadFromDisk((*mi).second);
2025                     pfrom->PushMessage("block", block);
2026 
2027                     // Trigger them to send a getblocks request for the next batch of inventory
2028                     if (inv.hash == pfrom->hashContinue)
2029                     {
2030                         // Bypass PushInventory, this must send even if redundant,
2031                         // and we want it right after the last block so they don't
2032                         // wait for other stuff first.
2033                         vector<CInv> vInv;
2034                         vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2035                         pfrom->PushMessage("inv", vInv);
2036                         pfrom->hashContinue = 0;
2037                     }
2038                 }
2039             }
2040             else if (inv.IsKnownType())
2041             {
2042                 // Send stream from relay memory
2043                 CRITICAL_BLOCK(cs_mapRelay)
2044                 {
2045                     map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2046                     if (mi != mapRelay.end())
2047                         pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2048                 }
2049             }
2050 
2051             // Track requests for our stuff
2052             Inventory(inv.hash);
2053         }
2054     }
2055 
2056 
2057     else if (strCommand == "getblocks")
2058     {
2059         CBlockLocator locator;
2060         uint256 hashStop;
2061         vRecv >> locator >> hashStop;
2062 
2063         // Find the last block the caller has in the main chain
2064         CBlockIndex* pindex = locator.GetBlockIndex();
2065 
2066         // Send the rest of the chain
2067         if (pindex)
2068             pindex = pindex->pnext;
2069         int nLimit = 500 + locator.GetDistanceBack();
2070         unsigned int nBytes = 0;
2071         printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2072         for (; pindex; pindex = pindex->pnext)
2073         {
2074             if (pindex->GetBlockHash() == hashStop)
2075             {
2076                 printf("  getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2077                 break;
2078             }
2079             pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2080             CBlock block;
2081             block.ReadFromDisk(pindex, true);
2082             nBytes += block.GetSerializeSize(SER_NETWORK);
2083             if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2084             {
2085                 // When this block is requested, we'll send an inv that'll make them
2086                 // getblocks the next batch of inventory.
2087                 printf("  getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2088                 pfrom->hashContinue = pindex->GetBlockHash();
2089                 break;
2090             }
2091         }
2092     }
2093 
2094 
2095     else if (strCommand == "getheaders")
2096     {
2097         CBlockLocator locator;
2098         uint256 hashStop;
2099         vRecv >> locator >> hashStop;
2100 
2101         CBlockIndex* pindex = NULL;
2102         if (locator.IsNull())
2103         {
2104             // If locator is null, return the hashStop block
2105             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2106             if (mi == mapBlockIndex.end())
2107                 return true;
2108             pindex = (*mi).second;
2109         }
2110         else
2111         {
2112             // Find the last block the caller has in the main chain
2113             pindex = locator.GetBlockIndex();
2114             if (pindex)
2115                 pindex = pindex->pnext;
2116         }
2117 
2118         vector<CBlock> vHeaders;
2119         int nLimit = 2000 + locator.GetDistanceBack();
2120         printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2121         for (; pindex; pindex = pindex->pnext)
2122         {
2123             vHeaders.push_back(pindex->GetBlockHeader());
2124             if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2125                 break;
2126         }
2127         pfrom->PushMessage("headers", vHeaders);
2128     }
2129 
2130 
2131     else if (strCommand == "tx")
2132     {
2133         vector<uint256> vWorkQueue;
2134         CDataStream vMsg(vRecv);
2135         CTransaction tx;
2136         vRecv >> tx;
2137 
2138         CInv inv(MSG_TX, tx.GetHash());
2139         pfrom->AddInventoryKnown(inv);
2140 
2141         bool fMissingInputs = false;
2142         if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2143         {
2144             SyncWithWallets(tx, NULL, true);
2145             RelayMessage(inv, vMsg);
2146             mapAlreadyAskedFor.erase(inv);
2147             vWorkQueue.push_back(inv.hash);
2148 
2149             // Recursively process any orphan transactions that depended on this one
2150             for (int i = 0; i < vWorkQueue.size(); i++)
2151             {
2152                 uint256 hashPrev = vWorkQueue[i];
2153                 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2154                      mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2155                      ++mi)
2156                 {
2157                     const CDataStream& vMsg = *((*mi).second);
2158                     CTransaction tx;
2159                     CDataStream(vMsg) >> tx;
2160                     CInv inv(MSG_TX, tx.GetHash());
2161 
2162                     if (tx.AcceptToMemoryPool(true))
2163                     {
2164                         printf("   accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2165                         SyncWithWallets(tx, NULL, true);
2166                         RelayMessage(inv, vMsg);
2167                         mapAlreadyAskedFor.erase(inv);
2168                         vWorkQueue.push_back(inv.hash);
2169                     }
2170                 }
2171             }
2172 
2173             BOOST_FOREACH(uint256 hash, vWorkQueue)
2174                 EraseOrphanTx(hash);
2175         }
2176         else if (fMissingInputs)
2177         {
2178             printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2179             AddOrphanTx(vMsg);
2180 
2181             // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2182             int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2183             if (nEvicted > 0)
2184                 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
2185         }
2186         if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2187     }
2188 
2189 
2190     else if (strCommand == "block")
2191     {
2192         CBlock block;
2193         vRecv >> block;
2194 
2195         printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2196         // block.print();
2197 
2198         CInv inv(MSG_BLOCK, block.GetHash());
2199         pfrom->AddInventoryKnown(inv);
2200 
2201         if (ProcessBlock(pfrom, &block))
2202             mapAlreadyAskedFor.erase(inv);
2203         if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2204     }
2205 
2206 
2207     else if (strCommand == "getaddr")
2208     {
2209         // Nodes rebroadcast an addr every 24 hours
2210         pfrom->vAddrToSend.clear();
2211         int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2212         CRITICAL_BLOCK(cs_mapAddresses)
2213         {
2214             unsigned int nCount = 0;
2215             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2216             {
2217                 const CAddress& addr = item.second;
2218                 if (addr.nTime > nSince)
2219                     nCount++;
2220             }
2221             BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2222             {
2223                 const CAddress& addr = item.second;
2224                 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2225                     pfrom->PushAddress(addr);
2226             }
2227         }
2228     }
2229 
2230 
2231     else if (strCommand == "checkorder")
2232     {
2233         uint256 hashReply;
2234         vRecv >> hashReply;
2235 
2236         if (!GetBoolArg("-allowreceivebyip"))
2237         {
2238             pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2239             return true;
2240         }
2241 
2242         CWalletTx order;
2243         vRecv >> order;
2244 
2245         /// we have a chance to check the order here
2246 
2247         // Keep giving the same key to the same ip until they use it
2248         if (!mapReuseKey.count(pfrom->addr.ip))
2249             pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2250 
2251         // Send back approval of order and pubkey to use
2252         CScript scriptPubKey;
2253         scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2254         pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2255     }
2256 
2257 
2258     else if (strCommand == "reply")
2259     {
2260         uint256 hashReply;
2261         vRecv >> hashReply;
2262 
2263         CRequestTracker tracker;
2264         CRITICAL_BLOCK(pfrom->cs_mapRequests)
2265         {
2266             map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2267             if (mi != pfrom->mapRequests.end())
2268             {
2269                 tracker = (*mi).second;
2270                 pfrom->mapRequests.erase(mi);
2271             }
2272         }
2273         if (!tracker.IsNull())
2274             tracker.fn(tracker.param1, vRecv);
2275     }
2276 
2277 
2278     else if (strCommand == "ping")
2279     {
2280     }
2281 
2282 
2283     else
2284     {
2285         // Ignore unknown commands for extensibility
2286     }
2287 
2288 
2289     // Update the last seen time for this node's address
2290     if (pfrom->fNetworkNode)
2291         if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2292             AddressCurrentlyConnected(pfrom->addr);
2293 
2294 
2295     return true;
2296 }
2297 
2298 bool ProcessMessages(CNode* pfrom)
2299 {
2300     CDataStream& vRecv = pfrom->vRecv;
2301     if (vRecv.empty())
2302         return true;
2303     //if (fDebug)
2304     //    printf("ProcessMessages(%u bytes)\n", vRecv.size());
2305 
2306     //
2307     // Message format
2308     //  (4) message start
2309     //  (12) command
2310     //  (4) size
2311     //  (4) checksum
2312     //  (x) data
2313     //
2314 
2315     loop
2316     {
2317         // Scan for message start
2318         CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2319         int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2320         if (vRecv.end() - pstart < nHeaderSize)
2321         {
2322             if (vRecv.size() > nHeaderSize)
2323             {
2324                 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2325                 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2326             }
2327             break;
2328         }
2329         if (pstart - vRecv.begin() > 0)
2330             printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2331         vRecv.erase(vRecv.begin(), pstart);
2332 
2333         // Read header
2334         vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2335         CMessageHeader hdr;
2336         vRecv >> hdr;
2337         if (!hdr.IsValid())
2338         {
2339             printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2340             continue;
2341         }
2342         string strCommand = hdr.GetCommand();
2343 
2344         // Message size
2345         unsigned int nMessageSize = hdr.nMessageSize;
2346         if (nMessageSize > MAX_SIZE)
2347         {
2348             printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2349             continue;
2350         }
2351         if (nMessageSize > vRecv.size())
2352         {
2353             // Rewind and wait for rest of message
2354             vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2355             break;
2356         }
2357 
2358         // Checksum
2359         if (vRecv.GetVersion() >= 209)
2360         {
2361             uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2362             unsigned int nChecksum = 0;
2363             memcpy(&nChecksum, &hash, sizeof(nChecksum));
2364             if (nChecksum != hdr.nChecksum)
2365             {
2366                 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2367                        strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2368                 continue;
2369             }
2370         }
2371 
2372         // Copy message to its own buffer
2373         CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2374         vRecv.ignore(nMessageSize);
2375 
2376         // Process message
2377         bool fRet = false;
2378         try
2379         {
2380             CRITICAL_BLOCK(cs_main)
2381                 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2382             if (fShutdown)
2383                 return true;
2384         }
2385         catch (std::ios_base::failure& e)
2386         {
2387             if (strstr(e.what(), "end of data"))
2388             {
2389                 // Allow exceptions from underlength message on vRecv
2390                 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());
2391             }
2392             else if (strstr(e.what(), "size too large"))
2393             {
2394                 // Allow exceptions from overlong size
2395                 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2396             }
2397             else
2398             {
2399                 PrintExceptionContinue(&e, "ProcessMessage()");
2400             }
2401         }
2402         catch (std::exception& e) {
2403             PrintExceptionContinue(&e, "ProcessMessage()");
2404         } catch (...) {
2405             PrintExceptionContinue(NULL, "ProcessMessage()");
2406         }
2407 
2408         if (!fRet)
2409             printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2410     }
2411 
2412     vRecv.Compact();
2413     return true;
2414 }
2415 
2416 
2417 bool SendMessages(CNode* pto, bool fSendTrickle)
2418 {
2419     CRITICAL_BLOCK(cs_main)
2420     {
2421         // Don't send anything until we get their version message
2422         if (pto->nVersion == 0)
2423             return true;
2424 
2425         // Keep-alive ping
2426         if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2427             pto->PushMessage("ping");
2428 
2429         // Resend wallet transactions that haven't gotten in a block yet
2430         ResendWalletTransactions();
2431 
2432         // Address refresh broadcast
2433         static int64 nLastRebroadcast;
2434         if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2435         {
2436             nLastRebroadcast = GetTime();
2437             CRITICAL_BLOCK(cs_vNodes)
2438             {
2439                 BOOST_FOREACH(CNode* pnode, vNodes)
2440                 {
2441                     // Periodically clear setAddrKnown to allow refresh broadcasts
2442                     pnode->setAddrKnown.clear();
2443 
2444                     // Rebroadcast our address
2445                     if (addrLocalHost.IsRoutable() && !fUseProxy)
2446                     {
2447                         CAddress addr(addrLocalHost);
2448                         addr.nTime = GetAdjustedTime();
2449                         pnode->PushAddress(addr);
2450                     }
2451                 }
2452             }
2453         }
2454 
2455         // Clear out old addresses periodically so it's not too much work at once
2456         static int64 nLastClear;
2457         if (nLastClear == 0)
2458             nLastClear = GetTime();
2459         if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2460         {
2461             nLastClear = GetTime();
2462             CRITICAL_BLOCK(cs_mapAddresses)
2463             {
2464                 CAddrDB addrdb;
2465                 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2466                 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2467                      mi != mapAddresses.end();)
2468                 {
2469                     const CAddress& addr = (*mi).second;
2470                     if (addr.nTime < nSince)
2471                     {
2472                         if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2473                             break;
2474                         addrdb.EraseAddress(addr);
2475                         mapAddresses.erase(mi++);
2476                     }
2477                     else
2478                         mi++;
2479                 }
2480             }
2481         }
2482 
2483 
2484         //
2485         // Message: addr
2486         //
2487         if (fSendTrickle)
2488         {
2489             vector<CAddress> vAddr;
2490             vAddr.reserve(pto->vAddrToSend.size());
2491             BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2492             {
2493                 // returns true if wasn't already contained in the set
2494                 if (pto->setAddrKnown.insert(addr).second)
2495                 {
2496                     vAddr.push_back(addr);
2497                     // receiver rejects addr messages larger than 1000
2498                     if (vAddr.size() >= 1000)
2499                     {
2500                         pto->PushMessage("addr", vAddr);
2501                         vAddr.clear();
2502                     }
2503                 }
2504             }
2505             pto->vAddrToSend.clear();
2506             if (!vAddr.empty())
2507                 pto->PushMessage("addr", vAddr);
2508         }
2509 
2510 
2511         //
2512         // Message: inventory
2513         //
2514         vector<CInv> vInv;
2515         vector<CInv> vInvWait;
2516         CRITICAL_BLOCK(pto->cs_inventory)
2517         {
2518             vInv.reserve(pto->vInventoryToSend.size());
2519             vInvWait.reserve(pto->vInventoryToSend.size());
2520             BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2521             {
2522                 if (pto->setInventoryKnown.count(inv))
2523                     continue;
2524 
2525                 // trickle out tx inv to protect privacy
2526                 if (inv.type == MSG_TX && !fSendTrickle)
2527                 {
2528                     // 1/4 of tx invs blast to all immediately
2529                     static uint256 hashSalt;
2530                     if (hashSalt == 0)
2531                         RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2532                     uint256 hashRand = inv.hash ^ hashSalt;
2533                     hashRand = Hash(BEGIN(hashRand), END(hashRand));
2534                     bool fTrickleWait = ((hashRand & 3) != 0);
2535 
2536                     // always trickle our own transactions
2537                     if (!fTrickleWait)
2538                     {
2539                         CWalletTx wtx;
2540                         if (GetTransaction(inv.hash, wtx))
2541                             if (wtx.fFromMe)
2542                                 fTrickleWait = true;
2543                     }
2544 
2545                     if (fTrickleWait)
2546                     {
2547                         vInvWait.push_back(inv);
2548                         continue;
2549                     }
2550                 }
2551 
2552                 // returns true if wasn't already contained in the set
2553                 if (pto->setInventoryKnown.insert(inv).second)
2554                 {
2555                     vInv.push_back(inv);
2556                     if (vInv.size() >= 1000)
2557                     {
2558                         pto->PushMessage("inv", vInv);
2559                         vInv.clear();
2560                     }
2561                 }
2562             }
2563             pto->vInventoryToSend = vInvWait;
2564         }
2565         if (!vInv.empty())
2566             pto->PushMessage("inv", vInv);
2567 
2568 
2569         //
2570         // Message: getdata
2571         //
2572         vector<CInv> vGetData;
2573         int64 nNow = GetTime() * 1000000;
2574         CTxDB txdb("r");
2575         while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2576         {
2577             const CInv& inv = (*pto->mapAskFor.begin()).second;
2578             if (!AlreadyHave(txdb, inv))
2579             {
2580                 printf("sending getdata: %s\n", inv.ToString().c_str());
2581                 vGetData.push_back(inv);
2582                 if (vGetData.size() >= 1000)
2583                 {
2584                     pto->PushMessage("getdata", vGetData);
2585                     vGetData.clear();
2586                 }
2587             }
2588             mapAlreadyAskedFor[inv] = nNow;
2589             pto->mapAskFor.erase(pto->mapAskFor.begin());
2590         }
2591         if (!vGetData.empty())
2592             pto->PushMessage("getdata", vGetData);
2593 
2594     }
2595     return true;
2596 }
2597 
2598 
2599 
2600 
2601 
2602 
2603 
2604 
2605 
2606 
2607 
2608 
2609 
2610 
2611 //////////////////////////////////////////////////////////////////////////////
2612 //
2613 // BitcoinMiner
2614 //
2615 
2616 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2617 {
2618     unsigned char* pdata = (unsigned char*)pbuffer;
2619     unsigned int blocks = 1 + ((len + 8) / 64);
2620     unsigned char* pend = pdata + 64 * blocks;
2621     memset(pdata + len, 0, 64 * blocks - len);
2622     pdata[len] = 0x80;
2623     unsigned int bits = len * 8;
2624     pend[-1] = (bits >> 0) & 0xff;
2625     pend[-2] = (bits >> 8) & 0xff;
2626     pend[-3] = (bits >> 16) & 0xff;
2627     pend[-4] = (bits >> 24) & 0xff;
2628     return blocks;
2629 }
2630 
2631 static const unsigned int pSHA256InitState[8] =
2632 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2633 
2634 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2635 {
2636     SHA256_CTX ctx;
2637     unsigned char data[64];
2638 
2639     SHA256_Init(&ctx);
2640 
2641     for (int i = 0; i < 16; i++)
2642         ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2643 
2644     for (int i = 0; i < 8; i++)
2645         ctx.h[i] = ((uint32_t*)pinit)[i];
2646 
2647     SHA256_Update(&ctx, data, sizeof(data));
2648     for (int i = 0; i < 8; i++) 
2649         ((uint32_t*)pstate)[i] = ctx.h[i];
2650 }
2651 
2652 //
2653 // ScanHash scans nonces looking for a hash with at least some zero bits.
2654 // It operates on big endian data.  Caller does the byte reversing.
2655 // All input buffers are 16-byte aligned.  nNonce is usually preserved
2656 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2657 // the block is rebuilt and nNonce starts over at zero.
2658 //
2659 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2660 {
2661     unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2662     for (;;)
2663     {
2664         // Crypto++ SHA-256
2665         // Hash pdata using pmidstate as the starting state into
2666         // preformatted buffer phash1, then hash phash1 into phash
2667         nNonce++;
2668         SHA256Transform(phash1, pdata, pmidstate);
2669         SHA256Transform(phash, phash1, pSHA256InitState);
2670 
2671         // Return the nonce if the hash has at least some zero bits,
2672         // caller will check if it has enough to reach the target
2673         if (((unsigned short*)phash)[14] == 0)
2674             return nNonce;
2675 
2676         // If nothing found after trying for a while, return -1
2677         if ((nNonce & 0xffff) == 0)
2678         {
2679             nHashesDone = 0xffff+1;
2680             return -1;
2681         }
2682     }
2683 }
2684 
2685 // Some explaining would be appreciated
2686 class COrphan
2687 {
2688 public:
2689     CTransaction* ptx;
2690     set<uint256> setDependsOn;
2691     double dPriority;
2692 
2693     COrphan(CTransaction* ptxIn)
2694     {
2695         ptx = ptxIn;
2696         dPriority = 0;
2697     }
2698 
2699     void print() const
2700     {
2701         printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2702         BOOST_FOREACH(uint256 hash, setDependsOn)
2703             printf("   setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2704     }
2705 };
2706 
2707 
2708 CBlock* CreateNewBlock(CReserveKey& reservekey)
2709 {
2710     CBlockIndex* pindexPrev = pindexBest;
2711 
2712     // Create new block
2713     auto_ptr<CBlock> pblock(new CBlock());
2714     if (!pblock.get())
2715         return NULL;
2716 
2717     // Create coinbase tx
2718     CTransaction txNew;
2719     txNew.vin.resize(1);
2720     txNew.vin[0].prevout.SetNull();
2721     txNew.vout.resize(1);
2722     txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2723 
2724     // Add our coinbase tx as first transaction
2725     pblock->vtx.push_back(txNew);
2726 
2727     // Collect memory pool transactions into the block
2728     int64 nFees = 0;
2729     CRITICAL_BLOCK(cs_main)
2730     CRITICAL_BLOCK(cs_mapTransactions)
2731     {
2732         CTxDB txdb("r");
2733 
2734         // Priority order to process transactions
2735         list<COrphan> vOrphan; // list memory doesn't move
2736         map<uint256, vector<COrphan*> > mapDependers;
2737         multimap<double, CTransaction*> mapPriority;
2738         for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2739         {
2740             CTransaction& tx = (*mi).second;
2741             if (tx.IsCoinBase() || !tx.IsFinal())
2742                 continue;
2743 
2744             COrphan* porphan = NULL;
2745             double dPriority = 0;
2746             BOOST_FOREACH(const CTxIn& txin, tx.vin)
2747             {
2748                 // Read prev transaction
2749                 CTransaction txPrev;
2750                 CTxIndex txindex;
2751                 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2752                 {
2753                     // Has to wait for dependencies
2754                     if (!porphan)
2755                     {
2756                         // Use list for automatic deletion
2757                         vOrphan.push_back(COrphan(&tx));
2758                         porphan = &vOrphan.back();
2759                     }
2760                     mapDependers[txin.prevout.hash].push_back(porphan);
2761                     porphan->setDependsOn.insert(txin.prevout.hash);
2762                     continue;
2763                 }
2764                 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2765 
2766                 // Read block header
2767                 int nConf = txindex.GetDepthInMainChain();
2768 
2769                 dPriority += (double)nValueIn * nConf;
2770 
2771                 if (fDebug && GetBoolArg("-printpriority"))
2772                     printf("priority     nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2773             }
2774 
2775             // Priority is sum(valuein * age) / txsize
2776             dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2777 
2778             if (porphan)
2779                 porphan->dPriority = dPriority;
2780             else
2781                 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2782 
2783             if (fDebug && GetBoolArg("-printpriority"))
2784             {
2785                 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2786                 if (porphan)
2787                     porphan->print();
2788                 printf("\n");
2789             }
2790         }
2791 
2792         // Collect transactions into block
2793         map<uint256, CTxIndex> mapTestPool;
2794         uint64 nBlockSize = 1000;
2795         int nBlockSigOps = 100;
2796         while (!mapPriority.empty())
2797         {
2798             // Take highest priority transaction off priority queue
2799             double dPriority = -(*mapPriority.begin()).first;
2800             CTransaction& tx = *(*mapPriority.begin()).second;
2801             mapPriority.erase(mapPriority.begin());
2802 
2803             // Size limits
2804             unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2805             if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2806                 continue;
2807             int nTxSigOps = tx.GetSigOpCount();
2808             if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2809                 continue;
2810 
2811             // Transaction fee required depends on block size
2812             bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2813             int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
2814 
2815             // Connecting shouldn't fail due to dependency on other memory pool transactions
2816             // because we're already processing them in order of dependency
2817             map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2818             bool fInvalid;
2819             if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee, fInvalid))
2820                 continue;
2821             swap(mapTestPool, mapTestPoolTmp);
2822 
2823             // Added
2824             pblock->vtx.push_back(tx);
2825             nBlockSize += nTxSize;
2826             nBlockSigOps += nTxSigOps;
2827 
2828             // Add transactions that depend on this one to the priority queue
2829             uint256 hash = tx.GetHash();
2830             if (mapDependers.count(hash))
2831             {
2832                 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2833                 {
2834                     if (!porphan->setDependsOn.empty())
2835                     {
2836                         porphan->setDependsOn.erase(hash);
2837                         if (porphan->setDependsOn.empty())
2838                             mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2839                     }
2840                 }
2841             }
2842         }
2843     }
2844     pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
2845 
2846     // Fill in header
2847     pblock->hashPrevBlock  = pindexPrev->GetBlockHash();
2848     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2849     pblock->nTime          = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
2850     pblock->nBits          = GetNextWorkRequired(pindexPrev, pblock.get());
2851     pblock->nNonce         = 0;
2852 
2853     return pblock.release();
2854 }
2855 
2856 
2857 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
2858 {
2859     // Update nExtraNonce
2860     static uint256 hashPrevBlock;
2861     if (hashPrevBlock != pblock->hashPrevBlock)
2862     {
2863         nExtraNonce = 0;
2864         hashPrevBlock = pblock->hashPrevBlock;
2865     }
2866     ++nExtraNonce;
2867     pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
2868     pblock->hashMerkleRoot = pblock->BuildMerkleTree();
2869 }
2870 
2871 
2872 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
2873 {
2874     //
2875     // Prebuild hash buffers
2876     //
2877     struct
2878     {
2879         struct unnamed2
2880         {
2881             int nVersion;
2882             uint256 hashPrevBlock;
2883             uint256 hashMerkleRoot;
2884             unsigned int nTime;
2885             unsigned int nBits;
2886             unsigned int nNonce;
2887         }
2888         block;
2889         unsigned char pchPadding0[64];
2890         uint256 hash1;
2891         unsigned char pchPadding1[64];
2892     }
2893     tmp;
2894     memset(&tmp, 0, sizeof(tmp));
2895 
2896     tmp.block.nVersion       = pblock->nVersion;
2897     tmp.block.hashPrevBlock  = pblock->hashPrevBlock;
2898     tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
2899     tmp.block.nTime          = pblock->nTime;
2900     tmp.block.nBits          = pblock->nBits;
2901     tmp.block.nNonce         = pblock->nNonce;
2902 
2903     FormatHashBlocks(&tmp.block, sizeof(tmp.block));
2904     FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
2905 
2906     // Byte swap all the input buffer
2907     for (int i = 0; i < sizeof(tmp)/4; i++)
2908         ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
2909 
2910     // Precalc the first half of the first hash, which stays constant
2911     SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
2912 
2913     memcpy(pdata, &tmp.block, 128);
2914     memcpy(phash1, &tmp.hash1, 64);
2915 }
2916 
2917 
2918 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
2919 {
2920     uint256 hash = pblock->GetHash();
2921     uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
2922 
2923     if (hash > hashTarget)
2924         return false;
2925 
2926     //// debug print
2927     printf("BitcoinMiner:\n");
2928     printf("proof-of-work found  \n  hash: %s  \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
2929     pblock->print();
2930     printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
2931     printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
2932 
2933     // Found a solution
2934     CRITICAL_BLOCK(cs_main)
2935     {
2936         if (pblock->hashPrevBlock != hashBestChain)
2937             return error("BitcoinMiner : generated block is stale");
2938 
2939         // Remove key from key pool
2940         reservekey.KeepKey();
2941 
2942         // Track how many getdata requests this block gets
2943         CRITICAL_BLOCK(wallet.cs_wallet)
2944             wallet.mapRequestCount[pblock->GetHash()] = 0;
2945 
2946         // Process this block the same as if we had received it from another node
2947         if (!ProcessBlock(NULL, pblock))
2948             return error("BitcoinMiner : ProcessBlock, block not accepted");
2949     }
2950 
2951     return true;
2952 }
2953 
2954 void static ThreadBitcoinMiner(void* parg);
2955 
2956 void static BitcoinMiner(CWallet *pwallet)
2957 {
2958     printf("BitcoinMiner started\n");
2959     SetThreadPriority(THREAD_PRIORITY_LOWEST);
2960 
2961     // Each thread has its own key and counter
2962     CReserveKey reservekey(pwallet);
2963     unsigned int nExtraNonce = 0;
2964 
2965     while (fGenerateBitcoins)
2966     {
2967         if (AffinityBugWorkaround(ThreadBitcoinMiner))
2968             return;
2969         if (fShutdown)
2970             return;
2971         while (vNodes.empty() || IsInitialBlockDownload())
2972         {
2973             Sleep(1000);
2974             if (fShutdown)
2975                 return;
2976             if (!fGenerateBitcoins)
2977                 return;
2978         }
2979 
2980 
2981         //
2982         // Create new block
2983         //
2984         unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
2985         CBlockIndex* pindexPrev = pindexBest;
2986 
2987         auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
2988         if (!pblock.get())
2989             return;
2990         IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
2991 
2992         printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
2993 
2994 
2995         //
2996         // Prebuild hash buffers
2997         //
2998         char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
2999         char pdatabuf[128+16];    char* pdata     = alignup<16>(pdatabuf);
3000         char phash1buf[64+16];    char* phash1    = alignup<16>(phash1buf);
3001 
3002         FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3003 
3004         unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3005         unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3006 
3007 
3008         //
3009         // Search
3010         //
3011         int64 nStart = GetTime();
3012         uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3013         uint256 hashbuf[2];
3014         uint256& hash = *alignup<16>(hashbuf);
3015         loop
3016         {
3017             unsigned int nHashesDone = 0;
3018             unsigned int nNonceFound;
3019 
3020             // Crypto++ SHA-256
3021             nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3022                                             (char*)&hash, nHashesDone);
3023 
3024             // Check if something found
3025             if (nNonceFound != -1)
3026             {
3027                 for (int i = 0; i < sizeof(hash)/4; i++)
3028                     ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3029 
3030                 if (hash <= hashTarget)
3031                 {
3032                     // Found a solution
3033                     pblock->nNonce = ByteReverse(nNonceFound);
3034                     assert(hash == pblock->GetHash());
3035 
3036                     SetThreadPriority(THREAD_PRIORITY_NORMAL);
3037                     CheckWork(pblock.get(), *pwalletMain, reservekey);
3038                     SetThreadPriority(THREAD_PRIORITY_LOWEST);
3039                     break;
3040                 }
3041             }
3042 
3043             // Meter hashes/sec
3044             static int64 nHashCounter;
3045             if (nHPSTimerStart == 0)
3046             {
3047                 nHPSTimerStart = GetTimeMillis();
3048                 nHashCounter = 0;
3049             }
3050             else
3051                 nHashCounter += nHashesDone;
3052             if (GetTimeMillis() - nHPSTimerStart > 4000)
3053             {
3054                 static CCriticalSection cs;
3055                 CRITICAL_BLOCK(cs)
3056                 {
3057                     if (GetTimeMillis() - nHPSTimerStart > 4000)
3058                     {
3059                         dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3060                         nHPSTimerStart = GetTimeMillis();
3061                         nHashCounter = 0;
3062                         string strStatus = strprintf("    %.0f khash/s", dHashesPerSec/1000.0);
3063                         UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3064                         static int64 nLogTime;
3065                         if (GetTime() - nLogTime > 30 * 60)
3066                         {
3067                             nLogTime = GetTime();
3068                             printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3069                             printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3070                         }
3071                     }
3072                 }
3073             }
3074 
3075             // Check for stop or if block needs to be rebuilt
3076             if (fShutdown)
3077                 return;
3078             if (!fGenerateBitcoins)
3079                 return;
3080             if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3081                 return;
3082             if (vNodes.empty())
3083                 break;
3084             if (nBlockNonce >= 0xffff0000)
3085                 break;
3086             if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3087                 break;
3088             if (pindexPrev != pindexBest)
3089                 break;
3090 
3091             // Update nTime every few seconds
3092             pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3093             nBlockTime = ByteReverse(pblock->nTime);
3094         }
3095     }
3096 }
3097 
3098 void static ThreadBitcoinMiner(void* parg)
3099 {
3100     CWallet* pwallet = (CWallet*)parg;
3101     try
3102     {
3103         vnThreadsRunning[3]++;
3104         BitcoinMiner(pwallet);
3105         vnThreadsRunning[3]--;
3106     }
3107     catch (std::exception& e) {
3108         vnThreadsRunning[3]--;
3109         PrintException(&e, "ThreadBitcoinMiner()");
3110     } catch (...) {
3111         vnThreadsRunning[3]--;
3112         PrintException(NULL, "ThreadBitcoinMiner()");
3113     }
3114     UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3115     nHPSTimerStart = 0;
3116     if (vnThreadsRunning[3] == 0)
3117         dHashesPerSec = 0;
3118     printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3119 }
3120 
3121 
3122 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3123 {
3124     if (fGenerateBitcoins != fGenerate)
3125     {
3126         fGenerateBitcoins = fGenerate;
3127         WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3128         MainFrameRepaint();
3129     }
3130     if (fGenerateBitcoins)
3131     {
3132         int nProcessors = boost::thread::hardware_concurrency();
3133         printf("%d processors\n", nProcessors);
3134         if (nProcessors < 1)
3135             nProcessors = 1;
3136         if (fLimitProcessors && nProcessors > nLimitProcessors)
3137             nProcessors = nLimitProcessors;
3138         int nAddThreads = nProcessors - vnThreadsRunning[3];
3139         printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3140         for (int i = 0; i < nAddThreads; i++)
3141         {
3142             if (!CreateThread(ThreadBitcoinMiner, pwallet))
3143                 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
3144             Sleep(10);
3145         }
3146     }
3147 }