Back to home page

Bitcoin sources

 
 

    


File indexing completed on 2020-06-25 20:10:12

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