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