Back to home page

Bitcoin sources

 
 

    


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