1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 CBlockIndex* pindexGenesisBlock = NULL;
36 CBigNum bnBestChainWork = 0;
37 CBigNum bnBestInvalidWork = 0;
38 uint256 hashBestChain = 0;
39 CBlockIndex* pindexBest = NULL;
40 int64 nTimeBestReceived = 0;
42 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
44 map<uint256, CBlock*> mapOrphanBlocks;
45 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
47 map<uint256, CDataStream*> mapOrphanTransactions;
48 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
55 int fGenerateBitcoins = false;
56 int64 nTransactionFee = 0;
57 int fLimitProcessors = false;
58 int nLimitProcessors = 1;
59 int fMinimizeToTray = true;
60 int fMinimizeOnClose = true;
68 //////////////////////////////////////////////////////////////////////////////
70 // dispatching functions
73 // These functions dispatch to one or all registered wallets
76 void RegisterWallet(CWallet* pwalletIn)
78 CRITICAL_BLOCK(cs_setpwalletRegistered)
80 setpwalletRegistered.insert(pwalletIn);
84 void UnregisterWallet(CWallet* pwalletIn)
86 CRITICAL_BLOCK(cs_setpwalletRegistered)
88 setpwalletRegistered.erase(pwalletIn);
92 // check whether the passed transaction is from us
93 bool static IsFromMe(CTransaction& tx)
95 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
96 if (pwallet->IsFromMe(tx))
101 // get the wallet transaction with the given hash (if it exists)
102 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 // erases transaction with the given hash from all wallets
111 void static EraseFromWallets(uint256 hash)
113 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114 pwallet->EraseFromWallet(hash);
117 // make sure all wallets know about the given transaction, in the given block
118 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
124 // notify wallets about a new best chain
125 void static SetBestChain(const CBlockLocator& loc)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 pwallet->SetBestChain(loc);
131 // notify wallets about an updated transaction
132 void static UpdatedTransaction(const uint256& hashTx)
134 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
135 pwallet->UpdatedTransaction(hashTx);
139 void static PrintWallets(const CBlock& block)
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 pwallet->PrintWallet(block);
145 // notify wallets about an incoming inventory (for request counts)
146 void static Inventory(const uint256& hash)
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->Inventory(hash);
152 // ask wallets to resend their transactions
153 void static ResendWalletTransactions()
155 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
156 pwallet->ResendWalletTransactions();
165 //////////////////////////////////////////////////////////////////////////////
167 // mapOrphanTransactions
170 void AddOrphanTx(const CDataStream& vMsg)
173 CDataStream(vMsg) >> tx;
174 uint256 hash = tx.GetHash();
175 if (mapOrphanTransactions.count(hash))
178 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
179 BOOST_FOREACH(const CTxIn& txin, tx.vin)
180 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
183 void static EraseOrphanTx(uint256 hash)
185 if (!mapOrphanTransactions.count(hash))
187 const CDataStream* pvMsg = mapOrphanTransactions[hash];
189 CDataStream(*pvMsg) >> tx;
190 BOOST_FOREACH(const CTxIn& txin, tx.vin)
192 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
193 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
195 if ((*mi).second == pvMsg)
196 mapOrphanTransactionsByPrev.erase(mi++);
202 mapOrphanTransactions.erase(hash);
205 int LimitOrphanTxSize(int nMaxOrphans)
208 while (mapOrphanTransactions.size() > nMaxOrphans)
210 // Evict a random orphan:
211 std::vector<unsigned char> randbytes(32);
212 RAND_bytes(&randbytes[0], 32);
213 uint256 randomhash(randbytes);
214 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
215 if (it == mapOrphanTransactions.end())
216 it = mapOrphanTransactions.begin();
217 EraseOrphanTx(it->first);
229 //////////////////////////////////////////////////////////////////////////////
231 // CTransaction and CTxIndex
234 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
237 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
239 if (!ReadFromDisk(txindexRet.pos))
241 if (prevout.n >= vout.size())
249 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
252 return ReadFromDisk(txdb, prevout, txindex);
255 bool CTransaction::ReadFromDisk(COutPoint prevout)
259 return ReadFromDisk(txdb, prevout, txindex);
264 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
276 // Load the block this tx is in
278 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
280 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
285 // Update the tx's hashBlock
286 hashBlock = pblock->GetHash();
288 // Locate the transaction
289 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
290 if (pblock->vtx[nIndex] == *(CTransaction*)this)
292 if (nIndex == pblock->vtx.size())
294 vMerkleBranch.clear();
296 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
300 // Fill in merkle branch
301 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
304 // Is the tx in a block that's in the main chain
305 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
306 if (mi == mapBlockIndex.end())
308 CBlockIndex* pindex = (*mi).second;
309 if (!pindex || !pindex->IsInMainChain())
312 return pindexBest->nHeight - pindex->nHeight + 1;
321 bool CTransaction::CheckTransaction() const
323 // Basic checks that don't depend on any context
325 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
327 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
329 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
330 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
332 // Check for negative or overflow output values
334 BOOST_FOREACH(const CTxOut& txout, vout)
336 if (txout.nValue < 0)
337 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
338 if (txout.nValue > MAX_MONEY)
339 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
340 nValueOut += txout.nValue;
341 if (!MoneyRange(nValueOut))
342 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
345 // Check for duplicate inputs
346 set<COutPoint> vInOutPoints;
347 BOOST_FOREACH(const CTxIn& txin, vin)
349 if (vInOutPoints.count(txin.prevout))
351 vInOutPoints.insert(txin.prevout);
356 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
357 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
361 BOOST_FOREACH(const CTxIn& txin, vin)
362 if (txin.prevout.IsNull())
363 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
369 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
372 *pfMissingInputs = false;
374 if (!CheckTransaction())
375 return error("AcceptToMemoryPool() : CheckTransaction failed");
377 // Coinbase is only valid in a block, not as a loose transaction
379 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
381 // To help v0.1.5 clients who would see it as a negative number
382 if ((int64)nLockTime > INT_MAX)
383 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
385 // Rather not work on nonstandard transactions (unless -testnet)
386 if (!fTestNet && !IsStandard())
387 return error("AcceptToMemoryPool() : nonstandard transaction type");
389 // Do we already have it?
390 uint256 hash = GetHash();
391 CRITICAL_BLOCK(cs_mapTransactions)
392 if (mapTransactions.count(hash))
395 if (txdb.ContainsTx(hash))
398 // Check for conflicts with in-memory transactions
399 CTransaction* ptxOld = NULL;
400 for (unsigned int i = 0; i < vin.size(); i++)
402 COutPoint outpoint = vin[i].prevout;
403 if (mapNextTx.count(outpoint))
405 // Disable replacement feature for now
408 // Allow replacing with a newer version of the same transaction
411 ptxOld = mapNextTx[outpoint].ptx;
412 if (ptxOld->IsFinal())
414 if (!IsNewerThan(*ptxOld))
416 for (unsigned int i = 0; i < vin.size(); i++)
418 COutPoint outpoint = vin[i].prevout;
419 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
429 map<uint256, CTxIndex> mapUnused;
430 bool fInvalid = false;
431 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
434 return error("AcceptToMemoryPool() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
436 *pfMissingInputs = true;
437 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
441 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
442 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
443 // attacks disallow transactions with more than one SigOp per 34 bytes.
444 // 34 bytes because a TxOut is:
445 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
446 if (GetSigOpCount() > nSize / 34 || nSize < 100)
447 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
449 int64 nFees = GetValueIn(mapInputs)-GetValueOut();
451 // Don't accept it if it can't get into a block
452 if (nFees < GetMinFee(1000, true, true))
453 return error("AcceptToMemoryPool() : not enough fees");
455 // Continuously rate-limit free transactions
456 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
457 // be annoying or make other's transactions take longer to confirm.
458 if (nFees < MIN_RELAY_TX_FEE)
460 static CCriticalSection cs;
461 static double dFreeCount;
462 static int64 nLastTime;
463 int64 nNow = GetTime();
467 // Use an exponentially decaying ~10-minute window:
468 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
470 // -limitfreerelay unit is thousand-bytes-per-minute
471 // At default rate it would take over a month to fill 1GB
472 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
473 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
475 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
480 // Check against previous transactions
481 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
482 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
484 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
488 // Store transaction in memory
489 CRITICAL_BLOCK(cs_mapTransactions)
493 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
494 ptxOld->RemoveFromMemoryPool();
496 AddToMemoryPoolUnchecked();
499 ///// are we sure this is ok when loading transactions or restoring block txes
500 // If updated, erase old tx from wallet
502 EraseFromWallets(ptxOld->GetHash());
504 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
508 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
511 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
514 bool CTransaction::AddToMemoryPoolUnchecked()
516 // Add to memory pool without checking anything. Don't call this directly,
517 // call AcceptToMemoryPool to properly check the transaction first.
518 CRITICAL_BLOCK(cs_mapTransactions)
520 uint256 hash = GetHash();
521 mapTransactions[hash] = *this;
522 for (unsigned int i = 0; i < vin.size(); i++)
523 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
524 nTransactionsUpdated++;
530 bool CTransaction::RemoveFromMemoryPool()
532 // Remove transaction from memory pool
533 CRITICAL_BLOCK(cs_mapTransactions)
535 BOOST_FOREACH(const CTxIn& txin, vin)
536 mapNextTx.erase(txin.prevout);
537 mapTransactions.erase(GetHash());
538 nTransactionsUpdated++;
548 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
550 if (hashBlock == 0 || nIndex == -1)
553 // Find the block it claims to be in
554 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
555 if (mi == mapBlockIndex.end())
557 CBlockIndex* pindex = (*mi).second;
558 if (!pindex || !pindex->IsInMainChain())
561 // Make sure the merkle branch connects to this block
562 if (!fMerkleVerified)
564 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
566 fMerkleVerified = true;
569 nHeightRet = pindex->nHeight;
570 return pindexBest->nHeight - pindex->nHeight + 1;
574 int CMerkleTx::GetBlocksToMaturity() const
578 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
582 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
586 if (!IsInMainChain() && !ClientConnectInputs())
588 return CTransaction::AcceptToMemoryPool(txdb, false);
592 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
596 bool CMerkleTx::AcceptToMemoryPool()
599 return AcceptToMemoryPool(txdb);
604 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
606 CRITICAL_BLOCK(cs_mapTransactions)
608 // Add previous supporting transactions first
609 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
611 if (!tx.IsCoinBase())
613 uint256 hash = tx.GetHash();
614 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
615 tx.AcceptToMemoryPool(txdb, fCheckInputs);
618 return AcceptToMemoryPool(txdb, fCheckInputs);
623 bool CWalletTx::AcceptWalletTransaction()
626 return AcceptWalletTransaction(txdb);
629 int CTxIndex::GetDepthInMainChain() const
633 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
635 // Find the block in the index
636 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
637 if (mi == mapBlockIndex.end())
639 CBlockIndex* pindex = (*mi).second;
640 if (!pindex || !pindex->IsInMainChain())
642 return 1 + nBestHeight - pindex->nHeight;
654 //////////////////////////////////////////////////////////////////////////////
656 // CBlock and CBlockIndex
659 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
661 if (!fReadTransactions)
663 *this = pindex->GetBlockHeader();
666 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
668 if (GetHash() != pindex->GetBlockHash())
669 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
673 uint256 static GetOrphanRoot(const CBlock* pblock)
675 // Work back to the first block in the orphan chain
676 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
677 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
678 return pblock->GetHash();
681 int64 static GetBlockValue(int nHeight, int64 nFees)
683 int64 nSubsidy = 50 * COIN;
685 // Subsidy is cut in half every 4 years
686 nSubsidy >>= (nHeight / 210000);
688 return nSubsidy + nFees;
691 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
692 static const int64 nTargetSpacing = 10 * 60;
693 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
696 // minimum amount of work that could possibly be required nTime after
697 // minimum work required was nBase
699 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
701 // Testnet has min-difficulty blocks
702 // after nTargetSpacing*2 time between blocks:
703 if (fTestNet && nTime > nTargetSpacing*2)
704 return bnProofOfWorkLimit.GetCompact();
707 bnResult.SetCompact(nBase);
708 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
710 // Maximum 400% adjustment...
712 // ... in best-case exactly 4-times-normal target time
713 nTime -= nTargetTimespan*4;
715 if (bnResult > bnProofOfWorkLimit)
716 bnResult = bnProofOfWorkLimit;
717 return bnResult.GetCompact();
720 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
722 unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
725 if (pindexLast == NULL)
726 return nProofOfWorkLimit;
728 // Only change once per interval
729 if ((pindexLast->nHeight+1) % nInterval != 0)
731 // Special rules for testnet after 15 Feb 2012:
732 if (fTestNet && pblock->nTime > 1329264000)
734 // If the new block's timestamp is more than 2* 10 minutes
735 // then allow mining of a min-difficulty block.
736 if (pblock->nTime - pindexLast->nTime > nTargetSpacing*2)
737 return nProofOfWorkLimit;
740 // Return the last non-special-min-difficulty-rules-block
741 const CBlockIndex* pindex = pindexLast;
742 while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
743 pindex = pindex->pprev;
744 return pindex->nBits;
748 return pindexLast->nBits;
751 // Go back by what we want to be 14 days worth of blocks
752 const CBlockIndex* pindexFirst = pindexLast;
753 for (int i = 0; pindexFirst && i < nInterval-1; i++)
754 pindexFirst = pindexFirst->pprev;
757 // Limit adjustment step
758 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
759 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
760 if (nActualTimespan < nTargetTimespan/4)
761 nActualTimespan = nTargetTimespan/4;
762 if (nActualTimespan > nTargetTimespan*4)
763 nActualTimespan = nTargetTimespan*4;
767 bnNew.SetCompact(pindexLast->nBits);
768 bnNew *= nActualTimespan;
769 bnNew /= nTargetTimespan;
771 if (bnNew > bnProofOfWorkLimit)
772 bnNew = bnProofOfWorkLimit;
775 printf("GetNextWorkRequired RETARGET\n");
776 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
777 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
778 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
780 return bnNew.GetCompact();
783 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
786 bnTarget.SetCompact(nBits);
789 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
790 return error("CheckProofOfWork() : nBits below minimum work");
792 // Check proof of work matches claimed amount
793 if (hash > bnTarget.getuint256())
794 return error("CheckProofOfWork() : hash doesn't match nBits");
799 // Return maximum amount of blocks that other nodes claim to have
800 int GetNumBlocksOfPeers()
802 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
805 bool IsInitialBlockDownload()
807 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
809 static int64 nLastUpdate;
810 static CBlockIndex* pindexLastBest;
811 if (pindexBest != pindexLastBest)
813 pindexLastBest = pindexBest;
814 nLastUpdate = GetTime();
816 return (GetTime() - nLastUpdate < 10 &&
817 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
820 void static InvalidChainFound(CBlockIndex* pindexNew)
822 if (pindexNew->bnChainWork > bnBestInvalidWork)
824 bnBestInvalidWork = pindexNew->bnChainWork;
825 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
828 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());
829 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
830 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
831 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
834 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
836 nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
838 // Updating time can change work required on testnet:
840 nBits = GetNextWorkRequired(pindexPrev, this);
853 bool CTransaction::DisconnectInputs(CTxDB& txdb)
855 // Relinquish previous transactions' spent pointers
858 BOOST_FOREACH(const CTxIn& txin, vin)
860 COutPoint prevout = txin.prevout;
862 // Get prev txindex from disk
864 if (!txdb.ReadTxIndex(prevout.hash, txindex))
865 return error("DisconnectInputs() : ReadTxIndex failed");
867 if (prevout.n >= txindex.vSpent.size())
868 return error("DisconnectInputs() : prevout.n out of range");
870 // Mark outpoint as not spent
871 txindex.vSpent[prevout.n].SetNull();
874 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
875 return error("DisconnectInputs() : UpdateTxIndex failed");
879 // Remove transaction from index
880 // This can fail if a duplicate of this transaction was in a chain that got
881 // reorganized away. This is only possible if this transaction was completely
882 // spent, so erasing it would be a no-op anway.
883 txdb.EraseTxIndex(*this);
889 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
890 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
892 // FetchInputs can return false either because we just haven't seen some inputs
893 // (in which case the transaction should be stored as an orphan)
894 // or because the transaction is malformed (in which case the transaction should
895 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
899 return true; // Coinbase transactions have no inputs to fetch.
901 for (unsigned int i = 0; i < vin.size(); i++)
903 COutPoint prevout = vin[i].prevout;
904 if (inputsRet.count(prevout.hash))
905 continue; // Got it already
908 CTxIndex& txindex = inputsRet[prevout.hash].first;
910 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
912 // Get txindex from current proposed changes
913 txindex = mapTestPool.find(prevout.hash)->second;
917 // Read txindex from txdb
918 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
920 if (!fFound && (fBlock || fMiner))
921 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());
924 CTransaction& txPrev = inputsRet[prevout.hash].second;
925 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
927 // Get prev tx from single transactions in memory
928 CRITICAL_BLOCK(cs_mapTransactions)
930 if (!mapTransactions.count(prevout.hash))
931 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
932 txPrev = mapTransactions[prevout.hash];
935 txindex.vSpent.resize(txPrev.vout.size());
939 // Get prev tx from disk
940 if (!txPrev.ReadFromDisk(txindex.pos))
941 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
945 // Make sure all prevout.n's are valid:
946 for (unsigned int i = 0; i < vin.size(); i++)
948 const COutPoint prevout = vin[i].prevout;
949 assert(inputsRet.count(prevout.hash) != 0);
950 const CTxIndex& txindex = inputsRet[prevout.hash].first;
951 const CTransaction& txPrev = inputsRet[prevout.hash].second;
952 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
954 // Revisit this if/when transaction replacement is implemented and allows
957 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()));
964 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
966 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
967 if (mi == inputs.end())
968 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
970 const CTransaction& txPrev = (mi->second).second;
971 if (input.prevout.n >= txPrev.vout.size())
972 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
974 return txPrev.vout[input.prevout.n];
977 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
983 for (unsigned int i = 0; i < vin.size(); i++)
985 nResult += GetOutputFor(vin[i], inputs).nValue;
991 int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
997 for (unsigned int i = 0; i < vin.size(); i++)
999 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1000 if (prevout.scriptPubKey.IsPayToScriptHash())
1001 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1006 bool CTransaction::ConnectInputs(MapPrevTx inputs,
1007 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1008 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1010 // Take over previous transactions' spent pointers
1011 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1012 // fMiner is true when called from the internal bitcoin miner
1013 // ... both are false when called from CTransaction::AcceptToMemoryPool
1018 for (unsigned int i = 0; i < vin.size(); i++)
1020 COutPoint prevout = vin[i].prevout;
1021 assert(inputs.count(prevout.hash) > 0);
1022 CTxIndex& txindex = inputs[prevout.hash].first;
1023 CTransaction& txPrev = inputs[prevout.hash].second;
1025 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1026 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()));
1028 // If prev is coinbase, check that it's matured
1029 if (txPrev.IsCoinBase())
1030 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1031 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1032 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1034 // Check for conflicts (double-spend)
1035 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1036 // for an attacker to attempt to split the network.
1037 if (!txindex.vSpent[prevout.n].IsNull())
1038 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());
1040 // Check for negative or overflow input values
1041 nValueIn += txPrev.vout[prevout.n].nValue;
1042 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1043 return DoS(100, error("ConnectInputs() : txin values out of range"));
1045 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1046 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1047 // still computed and checked, and any change will be caught at the next checkpoint.
1048 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1051 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1053 // only during transition phase for P2SH: do not invoke anti-DoS code for
1054 // potentially old clients relaying bad P2SH transactions
1055 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1056 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1058 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1062 // Mark outpoints as spent
1063 txindex.vSpent[prevout.n] = posThisTx;
1066 if (fBlock || fMiner)
1068 mapTestPool[prevout.hash] = txindex;
1072 if (nValueIn < GetValueOut())
1073 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1075 // Tally transaction fees
1076 int64 nTxFee = nValueIn - GetValueOut();
1078 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1080 if (!MoneyRange(nFees))
1081 return DoS(100, error("ConnectInputs() : nFees out of range"));
1088 bool CTransaction::ClientConnectInputs()
1093 // Take over previous transactions' spent pointers
1094 CRITICAL_BLOCK(cs_mapTransactions)
1097 for (unsigned int i = 0; i < vin.size(); i++)
1099 // Get prev tx from single transactions in memory
1100 COutPoint prevout = vin[i].prevout;
1101 if (!mapTransactions.count(prevout.hash))
1103 CTransaction& txPrev = mapTransactions[prevout.hash];
1105 if (prevout.n >= txPrev.vout.size())
1109 if (!VerifySignature(txPrev, *this, i, true, 0))
1110 return error("ConnectInputs() : VerifySignature failed");
1112 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1113 ///// this has to go away now that posNext is gone
1114 // // Check for conflicts
1115 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1116 // return error("ConnectInputs() : prev tx already used");
1118 // // Flag outpoints as used
1119 // txPrev.vout[prevout.n].posNext = posThisTx;
1121 nValueIn += txPrev.vout[prevout.n].nValue;
1123 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1124 return error("ClientConnectInputs() : txin values out of range");
1126 if (GetValueOut() > nValueIn)
1136 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1138 // Disconnect in reverse order
1139 for (int i = vtx.size()-1; i >= 0; i--)
1140 if (!vtx[i].DisconnectInputs(txdb))
1143 // Update block index on disk without changing it in memory.
1144 // The memory index structure will be changed after the db commits.
1147 CDiskBlockIndex blockindexPrev(pindex->pprev);
1148 blockindexPrev.hashNext = 0;
1149 if (!txdb.WriteBlockIndex(blockindexPrev))
1150 return error("DisconnectBlock() : WriteBlockIndex failed");
1156 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1158 // Check it again in case a previous version let a bad block in
1162 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1163 // unless those are already completely spent.
1164 // If such overwrites are allowed, coinbases and transactions depending upon those
1165 // can be duplicated to remove the ability to spend the first instance -- even after
1166 // being sent to another address.
1167 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1168 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1169 // already refuses previously-known transaction id's entirely.
1170 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1171 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1172 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1174 BOOST_FOREACH(CTransaction& tx, vtx)
1176 CTxIndex txindexOld;
1177 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1179 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1186 // P2SH didn't become active until Apr 1 2012 (Feb 15 on testnet)
1187 int64 nEvalSwitchTime = fTestNet ? 1329264000 : 1333238400;
1188 bool fStrictPayToScriptHash = (pindex->nTime >= nEvalSwitchTime);
1190 //// issue here: it doesn't know the version
1191 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1193 map<uint256, CTxIndex> mapQueuedChanges;
1196 BOOST_FOREACH(CTransaction& tx, vtx)
1198 nSigOps += tx.GetSigOpCount();
1199 if (nSigOps > MAX_BLOCK_SIGOPS)
1200 return DoS(100, error("ConnectBlock() : too many sigops"));
1202 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1203 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1206 MapPrevTx mapInputs;
1207 if (!tx.IsCoinBase())
1209 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1212 if (fStrictPayToScriptHash)
1214 // Add in sigops done by pay-to-script-hash inputs;
1215 // this is to prevent a "rogue miner" from creating
1216 // an incredibly-expensive-to-validate block.
1217 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1218 if (nSigOps > MAX_BLOCK_SIGOPS)
1219 return DoS(100, error("ConnectBlock() : too many sigops"));
1222 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1224 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1228 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1231 // Write queued txindex changes
1232 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1234 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1235 return error("ConnectBlock() : UpdateTxIndex failed");
1238 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1241 // Update block index on disk without changing it in memory.
1242 // The memory index structure will be changed after the db commits.
1245 CDiskBlockIndex blockindexPrev(pindex->pprev);
1246 blockindexPrev.hashNext = pindex->GetBlockHash();
1247 if (!txdb.WriteBlockIndex(blockindexPrev))
1248 return error("ConnectBlock() : WriteBlockIndex failed");
1251 // Watch for transactions paying to me
1252 BOOST_FOREACH(CTransaction& tx, vtx)
1253 SyncWithWallets(tx, this, true);
1258 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1260 printf("REORGANIZE\n");
1263 CBlockIndex* pfork = pindexBest;
1264 CBlockIndex* plonger = pindexNew;
1265 while (pfork != plonger)
1267 while (plonger->nHeight > pfork->nHeight)
1268 if (!(plonger = plonger->pprev))
1269 return error("Reorganize() : plonger->pprev is null");
1270 if (pfork == plonger)
1272 if (!(pfork = pfork->pprev))
1273 return error("Reorganize() : pfork->pprev is null");
1276 // List of what to disconnect
1277 vector<CBlockIndex*> vDisconnect;
1278 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1279 vDisconnect.push_back(pindex);
1281 // List of what to connect
1282 vector<CBlockIndex*> vConnect;
1283 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1284 vConnect.push_back(pindex);
1285 reverse(vConnect.begin(), vConnect.end());
1287 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());
1288 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());
1290 // Disconnect shorter branch
1291 vector<CTransaction> vResurrect;
1292 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1295 if (!block.ReadFromDisk(pindex))
1296 return error("Reorganize() : ReadFromDisk for disconnect failed");
1297 if (!block.DisconnectBlock(txdb, pindex))
1298 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1300 // Queue memory transactions to resurrect
1301 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1302 if (!tx.IsCoinBase())
1303 vResurrect.push_back(tx);
1306 // Connect longer branch
1307 vector<CTransaction> vDelete;
1308 for (unsigned int i = 0; i < vConnect.size(); i++)
1310 CBlockIndex* pindex = vConnect[i];
1312 if (!block.ReadFromDisk(pindex))
1313 return error("Reorganize() : ReadFromDisk for connect failed");
1314 if (!block.ConnectBlock(txdb, pindex))
1318 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1321 // Queue memory transactions to delete
1322 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1323 vDelete.push_back(tx);
1325 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1326 return error("Reorganize() : WriteHashBestChain failed");
1328 // Make sure it's successfully written to disk before changing memory structure
1329 if (!txdb.TxnCommit())
1330 return error("Reorganize() : TxnCommit failed");
1332 // Disconnect shorter branch
1333 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1335 pindex->pprev->pnext = NULL;
1337 // Connect longer branch
1338 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1340 pindex->pprev->pnext = pindex;
1342 // Resurrect memory transactions that were in the disconnected branch
1343 BOOST_FOREACH(CTransaction& tx, vResurrect)
1344 tx.AcceptToMemoryPool(txdb, false);
1346 // Delete redundant memory transactions that are in the connected branch
1347 BOOST_FOREACH(CTransaction& tx, vDelete)
1348 tx.RemoveFromMemoryPool();
1350 printf("REORGANIZE: done\n");
1356 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1358 uint256 hash = GetHash();
1361 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1363 txdb.WriteHashBestChain(hash);
1364 if (!txdb.TxnCommit())
1365 return error("SetBestChain() : TxnCommit failed");
1366 pindexGenesisBlock = pindexNew;
1368 else if (hashPrevBlock == hashBestChain)
1370 // Adding to current best branch
1371 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1374 InvalidChainFound(pindexNew);
1375 return error("SetBestChain() : ConnectBlock failed");
1377 if (!txdb.TxnCommit())
1378 return error("SetBestChain() : TxnCommit failed");
1380 // Add to current best branch
1381 pindexNew->pprev->pnext = pindexNew;
1383 // Delete redundant memory transactions
1384 BOOST_FOREACH(CTransaction& tx, vtx)
1385 tx.RemoveFromMemoryPool();
1390 if (!Reorganize(txdb, pindexNew))
1393 InvalidChainFound(pindexNew);
1394 return error("SetBestChain() : Reorganize failed");
1398 // Update best block in wallet (so we can detect restored wallets)
1399 if (!IsInitialBlockDownload())
1401 const CBlockLocator locator(pindexNew);
1402 ::SetBestChain(locator);
1406 hashBestChain = hash;
1407 pindexBest = pindexNew;
1408 nBestHeight = pindexBest->nHeight;
1409 bnBestChainWork = pindexNew->bnChainWork;
1410 nTimeBestReceived = GetTime();
1411 nTransactionsUpdated++;
1412 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1418 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1420 // Check for duplicate
1421 uint256 hash = GetHash();
1422 if (mapBlockIndex.count(hash))
1423 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1425 // Construct new block index object
1426 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1428 return error("AddToBlockIndex() : new CBlockIndex failed");
1429 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1430 pindexNew->phashBlock = &((*mi).first);
1431 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1432 if (miPrev != mapBlockIndex.end())
1434 pindexNew->pprev = (*miPrev).second;
1435 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1437 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1441 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1442 if (!txdb.TxnCommit())
1446 if (pindexNew->bnChainWork > bnBestChainWork)
1447 if (!SetBestChain(txdb, pindexNew))
1452 if (pindexNew == pindexBest)
1454 // Notify UI to display prev block's coinbase if it was ours
1455 static uint256 hashPrevBestCoinBase;
1456 UpdatedTransaction(hashPrevBestCoinBase);
1457 hashPrevBestCoinBase = vtx[0].GetHash();
1467 bool CBlock::CheckBlock() const
1469 // These are checks that are independent of context
1470 // that can be verified before saving an orphan block.
1473 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1474 return DoS(100, error("CheckBlock() : size limits failed"));
1476 // Check proof of work matches claimed amount
1477 if (!CheckProofOfWork(GetHash(), nBits))
1478 return DoS(50, error("CheckBlock() : proof of work failed"));
1481 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1482 return error("CheckBlock() : block timestamp too far in the future");
1484 // First transaction must be coinbase, the rest must not be
1485 if (vtx.empty() || !vtx[0].IsCoinBase())
1486 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1487 for (unsigned int i = 1; i < vtx.size(); i++)
1488 if (vtx[i].IsCoinBase())
1489 return DoS(100, error("CheckBlock() : more than one coinbase"));
1491 // Check transactions
1492 BOOST_FOREACH(const CTransaction& tx, vtx)
1493 if (!tx.CheckTransaction())
1494 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1496 // Check for duplicate txids. This is caught by ConnectInputs(),
1497 // but catching it earlier avoids a potential DoS attack:
1498 set<uint256> uniqueTx;
1499 BOOST_FOREACH(const CTransaction& tx, vtx)
1501 uniqueTx.insert(tx.GetHash());
1503 if (uniqueTx.size() != vtx.size())
1504 return DoS(100, error("CheckBlock() : duplicate transaction"));
1506 // Check that it's not full of nonstandard transactions
1507 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1508 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1511 if (hashMerkleRoot != BuildMerkleTree())
1512 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1517 bool CBlock::AcceptBlock()
1519 // Check for duplicate
1520 uint256 hash = GetHash();
1521 if (mapBlockIndex.count(hash))
1522 return error("AcceptBlock() : block already in mapBlockIndex");
1524 // Get prev block index
1525 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1526 if (mi == mapBlockIndex.end())
1527 return DoS(10, error("AcceptBlock() : prev block not found"));
1528 CBlockIndex* pindexPrev = (*mi).second;
1529 int nHeight = pindexPrev->nHeight+1;
1531 // Check proof of work
1532 if (nBits != GetNextWorkRequired(pindexPrev, this))
1533 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1535 // Check timestamp against prev
1536 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1537 return error("AcceptBlock() : block's timestamp is too early");
1539 // Check that all transactions are finalized
1540 BOOST_FOREACH(const CTransaction& tx, vtx)
1541 if (!tx.IsFinal(nHeight, GetBlockTime()))
1542 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1544 // Check that the block chain matches the known block chain up to a checkpoint
1545 if (!Checkpoints::CheckBlock(nHeight, hash))
1546 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1548 // Write block to history file
1549 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1550 return error("AcceptBlock() : out of disk space");
1551 unsigned int nFile = -1;
1552 unsigned int nBlockPos = 0;
1553 if (!WriteToDisk(nFile, nBlockPos))
1554 return error("AcceptBlock() : WriteToDisk failed");
1555 if (!AddToBlockIndex(nFile, nBlockPos))
1556 return error("AcceptBlock() : AddToBlockIndex failed");
1558 // Relay inventory, but don't relay old inventory during initial block download
1559 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1560 if (hashBestChain == hash)
1561 CRITICAL_BLOCK(cs_vNodes)
1562 BOOST_FOREACH(CNode* pnode, vNodes)
1563 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1564 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1569 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1571 // Check for duplicate
1572 uint256 hash = pblock->GetHash();
1573 if (mapBlockIndex.count(hash))
1574 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1575 if (mapOrphanBlocks.count(hash))
1576 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1578 // Preliminary checks
1579 if (!pblock->CheckBlock())
1580 return error("ProcessBlock() : CheckBlock FAILED");
1582 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1583 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1585 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1586 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1590 pfrom->Misbehaving(100);
1591 return error("ProcessBlock() : block with timestamp before last checkpoint");
1594 bnNewBlock.SetCompact(pblock->nBits);
1596 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1597 if (bnNewBlock > bnRequired)
1600 pfrom->Misbehaving(100);
1601 return error("ProcessBlock() : block with too little proof-of-work");
1606 // If don't already have its previous block, shunt it off to holding area until we get it
1607 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1609 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1610 CBlock* pblock2 = new CBlock(*pblock);
1611 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1612 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1614 // Ask this guy to fill in what we're missing
1616 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1621 if (!pblock->AcceptBlock())
1622 return error("ProcessBlock() : AcceptBlock FAILED");
1624 // Recursively process any orphan blocks that depended on this one
1625 vector<uint256> vWorkQueue;
1626 vWorkQueue.push_back(hash);
1627 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
1629 uint256 hashPrev = vWorkQueue[i];
1630 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1631 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1634 CBlock* pblockOrphan = (*mi).second;
1635 if (pblockOrphan->AcceptBlock())
1636 vWorkQueue.push_back(pblockOrphan->GetHash());
1637 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1638 delete pblockOrphan;
1640 mapOrphanBlocksByPrev.erase(hashPrev);
1643 printf("ProcessBlock: ACCEPTED\n");
1654 bool CheckDiskSpace(uint64 nAdditionalBytes)
1656 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1658 // Check for 15MB because database could create another 10MB log file at any time
1659 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1662 string strMessage = _("Warning: Disk space is low ");
1663 strMiscWarning = strMessage;
1664 printf("*** %s\n", strMessage.c_str());
1665 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1666 CreateThread(Shutdown, NULL);
1672 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1676 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1679 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1681 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1690 static unsigned int nCurrentBlockFile = 1;
1692 FILE* AppendBlockFile(unsigned int& nFileRet)
1697 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1700 if (fseek(file, 0, SEEK_END) != 0)
1702 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1703 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1705 nFileRet = nCurrentBlockFile;
1709 nCurrentBlockFile++;
1713 bool LoadBlockIndex(bool fAllowNew)
1717 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1718 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1719 pchMessageStart[0] = 0xfa;
1720 pchMessageStart[1] = 0xbf;
1721 pchMessageStart[2] = 0xb5;
1722 pchMessageStart[3] = 0xda;
1729 if (!txdb.LoadBlockIndex())
1734 // Init with genesis block
1736 if (mapBlockIndex.empty())
1742 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1743 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1744 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1745 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1746 // vMerkleTree: 4a5e1e
1749 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1751 txNew.vin.resize(1);
1752 txNew.vout.resize(1);
1753 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1754 txNew.vout[0].nValue = 50 * COIN;
1755 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1757 block.vtx.push_back(txNew);
1758 block.hashPrevBlock = 0;
1759 block.hashMerkleRoot = block.BuildMerkleTree();
1761 block.nTime = 1231006505;
1762 block.nBits = 0x1d00ffff;
1763 block.nNonce = 2083236893;
1767 block.nTime = 1296688602;
1768 block.nBits = 0x1d07fff8;
1769 block.nNonce = 384568319;
1773 printf("%s\n", block.GetHash().ToString().c_str());
1774 printf("%s\n", hashGenesisBlock.ToString().c_str());
1775 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1776 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1778 assert(block.GetHash() == hashGenesisBlock);
1780 // Start new block file
1782 unsigned int nBlockPos;
1783 if (!block.WriteToDisk(nFile, nBlockPos))
1784 return error("LoadBlockIndex() : writing genesis block to disk failed");
1785 if (!block.AddToBlockIndex(nFile, nBlockPos))
1786 return error("LoadBlockIndex() : genesis block not accepted");
1794 void PrintBlockTree()
1796 // precompute tree structure
1797 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1798 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1800 CBlockIndex* pindex = (*mi).second;
1801 mapNext[pindex->pprev].push_back(pindex);
1803 //while (rand() % 3 == 0)
1804 // mapNext[pindex->pprev].push_back(pindex);
1807 vector<pair<int, CBlockIndex*> > vStack;
1808 vStack.push_back(make_pair(0, pindexGenesisBlock));
1811 while (!vStack.empty())
1813 int nCol = vStack.back().first;
1814 CBlockIndex* pindex = vStack.back().second;
1817 // print split or gap
1818 if (nCol > nPrevCol)
1820 for (int i = 0; i < nCol-1; i++)
1824 else if (nCol < nPrevCol)
1826 for (int i = 0; i < nCol; i++)
1833 for (int i = 0; i < nCol; i++)
1838 block.ReadFromDisk(pindex);
1839 printf("%d (%u,%u) %s %s tx %d",
1843 block.GetHash().ToString().substr(0,20).c_str(),
1844 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1847 PrintWallets(block);
1849 // put the main timechain first
1850 vector<CBlockIndex*>& vNext = mapNext[pindex];
1851 for (unsigned int i = 0; i < vNext.size(); i++)
1853 if (vNext[i]->pnext)
1855 swap(vNext[0], vNext[i]);
1861 for (unsigned int i = 0; i < vNext.size(); i++)
1862 vStack.push_back(make_pair(nCol+i, vNext[i]));
1875 //////////////////////////////////////////////////////////////////////////////
1880 map<uint256, CAlert> mapAlerts;
1881 CCriticalSection cs_mapAlerts;
1883 string GetWarnings(string strFor)
1886 string strStatusBar;
1888 if (GetBoolArg("-testsafemode"))
1891 // Misc warnings like out of disk space and clock is wrong
1892 if (strMiscWarning != "")
1895 strStatusBar = strMiscWarning;
1898 // Longer invalid proof-of-work chain
1899 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1902 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1906 CRITICAL_BLOCK(cs_mapAlerts)
1908 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1910 const CAlert& alert = item.second;
1911 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1913 nPriority = alert.nPriority;
1914 strStatusBar = alert.strStatusBar;
1919 if (strFor == "statusbar")
1920 return strStatusBar;
1921 else if (strFor == "rpc")
1923 assert(!"GetWarnings() : invalid parameter");
1927 bool CAlert::ProcessAlert()
1929 if (!CheckSignature())
1934 CRITICAL_BLOCK(cs_mapAlerts)
1936 // Cancel previous alerts
1937 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1939 const CAlert& alert = (*mi).second;
1942 printf("cancelling alert %d\n", alert.nID);
1943 mapAlerts.erase(mi++);
1945 else if (!alert.IsInEffect())
1947 printf("expiring alert %d\n", alert.nID);
1948 mapAlerts.erase(mi++);
1954 // Check if this alert has been cancelled
1955 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1957 const CAlert& alert = item.second;
1958 if (alert.Cancels(*this))
1960 printf("alert already cancelled by %d\n", alert.nID);
1966 mapAlerts.insert(make_pair(GetHash(), *this));
1969 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1981 //////////////////////////////////////////////////////////////////////////////
1987 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1993 bool txInMap = false;
1994 CRITICAL_BLOCK(cs_mapTransactions)
1996 txInMap = (mapTransactions.count(inv.hash) != 0);
1999 mapOrphanTransactions.count(inv.hash) ||
2000 txdb.ContainsTx(inv.hash);
2003 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2005 // Don't know what it is, just say we already got one
2012 // The message start string is designed to be unlikely to occur in normal data.
2013 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2014 // a large 4-byte int at any alignment.
2015 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2018 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2020 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2021 RandAddSeedPerfmon();
2023 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2024 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2026 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2028 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2036 if (strCommand == "version")
2038 // Each connection can only send one version message
2039 if (pfrom->nVersion != 0)
2041 pfrom->Misbehaving(1);
2049 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2050 if (pfrom->nVersion == 10300)
2051 pfrom->nVersion = 300;
2052 if (pfrom->nVersion >= 106 && !vRecv.empty())
2053 vRecv >> addrFrom >> nNonce;
2054 if (pfrom->nVersion >= 106 && !vRecv.empty())
2055 vRecv >> pfrom->strSubVer;
2056 if (pfrom->nVersion >= 209 && !vRecv.empty())
2057 vRecv >> pfrom->nStartingHeight;
2059 if (pfrom->nVersion == 0)
2062 // Disconnect if we connected to ourself
2063 if (nNonce == nLocalHostNonce && nNonce > 1)
2065 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2066 pfrom->fDisconnect = true;
2070 // Be shy and don't send version until we hear
2071 if (pfrom->fInbound)
2072 pfrom->PushVersion();
2074 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2076 AddTimeData(pfrom->addr.ip, nTime);
2079 if (pfrom->nVersion >= 209)
2080 pfrom->PushMessage("verack");
2081 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2082 if (pfrom->nVersion < 209)
2083 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2085 if (!pfrom->fInbound)
2087 // Advertise our address
2088 if (addrLocalHost.IsRoutable() && !fUseProxy)
2090 CAddress addr(addrLocalHost);
2091 addr.nTime = GetAdjustedTime();
2092 pfrom->PushAddress(addr);
2095 // Get recent addresses
2096 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2098 pfrom->PushMessage("getaddr");
2099 pfrom->fGetAddr = true;
2103 // Ask the first connected node for block updates
2104 static int nAskedForBlocks = 0;
2105 if (!pfrom->fClient &&
2106 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2107 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2110 pfrom->PushGetBlocks(pindexBest, uint256(0));
2114 CRITICAL_BLOCK(cs_mapAlerts)
2115 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2116 item.second.RelayTo(pfrom);
2118 pfrom->fSuccessfullyConnected = true;
2120 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2122 cPeerBlockCounts.input(pfrom->nStartingHeight);
2126 else if (pfrom->nVersion == 0)
2128 // Must have a version message before anything else
2129 pfrom->Misbehaving(1);
2134 else if (strCommand == "verack")
2136 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2140 else if (strCommand == "addr")
2142 vector<CAddress> vAddr;
2145 // Don't want addr from older versions unless seeding
2146 if (pfrom->nVersion < 209)
2148 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2150 if (vAddr.size() > 1000)
2152 pfrom->Misbehaving(20);
2153 return error("message addr size() = %d", vAddr.size());
2156 // Store the new addresses
2159 int64 nNow = GetAdjustedTime();
2160 int64 nSince = nNow - 10 * 60;
2161 BOOST_FOREACH(CAddress& addr, vAddr)
2165 // ignore IPv6 for now, since it isn't implemented anyway
2168 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2169 addr.nTime = nNow - 5 * 24 * 60 * 60;
2170 AddAddress(addr, 2 * 60 * 60, &addrDB);
2171 pfrom->AddAddressKnown(addr);
2172 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2174 // Relay to a limited number of other nodes
2175 CRITICAL_BLOCK(cs_vNodes)
2177 // Use deterministic randomness to send to the same nodes for 24 hours
2178 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2179 static uint256 hashSalt;
2181 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2182 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2183 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2184 multimap<uint256, CNode*> mapMix;
2185 BOOST_FOREACH(CNode* pnode, vNodes)
2187 if (pnode->nVersion < 31402)
2189 unsigned int nPointer;
2190 memcpy(&nPointer, &pnode, sizeof(nPointer));
2191 uint256 hashKey = hashRand ^ nPointer;
2192 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2193 mapMix.insert(make_pair(hashKey, pnode));
2195 int nRelayNodes = 2;
2196 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2197 ((*mi).second)->PushAddress(addr);
2201 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2202 if (vAddr.size() < 1000)
2203 pfrom->fGetAddr = false;
2207 else if (strCommand == "inv")
2211 if (vInv.size() > 50000)
2213 pfrom->Misbehaving(20);
2214 return error("message inv size() = %d", vInv.size());
2217 // find last block in inv vector
2218 unsigned int nLastBlock = (unsigned int)(-1);
2219 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2220 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK)
2221 nLastBlock = vInv.size() - 1 - nInv;
2224 for (int nInv = 0; nInv < vInv.size(); nInv++)
2226 const CInv &inv = vInv[nInv];
2230 pfrom->AddInventoryKnown(inv);
2232 bool fAlreadyHave = AlreadyHave(txdb, inv);
2234 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2236 // Always request the last block in an inv bundle (even if we already have it), as it is the
2237 // trigger for the other side to send further invs. If we are stuck on a (very long) side chain,
2238 // this is necessary to connect earlier received orphan blocks to the chain again.
2239 if (fAlreadyHave && nInv == nLastBlock) {
2240 // bypass mapAskFor, and send request directly; it must go through.
2241 std::vector<CInv> vGetData(1,inv);
2242 pfrom->PushMessage("getdata", vGetData);
2247 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2248 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2250 // Track requests for our stuff
2251 Inventory(inv.hash);
2256 else if (strCommand == "getdata")
2260 if (vInv.size() > 50000)
2262 pfrom->Misbehaving(20);
2263 return error("message getdata size() = %d", vInv.size());
2266 BOOST_FOREACH(const CInv& inv, vInv)
2270 printf("received getdata for: %s\n", inv.ToString().c_str());
2272 if (inv.type == MSG_BLOCK)
2274 // Send block from disk
2275 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2276 if (mi != mapBlockIndex.end())
2279 block.ReadFromDisk((*mi).second);
2280 pfrom->PushMessage("block", block);
2282 // Trigger them to send a getblocks request for the next batch of inventory
2283 if (inv.hash == pfrom->hashContinue)
2285 // Bypass PushInventory, this must send even if redundant,
2286 // and we want it right after the last block so they don't
2287 // wait for other stuff first.
2289 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2290 pfrom->PushMessage("inv", vInv);
2291 pfrom->hashContinue = 0;
2295 else if (inv.IsKnownType())
2297 // Send stream from relay memory
2298 CRITICAL_BLOCK(cs_mapRelay)
2300 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2301 if (mi != mapRelay.end())
2302 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2306 // Track requests for our stuff
2307 Inventory(inv.hash);
2312 else if (strCommand == "getblocks")
2314 CBlockLocator locator;
2316 vRecv >> locator >> hashStop;
2318 // Find the last block the caller has in the main chain
2319 CBlockIndex* pindex = locator.GetBlockIndex();
2321 // Send the rest of the chain
2323 pindex = pindex->pnext;
2324 int nLimit = 500 + locator.GetDistanceBack();
2325 unsigned int nBytes = 0;
2326 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2327 for (; pindex; pindex = pindex->pnext)
2329 if (pindex->GetBlockHash() == hashStop)
2331 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2334 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2336 block.ReadFromDisk(pindex, true);
2337 nBytes += block.GetSerializeSize(SER_NETWORK);
2338 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2340 // When this block is requested, we'll send an inv that'll make them
2341 // getblocks the next batch of inventory.
2342 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2343 pfrom->hashContinue = pindex->GetBlockHash();
2350 else if (strCommand == "getheaders")
2352 CBlockLocator locator;
2354 vRecv >> locator >> hashStop;
2356 CBlockIndex* pindex = NULL;
2357 if (locator.IsNull())
2359 // If locator is null, return the hashStop block
2360 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2361 if (mi == mapBlockIndex.end())
2363 pindex = (*mi).second;
2367 // Find the last block the caller has in the main chain
2368 pindex = locator.GetBlockIndex();
2370 pindex = pindex->pnext;
2373 vector<CBlock> vHeaders;
2374 int nLimit = 2000 + locator.GetDistanceBack();
2375 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2376 for (; pindex; pindex = pindex->pnext)
2378 vHeaders.push_back(pindex->GetBlockHeader());
2379 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2382 pfrom->PushMessage("headers", vHeaders);
2386 else if (strCommand == "tx")
2388 vector<uint256> vWorkQueue;
2389 CDataStream vMsg(vRecv);
2393 CInv inv(MSG_TX, tx.GetHash());
2394 pfrom->AddInventoryKnown(inv);
2396 bool fMissingInputs = false;
2397 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2399 SyncWithWallets(tx, NULL, true);
2400 RelayMessage(inv, vMsg);
2401 mapAlreadyAskedFor.erase(inv);
2402 vWorkQueue.push_back(inv.hash);
2404 // Recursively process any orphan transactions that depended on this one
2405 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2407 uint256 hashPrev = vWorkQueue[i];
2408 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2409 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2412 const CDataStream& vMsg = *((*mi).second);
2414 CDataStream(vMsg) >> tx;
2415 CInv inv(MSG_TX, tx.GetHash());
2417 if (tx.AcceptToMemoryPool(true))
2419 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2420 SyncWithWallets(tx, NULL, true);
2421 RelayMessage(inv, vMsg);
2422 mapAlreadyAskedFor.erase(inv);
2423 vWorkQueue.push_back(inv.hash);
2428 BOOST_FOREACH(uint256 hash, vWorkQueue)
2429 EraseOrphanTx(hash);
2431 else if (fMissingInputs)
2433 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2436 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
2437 int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
2439 printf("mapOrphan overflow, removed %d tx\n", nEvicted);
2441 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2445 else if (strCommand == "block")
2450 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2453 CInv inv(MSG_BLOCK, block.GetHash());
2454 pfrom->AddInventoryKnown(inv);
2456 if (ProcessBlock(pfrom, &block))
2457 mapAlreadyAskedFor.erase(inv);
2458 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2462 else if (strCommand == "getaddr")
2464 // Nodes rebroadcast an addr every 24 hours
2465 pfrom->vAddrToSend.clear();
2466 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2467 CRITICAL_BLOCK(cs_mapAddresses)
2469 unsigned int nCount = 0;
2470 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2472 const CAddress& addr = item.second;
2473 if (addr.nTime > nSince)
2476 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2478 const CAddress& addr = item.second;
2479 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2480 pfrom->PushAddress(addr);
2486 else if (strCommand == "checkorder")
2491 if (!GetBoolArg("-allowreceivebyip"))
2493 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2500 /// we have a chance to check the order here
2502 // Keep giving the same key to the same ip until they use it
2503 if (!mapReuseKey.count(pfrom->addr.ip))
2504 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2506 // Send back approval of order and pubkey to use
2507 CScript scriptPubKey;
2508 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2509 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2513 else if (strCommand == "reply")
2518 CRequestTracker tracker;
2519 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2521 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2522 if (mi != pfrom->mapRequests.end())
2524 tracker = (*mi).second;
2525 pfrom->mapRequests.erase(mi);
2528 if (!tracker.IsNull())
2529 tracker.fn(tracker.param1, vRecv);
2533 else if (strCommand == "ping")
2538 else if (strCommand == "alert")
2543 if (alert.ProcessAlert())
2546 pfrom->setKnown.insert(alert.GetHash());
2547 CRITICAL_BLOCK(cs_vNodes)
2548 BOOST_FOREACH(CNode* pnode, vNodes)
2549 alert.RelayTo(pnode);
2556 // Ignore unknown commands for extensibility
2560 // Update the last seen time for this node's address
2561 if (pfrom->fNetworkNode)
2562 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2563 AddressCurrentlyConnected(pfrom->addr);
2569 bool ProcessMessages(CNode* pfrom)
2571 CDataStream& vRecv = pfrom->vRecv;
2575 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2579 // (4) message start
2588 // Scan for message start
2589 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2590 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2591 if (vRecv.end() - pstart < nHeaderSize)
2593 if (vRecv.size() > nHeaderSize)
2595 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2596 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2600 if (pstart - vRecv.begin() > 0)
2601 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2602 vRecv.erase(vRecv.begin(), pstart);
2605 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2610 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2613 string strCommand = hdr.GetCommand();
2616 unsigned int nMessageSize = hdr.nMessageSize;
2617 if (nMessageSize > MAX_SIZE)
2619 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2622 if (nMessageSize > vRecv.size())
2624 // Rewind and wait for rest of message
2625 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2630 if (vRecv.GetVersion() >= 209)
2632 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2633 unsigned int nChecksum = 0;
2634 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2635 if (nChecksum != hdr.nChecksum)
2637 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2638 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2643 // Copy message to its own buffer
2644 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2645 vRecv.ignore(nMessageSize);
2651 CRITICAL_BLOCK(cs_main)
2652 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2656 catch (std::ios_base::failure& e)
2658 if (strstr(e.what(), "end of data"))
2660 // Allow exceptions from underlength message on vRecv
2661 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());
2663 else if (strstr(e.what(), "size too large"))
2665 // Allow exceptions from overlong size
2666 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2670 PrintExceptionContinue(&e, "ProcessMessage()");
2673 catch (std::exception& e) {
2674 PrintExceptionContinue(&e, "ProcessMessage()");
2676 PrintExceptionContinue(NULL, "ProcessMessage()");
2680 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2688 bool SendMessages(CNode* pto, bool fSendTrickle)
2690 TRY_CRITICAL_BLOCK(cs_main)
2692 // Don't send anything until we get their version message
2693 if (pto->nVersion == 0)
2697 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2698 pto->PushMessage("ping");
2700 // Resend wallet transactions that haven't gotten in a block yet
2701 ResendWalletTransactions();
2703 // Address refresh broadcast
2704 static int64 nLastRebroadcast;
2705 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2707 nLastRebroadcast = GetTime();
2708 CRITICAL_BLOCK(cs_vNodes)
2710 BOOST_FOREACH(CNode* pnode, vNodes)
2712 // Periodically clear setAddrKnown to allow refresh broadcasts
2713 pnode->setAddrKnown.clear();
2715 // Rebroadcast our address
2716 if (addrLocalHost.IsRoutable() && !fUseProxy)
2718 CAddress addr(addrLocalHost);
2719 addr.nTime = GetAdjustedTime();
2720 pnode->PushAddress(addr);
2726 // Clear out old addresses periodically so it's not too much work at once
2727 static int64 nLastClear;
2728 if (nLastClear == 0)
2729 nLastClear = GetTime();
2730 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2732 nLastClear = GetTime();
2733 CRITICAL_BLOCK(cs_mapAddresses)
2736 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2737 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2738 mi != mapAddresses.end();)
2740 const CAddress& addr = (*mi).second;
2741 if (addr.nTime < nSince)
2743 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2745 addrdb.EraseAddress(addr);
2746 mapAddresses.erase(mi++);
2760 vector<CAddress> vAddr;
2761 vAddr.reserve(pto->vAddrToSend.size());
2762 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2764 // returns true if wasn't already contained in the set
2765 if (pto->setAddrKnown.insert(addr).second)
2767 vAddr.push_back(addr);
2768 // receiver rejects addr messages larger than 1000
2769 if (vAddr.size() >= 1000)
2771 pto->PushMessage("addr", vAddr);
2776 pto->vAddrToSend.clear();
2778 pto->PushMessage("addr", vAddr);
2783 // Message: inventory
2786 vector<CInv> vInvWait;
2787 CRITICAL_BLOCK(pto->cs_inventory)
2789 vInv.reserve(pto->vInventoryToSend.size());
2790 vInvWait.reserve(pto->vInventoryToSend.size());
2791 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2793 if (pto->setInventoryKnown.count(inv))
2796 // trickle out tx inv to protect privacy
2797 if (inv.type == MSG_TX && !fSendTrickle)
2799 // 1/4 of tx invs blast to all immediately
2800 static uint256 hashSalt;
2802 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2803 uint256 hashRand = inv.hash ^ hashSalt;
2804 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2805 bool fTrickleWait = ((hashRand & 3) != 0);
2807 // always trickle our own transactions
2811 if (GetTransaction(inv.hash, wtx))
2813 fTrickleWait = true;
2818 vInvWait.push_back(inv);
2823 // returns true if wasn't already contained in the set
2824 if (pto->setInventoryKnown.insert(inv).second)
2826 vInv.push_back(inv);
2827 if (vInv.size() >= 1000)
2829 pto->PushMessage("inv", vInv);
2834 pto->vInventoryToSend = vInvWait;
2837 pto->PushMessage("inv", vInv);
2843 vector<CInv> vGetData;
2844 int64 nNow = GetTime() * 1000000;
2846 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2848 const CInv& inv = (*pto->mapAskFor.begin()).second;
2849 if (!AlreadyHave(txdb, inv))
2851 printf("sending getdata: %s\n", inv.ToString().c_str());
2852 vGetData.push_back(inv);
2853 if (vGetData.size() >= 1000)
2855 pto->PushMessage("getdata", vGetData);
2859 mapAlreadyAskedFor[inv] = nNow;
2860 pto->mapAskFor.erase(pto->mapAskFor.begin());
2862 if (!vGetData.empty())
2863 pto->PushMessage("getdata", vGetData);
2882 //////////////////////////////////////////////////////////////////////////////
2887 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2889 unsigned char* pdata = (unsigned char*)pbuffer;
2890 unsigned int blocks = 1 + ((len + 8) / 64);
2891 unsigned char* pend = pdata + 64 * blocks;
2892 memset(pdata + len, 0, 64 * blocks - len);
2894 unsigned int bits = len * 8;
2895 pend[-1] = (bits >> 0) & 0xff;
2896 pend[-2] = (bits >> 8) & 0xff;
2897 pend[-3] = (bits >> 16) & 0xff;
2898 pend[-4] = (bits >> 24) & 0xff;
2902 static const unsigned int pSHA256InitState[8] =
2903 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2905 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2908 unsigned char data[64];
2912 for (int i = 0; i < 16; i++)
2913 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2915 for (int i = 0; i < 8; i++)
2916 ctx.h[i] = ((uint32_t*)pinit)[i];
2918 SHA256_Update(&ctx, data, sizeof(data));
2919 for (int i = 0; i < 8; i++)
2920 ((uint32_t*)pstate)[i] = ctx.h[i];
2924 // ScanHash scans nonces looking for a hash with at least some zero bits.
2925 // It operates on big endian data. Caller does the byte reversing.
2926 // All input buffers are 16-byte aligned. nNonce is usually preserved
2927 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2928 // the block is rebuilt and nNonce starts over at zero.
2930 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2932 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2936 // Hash pdata using pmidstate as the starting state into
2937 // preformatted buffer phash1, then hash phash1 into phash
2939 SHA256Transform(phash1, pdata, pmidstate);
2940 SHA256Transform(phash, phash1, pSHA256InitState);
2942 // Return the nonce if the hash has at least some zero bits,
2943 // caller will check if it has enough to reach the target
2944 if (((unsigned short*)phash)[14] == 0)
2947 // If nothing found after trying for a while, return -1
2948 if ((nNonce & 0xffff) == 0)
2950 nHashesDone = 0xffff+1;
2956 // Some explaining would be appreciated
2961 set<uint256> setDependsOn;
2964 COrphan(CTransaction* ptxIn)
2972 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2973 BOOST_FOREACH(uint256 hash, setDependsOn)
2974 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2979 CBlock* CreateNewBlock(CReserveKey& reservekey)
2981 CBlockIndex* pindexPrev = pindexBest;
2984 auto_ptr<CBlock> pblock(new CBlock());
2988 // Create coinbase tx
2990 txNew.vin.resize(1);
2991 txNew.vin[0].prevout.SetNull();
2992 txNew.vout.resize(1);
2993 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2995 // Add our coinbase tx as first transaction
2996 pblock->vtx.push_back(txNew);
2998 // Collect memory pool transactions into the block
3000 CRITICAL_BLOCK(cs_main)
3001 CRITICAL_BLOCK(cs_mapTransactions)
3005 // Priority order to process transactions
3006 list<COrphan> vOrphan; // list memory doesn't move
3007 map<uint256, vector<COrphan*> > mapDependers;
3008 multimap<double, CTransaction*> mapPriority;
3009 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3011 CTransaction& tx = (*mi).second;
3012 if (tx.IsCoinBase() || !tx.IsFinal())
3015 COrphan* porphan = NULL;
3016 double dPriority = 0;
3017 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3019 // Read prev transaction
3020 CTransaction txPrev;
3022 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3024 // Has to wait for dependencies
3027 // Use list for automatic deletion
3028 vOrphan.push_back(COrphan(&tx));
3029 porphan = &vOrphan.back();
3031 mapDependers[txin.prevout.hash].push_back(porphan);
3032 porphan->setDependsOn.insert(txin.prevout.hash);
3035 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3037 // Read block header
3038 int nConf = txindex.GetDepthInMainChain();
3040 dPriority += (double)nValueIn * nConf;
3042 if (fDebug && GetBoolArg("-printpriority"))
3043 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3046 // Priority is sum(valuein * age) / txsize
3047 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3050 porphan->dPriority = dPriority;
3052 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3054 if (fDebug && GetBoolArg("-printpriority"))
3056 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3063 // Collect transactions into block
3064 map<uint256, CTxIndex> mapTestPool;
3065 uint64 nBlockSize = 1000;
3066 int nBlockSigOps = 100;
3067 while (!mapPriority.empty())
3069 // Take highest priority transaction off priority queue
3070 double dPriority = -(*mapPriority.begin()).first;
3071 CTransaction& tx = *(*mapPriority.begin()).second;
3072 mapPriority.erase(mapPriority.begin());
3075 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3076 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3079 // Legacy limits on sigOps:
3080 int nTxSigOps = tx.GetSigOpCount();
3081 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3084 // Transaction fee required depends on block size
3085 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
3086 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3088 // Connecting shouldn't fail due to dependency on other memory pool transactions
3089 // because we're already processing them in order of dependency
3090 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3092 MapPrevTx mapInputs;
3093 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3096 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3097 if (nTxFees < nMinFee)
3100 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3101 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3104 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3106 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3107 swap(mapTestPool, mapTestPoolTmp);
3110 pblock->vtx.push_back(tx);
3111 nBlockSize += nTxSize;
3112 nBlockSigOps += nTxSigOps;
3115 // Add transactions that depend on this one to the priority queue
3116 uint256 hash = tx.GetHash();
3117 if (mapDependers.count(hash))
3119 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3121 if (!porphan->setDependsOn.empty())
3123 porphan->setDependsOn.erase(hash);
3124 if (porphan->setDependsOn.empty())
3125 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3131 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3134 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3135 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3136 pblock->UpdateTime(pindexPrev);
3137 pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
3140 return pblock.release();
3144 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3146 // Update nExtraNonce
3147 static uint256 hashPrevBlock;
3148 if (hashPrevBlock != pblock->hashPrevBlock)
3151 hashPrevBlock = pblock->hashPrevBlock;
3154 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3155 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3159 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3162 // Prebuild hash buffers
3169 uint256 hashPrevBlock;
3170 uint256 hashMerkleRoot;
3173 unsigned int nNonce;
3176 unsigned char pchPadding0[64];
3178 unsigned char pchPadding1[64];
3181 memset(&tmp, 0, sizeof(tmp));
3183 tmp.block.nVersion = pblock->nVersion;
3184 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3185 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3186 tmp.block.nTime = pblock->nTime;
3187 tmp.block.nBits = pblock->nBits;
3188 tmp.block.nNonce = pblock->nNonce;
3190 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3191 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3193 // Byte swap all the input buffer
3194 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3195 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3197 // Precalc the first half of the first hash, which stays constant
3198 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3200 memcpy(pdata, &tmp.block, 128);
3201 memcpy(phash1, &tmp.hash1, 64);
3205 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3207 uint256 hash = pblock->GetHash();
3208 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3210 if (hash > hashTarget)
3214 printf("BitcoinMiner:\n");
3215 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3217 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3218 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3221 CRITICAL_BLOCK(cs_main)
3223 if (pblock->hashPrevBlock != hashBestChain)
3224 return error("BitcoinMiner : generated block is stale");
3226 // Remove key from key pool
3227 reservekey.KeepKey();
3229 // Track how many getdata requests this block gets
3230 CRITICAL_BLOCK(wallet.cs_wallet)
3231 wallet.mapRequestCount[pblock->GetHash()] = 0;
3233 // Process this block the same as if we had received it from another node
3234 if (!ProcessBlock(NULL, pblock))
3235 return error("BitcoinMiner : ProcessBlock, block not accepted");
3241 void static ThreadBitcoinMiner(void* parg);
3243 void static BitcoinMiner(CWallet *pwallet)
3245 printf("BitcoinMiner started\n");
3246 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3248 // Each thread has its own key and counter
3249 CReserveKey reservekey(pwallet);
3250 unsigned int nExtraNonce = 0;
3252 while (fGenerateBitcoins)
3254 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3258 while (vNodes.empty() || IsInitialBlockDownload())
3263 if (!fGenerateBitcoins)
3271 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3272 CBlockIndex* pindexPrev = pindexBest;
3274 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3277 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3279 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3283 // Prebuild hash buffers
3285 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3286 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3287 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3289 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3291 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3292 unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
3293 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3299 int64 nStart = GetTime();
3300 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3302 uint256& hash = *alignup<16>(hashbuf);
3305 unsigned int nHashesDone = 0;
3306 unsigned int nNonceFound;
3309 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3310 (char*)&hash, nHashesDone);
3312 // Check if something found
3313 if (nNonceFound != -1)
3315 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3316 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3318 if (hash <= hashTarget)
3321 pblock->nNonce = ByteReverse(nNonceFound);
3322 assert(hash == pblock->GetHash());
3324 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3325 CheckWork(pblock.get(), *pwalletMain, reservekey);
3326 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3332 static int64 nHashCounter;
3333 if (nHPSTimerStart == 0)
3335 nHPSTimerStart = GetTimeMillis();
3339 nHashCounter += nHashesDone;
3340 if (GetTimeMillis() - nHPSTimerStart > 4000)
3342 static CCriticalSection cs;
3345 if (GetTimeMillis() - nHPSTimerStart > 4000)
3347 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3348 nHPSTimerStart = GetTimeMillis();
3350 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3351 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3352 static int64 nLogTime;
3353 if (GetTime() - nLogTime > 30 * 60)
3355 nLogTime = GetTime();
3356 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3357 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3363 // Check for stop or if block needs to be rebuilt
3366 if (!fGenerateBitcoins)
3368 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3372 if (nBlockNonce >= 0xffff0000)
3374 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3376 if (pindexPrev != pindexBest)
3379 // Update nTime every few seconds
3380 pblock->UpdateTime(pindexPrev);
3381 nBlockTime = ByteReverse(pblock->nTime);
3384 // Changing pblock->nTime can change work required on testnet:
3385 nBlockBits = ByteReverse(pblock->nBits);
3386 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3392 void static ThreadBitcoinMiner(void* parg)
3394 CWallet* pwallet = (CWallet*)parg;
3397 vnThreadsRunning[3]++;
3398 BitcoinMiner(pwallet);
3399 vnThreadsRunning[3]--;
3401 catch (std::exception& e) {
3402 vnThreadsRunning[3]--;
3403 PrintException(&e, "ThreadBitcoinMiner()");
3405 vnThreadsRunning[3]--;
3406 PrintException(NULL, "ThreadBitcoinMiner()");
3408 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3410 if (vnThreadsRunning[3] == 0)
3412 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3416 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3418 if (fGenerateBitcoins != fGenerate)
3420 fGenerateBitcoins = fGenerate;
3421 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3424 if (fGenerateBitcoins)
3426 int nProcessors = boost::thread::hardware_concurrency();
3427 printf("%d processors\n", nProcessors);
3428 if (nProcessors < 1)
3430 if (fLimitProcessors && nProcessors > nLimitProcessors)
3431 nProcessors = nLimitProcessors;
3432 int nAddThreads = nProcessors - vnThreadsRunning[3];
3433 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3434 for (int i = 0; i < nAddThreads; i++)
3436 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3437 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");