1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
9 #include "checkpoints.h"
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
17 using namespace boost;
23 // Name of client reported in the 'version' message. Report the same name
24 // for both bitcoind and bitcoin-qt, to make it harder for attackers to
25 // target servers or GUI users specifically.
26 const std::string CLIENT_NAME("bitcoin-qt");
28 CCriticalSection cs_setpwalletRegistered;
29 set<CWallet*> setpwalletRegistered;
31 CCriticalSection cs_main;
33 static map<uint256, CTransaction> mapTransactions;
34 CCriticalSection cs_mapTransactions;
35 unsigned int nTransactionsUpdated = 0;
36 map<COutPoint, CInPoint> mapNextTx;
38 map<uint256, CBlockIndex*> mapBlockIndex;
39 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
40 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
41 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
42 CBlockIndex* pindexGenesisBlock = NULL;
44 CBigNum bnBestChainWork = 0;
45 CBigNum bnBestInvalidWork = 0;
46 uint256 hashBestChain = 0;
47 CBlockIndex* pindexBest = NULL;
48 int64_t nTimeBestReceived = 0;
50 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
52 map<uint256, CBlock*> mapOrphanBlocks;
53 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
55 map<uint256, CDataStream*> mapOrphanTransactions;
56 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
60 int64_t nHPSTimerStart;
63 int fGenerateBitcoins = false;
64 int64_t nTransactionFee = 0;
65 int fLimitProcessors = false;
66 int nLimitProcessors = 1;
67 int fMinimizeToTray = true;
68 int fMinimizeOnClose = true;
76 //////////////////////////////////////////////////////////////////////////////
78 // dispatching functions
81 // These functions dispatch to one or all registered wallets
84 void RegisterWallet(CWallet* pwalletIn)
86 CRITICAL_BLOCK(cs_setpwalletRegistered)
88 setpwalletRegistered.insert(pwalletIn);
92 void UnregisterWallet(CWallet* pwalletIn)
94 CRITICAL_BLOCK(cs_setpwalletRegistered)
96 setpwalletRegistered.erase(pwalletIn);
100 // check whether the passed transaction is from us
101 bool static IsFromMe(CTransaction& tx)
103 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
104 if (pwallet->IsFromMe(tx))
109 // get the wallet transaction with the given hash (if it exists)
110 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
112 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
113 if (pwallet->GetTransaction(hashTx,wtx))
118 // erases transaction with the given hash from all wallets
119 void static EraseFromWallets(uint256 hash)
121 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
122 pwallet->EraseFromWallet(hash);
125 // make sure all wallets know about the given transaction, in the given block
126 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
132 // notify wallets about a new best chain
133 void static SetBestChain(const CBlockLocator& loc)
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 pwallet->SetBestChain(loc);
139 // notify wallets about an updated transaction
140 void static UpdatedTransaction(const uint256& hashTx)
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->UpdatedTransaction(hashTx);
147 void static PrintWallets(const CBlock& block)
149 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
150 pwallet->PrintWallet(block);
153 // notify wallets about an incoming inventory (for request counts)
154 void static Inventory(const uint256& hash)
156 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
157 pwallet->Inventory(hash);
160 // ask wallets to resend their transactions
161 void static ResendWalletTransactions()
163 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
164 pwallet->ResendWalletTransactions();
173 //////////////////////////////////////////////////////////////////////////////
175 // mapOrphanTransactions
178 void static AddOrphanTx(const CDataStream& vMsg)
181 CDataStream(vMsg) >> tx;
182 uint256 hash = tx.GetHash();
183 if (mapOrphanTransactions.count(hash))
185 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
186 BOOST_FOREACH(const CTxIn& txin, tx.vin)
187 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
190 void static EraseOrphanTx(uint256 hash)
192 if (!mapOrphanTransactions.count(hash))
194 const CDataStream* pvMsg = mapOrphanTransactions[hash];
196 CDataStream(*pvMsg) >> tx;
197 BOOST_FOREACH(const CTxIn& txin, tx.vin)
199 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
200 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
202 if ((*mi).second == pvMsg)
203 mapOrphanTransactionsByPrev.erase(mi++);
209 mapOrphanTransactions.erase(hash);
219 //////////////////////////////////////////////////////////////////////////////
221 // CTransaction and CTxIndex
224 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
227 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
229 if (!ReadFromDisk(txindexRet.pos))
231 if (prevout.n >= vout.size())
239 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
242 return ReadFromDisk(txdb, prevout, txindex);
245 bool CTransaction::ReadFromDisk(COutPoint prevout)
249 return ReadFromDisk(txdb, prevout, txindex);
252 bool CTransaction::IsStandard() const
254 BOOST_FOREACH(const CTxIn& txin, vin)
256 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
257 // in an OP_EVAL, which is 3 ~80-byte signatures, 3
258 // ~65-byte public keys, plus a few script ops.
259 if (txin.scriptSig.size() > 500)
260 return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
261 if (!txin.scriptSig.IsPushOnly())
262 return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
264 BOOST_FOREACH(const CTxOut& txout, vout)
265 if (!::IsStandard(txout.scriptPubKey))
266 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
271 // Check transaction inputs, and make sure any
272 // OP_EVAL transactions are evaluating IsStandard scripts
274 // Why bother? To avoid denial-of-service attacks; an attacker
275 // can submit a standard DUP HASH... OP_EVAL transaction,
276 // which will get accepted into blocks. The script being
277 // EVAL'ed can be anything; an attacker could use a very
278 // expensive-to-check-upon-redemption script like:
279 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
281 bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
284 return true; // Allow non-standard on testnet
286 for (int i = 0; i < vin.size(); i++)
288 COutPoint prevout = vin[i].prevout;
289 assert(mapInputs.count(prevout.hash) > 0);
290 CTransaction& txPrev = mapInputs[prevout.hash].second;
292 vector<vector<unsigned char> > vSolutions;
293 txnouttype whichType;
294 // get the scriptPubKey corresponding to this input:
295 CScript& prevScript = txPrev.vout[prevout.n].scriptPubKey;
296 if (!Solver(prevScript, whichType, vSolutions))
297 return error("nonstandard txin (spending nonstandard txout %s)", prevScript.ToString().c_str());
298 if (whichType == TX_SCRIPTHASH)
300 vector<vector<unsigned char> > stack;
302 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, true, nUnused))
304 CScript subscript(stack.back().begin(), stack.back().end());
305 if (!::IsStandard(subscript))
306 return error("nonstandard txin (nonstandard OP_EVAL subscript %s)", subscript.ToString().c_str());
315 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
327 // Load the block this tx is in
329 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
331 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
336 // Update the tx's hashBlock
337 hashBlock = pblock->GetHash();
339 // Locate the transaction
340 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
341 if (pblock->vtx[nIndex] == *(CTransaction*)this)
343 if (nIndex == pblock->vtx.size())
345 vMerkleBranch.clear();
347 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
351 // Fill in merkle branch
352 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
355 // Is the tx in a block that's in the main chain
356 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
357 if (mi == mapBlockIndex.end())
359 CBlockIndex* pindex = (*mi).second;
360 if (!pindex || !pindex->IsInMainChain())
363 return pindexBest->nHeight - pindex->nHeight + 1;
372 bool CTransaction::CheckTransaction() const
374 // Basic checks that don't depend on any context
376 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
378 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
380 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
381 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
383 // Check for negative or overflow output values
384 int64_t nValueOut = 0;
385 BOOST_FOREACH(const CTxOut& txout, vout)
387 if (txout.nValue < 0)
388 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
389 if (txout.nValue > MAX_MONEY)
390 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
391 nValueOut += txout.nValue;
392 if (!MoneyRange(nValueOut))
393 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
396 // Check for duplicate inputs
397 set<COutPoint> vInOutPoints;
398 BOOST_FOREACH(const CTxIn& txin, vin)
400 if (vInOutPoints.count(txin.prevout))
402 vInOutPoints.insert(txin.prevout);
407 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
408 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
412 BOOST_FOREACH(const CTxIn& txin, vin)
413 if (txin.prevout.IsNull())
414 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
420 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
423 *pfMissingInputs = false;
425 if (!CheckTransaction())
426 return error("AcceptToMemoryPool() : CheckTransaction failed");
428 // Coinbase is only valid in a block, not as a loose transaction
430 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
432 // To help v0.1.5 clients who would see it as a negative number
433 if ((int64_t)nLockTime > std::numeric_limits<int>::max())
434 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
436 // Rather not work on nonstandard transactions (unless -testnet)
437 if (!fTestNet && !IsStandard())
438 return error("AcceptToMemoryPool() : nonstandard transaction type");
440 // Do we already have it?
441 uint256 hash = GetHash();
442 CRITICAL_BLOCK(cs_mapTransactions)
443 if (mapTransactions.count(hash))
446 if (txdb.ContainsTx(hash))
449 // Check for conflicts with in-memory transactions
450 CTransaction* ptxOld = NULL;
451 for (int i = 0; i < vin.size(); i++)
453 COutPoint outpoint = vin[i].prevout;
454 if (mapNextTx.count(outpoint))
456 // Disable replacement feature for now
459 // Allow replacing with a newer version of the same transaction
462 ptxOld = mapNextTx[outpoint].ptx;
463 if (ptxOld->IsFinal())
465 if (!IsNewerThan(*ptxOld))
467 for (int i = 0; i < vin.size(); i++)
469 COutPoint outpoint = vin[i].prevout;
470 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
479 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
480 map<uint256, CTxIndex> mapUnused;
481 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
484 *pfMissingInputs = true;
485 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
488 // Check for non-standard OP_EVALs in inputs
489 if (!AreInputsStandard(mapInputs))
490 return error("AcceptToMemoryPool() : nonstandard transaction input");
492 // Check against previous transactions
495 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
498 *pfMissingInputs = true;
499 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
501 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
502 // attacks disallow transactions with more than one SigOp per 65 bytes.
503 // 65 bytes because that is the minimum size of an ECDSA signature
504 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
505 if (nSigOps > nSize / 65 || nSize < 100)
506 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
508 // Don't accept it if it can't get into a block
509 if (nFees < GetMinFee(1000, true, GMF_RELAY))
510 return error("AcceptToMemoryPool() : not enough fees");
512 // Continuously rate-limit free transactions
513 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
514 // be annoying or make other's transactions take longer to confirm.
515 if (nFees < MIN_RELAY_TX_FEE)
517 static CCriticalSection cs;
518 static double dFreeCount;
519 static int64_t nLastTime;
520 int64_t nNow = GetTime();
524 // Use an exponentially decaying ~10-minute window:
525 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
527 // -limitfreerelay unit is thousand-bytes-per-minute
528 // At default rate it would take over a month to fill 1GB
529 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
530 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
532 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
538 // Store transaction in memory
539 CRITICAL_BLOCK(cs_mapTransactions)
543 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
544 ptxOld->RemoveFromMemoryPool();
546 AddToMemoryPoolUnchecked();
549 ///// are we sure this is ok when loading transactions or restoring block txes
550 // If updated, erase old tx from wallet
552 EraseFromWallets(ptxOld->GetHash());
554 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
558 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
561 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
564 bool CTransaction::AddToMemoryPoolUnchecked()
566 // Add to memory pool without checking anything. Don't call this directly,
567 // call AcceptToMemoryPool to properly check the transaction first.
568 CRITICAL_BLOCK(cs_mapTransactions)
570 uint256 hash = GetHash();
571 mapTransactions[hash] = *this;
572 for (int i = 0; i < vin.size(); i++)
573 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
574 nTransactionsUpdated++;
580 bool CTransaction::RemoveFromMemoryPool()
582 // Remove transaction from memory pool
583 CRITICAL_BLOCK(cs_mapTransactions)
585 BOOST_FOREACH(const CTxIn& txin, vin)
586 mapNextTx.erase(txin.prevout);
587 mapTransactions.erase(GetHash());
588 nTransactionsUpdated++;
598 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
600 if (hashBlock == 0 || nIndex == -1)
603 // Find the block it claims to be in
604 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
605 if (mi == mapBlockIndex.end())
607 CBlockIndex* pindex = (*mi).second;
608 if (!pindex || !pindex->IsInMainChain())
611 // Make sure the merkle branch connects to this block
612 if (!fMerkleVerified)
614 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
616 fMerkleVerified = true;
620 return pindexBest->nHeight - pindex->nHeight + 1;
624 int CMerkleTx::GetBlocksToMaturity() const
628 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
632 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
636 if (!IsInMainChain() && !ClientConnectInputs())
638 return CTransaction::AcceptToMemoryPool(txdb, false);
642 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
646 bool CMerkleTx::AcceptToMemoryPool()
649 return AcceptToMemoryPool(txdb);
654 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
656 CRITICAL_BLOCK(cs_mapTransactions)
658 // Add previous supporting transactions first
659 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
661 if (!tx.IsCoinBase())
663 uint256 hash = tx.GetHash();
664 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
665 tx.AcceptToMemoryPool(txdb, fCheckInputs);
668 return AcceptToMemoryPool(txdb, fCheckInputs);
673 bool CWalletTx::AcceptWalletTransaction()
676 return AcceptWalletTransaction(txdb);
679 int CTxIndex::GetDepthInMainChain() const
683 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
685 // Find the block in the index
686 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
687 if (mi == mapBlockIndex.end())
689 CBlockIndex* pindex = (*mi).second;
690 if (!pindex || !pindex->IsInMainChain())
692 return 1 + nBestHeight - pindex->nHeight;
704 //////////////////////////////////////////////////////////////////////////////
706 // CBlock and CBlockIndex
709 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
711 if (!fReadTransactions)
713 *this = pindex->GetBlockHeader();
716 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
718 if (GetHash() != pindex->GetBlockHash())
719 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
723 uint256 static GetOrphanRoot(const CBlock* pblock)
725 // Work back to the first block in the orphan chain
726 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
727 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
728 return pblock->GetHash();
731 int64_t static GetBlockValue(int nHeight, int64_t nFees)
733 int64_t nSubsidy = 50 * COIN;
735 // Subsidy is cut in half every 4 years
736 nSubsidy >>= (nHeight / 210000);
738 return nSubsidy + nFees;
741 static const int64_t nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
742 static const int64_t nTargetSpacing = 10 * 60;
743 static const int64_t nInterval = nTargetTimespan / nTargetSpacing;
746 // minimum amount of work that could possibly be required nTime after
747 // minimum work required was nBase
749 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
752 bnResult.SetCompact(nBase);
753 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
755 // Maximum 400% adjustment...
757 // ... in best-case exactly 4-times-normal target time
758 nTime -= nTargetTimespan*4;
760 if (bnResult > bnProofOfWorkLimit)
761 bnResult = bnProofOfWorkLimit;
762 return bnResult.GetCompact();
765 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
769 if (pindexLast == NULL)
770 return bnProofOfWorkLimit.GetCompact();
772 // Only change once per interval
773 if ((pindexLast->nHeight+1) % nInterval != 0)
774 return pindexLast->nBits;
776 // Go back by what we want to be 14 days worth of blocks
777 const CBlockIndex* pindexFirst = pindexLast;
778 for (int i = 0; pindexFirst && i < nInterval-1; i++)
779 pindexFirst = pindexFirst->pprev;
782 // Limit adjustment step
783 int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
784 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
785 if (nActualTimespan < nTargetTimespan/4)
786 nActualTimespan = nTargetTimespan/4;
787 if (nActualTimespan > nTargetTimespan*4)
788 nActualTimespan = nTargetTimespan*4;
792 bnNew.SetCompact(pindexLast->nBits);
793 bnNew *= nActualTimespan;
794 bnNew /= nTargetTimespan;
796 if (bnNew > bnProofOfWorkLimit)
797 bnNew = bnProofOfWorkLimit;
800 printf("GetNextWorkRequired RETARGET\n");
801 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
802 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
803 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
805 return bnNew.GetCompact();
808 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
811 bnTarget.SetCompact(nBits);
814 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
815 return error("CheckProofOfWork() : nBits below minimum work");
817 // Check proof of work matches claimed amount
818 if (hash > bnTarget.getuint256())
819 return error("CheckProofOfWork() : hash doesn't match nBits");
824 // Return maximum amount of blocks that other nodes claim to have
825 int GetNumBlocksOfPeers()
827 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
830 bool IsInitialBlockDownload()
832 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
834 static int64_t nLastUpdate;
835 static CBlockIndex* pindexLastBest;
836 if (pindexBest != pindexLastBest)
838 pindexLastBest = pindexBest;
839 nLastUpdate = GetTime();
841 return (GetTime() - nLastUpdate < 10 &&
842 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
845 void static InvalidChainFound(CBlockIndex* pindexNew)
847 if (pindexNew->bnChainWork > bnBestInvalidWork)
849 bnBestInvalidWork = pindexNew->bnChainWork;
850 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
853 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());
854 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
855 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
856 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
869 bool CTransaction::DisconnectInputs(CTxDB& txdb)
871 // Relinquish previous transactions' spent pointers
874 BOOST_FOREACH(const CTxIn& txin, vin)
876 COutPoint prevout = txin.prevout;
878 // Get prev txindex from disk
880 if (!txdb.ReadTxIndex(prevout.hash, txindex))
881 return error("DisconnectInputs() : ReadTxIndex failed");
883 if (prevout.n >= txindex.vSpent.size())
884 return error("DisconnectInputs() : prevout.n out of range");
886 // Mark outpoint as not spent
887 txindex.vSpent[prevout.n].SetNull();
890 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
891 return error("DisconnectInputs() : UpdateTxIndex failed");
895 // Remove transaction from index
896 if (!txdb.EraseTxIndex(*this))
897 return error("DisconnectInputs() : EraseTxPos failed");
903 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
904 bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
907 return true; // Coinbase transactions have no inputs to fetch.
909 for (int i = 0; i < vin.size(); i++)
911 COutPoint prevout = vin[i].prevout;
912 if (inputsRet.count(prevout.hash))
913 continue; // Got it already
916 CTxIndex& txindex = inputsRet[prevout.hash].first;
918 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
920 // Get txindex from current proposed changes
921 txindex = mapTestPool.find(prevout.hash)->second;
925 // Read txindex from txdb
926 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
928 if (!fFound && (fBlock || fMiner))
929 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());
932 CTransaction& txPrev = inputsRet[prevout.hash].second;
933 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
935 // Get prev tx from single transactions in memory
936 CRITICAL_BLOCK(cs_mapTransactions)
938 if (!mapTransactions.count(prevout.hash))
939 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
940 txPrev = mapTransactions[prevout.hash];
943 txindex.vSpent.resize(txPrev.vout.size());
947 // Get prev tx from disk
948 if (!txPrev.ReadFromDisk(txindex.pos))
949 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
955 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
956 map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
957 CBlockIndex* pindexBlock, int64_t& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64_t nMinFee)
959 // Take over previous transactions' spent pointers
960 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
961 // fMiner is true when called from the internal bitcoin miner
962 // ... both are false when called from CTransaction::AcceptToMemoryPool
965 int64_t nValueIn = 0;
966 for (int i = 0; i < vin.size(); i++)
968 COutPoint prevout = vin[i].prevout;
969 assert(inputs.count(prevout.hash) > 0);
970 CTxIndex& txindex = inputs[prevout.hash].first;
971 CTransaction& txPrev = inputs[prevout.hash].second;
973 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
974 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()));
976 // If prev is coinbase, check that it's matured
977 if (txPrev.IsCoinBase())
978 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
979 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
980 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
982 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
983 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
984 // still computed and checked, and any change will be caught at the next checkpoint.
985 if (!(fBlock && IsInitialBlockDownload()))
987 bool fStrictOpEval = true;
988 // This code should be removed when OP_EVAL has
989 // a majority of hashing power on the network.
992 // To avoid being on the short end of a block-chain split,
993 // interpret OP_EVAL as a NO_OP until blocks with timestamps
995 int64_t nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
996 fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
998 // if !fBlock, then always be strict-- don't accept
999 // invalid-under-new-rules OP_EVAL transactions into
1000 // our memory pool (don't relay them, don't include them
1001 // in blocks we mine).
1004 if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
1005 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1008 // Check for conflicts (double-spend)
1009 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1010 // for an attacker to attempt to split the network.
1011 if (!txindex.vSpent[prevout.n].IsNull())
1012 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());
1014 // Check for negative or overflow input values
1015 nValueIn += txPrev.vout[prevout.n].nValue;
1016 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1017 return DoS(100, error("ConnectInputs() : txin values out of range"));
1019 // Mark outpoints as spent
1020 txindex.vSpent[prevout.n] = posThisTx;
1023 if (fBlock || fMiner)
1025 mapTestPool[prevout.hash] = txindex;
1029 if (nValueIn < GetValueOut())
1030 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1032 // Tally transaction fees
1033 int64_t nTxFee = nValueIn - GetValueOut();
1035 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1036 if (nTxFee < nMinFee)
1039 if (!MoneyRange(nFees))
1040 return DoS(100, error("ConnectInputs() : nFees out of range"));
1045 // Add transaction to changes
1046 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1050 // Add transaction to test pool
1051 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1058 bool CTransaction::ClientConnectInputs()
1063 // Take over previous transactions' spent pointers
1064 CRITICAL_BLOCK(cs_mapTransactions)
1066 int64_t nValueIn = 0;
1067 for (int i = 0; i < vin.size(); i++)
1069 // Get prev tx from single transactions in memory
1070 COutPoint prevout = vin[i].prevout;
1071 if (!mapTransactions.count(prevout.hash))
1073 CTransaction& txPrev = mapTransactions[prevout.hash];
1075 if (prevout.n >= txPrev.vout.size())
1080 if (!VerifySignature(txPrev, *this, i, nUnused, false))
1081 return error("ConnectInputs() : VerifySignature failed");
1083 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1084 ///// this has to go away now that posNext is gone
1085 // // Check for conflicts
1086 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1087 // return error("ConnectInputs() : prev tx already used");
1089 // // Flag outpoints as used
1090 // txPrev.vout[prevout.n].posNext = posThisTx;
1092 nValueIn += txPrev.vout[prevout.n].nValue;
1094 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1095 return error("ClientConnectInputs() : txin values out of range");
1097 if (GetValueOut() > nValueIn)
1107 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1109 // Disconnect in reverse order
1110 for (int i = vtx.size()-1; i >= 0; i--)
1111 if (!vtx[i].DisconnectInputs(txdb))
1114 // Update block index on disk without changing it in memory.
1115 // The memory index structure will be changed after the db commits.
1118 CDiskBlockIndex blockindexPrev(pindex->pprev);
1119 blockindexPrev.hashNext = 0;
1120 if (!txdb.WriteBlockIndex(blockindexPrev))
1121 return error("DisconnectBlock() : WriteBlockIndex failed");
1127 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1129 // Check it again in case a previous version let a bad block in
1133 //// issue here: it doesn't know the version
1134 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1136 map<uint256, CTxIndex> mapQueuedChanges;
1139 BOOST_FOREACH(CTransaction& tx, vtx)
1141 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1142 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1144 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1145 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1147 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1149 if (nSigOps > MAX_BLOCK_SIGOPS)
1150 return DoS(100, error("ConnectBlock() : too many sigops"));
1153 // Write queued txindex changes
1154 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1156 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1157 return error("ConnectBlock() : UpdateTxIndex failed");
1160 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1163 // Update block index on disk without changing it in memory.
1164 // The memory index structure will be changed after the db commits.
1167 CDiskBlockIndex blockindexPrev(pindex->pprev);
1168 blockindexPrev.hashNext = pindex->GetBlockHash();
1169 if (!txdb.WriteBlockIndex(blockindexPrev))
1170 return error("ConnectBlock() : WriteBlockIndex failed");
1173 // Watch for transactions paying to me
1174 BOOST_FOREACH(CTransaction& tx, vtx)
1175 SyncWithWallets(tx, this, true);
1180 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1182 printf("REORGANIZE\n");
1185 CBlockIndex* pfork = pindexBest;
1186 CBlockIndex* plonger = pindexNew;
1187 while (pfork != plonger)
1189 while (plonger->nHeight > pfork->nHeight)
1190 if (!(plonger = plonger->pprev))
1191 return error("Reorganize() : plonger->pprev is null");
1192 if (pfork == plonger)
1194 if (!(pfork = pfork->pprev))
1195 return error("Reorganize() : pfork->pprev is null");
1198 // List of what to disconnect
1199 vector<CBlockIndex*> vDisconnect;
1200 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1201 vDisconnect.push_back(pindex);
1203 // List of what to connect
1204 vector<CBlockIndex*> vConnect;
1205 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1206 vConnect.push_back(pindex);
1207 reverse(vConnect.begin(), vConnect.end());
1209 // Disconnect shorter branch
1210 vector<CTransaction> vResurrect;
1211 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1214 if (!block.ReadFromDisk(pindex))
1215 return error("Reorganize() : ReadFromDisk for disconnect failed");
1216 if (!block.DisconnectBlock(txdb, pindex))
1217 return error("Reorganize() : DisconnectBlock failed");
1219 // Queue memory transactions to resurrect
1220 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1221 if (!tx.IsCoinBase())
1222 vResurrect.push_back(tx);
1225 // Connect longer branch
1226 vector<CTransaction> vDelete;
1227 for (int i = 0; i < vConnect.size(); i++)
1229 CBlockIndex* pindex = vConnect[i];
1231 if (!block.ReadFromDisk(pindex))
1232 return error("Reorganize() : ReadFromDisk for connect failed");
1233 if (!block.ConnectBlock(txdb, pindex))
1237 return error("Reorganize() : ConnectBlock failed");
1240 // Queue memory transactions to delete
1241 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1242 vDelete.push_back(tx);
1244 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1245 return error("Reorganize() : WriteHashBestChain failed");
1247 // Make sure it's successfully written to disk before changing memory structure
1248 if (!txdb.TxnCommit())
1249 return error("Reorganize() : TxnCommit failed");
1251 // Disconnect shorter branch
1252 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1254 pindex->pprev->pnext = NULL;
1256 // Connect longer branch
1257 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1259 pindex->pprev->pnext = pindex;
1261 // Resurrect memory transactions that were in the disconnected branch
1262 BOOST_FOREACH(CTransaction& tx, vResurrect)
1263 tx.AcceptToMemoryPool(txdb, false);
1265 // Delete redundant memory transactions that are in the connected branch
1266 BOOST_FOREACH(CTransaction& tx, vDelete)
1267 tx.RemoveFromMemoryPool();
1273 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1275 uint256 hash = GetHash();
1278 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1280 txdb.WriteHashBestChain(hash);
1281 if (!txdb.TxnCommit())
1282 return error("SetBestChain() : TxnCommit failed");
1283 pindexGenesisBlock = pindexNew;
1285 else if (hashPrevBlock == hashBestChain)
1287 // Adding to current best branch
1288 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1291 InvalidChainFound(pindexNew);
1292 return error("SetBestChain() : ConnectBlock failed");
1294 if (!txdb.TxnCommit())
1295 return error("SetBestChain() : TxnCommit failed");
1297 // Add to current best branch
1298 pindexNew->pprev->pnext = pindexNew;
1300 // Delete redundant memory transactions
1301 BOOST_FOREACH(CTransaction& tx, vtx)
1302 tx.RemoveFromMemoryPool();
1307 if (!Reorganize(txdb, pindexNew))
1310 InvalidChainFound(pindexNew);
1311 return error("SetBestChain() : Reorganize failed");
1315 // Update best block in wallet (so we can detect restored wallets)
1316 if (!IsInitialBlockDownload())
1318 const CBlockLocator locator(pindexNew);
1319 ::SetBestChain(locator);
1323 hashBestChain = hash;
1324 pindexBest = pindexNew;
1325 nBestHeight = pindexBest->nHeight;
1326 bnBestChainWork = pindexNew->bnChainWork;
1327 nTimeBestReceived = GetTime();
1328 nTransactionsUpdated++;
1329 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1335 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1337 // Check for duplicate
1338 uint256 hash = GetHash();
1339 if (mapBlockIndex.count(hash))
1340 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1342 // Construct new block index object
1343 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1345 return error("AddToBlockIndex() : new CBlockIndex failed");
1346 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1347 pindexNew->phashBlock = &((*mi).first);
1348 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1349 if (miPrev != mapBlockIndex.end())
1351 pindexNew->pprev = (*miPrev).second;
1352 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1354 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1358 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1359 if (!txdb.TxnCommit())
1363 if (pindexNew->bnChainWork > bnBestChainWork)
1364 if (!SetBestChain(txdb, pindexNew))
1369 if (pindexNew == pindexBest)
1371 // Notify UI to display prev block's coinbase if it was ours
1372 static uint256 hashPrevBestCoinBase;
1373 UpdatedTransaction(hashPrevBestCoinBase);
1374 hashPrevBestCoinBase = vtx[0].GetHash();
1384 bool CBlock::CheckBlock() const
1386 // These are checks that are independent of context
1387 // that can be verified before saving an orphan block.
1390 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1391 return DoS(100, error("CheckBlock() : size limits failed"));
1393 // Check proof of work matches claimed amount
1394 if (!CheckProofOfWork(GetHash(), nBits))
1395 return DoS(50, error("CheckBlock() : proof of work failed"));
1398 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1399 return error("CheckBlock() : block timestamp too far in the future");
1401 // First transaction must be coinbase, the rest must not be
1402 if (vtx.empty() || !vtx[0].IsCoinBase())
1403 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1404 for (int i = 1; i < vtx.size(); i++)
1405 if (vtx[i].IsCoinBase())
1406 return DoS(100, error("CheckBlock() : more than one coinbase"));
1408 // Check transactions
1409 BOOST_FOREACH(const CTransaction& tx, vtx)
1410 if (!tx.CheckTransaction())
1411 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1413 // This code should be removed when a compatibility-breaking block chain split has passed.
1414 // Compatibility check for old clients that counted sigops differently:
1416 BOOST_FOREACH(const CTransaction& tx, vtx)
1418 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1420 nSigOps += txin.scriptSig.GetSigOpCount();
1422 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1424 nSigOps += txout.scriptPubKey.GetSigOpCount();
1427 if (nSigOps > MAX_BLOCK_SIGOPS)
1428 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1431 if (hashMerkleRoot != BuildMerkleTree())
1432 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1437 bool CBlock::AcceptBlock()
1439 // Check for duplicate
1440 uint256 hash = GetHash();
1441 if (mapBlockIndex.count(hash))
1442 return error("AcceptBlock() : block already in mapBlockIndex");
1444 // Get prev block index
1445 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1446 if (mi == mapBlockIndex.end())
1447 return DoS(10, error("AcceptBlock() : prev block not found"));
1448 CBlockIndex* pindexPrev = (*mi).second;
1449 int nHeight = pindexPrev->nHeight+1;
1451 // Check proof of work
1452 if (nBits != GetNextWorkRequired(pindexPrev))
1453 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1455 // Check timestamp against prev
1456 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1457 return error("AcceptBlock() : block's timestamp is too early");
1459 // Check that all transactions are finalized
1460 BOOST_FOREACH(const CTransaction& tx, vtx)
1461 if (!tx.IsFinal(nHeight, GetBlockTime()))
1462 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1464 // Check that the block chain matches the known block chain up to a checkpoint
1465 if (!Checkpoints::CheckBlock(nHeight, hash))
1466 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1468 // Write block to history file
1469 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1470 return error("AcceptBlock() : out of disk space");
1471 unsigned int nFile = -1;
1472 unsigned int nBlockPos = 0;
1473 if (!WriteToDisk(nFile, nBlockPos))
1474 return error("AcceptBlock() : WriteToDisk failed");
1475 if (!AddToBlockIndex(nFile, nBlockPos))
1476 return error("AcceptBlock() : AddToBlockIndex failed");
1478 // Relay inventory, but don't relay old inventory during initial block download
1479 if (hashBestChain == hash)
1480 CRITICAL_BLOCK(cs_vNodes)
1481 BOOST_FOREACH(CNode* pnode, vNodes)
1482 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1483 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1488 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1490 // Check for duplicate
1491 uint256 hash = pblock->GetHash();
1492 if (mapBlockIndex.count(hash))
1493 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1494 if (mapOrphanBlocks.count(hash))
1495 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1497 // Preliminary checks
1498 if (!pblock->CheckBlock())
1499 return error("ProcessBlock() : CheckBlock FAILED");
1501 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1502 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1504 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1505 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1508 pfrom->Misbehaving(100);
1509 return error("ProcessBlock() : block with timestamp before last checkpoint");
1512 bnNewBlock.SetCompact(pblock->nBits);
1514 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1515 if (bnNewBlock > bnRequired)
1517 pfrom->Misbehaving(100);
1518 return error("ProcessBlock() : block with too little proof-of-work");
1523 // If don't already have its previous block, shunt it off to holding area until we get it
1524 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1526 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1527 CBlock* pblock2 = new CBlock(*pblock);
1528 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1529 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1531 // Ask this guy to fill in what we're missing
1533 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1538 if (!pblock->AcceptBlock())
1539 return error("ProcessBlock() : AcceptBlock FAILED");
1541 // Recursively process any orphan blocks that depended on this one
1542 vector<uint256> vWorkQueue;
1543 vWorkQueue.push_back(hash);
1544 for (int i = 0; i < vWorkQueue.size(); i++)
1546 uint256 hashPrev = vWorkQueue[i];
1547 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1548 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1551 CBlock* pblockOrphan = (*mi).second;
1552 if (pblockOrphan->AcceptBlock())
1553 vWorkQueue.push_back(pblockOrphan->GetHash());
1554 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1555 delete pblockOrphan;
1557 mapOrphanBlocksByPrev.erase(hashPrev);
1560 printf("ProcessBlock: ACCEPTED\n");
1571 bool CheckDiskSpace(uint64_t nAdditionalBytes)
1573 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1575 // Check for 15MB because database could create another 10MB log file at any time
1576 if (nFreeBytesAvailable < (uint64_t)15000000 + nAdditionalBytes)
1579 string strMessage = _("Warning: Disk space is low ");
1580 strMiscWarning = strMessage;
1581 printf("*** %s\n", strMessage.c_str());
1582 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1583 CreateThread(Shutdown, NULL);
1589 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1593 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1596 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1598 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1607 static unsigned int nCurrentBlockFile = 1;
1609 FILE* AppendBlockFile(unsigned int& nFileRet)
1614 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1617 if (fseek(file, 0, SEEK_END) != 0)
1619 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1620 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1622 nFileRet = nCurrentBlockFile;
1626 nCurrentBlockFile++;
1630 bool LoadBlockIndex(bool fAllowNew)
1634 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1635 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1636 pchMessageStart[0] = 0xfa;
1637 pchMessageStart[1] = 0xbf;
1638 pchMessageStart[2] = 0xb5;
1639 pchMessageStart[3] = 0xda;
1646 if (!txdb.LoadBlockIndex())
1651 // Init with genesis block
1653 if (mapBlockIndex.empty())
1659 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1660 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1661 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1662 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1663 // vMerkleTree: 4a5e1e
1666 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1668 txNew.vin.resize(1);
1669 txNew.vout.resize(1);
1670 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1671 txNew.vout[0].nValue = 50 * COIN;
1672 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1674 block.vtx.push_back(txNew);
1675 block.hashPrevBlock = 0;
1676 block.hashMerkleRoot = block.BuildMerkleTree();
1678 block.nTime = 1231006505;
1679 block.nBits = 0x1d00ffff;
1680 block.nNonce = 2083236893;
1684 block.nTime = 1296688602;
1685 block.nBits = 0x1d07fff8;
1686 block.nNonce = 384568319;
1690 printf("%s\n", block.GetHash().ToString().c_str());
1691 printf("%s\n", hashGenesisBlock.ToString().c_str());
1692 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1693 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1695 assert(block.GetHash() == hashGenesisBlock);
1697 // Start new block file
1699 unsigned int nBlockPos;
1700 if (!block.WriteToDisk(nFile, nBlockPos))
1701 return error("LoadBlockIndex() : writing genesis block to disk failed");
1702 if (!block.AddToBlockIndex(nFile, nBlockPos))
1703 return error("LoadBlockIndex() : genesis block not accepted");
1711 void PrintBlockTree()
1713 // precompute tree structure
1714 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1715 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1717 CBlockIndex* pindex = (*mi).second;
1718 mapNext[pindex->pprev].push_back(pindex);
1720 //while (rand() % 3 == 0)
1721 // mapNext[pindex->pprev].push_back(pindex);
1724 vector<pair<int, CBlockIndex*> > vStack;
1725 vStack.push_back(make_pair(0, pindexGenesisBlock));
1728 while (!vStack.empty())
1730 int nCol = vStack.back().first;
1731 CBlockIndex* pindex = vStack.back().second;
1734 // print split or gap
1735 if (nCol > nPrevCol)
1737 for (int i = 0; i < nCol-1; i++)
1741 else if (nCol < nPrevCol)
1743 for (int i = 0; i < nCol; i++)
1750 for (int i = 0; i < nCol; i++)
1755 block.ReadFromDisk(pindex);
1756 printf("%d (%u,%u) %s %s tx %d",
1760 block.GetHash().ToString().substr(0,20).c_str(),
1761 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1764 PrintWallets(block);
1766 // put the main timechain first
1767 vector<CBlockIndex*>& vNext = mapNext[pindex];
1768 for (int i = 0; i < vNext.size(); i++)
1770 if (vNext[i]->pnext)
1772 swap(vNext[0], vNext[i]);
1778 for (int i = 0; i < vNext.size(); i++)
1779 vStack.push_back(make_pair(nCol+i, vNext[i]));
1792 //////////////////////////////////////////////////////////////////////////////
1797 map<uint256, CAlert> mapAlerts;
1798 CCriticalSection cs_mapAlerts;
1800 string GetWarnings(string strFor)
1803 string strStatusBar;
1805 if (GetBoolArg("-testsafemode"))
1808 // Misc warnings like out of disk space and clock is wrong
1809 if (strMiscWarning != "")
1812 strStatusBar = strMiscWarning;
1815 // Longer invalid proof-of-work chain
1816 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1819 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1823 CRITICAL_BLOCK(cs_mapAlerts)
1825 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1827 const CAlert& alert = item.second;
1828 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1830 nPriority = alert.nPriority;
1831 strStatusBar = alert.strStatusBar;
1836 if (strFor == "statusbar")
1837 return strStatusBar;
1838 else if (strFor == "rpc")
1840 assert(!"GetWarnings() : invalid parameter");
1844 bool CAlert::ProcessAlert()
1846 if (!CheckSignature())
1851 CRITICAL_BLOCK(cs_mapAlerts)
1853 // Cancel previous alerts
1854 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1856 const CAlert& alert = (*mi).second;
1859 printf("cancelling alert %d\n", alert.nID);
1860 mapAlerts.erase(mi++);
1862 else if (!alert.IsInEffect())
1864 printf("expiring alert %d\n", alert.nID);
1865 mapAlerts.erase(mi++);
1871 // Check if this alert has been cancelled
1872 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1874 const CAlert& alert = item.second;
1875 if (alert.Cancels(*this))
1877 printf("alert already cancelled by %d\n", alert.nID);
1883 mapAlerts.insert(make_pair(GetHash(), *this));
1886 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1898 //////////////////////////////////////////////////////////////////////////////
1904 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1908 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1909 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1911 // Don't know what it is, just say we already got one
1918 // The message start string is designed to be unlikely to occur in normal data.
1919 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1920 // a large 4-byte int at any alignment.
1921 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1924 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1926 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1927 RandAddSeedPerfmon();
1929 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1930 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1932 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1934 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1942 if (strCommand == "version")
1944 // Each connection can only send one version message
1945 if (pfrom->nVersion != 0)
1947 pfrom->Misbehaving(1);
1954 uint64_t nNonce = 1;
1955 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1956 if (pfrom->nVersion == 10300)
1957 pfrom->nVersion = 300;
1958 if (pfrom->nVersion >= 106 && !vRecv.empty())
1959 vRecv >> addrFrom >> nNonce;
1960 if (pfrom->nVersion >= 106 && !vRecv.empty())
1961 vRecv >> pfrom->strSubVer;
1962 if (pfrom->nVersion >= 209 && !vRecv.empty())
1963 vRecv >> pfrom->nStartingHeight;
1965 if (pfrom->nVersion == 0)
1968 // Disconnect if we connected to ourself
1969 if (nNonce == nLocalHostNonce && nNonce > 1)
1971 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1972 pfrom->fDisconnect = true;
1976 // Be shy and don't send version until we hear
1977 if (pfrom->fInbound)
1978 pfrom->PushVersion();
1980 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1982 AddTimeData(pfrom->addr.ip, nTime);
1985 if (pfrom->nVersion >= 209)
1986 pfrom->PushMessage("verack");
1987 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1988 if (pfrom->nVersion < 209)
1989 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1991 if (!pfrom->fInbound)
1993 // Advertise our address
1994 if (addrLocalHost.IsRoutable() && !fUseProxy)
1996 CAddress addr(addrLocalHost);
1997 addr.nTime = GetAdjustedTime();
1998 pfrom->PushAddress(addr);
2001 // Get recent addresses
2002 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2004 pfrom->PushMessage("getaddr");
2005 pfrom->fGetAddr = true;
2009 // Ask the first connected node for block updates
2010 static int nAskedForBlocks = 0;
2011 if (!pfrom->fClient &&
2012 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2013 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2016 pfrom->PushGetBlocks(pindexBest, uint256(0));
2020 CRITICAL_BLOCK(cs_mapAlerts)
2021 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2022 item.second.RelayTo(pfrom);
2024 pfrom->fSuccessfullyConnected = true;
2026 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2028 cPeerBlockCounts.input(pfrom->nStartingHeight);
2032 else if (pfrom->nVersion == 0)
2034 // Must have a version message before anything else
2035 pfrom->Misbehaving(1);
2040 else if (strCommand == "verack")
2042 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2046 else if (strCommand == "addr")
2048 vector<CAddress> vAddr;
2051 // Don't want addr from older versions unless seeding
2052 if (pfrom->nVersion < 209)
2054 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2056 if (vAddr.size() > 1000)
2058 pfrom->Misbehaving(20);
2059 return error("message addr size() = %d", vAddr.size());
2062 // Store the new addresses
2065 int64_t nNow = GetAdjustedTime();
2066 int64_t nSince = nNow - 10 * 60;
2067 BOOST_FOREACH(CAddress& addr, vAddr)
2071 // ignore IPv6 for now, since it isn't implemented anyway
2074 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2075 addr.nTime = nNow - 5 * 24 * 60 * 60;
2076 AddAddress(addr, 2 * 60 * 60, &addrDB);
2077 pfrom->AddAddressKnown(addr);
2078 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2080 // Relay to a limited number of other nodes
2081 CRITICAL_BLOCK(cs_vNodes)
2083 // Use deterministic randomness to send to the same nodes for 24 hours
2084 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2085 static uint256 hashSalt;
2087 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2088 uint256 hashRand = hashSalt ^ (((int64_t)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2089 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2090 multimap<uint256, CNode*> mapMix;
2091 BOOST_FOREACH(CNode* pnode, vNodes)
2093 if (pnode->nVersion < 31402)
2095 unsigned int nPointer;
2096 memcpy(&nPointer, &pnode, sizeof(nPointer));
2097 uint256 hashKey = hashRand ^ nPointer;
2098 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2099 mapMix.insert(make_pair(hashKey, pnode));
2101 int nRelayNodes = 2;
2102 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2103 ((*mi).second)->PushAddress(addr);
2107 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2108 if (vAddr.size() < 1000)
2109 pfrom->fGetAddr = false;
2113 else if (strCommand == "inv")
2117 if (vInv.size() > 50000)
2119 pfrom->Misbehaving(20);
2120 return error("message inv size() = %d", vInv.size());
2124 BOOST_FOREACH(const CInv& inv, vInv)
2128 pfrom->AddInventoryKnown(inv);
2130 bool fAlreadyHave = AlreadyHave(txdb, inv);
2132 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2136 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2137 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2139 // Track requests for our stuff
2140 Inventory(inv.hash);
2145 else if (strCommand == "getdata")
2149 if (vInv.size() > 50000)
2151 pfrom->Misbehaving(20);
2152 return error("message getdata size() = %d", vInv.size());
2155 BOOST_FOREACH(const CInv& inv, vInv)
2159 printf("received getdata for: %s\n", inv.ToString().c_str());
2161 if (inv.type == MSG_BLOCK)
2163 // Send block from disk
2164 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2165 if (mi != mapBlockIndex.end())
2168 block.ReadFromDisk((*mi).second);
2169 pfrom->PushMessage("block", block);
2171 // Trigger them to send a getblocks request for the next batch of inventory
2172 if (inv.hash == pfrom->hashContinue)
2174 // Bypass PushInventory, this must send even if redundant,
2175 // and we want it right after the last block so they don't
2176 // wait for other stuff first.
2178 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2179 pfrom->PushMessage("inv", vInv);
2180 pfrom->hashContinue = 0;
2184 else if (inv.IsKnownType())
2186 // Send stream from relay memory
2187 CRITICAL_BLOCK(cs_mapRelay)
2189 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2190 if (mi != mapRelay.end())
2191 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2195 // Track requests for our stuff
2196 Inventory(inv.hash);
2201 else if (strCommand == "getblocks")
2203 CBlockLocator locator;
2205 vRecv >> locator >> hashStop;
2207 // Find the last block the caller has in the main chain
2208 CBlockIndex* pindex = locator.GetBlockIndex();
2210 // Send the rest of the chain
2212 pindex = pindex->pnext;
2213 int nLimit = 500 + locator.GetDistanceBack();
2214 unsigned int nBytes = 0;
2215 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2216 for (; pindex; pindex = pindex->pnext)
2218 if (pindex->GetBlockHash() == hashStop)
2220 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2223 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2225 block.ReadFromDisk(pindex, true);
2226 nBytes += block.GetSerializeSize(SER_NETWORK);
2227 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2229 // When this block is requested, we'll send an inv that'll make them
2230 // getblocks the next batch of inventory.
2231 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2232 pfrom->hashContinue = pindex->GetBlockHash();
2239 else if (strCommand == "getheaders")
2241 CBlockLocator locator;
2243 vRecv >> locator >> hashStop;
2245 CBlockIndex* pindex = NULL;
2246 if (locator.IsNull())
2248 // If locator is null, return the hashStop block
2249 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2250 if (mi == mapBlockIndex.end())
2252 pindex = (*mi).second;
2256 // Find the last block the caller has in the main chain
2257 pindex = locator.GetBlockIndex();
2259 pindex = pindex->pnext;
2262 vector<CBlock> vHeaders;
2263 int nLimit = 2000 + locator.GetDistanceBack();
2264 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2265 for (; pindex; pindex = pindex->pnext)
2267 vHeaders.push_back(pindex->GetBlockHeader());
2268 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2271 pfrom->PushMessage("headers", vHeaders);
2275 else if (strCommand == "tx")
2277 vector<uint256> vWorkQueue;
2278 CDataStream vMsg(vRecv);
2282 CInv inv(MSG_TX, tx.GetHash());
2283 pfrom->AddInventoryKnown(inv);
2285 bool fMissingInputs = false;
2286 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2288 SyncWithWallets(tx, NULL, true);
2289 RelayMessage(inv, vMsg);
2290 mapAlreadyAskedFor.erase(inv);
2291 vWorkQueue.push_back(inv.hash);
2293 // Recursively process any orphan transactions that depended on this one
2294 for (int i = 0; i < vWorkQueue.size(); i++)
2296 uint256 hashPrev = vWorkQueue[i];
2297 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2298 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2301 const CDataStream& vMsg = *((*mi).second);
2303 CDataStream(vMsg) >> tx;
2304 CInv inv(MSG_TX, tx.GetHash());
2306 if (tx.AcceptToMemoryPool(true))
2308 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2309 SyncWithWallets(tx, NULL, true);
2310 RelayMessage(inv, vMsg);
2311 mapAlreadyAskedFor.erase(inv);
2312 vWorkQueue.push_back(inv.hash);
2317 BOOST_FOREACH(uint256 hash, vWorkQueue)
2318 EraseOrphanTx(hash);
2320 else if (fMissingInputs)
2322 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2325 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2329 else if (strCommand == "block")
2334 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2337 CInv inv(MSG_BLOCK, block.GetHash());
2338 pfrom->AddInventoryKnown(inv);
2340 if (ProcessBlock(pfrom, &block))
2341 mapAlreadyAskedFor.erase(inv);
2342 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2346 else if (strCommand == "getaddr")
2348 // Nodes rebroadcast an addr every 24 hours
2349 pfrom->vAddrToSend.clear();
2350 int64_t nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2351 CRITICAL_BLOCK(cs_mapAddresses)
2353 unsigned int nCount = 0;
2354 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2356 const CAddress& addr = item.second;
2357 if (addr.nTime > nSince)
2360 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2362 const CAddress& addr = item.second;
2363 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2364 pfrom->PushAddress(addr);
2370 else if (strCommand == "checkorder")
2375 if (!GetBoolArg("-allowreceivebyip"))
2377 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2384 /// we have a chance to check the order here
2386 // Keep giving the same key to the same ip until they use it
2387 if (!mapReuseKey.count(pfrom->addr.ip))
2388 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2390 // Send back approval of order and pubkey to use
2391 CScript scriptPubKey;
2392 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2393 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2397 else if (strCommand == "reply")
2402 CRequestTracker tracker;
2403 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2405 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2406 if (mi != pfrom->mapRequests.end())
2408 tracker = (*mi).second;
2409 pfrom->mapRequests.erase(mi);
2412 if (!tracker.IsNull())
2413 tracker.fn(tracker.param1, vRecv);
2417 else if (strCommand == "ping")
2422 else if (strCommand == "alert")
2427 if (alert.ProcessAlert())
2430 pfrom->setKnown.insert(alert.GetHash());
2431 CRITICAL_BLOCK(cs_vNodes)
2432 BOOST_FOREACH(CNode* pnode, vNodes)
2433 alert.RelayTo(pnode);
2440 // Ignore unknown commands for extensibility
2444 // Update the last seen time for this node's address
2445 if (pfrom->fNetworkNode)
2446 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2447 AddressCurrentlyConnected(pfrom->addr);
2453 bool ProcessMessages(CNode* pfrom)
2455 CDataStream& vRecv = pfrom->vRecv;
2459 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2463 // (4) message start
2472 // Scan for message start
2473 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2474 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2475 if (vRecv.end() - pstart < nHeaderSize)
2477 if (vRecv.size() > nHeaderSize)
2479 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2480 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2484 if (pstart - vRecv.begin() > 0)
2485 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2486 vRecv.erase(vRecv.begin(), pstart);
2489 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2494 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2497 string strCommand = hdr.GetCommand();
2500 unsigned int nMessageSize = hdr.nMessageSize;
2501 if (nMessageSize > MAX_SIZE)
2503 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2506 if (nMessageSize > vRecv.size())
2508 // Rewind and wait for rest of message
2509 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2514 if (vRecv.GetVersion() >= 209)
2516 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2517 unsigned int nChecksum = 0;
2518 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2519 if (nChecksum != hdr.nChecksum)
2521 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2522 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2527 // Copy message to its own buffer
2528 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2529 vRecv.ignore(nMessageSize);
2535 CRITICAL_BLOCK(cs_main)
2536 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2540 catch (std::ios_base::failure& e)
2542 if (strstr(e.what(), "end of data"))
2544 // Allow exceptions from underlength message on vRecv
2545 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());
2547 else if (strstr(e.what(), "size too large"))
2549 // Allow exceptions from overlong size
2550 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2554 PrintExceptionContinue(&e, "ProcessMessage()");
2557 catch (std::exception& e) {
2558 PrintExceptionContinue(&e, "ProcessMessage()");
2560 PrintExceptionContinue(NULL, "ProcessMessage()");
2564 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2572 bool SendMessages(CNode* pto, bool fSendTrickle)
2574 CRITICAL_BLOCK(cs_main)
2576 // Don't send anything until we get their version message
2577 if (pto->nVersion == 0)
2581 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2582 pto->PushMessage("ping");
2584 // Resend wallet transactions that haven't gotten in a block yet
2585 ResendWalletTransactions();
2587 // Address refresh broadcast
2588 static int64_t nLastRebroadcast;
2589 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2591 nLastRebroadcast = GetTime();
2592 CRITICAL_BLOCK(cs_vNodes)
2594 BOOST_FOREACH(CNode* pnode, vNodes)
2596 // Periodically clear setAddrKnown to allow refresh broadcasts
2597 pnode->setAddrKnown.clear();
2599 // Rebroadcast our address
2600 if (addrLocalHost.IsRoutable() && !fUseProxy)
2602 CAddress addr(addrLocalHost);
2603 addr.nTime = GetAdjustedTime();
2604 pnode->PushAddress(addr);
2610 // Clear out old addresses periodically so it's not too much work at once
2611 static int64_t nLastClear;
2612 if (nLastClear == 0)
2613 nLastClear = GetTime();
2614 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2616 nLastClear = GetTime();
2617 CRITICAL_BLOCK(cs_mapAddresses)
2620 int64_t nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2621 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2622 mi != mapAddresses.end();)
2624 const CAddress& addr = (*mi).second;
2625 if (addr.nTime < nSince)
2627 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2629 addrdb.EraseAddress(addr);
2630 mapAddresses.erase(mi++);
2644 vector<CAddress> vAddr;
2645 vAddr.reserve(pto->vAddrToSend.size());
2646 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2648 // returns true if wasn't already contained in the set
2649 if (pto->setAddrKnown.insert(addr).second)
2651 vAddr.push_back(addr);
2652 // receiver rejects addr messages larger than 1000
2653 if (vAddr.size() >= 1000)
2655 pto->PushMessage("addr", vAddr);
2660 pto->vAddrToSend.clear();
2662 pto->PushMessage("addr", vAddr);
2667 // Message: inventory
2670 vector<CInv> vInvWait;
2671 CRITICAL_BLOCK(pto->cs_inventory)
2673 vInv.reserve(pto->vInventoryToSend.size());
2674 vInvWait.reserve(pto->vInventoryToSend.size());
2675 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2677 if (pto->setInventoryKnown.count(inv))
2680 // trickle out tx inv to protect privacy
2681 if (inv.type == MSG_TX && !fSendTrickle)
2683 // 1/4 of tx invs blast to all immediately
2684 static uint256 hashSalt;
2686 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2687 uint256 hashRand = inv.hash ^ hashSalt;
2688 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2689 bool fTrickleWait = ((hashRand & 3) != 0);
2691 // always trickle our own transactions
2695 if (GetTransaction(inv.hash, wtx))
2697 fTrickleWait = true;
2702 vInvWait.push_back(inv);
2707 // returns true if wasn't already contained in the set
2708 if (pto->setInventoryKnown.insert(inv).second)
2710 vInv.push_back(inv);
2711 if (vInv.size() >= 1000)
2713 pto->PushMessage("inv", vInv);
2718 pto->vInventoryToSend = vInvWait;
2721 pto->PushMessage("inv", vInv);
2727 vector<CInv> vGetData;
2728 int64_t nNow = GetTime() * 1000000;
2730 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2732 const CInv& inv = (*pto->mapAskFor.begin()).second;
2733 if (!AlreadyHave(txdb, inv))
2735 printf("sending getdata: %s\n", inv.ToString().c_str());
2736 vGetData.push_back(inv);
2737 if (vGetData.size() >= 1000)
2739 pto->PushMessage("getdata", vGetData);
2743 mapAlreadyAskedFor[inv] = nNow;
2744 pto->mapAskFor.erase(pto->mapAskFor.begin());
2746 if (!vGetData.empty())
2747 pto->PushMessage("getdata", vGetData);
2766 //////////////////////////////////////////////////////////////////////////////
2771 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2773 unsigned char* pdata = (unsigned char*)pbuffer;
2774 unsigned int blocks = 1 + ((len + 8) / 64);
2775 unsigned char* pend = pdata + 64 * blocks;
2776 memset(pdata + len, 0, 64 * blocks - len);
2778 unsigned int bits = len * 8;
2779 pend[-1] = (bits >> 0) & 0xff;
2780 pend[-2] = (bits >> 8) & 0xff;
2781 pend[-3] = (bits >> 16) & 0xff;
2782 pend[-4] = (bits >> 24) & 0xff;
2786 static const unsigned int pSHA256InitState[8] =
2787 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2789 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2792 unsigned char data[64];
2796 for (int i = 0; i < 16; i++)
2797 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2799 for (int i = 0; i < 8; i++)
2800 ctx.h[i] = ((uint32_t*)pinit)[i];
2802 SHA256_Update(&ctx, data, sizeof(data));
2803 for (int i = 0; i < 8; i++)
2804 ((uint32_t*)pstate)[i] = ctx.h[i];
2808 // ScanHash scans nonces looking for a hash with at least some zero bits.
2809 // It operates on big endian data. Caller does the byte reversing.
2810 // All input buffers are 16-byte aligned. nNonce is usually preserved
2811 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2812 // the block is rebuilt and nNonce starts over at zero.
2814 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2816 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2820 // Hash pdata using pmidstate as the starting state into
2821 // preformatted buffer phash1, then hash phash1 into phash
2823 SHA256Transform(phash1, pdata, pmidstate);
2824 SHA256Transform(phash, phash1, pSHA256InitState);
2826 // Return the nonce if the hash has at least some zero bits,
2827 // caller will check if it has enough to reach the target
2828 if (((unsigned short*)phash)[14] == 0)
2831 // If nothing found after trying for a while, return -1
2832 if ((nNonce & 0xffff) == 0)
2834 nHashesDone = 0xffff+1;
2840 // Some explaining would be appreciated
2845 set<uint256> setDependsOn;
2848 COrphan(CTransaction* ptxIn)
2856 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2857 BOOST_FOREACH(uint256 hash, setDependsOn)
2858 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2863 CBlock* CreateNewBlock(CReserveKey& reservekey)
2865 CBlockIndex* pindexPrev = pindexBest;
2868 auto_ptr<CBlock> pblock(new CBlock());
2872 // Create coinbase tx
2874 txNew.vin.resize(1);
2875 txNew.vin[0].prevout.SetNull();
2876 txNew.vout.resize(1);
2877 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2879 // Add our coinbase tx as first transaction
2880 pblock->vtx.push_back(txNew);
2882 // Collect memory pool transactions into the block
2884 CRITICAL_BLOCK(cs_main)
2885 CRITICAL_BLOCK(cs_mapTransactions)
2889 // Priority order to process transactions
2890 list<COrphan> vOrphan; // list memory doesn't move
2891 map<uint256, vector<COrphan*> > mapDependers;
2892 multimap<double, CTransaction*> mapPriority;
2893 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2895 CTransaction& tx = (*mi).second;
2896 if (tx.IsCoinBase() || !tx.IsFinal())
2899 COrphan* porphan = NULL;
2900 double dPriority = 0;
2901 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2903 // Read prev transaction
2904 CTransaction txPrev;
2906 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2908 // Has to wait for dependencies
2911 // Use list for automatic deletion
2912 vOrphan.push_back(COrphan(&tx));
2913 porphan = &vOrphan.back();
2915 mapDependers[txin.prevout.hash].push_back(porphan);
2916 porphan->setDependsOn.insert(txin.prevout.hash);
2919 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2921 // Read block header
2922 int nConf = txindex.GetDepthInMainChain();
2924 dPriority += (double)nValueIn * nConf;
2926 if (fDebug && GetBoolArg("-printpriority"))
2927 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2930 // Priority is sum(valuein * age) / txsize
2931 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2934 porphan->dPriority = dPriority;
2936 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2938 if (fDebug && GetBoolArg("-printpriority"))
2940 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2947 // Collect transactions into block
2948 map<uint256, CTxIndex> mapTestPool;
2949 uint64_t nBlockSize = 1000;
2950 int nBlockSigOps = 100;
2951 while (!mapPriority.empty())
2953 // Take highest priority transaction off priority queue
2954 double dPriority = -(*mapPriority.begin()).first;
2955 CTransaction& tx = *(*mapPriority.begin()).second;
2956 mapPriority.erase(mapPriority.begin());
2959 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2960 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2963 // Transaction fee required depends on block size
2964 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2965 int64_t nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
2967 // Connecting shouldn't fail due to dependency on other memory pool transactions
2968 // because we're already processing them in order of dependency
2969 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2970 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2971 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2974 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2976 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2978 swap(mapTestPool, mapTestPoolTmp);
2981 pblock->vtx.push_back(tx);
2982 nBlockSize += nTxSize;
2983 nBlockSigOps += nTxSigOps;
2985 // Add transactions that depend on this one to the priority queue
2986 uint256 hash = tx.GetHash();
2987 if (mapDependers.count(hash))
2989 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2991 if (!porphan->setDependsOn.empty())
2993 porphan->setDependsOn.erase(hash);
2994 if (porphan->setDependsOn.empty())
2995 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3001 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3004 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3005 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3006 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3007 pblock->nBits = GetNextWorkRequired(pindexPrev);
3010 return pblock.release();
3014 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3016 // Update nExtraNonce
3017 static uint256 hashPrevBlock;
3018 if (hashPrevBlock != pblock->hashPrevBlock)
3021 hashPrevBlock = pblock->hashPrevBlock;
3024 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3026 // Put "OP_EVAL" in the coinbase so everybody can tell when
3027 // a majority of miners support it
3028 const char* pOpEvalName = GetOpName(OP_EVAL);
3029 pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3030 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3032 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3036 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3039 // Prebuild hash buffers
3046 uint256 hashPrevBlock;
3047 uint256 hashMerkleRoot;
3050 unsigned int nNonce;
3053 unsigned char pchPadding0[64];
3055 unsigned char pchPadding1[64];
3058 memset(&tmp, 0, sizeof(tmp));
3060 tmp.block.nVersion = pblock->nVersion;
3061 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3062 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3063 tmp.block.nTime = pblock->nTime;
3064 tmp.block.nBits = pblock->nBits;
3065 tmp.block.nNonce = pblock->nNonce;
3067 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3068 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3070 // Byte swap all the input buffer
3071 for (int i = 0; i < sizeof(tmp)/4; i++)
3072 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3074 // Precalc the first half of the first hash, which stays constant
3075 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3077 memcpy(pdata, &tmp.block, 128);
3078 memcpy(phash1, &tmp.hash1, 64);
3082 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3084 uint256 hash = pblock->GetHash();
3085 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3087 if (hash > hashTarget)
3091 printf("BitcoinMiner:\n");
3092 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3094 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3095 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3098 CRITICAL_BLOCK(cs_main)
3100 if (pblock->hashPrevBlock != hashBestChain)
3101 return error("BitcoinMiner : generated block is stale");
3103 // Remove key from key pool
3104 reservekey.KeepKey();
3106 // Track how many getdata requests this block gets
3107 CRITICAL_BLOCK(wallet.cs_wallet)
3108 wallet.mapRequestCount[pblock->GetHash()] = 0;
3110 // Process this block the same as if we had received it from another node
3111 if (!ProcessBlock(NULL, pblock))
3112 return error("BitcoinMiner : ProcessBlock, block not accepted");
3118 void static ThreadBitcoinMiner(void* parg);
3120 void static BitcoinMiner(CWallet *pwallet)
3122 printf("BitcoinMiner started\n");
3123 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3125 // Each thread has its own key and counter
3126 CReserveKey reservekey(pwallet);
3127 unsigned int nExtraNonce = 0;
3129 while (fGenerateBitcoins)
3131 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3135 while (vNodes.empty() || IsInitialBlockDownload())
3140 if (!fGenerateBitcoins)
3148 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3149 CBlockIndex* pindexPrev = pindexBest;
3151 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3154 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3156 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3160 // Prebuild hash buffers
3162 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3163 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3164 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3166 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3168 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3169 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3175 int64_t nStart = GetTime();
3176 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3178 uint256& hash = *alignup<16>(hashbuf);
3181 unsigned int nHashesDone = 0;
3182 unsigned int nNonceFound;
3185 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3186 (char*)&hash, nHashesDone);
3188 // Check if something found
3189 if (nNonceFound != -1)
3191 for (int i = 0; i < sizeof(hash)/4; i++)
3192 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3194 if (hash <= hashTarget)
3197 pblock->nNonce = ByteReverse(nNonceFound);
3198 assert(hash == pblock->GetHash());
3200 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3201 CheckWork(pblock.get(), *pwalletMain, reservekey);
3202 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3208 static int64_t nHashCounter;
3209 if (nHPSTimerStart == 0)
3211 nHPSTimerStart = GetTimeMillis();
3215 nHashCounter += nHashesDone;
3216 if (GetTimeMillis() - nHPSTimerStart > 4000)
3218 static CCriticalSection cs;
3221 if (GetTimeMillis() - nHPSTimerStart > 4000)
3223 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3224 nHPSTimerStart = GetTimeMillis();
3226 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3227 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3228 static int64_t nLogTime;
3229 if (GetTime() - nLogTime > 30 * 60)
3231 nLogTime = GetTime();
3232 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3233 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3239 // Check for stop or if block needs to be rebuilt
3242 if (!fGenerateBitcoins)
3244 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3248 if (nBlockNonce >= 0xffff0000)
3250 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3252 if (pindexPrev != pindexBest)
3255 // Update nTime every few seconds
3256 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3257 nBlockTime = ByteReverse(pblock->nTime);
3262 void static ThreadBitcoinMiner(void* parg)
3264 CWallet* pwallet = (CWallet*)parg;
3267 vnThreadsRunning[3]++;
3268 BitcoinMiner(pwallet);
3269 vnThreadsRunning[3]--;
3271 catch (std::exception& e) {
3272 vnThreadsRunning[3]--;
3273 PrintException(&e, "ThreadBitcoinMiner()");
3275 vnThreadsRunning[3]--;
3276 PrintException(NULL, "ThreadBitcoinMiner()");
3278 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3280 if (vnThreadsRunning[3] == 0)
3282 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3286 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3288 if (fGenerateBitcoins != fGenerate)
3290 fGenerateBitcoins = fGenerate;
3291 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3294 if (fGenerateBitcoins)
3296 int nProcessors = boost::thread::hardware_concurrency();
3297 printf("%d processors\n", nProcessors);
3298 if (nProcessors < 1)
3300 if (fLimitProcessors && nProcessors > nLimitProcessors)
3301 nProcessors = nLimitProcessors;
3302 int nAddThreads = nProcessors - vnThreadsRunning[3];
3303 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3304 for (int i = 0; i < nAddThreads; i++)
3306 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3307 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");