Back to home page

Bitcoin sources

 
 

    


File indexing completed on 2020-06-25 15:53:08

0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #include "headers.h"
0006 #include "checkpoints.h"
0007 #include "db.h"
0008 #include "net.h"
0009 #include "init.h"
0010 #include <boost/filesystem.hpp>
0011 #include <boost/filesystem/fstream.hpp>
0012 
0013 using namespace std;
0014 using namespace boost;
0015 
0016 //
0017 // Global state
0018 //
0019 
0020 CCriticalSection cs_setpwalletRegistered;
0021 set<CWallet*> setpwalletRegistered;
0022 
0023 CCriticalSection cs_main;
0024 
0025 static map<uint256, CTransaction> mapTransactions;
0026 CCriticalSection cs_mapTransactions;
0027 unsigned int nTransactionsUpdated = 0;
0028 map<COutPoint, CInPoint> mapNextTx;
0029 
0030 map<uint256, CBlockIndex*> mapBlockIndex;
0031 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
0032 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
0033 CBlockIndex* pindexGenesisBlock = NULL;
0034 int nBestHeight = -1;
0035 CBigNum bnBestChainWork = 0;
0036 CBigNum bnBestInvalidWork = 0;
0037 uint256 hashBestChain = 0;
0038 CBlockIndex* pindexBest = NULL;
0039 int64 nTimeBestReceived = 0;
0040 
0041 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
0042 
0043 
0044 
0045 double dHashesPerSec;
0046 int64 nHPSTimerStart;
0047 
0048 // Settings
0049 int fGenerateBitcoins = false;
0050 int64 nTransactionFee = 0;
0051 int fLimitProcessors = false;
0052 int nLimitProcessors = 1;
0053 int fMinimizeToTray = true;
0054 int fMinimizeOnClose = true;
0055 
0056 
0057 //////////////////////////////////////////////////////////////////////////////
0058 //
0059 // dispatching functions
0060 //
0061 
0062 // These functions dispatch to one or all registered wallets
0063 
0064 
0065 void RegisterWallet(CWallet* pwalletIn)
0066 {
0067     CRITICAL_BLOCK(cs_setpwalletRegistered)
0068     {
0069         setpwalletRegistered.insert(pwalletIn);
0070     }
0071 }
0072 
0073 void UnregisterWallet(CWallet* pwalletIn)
0074 {
0075     CRITICAL_BLOCK(cs_setpwalletRegistered)
0076     {
0077         setpwalletRegistered.erase(pwalletIn);
0078     }
0079 }
0080 
0081 // check whether the passed transaction is from us
0082 bool static IsFromMe(CTransaction& tx)
0083 {
0084     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0085         if (pwallet->IsFromMe(tx))
0086             return true;
0087     return false;
0088 }
0089 
0090 // get the wallet transaction with the given hash (if it exists)
0091 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
0092 {
0093     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0094         if (pwallet->GetTransaction(hashTx,wtx))
0095             return true;
0096     return false;
0097 }
0098 
0099 // erases transaction with the given hash from all wallets
0100 void static EraseFromWallets(uint256 hash)
0101 {
0102     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0103         pwallet->EraseFromWallet(hash);
0104 }
0105 
0106 // make sure all wallets know about the given transaction, in the given block
0107 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
0108 {
0109     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0110         pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
0111 }
0112 
0113 // notify wallets about a new best chain
0114 void static SetBestChain(const CBlockLocator& loc)
0115 {
0116     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0117         pwallet->SetBestChain(loc);
0118 }
0119 
0120 // notify wallets about an updated transaction
0121 void static UpdatedTransaction(const uint256& hashTx)
0122 {
0123     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0124         pwallet->UpdatedTransaction(hashTx);
0125 }
0126 
0127 // dump all wallets
0128 void static PrintWallets(const CBlock& block)
0129 {
0130     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0131         pwallet->PrintWallet(block);
0132 }
0133 
0134 // notify wallets about an incoming inventory (for request counts)
0135 void static Inventory(const uint256& hash)
0136 {
0137     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0138         pwallet->Inventory(hash);
0139 }
0140 
0141 // ask wallets to resend their transactions
0142 void static ResendWalletTransactions()
0143 {
0144     BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
0145         pwallet->ResendWalletTransactions();
0146 }
0147 
0148 
0149 //////////////////////////////////////////////////////////////////////////////
0150 //
0151 // CTransaction and CTxIndex
0152 //
0153 
0154 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
0155 {
0156     SetNull();
0157     if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
0158         return false;
0159     if (!ReadFromDisk(txindexRet.pos))
0160         return false;
0161     if (prevout.n >= vout.size())
0162     {
0163         SetNull();
0164         return false;
0165     }
0166     return true;
0167 }
0168 
0169 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
0170 {
0171     CTxIndex txindex;
0172     return ReadFromDisk(txdb, prevout, txindex);
0173 }
0174 
0175 bool CTransaction::ReadFromDisk(COutPoint prevout)
0176 {
0177     CTxDB txdb("r");
0178     CTxIndex txindex;
0179     return ReadFromDisk(txdb, prevout, txindex);
0180 }
0181 
0182 
0183 
0184 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
0185 {
0186     if (fClient)
0187     {
0188         if (hashBlock == 0)
0189             return 0;
0190     }
0191     else
0192     {
0193         CBlock blockTmp;
0194         if (pblock == NULL)
0195         {
0196             // Load the block this tx is in
0197             CTxIndex txindex;
0198             if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
0199                 return 0;
0200             if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
0201                 return 0;
0202             pblock = &blockTmp;
0203         }
0204 
0205         // Update the tx's hashBlock
0206         hashBlock = pblock->GetHash();
0207 
0208         // Locate the transaction
0209         for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
0210             if (pblock->vtx[nIndex] == *(CTransaction*)this)
0211                 break;
0212         if (nIndex == pblock->vtx.size())
0213         {
0214             vMerkleBranch.clear();
0215             nIndex = -1;
0216             printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
0217             return 0;
0218         }
0219 
0220         // Fill in merkle branch
0221         vMerkleBranch = pblock->GetMerkleBranch(nIndex);
0222     }
0223 
0224     // Is the tx in a block that's in the main chain
0225     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
0226     if (mi == mapBlockIndex.end())
0227         return 0;
0228     CBlockIndex* pindex = (*mi).second;
0229     if (!pindex || !pindex->IsInMainChain())
0230         return 0;
0231 
0232     return pindexBest->nHeight - pindex->nHeight + 1;
0233 }
0234 
0235 
0236 
0237 
0238 
0239 
0240 
0241 bool CTransaction::CheckTransaction() const
0242 {
0243     // Basic checks that don't depend on any context
0244     if (vin.empty())
0245         return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
0246     if (vout.empty())
0247         return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
0248     // Size limits
0249     if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
0250         return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
0251 
0252     // Check for negative or overflow output values
0253     int64 nValueOut = 0;
0254     BOOST_FOREACH(const CTxOut& txout, vout)
0255     {
0256         if (txout.nValue < 0)
0257             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
0258         if (txout.nValue > MAX_MONEY)
0259             return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
0260         nValueOut += txout.nValue;
0261         if (!MoneyRange(nValueOut))
0262             return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
0263     }
0264 
0265     // Check for duplicate inputs
0266     set<COutPoint> vInOutPoints;
0267     BOOST_FOREACH(const CTxIn& txin, vin)
0268     {
0269         if (vInOutPoints.count(txin.prevout))
0270             return false;
0271         vInOutPoints.insert(txin.prevout);
0272     }
0273 
0274     if (IsCoinBase())
0275     {
0276         if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
0277             return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
0278     }
0279     else
0280     {
0281         BOOST_FOREACH(const CTxIn& txin, vin)
0282             if (txin.prevout.IsNull())
0283                 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
0284     }
0285 
0286     return true;
0287 }
0288 
0289 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
0290 {
0291     if (pfMissingInputs)
0292         *pfMissingInputs = false;
0293 
0294     if (!CheckTransaction())
0295         return error("AcceptToMemoryPool() : CheckTransaction failed");
0296 
0297     // Coinbase is only valid in a block, not as a loose transaction
0298     if (IsCoinBase())
0299         return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
0300 
0301     // To help v0.1.5 clients who would see it as a negative number
0302     if ((int64)nLockTime > INT_MAX)
0303         return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
0304 
0305     // Safety limits
0306     unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
0307     // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
0308     // attacks disallow transactions with more than one SigOp per 34 bytes.
0309     // 34 bytes because a TxOut is:
0310     //   20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
0311     if (GetSigOpCount() > nSize / 34 || nSize < 100)
0312         return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
0313 
0314     // Rather not work on nonstandard transactions
0315     if (!IsStandard())
0316         return error("AcceptToMemoryPool() : nonstandard transaction type");
0317 
0318     // Do we already have it?
0319     uint256 hash = GetHash();
0320     CRITICAL_BLOCK(cs_mapTransactions)
0321         if (mapTransactions.count(hash))
0322             return false;
0323     if (fCheckInputs)
0324         if (txdb.ContainsTx(hash))
0325             return false;
0326 
0327     // Check for conflicts with in-memory transactions
0328     CTransaction* ptxOld = NULL;
0329     for (int i = 0; i < vin.size(); i++)
0330     {
0331         COutPoint outpoint = vin[i].prevout;
0332         if (mapNextTx.count(outpoint))
0333         {
0334             // Disable replacement feature for now
0335             return false;
0336 
0337             // Allow replacing with a newer version of the same transaction
0338             if (i != 0)
0339                 return false;
0340             ptxOld = mapNextTx[outpoint].ptx;
0341             if (ptxOld->IsFinal())
0342                 return false;
0343             if (!IsNewerThan(*ptxOld))
0344                 return false;
0345             for (int i = 0; i < vin.size(); i++)
0346             {
0347                 COutPoint outpoint = vin[i].prevout;
0348                 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
0349                     return false;
0350             }
0351             break;
0352         }
0353     }
0354 
0355     if (fCheckInputs)
0356     {
0357         // Check against previous transactions
0358         map<uint256, CTxIndex> mapUnused;
0359         int64 nFees = 0;
0360         bool fInvalid = false;
0361         if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, 0, fInvalid))
0362         {
0363             if (fInvalid)
0364                 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
0365             return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
0366         }
0367 
0368         // Don't accept it if it can't get into a block
0369         if (nFees < GetMinFee(1000, true, true))
0370             return error("AcceptToMemoryPool() : not enough fees");
0371 
0372         // Continuously rate-limit free transactions
0373         // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
0374         // be annoying or make other's transactions take longer to confirm.
0375         if (nFees < MIN_RELAY_TX_FEE)
0376         {
0377             static CCriticalSection cs;
0378             static double dFreeCount;
0379             static int64 nLastTime;
0380             int64 nNow = GetTime();
0381 
0382             CRITICAL_BLOCK(cs)
0383             {
0384                 // Use an exponentially decaying ~10-minute window:
0385                 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
0386                 nLastTime = nNow;
0387                 // -limitfreerelay unit is thousand-bytes-per-minute
0388                 // At default rate it would take over a month to fill 1GB
0389                 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
0390                     return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
0391                 if (fDebug)
0392                     printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
0393                 dFreeCount += nSize;
0394             }
0395         }
0396     }
0397 
0398     // Store transaction in memory
0399     CRITICAL_BLOCK(cs_mapTransactions)
0400     {
0401         if (ptxOld)
0402         {
0403             printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
0404             ptxOld->RemoveFromMemoryPool();
0405         }
0406         AddToMemoryPoolUnchecked();
0407     }
0408 
0409     ///// are we sure this is ok when loading transactions or restoring block txes
0410     // If updated, erase old tx from wallet
0411     if (ptxOld)
0412         EraseFromWallets(ptxOld->GetHash());
0413 
0414     printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
0415     return true;
0416 }
0417 
0418 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
0419 {
0420     CTxDB txdb("r");
0421     return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
0422 }
0423 
0424 bool CTransaction::AddToMemoryPoolUnchecked()
0425 {
0426     // Add to memory pool without checking anything.  Don't call this directly,
0427     // call AcceptToMemoryPool to properly check the transaction first.
0428     CRITICAL_BLOCK(cs_mapTransactions)
0429     {
0430         uint256 hash = GetHash();
0431         mapTransactions[hash] = *this;
0432         for (int i = 0; i < vin.size(); i++)
0433             mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
0434         nTransactionsUpdated++;
0435     }
0436     return true;
0437 }
0438 
0439 
0440 bool CTransaction::RemoveFromMemoryPool()
0441 {
0442     // Remove transaction from memory pool
0443     CRITICAL_BLOCK(cs_mapTransactions)
0444     {
0445         BOOST_FOREACH(const CTxIn& txin, vin)
0446             mapNextTx.erase(txin.prevout);
0447         mapTransactions.erase(GetHash());
0448         nTransactionsUpdated++;
0449     }
0450     return true;
0451 }
0452 
0453 
0454 
0455 
0456 
0457 
0458 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
0459 {
0460     if (hashBlock == 0 || nIndex == -1)
0461         return 0;
0462 
0463     // Find the block it claims to be in
0464     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
0465     if (mi == mapBlockIndex.end())
0466         return 0;
0467     CBlockIndex* pindex = (*mi).second;
0468     if (!pindex || !pindex->IsInMainChain())
0469         return 0;
0470 
0471     // Make sure the merkle branch connects to this block
0472     if (!fMerkleVerified)
0473     {
0474         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
0475             return 0;
0476         fMerkleVerified = true;
0477     }
0478 
0479     nHeightRet = pindex->nHeight;
0480     return pindexBest->nHeight - pindex->nHeight + 1;
0481 }
0482 
0483 
0484 int CMerkleTx::GetBlocksToMaturity() const
0485 {
0486     if (!IsCoinBase())
0487         return 0;
0488     return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
0489 }
0490 
0491 
0492 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
0493 {
0494     if (fClient)
0495     {
0496         if (!IsInMainChain() && !ClientConnectInputs())
0497             return false;
0498         return CTransaction::AcceptToMemoryPool(txdb, false);
0499     }
0500     else
0501     {
0502         return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
0503     }
0504 }
0505 
0506 bool CMerkleTx::AcceptToMemoryPool()
0507 {
0508     CTxDB txdb("r");
0509     return AcceptToMemoryPool(txdb);
0510 }
0511 
0512 
0513 
0514 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
0515 {
0516     CRITICAL_BLOCK(cs_mapTransactions)
0517     {
0518         // Add previous supporting transactions first
0519         BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
0520         {
0521             if (!tx.IsCoinBase())
0522             {
0523                 uint256 hash = tx.GetHash();
0524                 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
0525                     tx.AcceptToMemoryPool(txdb, fCheckInputs);
0526             }
0527         }
0528         return AcceptToMemoryPool(txdb, fCheckInputs);
0529     }
0530     return false;
0531 }
0532 
0533 bool CWalletTx::AcceptWalletTransaction() 
0534 {
0535     CTxDB txdb("r");
0536     return AcceptWalletTransaction(txdb);
0537 }
0538 
0539 int CTxIndex::GetDepthInMainChain() const
0540 {
0541     // Read block header
0542     CBlock block;
0543     if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
0544         return 0;
0545     // Find the block in the index
0546     map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
0547     if (mi == mapBlockIndex.end())
0548         return 0;
0549     CBlockIndex* pindex = (*mi).second;
0550     if (!pindex || !pindex->IsInMainChain())
0551         return 0;
0552     return 1 + nBestHeight - pindex->nHeight;
0553 }
0554 
0555 
0556 
0557 
0558 
0559 
0560 
0561 
0562 
0563 
0564 //////////////////////////////////////////////////////////////////////////////
0565 //
0566 // CBlock and CBlockIndex
0567 //
0568 
0569 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
0570 {
0571     if (!fReadTransactions)
0572     {
0573         *this = pindex->GetBlockHeader();
0574         return true;
0575     }
0576     if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
0577         return false;
0578     if (GetHash() != pindex->GetBlockHash())
0579         return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
0580     return true;
0581 }
0582 
0583 int64 static GetBlockValue(int nHeight, int64 nFees)
0584 {
0585     int64 nSubsidy = 50 * COIN;
0586 
0587     // Subsidy is cut in half every 4 years
0588     nSubsidy >>= (nHeight / 210000);
0589 
0590     return nSubsidy + nFees;
0591 }
0592 
0593 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
0594 static const int64 nTargetSpacing = 10 * 60;
0595 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
0596 
0597 //
0598 // minimum amount of work that could possibly be required nTime after
0599 // minimum work required was nBase
0600 //
0601 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
0602 {
0603     CBigNum bnResult;
0604     bnResult.SetCompact(nBase);
0605     while (nTime > 0 && bnResult < bnProofOfWorkLimit)
0606     {
0607         // Maximum 400% adjustment...
0608         bnResult *= 4;
0609         // ... in best-case exactly 4-times-normal target time
0610         nTime -= nTargetTimespan*4;
0611     }
0612     if (bnResult > bnProofOfWorkLimit)
0613         bnResult = bnProofOfWorkLimit;
0614     return bnResult.GetCompact();
0615 }
0616 
0617 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
0618 {
0619     unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
0620 
0621     // Genesis block
0622     if (pindexLast == NULL)
0623         return nProofOfWorkLimit;
0624 
0625     // Only change once per interval
0626     if ((pindexLast->nHeight+1) % nInterval != 0)
0627     {
0628         return pindexLast->nBits;
0629     }
0630 
0631     // Go back by what we want to be 14 days worth of blocks
0632     const CBlockIndex* pindexFirst = pindexLast;
0633     for (int i = 0; pindexFirst && i < nInterval-1; i++)
0634         pindexFirst = pindexFirst->pprev;
0635     assert(pindexFirst);
0636 
0637     // Limit adjustment step
0638     int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
0639     printf("  nActualTimespan = %"PRI64d"  before bounds\n", nActualTimespan);
0640     if (nActualTimespan < nTargetTimespan/4)
0641         nActualTimespan = nTargetTimespan/4;
0642     if (nActualTimespan > nTargetTimespan*4)
0643         nActualTimespan = nTargetTimespan*4;
0644 
0645     // Retarget
0646     CBigNum bnNew;
0647     bnNew.SetCompact(pindexLast->nBits);
0648     bnNew *= nActualTimespan;
0649     bnNew /= nTargetTimespan;
0650 
0651     if (bnNew > bnProofOfWorkLimit)
0652         bnNew = bnProofOfWorkLimit;
0653 
0654     /// debug print
0655     printf("GetNextWorkRequired RETARGET\n");
0656     printf("nTargetTimespan = %"PRI64d"    nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
0657     printf("Before: %08x  %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
0658     printf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
0659 
0660     return bnNew.GetCompact();
0661 }
0662 
0663 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
0664 {
0665     CBigNum bnTarget;
0666     bnTarget.SetCompact(nBits);
0667 
0668     // Check range
0669     if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
0670         return error("CheckProofOfWork() : nBits below minimum work");
0671 
0672     // Check proof of work matches claimed amount
0673     if (hash > bnTarget.getuint256())
0674         return error("CheckProofOfWork() : hash doesn't match nBits");
0675 
0676     return true;
0677 }
0678 
0679 // Return maximum amount of blocks that other nodes claim to have
0680 int GetNumBlocksOfPeers()
0681 {
0682     return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
0683 }
0684 
0685 bool IsInitialBlockDownload()
0686 {
0687     if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
0688         return true;
0689     static int64 nLastUpdate;
0690     static CBlockIndex* pindexLastBest;
0691     if (pindexBest != pindexLastBest)
0692     {
0693         pindexLastBest = pindexBest;
0694         nLastUpdate = GetTime();
0695     }
0696     return (GetTime() - nLastUpdate < 10 &&
0697             pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
0698 }
0699 
0700 void static InvalidChainFound(CBlockIndex* pindexNew)
0701 {
0702     if (pindexNew->bnChainWork > bnBestInvalidWork)
0703     {
0704         bnBestInvalidWork = pindexNew->bnChainWork;
0705         CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
0706         MainFrameRepaint();
0707     }
0708     printf("InvalidChainFound: invalid block=%s  height=%d  work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
0709     printf("InvalidChainFound:  current best=%s  height=%d  work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
0710     if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
0711         printf("InvalidChainFound: WARNING: Displayed transactions may not be correct!  You may need to upgrade, or other nodes may need to upgrade.\n");
0712 }
0713 
0714 
0715 
0716 
0717 
0718 
0719 
0720 
0721 
0722 
0723 
0724 bool CTransaction::DisconnectInputs(CTxDB& txdb)
0725 {
0726     // Relinquish previous transactions' spent pointers
0727     if (!IsCoinBase())
0728     {
0729         BOOST_FOREACH(const CTxIn& txin, vin)
0730         {
0731             COutPoint prevout = txin.prevout;
0732 
0733             // Get prev txindex from disk
0734             CTxIndex txindex;
0735             if (!txdb.ReadTxIndex(prevout.hash, txindex))
0736                 return error("DisconnectInputs() : ReadTxIndex failed");
0737 
0738             if (prevout.n >= txindex.vSpent.size())
0739                 return error("DisconnectInputs() : prevout.n out of range");
0740 
0741             // Mark outpoint as not spent
0742             txindex.vSpent[prevout.n].SetNull();
0743 
0744             // Write back
0745             if (!txdb.UpdateTxIndex(prevout.hash, txindex))
0746                 return error("DisconnectInputs() : UpdateTxIndex failed");
0747         }
0748     }
0749 
0750     // Remove transaction from index
0751     // This can fail if a duplicate of this transaction was in a chain that got
0752     // reorganized away. This is only possible if this transaction was completely
0753     // spent, so erasing it would be a no-op anway.
0754     txdb.EraseTxIndex(*this);
0755 
0756     return true;
0757 }
0758 
0759 
0760 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
0761                                  CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee,
0762                                  bool& fInvalid)
0763 {
0764     // FetchInputs can return false either because we just haven't seen some inputs
0765     // (in which case the transaction should be stored as an orphan)
0766     // or because the transaction is malformed (in which case the transaction should
0767     // be dropped).  If tx is definitely invalid, fInvalid will be set to true.
0768     fInvalid = false;
0769 
0770     // Take over previous transactions' spent pointers
0771     // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
0772     // fMiner is true when called from the internal bitcoin miner
0773     // ... both are false when called from CTransaction::AcceptToMemoryPool
0774     if (!IsCoinBase())
0775     {
0776         int64 nValueIn = 0;
0777         for (int i = 0; i < vin.size(); i++)
0778         {
0779             COutPoint prevout = vin[i].prevout;
0780 
0781             // Read txindex
0782             CTxIndex txindex;
0783             bool fFound = true;
0784             if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
0785             {
0786                 // Get txindex from current proposed changes
0787                 txindex = mapTestPool[prevout.hash];
0788             }
0789             else
0790             {
0791                 // Read txindex from txdb
0792                 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
0793             }
0794             if (!fFound && (fBlock || fMiner))
0795                 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
0796 
0797             // Read txPrev
0798             CTransaction txPrev;
0799             if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
0800             {
0801                 // Get prev tx from single transactions in memory
0802                 CRITICAL_BLOCK(cs_mapTransactions)
0803                 {
0804                     if (!mapTransactions.count(prevout.hash))
0805                         return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
0806                     txPrev = mapTransactions[prevout.hash];
0807                 }
0808                 if (!fFound)
0809                     txindex.vSpent.resize(txPrev.vout.size());
0810             }
0811             else
0812             {
0813                 // Get prev tx from disk
0814                 if (!txPrev.ReadFromDisk(txindex.pos))
0815                     return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(),  prevout.hash.ToString().substr(0,10).c_str());
0816             }
0817 
0818             if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
0819             {
0820                 // Revisit this if/when transaction replacement is implemented and allows
0821                 // adding inputs:
0822                 fInvalid = true;
0823                 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
0824             }
0825 
0826             // If prev is coinbase, check that it's matured
0827             if (txPrev.IsCoinBase())
0828                 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
0829                     if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
0830                         return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
0831 
0832             // Skip ECDSA signature verification when connecting blocks (fBlock=true)
0833             // before the last blockchain checkpoint. This is safe because block merkle hashes are
0834             // still computed and checked, and any change will be caught at the next checkpoint.
0835             if (fVerifyAll || (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))))
0836                 // Verify signature
0837                 if (!VerifySignature(txPrev, *this, i))
0838                     return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
0839 
0840             // Check for conflicts (double-spend)
0841             // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
0842             // for an attacker to attempt to split the network.
0843             if (!txindex.vSpent[prevout.n].IsNull())
0844                 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
0845 
0846             // Check for negative or overflow input values
0847             nValueIn += txPrev.vout[prevout.n].nValue;
0848             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
0849                 return DoS(100, error("ConnectInputs() : txin values out of range"));
0850 
0851             // Mark outpoints as spent
0852             txindex.vSpent[prevout.n] = posThisTx;
0853 
0854             // Write back
0855             if (fBlock || fMiner)
0856             {
0857                 mapTestPool[prevout.hash] = txindex;
0858             }
0859         }
0860 
0861         if (nValueIn < GetValueOut())
0862             return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
0863 
0864         // Tally transaction fees
0865         int64 nTxFee = nValueIn - GetValueOut();
0866         if (nTxFee < 0)
0867             return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
0868         if (nTxFee < nMinFee)
0869             return false;
0870         nFees += nTxFee;
0871         if (!MoneyRange(nFees))
0872             return DoS(100, error("ConnectInputs() : nFees out of range"));
0873     }
0874 
0875     if (fBlock)
0876     {
0877         // Add transaction to changes
0878         mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
0879     }
0880     else if (fMiner)
0881     {
0882         // Add transaction to test pool
0883         mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
0884     }
0885 
0886     return true;
0887 }
0888 
0889 
0890 bool CTransaction::ClientConnectInputs()
0891 {
0892     if (IsCoinBase())
0893         return false;
0894 
0895     // Take over previous transactions' spent pointers
0896     CRITICAL_BLOCK(cs_mapTransactions)
0897     {
0898         int64 nValueIn = 0;
0899         for (int i = 0; i < vin.size(); i++)
0900         {
0901             // Get prev tx from single transactions in memory
0902             COutPoint prevout = vin[i].prevout;
0903             if (!mapTransactions.count(prevout.hash))
0904                 return false;
0905             CTransaction& txPrev = mapTransactions[prevout.hash];
0906 
0907             if (prevout.n >= txPrev.vout.size())
0908                 return false;
0909 
0910             // Verify signature
0911             if (!VerifySignature(txPrev, *this, i))
0912                 return error("ConnectInputs() : VerifySignature failed");
0913 
0914             ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
0915             ///// this has to go away now that posNext is gone
0916             // // Check for conflicts
0917             // if (!txPrev.vout[prevout.n].posNext.IsNull())
0918             //     return error("ConnectInputs() : prev tx already used");
0919             //
0920             // // Flag outpoints as used
0921             // txPrev.vout[prevout.n].posNext = posThisTx;
0922 
0923             nValueIn += txPrev.vout[prevout.n].nValue;
0924 
0925             if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
0926                 return error("ClientConnectInputs() : txin values out of range");
0927         }
0928         if (GetValueOut() > nValueIn)
0929             return false;
0930     }
0931 
0932     return true;
0933 }
0934 
0935 
0936 
0937 
0938 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
0939 {
0940     // Disconnect in reverse order
0941     for (int i = vtx.size()-1; i >= 0; i--)
0942         if (!vtx[i].DisconnectInputs(txdb))
0943             return false;
0944 
0945     // Update block index on disk without changing it in memory.
0946     // The memory index structure will be changed after the db commits.
0947     if (pindex->pprev)
0948     {
0949         CDiskBlockIndex blockindexPrev(pindex->pprev);
0950         blockindexPrev.hashNext = 0;
0951         if (!txdb.WriteBlockIndex(blockindexPrev))
0952             return error("DisconnectBlock() : WriteBlockIndex failed");
0953     }
0954 
0955     return true;
0956 }
0957 
0958 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
0959 {
0960     // Check it again in case a previous version let a bad block in
0961     if (!CheckBlock())
0962         return false;
0963 
0964     // Do not allow blocks that contain transactions which 'overwrite' older transactions,
0965     // unless those are already completely spent.
0966     // If such overwrites are allowed, coinbases and transactions depending upon those
0967     // can be duplicated to remove the ability to spend the first instance -- even after
0968     // being sent to another address.
0969     // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
0970     // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
0971     // already refuses previously-known transaction id's entirely.
0972     // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
0973     if (pindex->nTime > 1331769600)
0974         BOOST_FOREACH(CTransaction& tx, vtx)
0975         {
0976             CTxIndex txindexOld;
0977             if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
0978                 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
0979                     if (pos.IsNull())
0980                         return false;
0981         }
0982 
0983     //// issue here: it doesn't know the version
0984     unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
0985 
0986     map<uint256, CTxIndex> mapQueuedChanges;
0987     int64 nFees = 0;
0988     BOOST_FOREACH(CTransaction& tx, vtx)
0989     {
0990         CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
0991         nTxPos += ::GetSerializeSize(tx, SER_DISK);
0992 
0993         bool fInvalid;
0994         if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, 0, fInvalid))
0995             return false;
0996     }
0997     // Wri