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.
6 #include "checkpoints.h"
10 #include <boost/filesystem.hpp>
11 #include <boost/filesystem/fstream.hpp>
14 using namespace boost;
20 // Name of client reported in the 'version' message. Report the same name
21 // for both bitcoind and bitcoin-qt, to make it harder for attackers to
22 // target servers or GUI users specifically.
23 const std::string CLIENT_NAME("bitcoin-qt");
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
30 static map<uint256, CTransaction> mapTransactions;
31 CCriticalSection cs_mapTransactions;
32 unsigned int nTransactionsUpdated = 0;
33 map<COutPoint, CInPoint> mapNextTx;
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
37 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
38 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
39 CBlockIndex* pindexGenesisBlock = NULL;
41 CBigNum bnBestChainWork = 0;
42 CBigNum bnBestInvalidWork = 0;
43 uint256 hashBestChain = 0;
44 CBlockIndex* pindexBest = NULL;
45 int64 nTimeBestReceived = 0;
47 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
49 map<uint256, CBlock*> mapOrphanBlocks;
50 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
52 map<uint256, CDataStream*> mapOrphanTransactions;
53 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
60 int fGenerateBitcoins = false;
61 int64 nTransactionFee = 0;
62 int fLimitProcessors = false;
63 int nLimitProcessors = 1;
64 int fMinimizeToTray = true;
65 int fMinimizeOnClose = true;
73 //////////////////////////////////////////////////////////////////////////////
75 // dispatching functions
78 // These functions dispatch to one or all registered wallets
81 void RegisterWallet(CWallet* pwalletIn)
83 CRITICAL_BLOCK(cs_setpwalletRegistered)
85 setpwalletRegistered.insert(pwalletIn);
89 void UnregisterWallet(CWallet* pwalletIn)
91 CRITICAL_BLOCK(cs_setpwalletRegistered)
93 setpwalletRegistered.erase(pwalletIn);
97 // check whether the passed transaction is from us
98 bool static IsFromMe(CTransaction& tx)
100 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
101 if (pwallet->IsFromMe(tx))
106 // get the wallet transaction with the given hash (if it exists)
107 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
109 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
110 if (pwallet->GetTransaction(hashTx,wtx))
115 // erases transaction with the given hash from all wallets
116 void static EraseFromWallets(uint256 hash)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 pwallet->EraseFromWallet(hash);
122 // make sure all wallets know about the given transaction, in the given block
123 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
129 // notify wallets about a new best chain
130 void static SetBestChain(const CBlockLocator& loc)
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->SetBestChain(loc);
136 // notify wallets about an updated transaction
137 void static UpdatedTransaction(const uint256& hashTx)
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->UpdatedTransaction(hashTx);
144 void static PrintWallets(const CBlock& block)
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->PrintWallet(block);
150 // notify wallets about an incoming inventory (for request counts)
151 void static Inventory(const uint256& hash)
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->Inventory(hash);
157 // ask wallets to resend their transactions
158 void static ResendWalletTransactions()
160 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161 pwallet->ResendWalletTransactions();
170 //////////////////////////////////////////////////////////////////////////////
172 // mapOrphanTransactions
175 void static AddOrphanTx(const CDataStream& vMsg)
178 CDataStream(vMsg) >> tx;
179 uint256 hash = tx.GetHash();
180 if (mapOrphanTransactions.count(hash))
182 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
183 BOOST_FOREACH(const CTxIn& txin, tx.vin)
184 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
187 void static EraseOrphanTx(uint256 hash)
189 if (!mapOrphanTransactions.count(hash))
191 const CDataStream* pvMsg = mapOrphanTransactions[hash];
193 CDataStream(*pvMsg) >> tx;
194 BOOST_FOREACH(const CTxIn& txin, tx.vin)
196 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
197 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
199 if ((*mi).second == pvMsg)
200 mapOrphanTransactionsByPrev.erase(mi++);
206 mapOrphanTransactions.erase(hash);
216 //////////////////////////////////////////////////////////////////////////////
218 // CTransaction and CTxIndex
221 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
224 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
226 if (!ReadFromDisk(txindexRet.pos))
228 if (prevout.n >= vout.size())
236 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
239 return ReadFromDisk(txdb, prevout, txindex);
242 bool CTransaction::ReadFromDisk(COutPoint prevout)
246 return ReadFromDisk(txdb, prevout, txindex);
249 bool CTransaction::IsStandard() const
251 BOOST_FOREACH(const CTxIn& txin, vin)
253 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
254 // in an OP_EVAL, which is 3 ~80-byte signatures, 3
255 // ~65-byte public keys, plus a few script ops.
256 if (txin.scriptSig.size() > 500)
257 return error("nonstandard txin, size %d is too large\n", txin.scriptSig.size());
258 if (!txin.scriptSig.IsPushOnly())
259 return error("nonstandard txin (opcodes other than PUSH): %s", txin.scriptSig.ToString().c_str());
261 BOOST_FOREACH(const CTxOut& txout, vout)
262 if (!::IsStandard(txout.scriptPubKey))
263 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
268 // Check transaction inputs, and make sure any
269 // OP_EVAL transactions are evaluating IsStandard scripts
271 // Why bother? To avoid denial-of-service attacks; an attacker
272 // can submit a standard DUP HASH... OP_EVAL transaction,
273 // which will get accepted into blocks. The script being
274 // EVAL'ed can be anything; an attacker could use a very
275 // expensive-to-check-upon-redemption script like:
276 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
278 bool CTransaction::AreInputsStandard(std::map<uint256, std::pair<CTxIndex, CTransaction> > mapInputs) const
281 return true; // Allow non-standard on testnet
283 for (int i = 0; i < vin.size(); i++)
285 COutPoint prevout = vin[i].prevout;
286 assert(mapInputs.count(prevout.hash) > 0);
287 CTransaction& txPrev = mapInputs[prevout.hash].second;
289 vector<vector<unsigned char> > vSolutions;
290 txnouttype whichType;
291 // get the scriptPubKey corresponding to this input:
292 CScript& prevScript = txPrev.vout[prevout.n].scriptPubKey;
293 if (!Solver(prevScript, whichType, vSolutions))
294 return error("nonstandard txin (spending nonstandard txout %s)", prevScript.ToString().c_str());
295 if (whichType == TX_SCRIPTHASH)
297 vector<vector<unsigned char> > stack;
299 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0, true, nUnused))
301 CScript subscript(stack.back().begin(), stack.back().end());
302 if (!::IsStandard(subscript))
303 return error("nonstandard txin (nonstandard OP_EVAL subscript %s)", subscript.ToString().c_str());
312 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
324 // Load the block this tx is in
326 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
328 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
333 // Update the tx's hashBlock
334 hashBlock = pblock->GetHash();
336 // Locate the transaction
337 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
338 if (pblock->vtx[nIndex] == *(CTransaction*)this)
340 if (nIndex == pblock->vtx.size())
342 vMerkleBranch.clear();
344 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
348 // Fill in merkle branch
349 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
352 // Is the tx in a block that's in the main chain
353 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
354 if (mi == mapBlockIndex.end())
356 CBlockIndex* pindex = (*mi).second;
357 if (!pindex || !pindex->IsInMainChain())
360 return pindexBest->nHeight - pindex->nHeight + 1;
369 bool CTransaction::CheckTransaction() const
371 // Basic checks that don't depend on any context
373 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
375 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
377 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
378 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
380 // Check for negative or overflow output values
382 BOOST_FOREACH(const CTxOut& txout, vout)
384 if (txout.nValue < 0)
385 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
386 if (txout.nValue > MAX_MONEY)
387 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
388 nValueOut += txout.nValue;
389 if (!MoneyRange(nValueOut))
390 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
393 // Check for duplicate inputs
394 set<COutPoint> vInOutPoints;
395 BOOST_FOREACH(const CTxIn& txin, vin)
397 if (vInOutPoints.count(txin.prevout))
399 vInOutPoints.insert(txin.prevout);
404 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
405 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
409 BOOST_FOREACH(const CTxIn& txin, vin)
410 if (txin.prevout.IsNull())
411 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
417 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
420 *pfMissingInputs = false;
422 if (!CheckTransaction())
423 return error("AcceptToMemoryPool() : CheckTransaction failed");
425 // Coinbase is only valid in a block, not as a loose transaction
427 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
429 // To help v0.1.5 clients who would see it as a negative number
430 if ((int64)nLockTime > INT_MAX)
431 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
433 // Rather not work on nonstandard transactions (unless -testnet)
434 if (!fTestNet && !IsStandard())
435 return error("AcceptToMemoryPool() : nonstandard transaction type");
437 // Do we already have it?
438 uint256 hash = GetHash();
439 CRITICAL_BLOCK(cs_mapTransactions)
440 if (mapTransactions.count(hash))
443 if (txdb.ContainsTx(hash))
446 // Check for conflicts with in-memory transactions
447 CTransaction* ptxOld = NULL;
448 for (int i = 0; i < vin.size(); i++)
450 COutPoint outpoint = vin[i].prevout;
451 if (mapNextTx.count(outpoint))
453 // Disable replacement feature for now
456 // Allow replacing with a newer version of the same transaction
459 ptxOld = mapNextTx[outpoint].ptx;
460 if (ptxOld->IsFinal())
462 if (!IsNewerThan(*ptxOld))
464 for (int i = 0; i < vin.size(); i++)
466 COutPoint outpoint = vin[i].prevout;
467 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
476 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
477 map<uint256, CTxIndex> mapUnused;
478 if (!FetchInputs(txdb, mapUnused, false, false, mapInputs))
481 *pfMissingInputs = true;
482 return error("AcceptToMemoryPool() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
485 // Check for non-standard OP_EVALs in inputs
486 if (!AreInputsStandard(mapInputs))
487 return error("AcceptToMemoryPool() : nonstandard transaction input");
489 // Check against previous transactions
492 if (!ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false, nSigOps))
495 *pfMissingInputs = true;
496 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
498 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
499 // attacks disallow transactions with more than one SigOp per 65 bytes.
500 // 65 bytes because that is the minimum size of an ECDSA signature
501 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
502 if (nSigOps > nSize / 65 || nSize < 100)
503 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
505 // Don't accept it if it can't get into a block
506 if (nFees < GetMinFee(1000, true, true))
507 return error("AcceptToMemoryPool() : not enough fees");
509 // Continuously rate-limit free transactions
510 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
511 // be annoying or make other's transactions take longer to confirm.
512 if (nFees < MIN_RELAY_TX_FEE)
514 static CCriticalSection cs;
515 static double dFreeCount;
516 static int64 nLastTime;
517 int64 nNow = GetTime();
521 // Use an exponentially decaying ~10-minute window:
522 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
524 // -limitfreerelay unit is thousand-bytes-per-minute
525 // At default rate it would take over a month to fill 1GB
526 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
527 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
529 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
535 // Store transaction in memory
536 CRITICAL_BLOCK(cs_mapTransactions)
540 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
541 ptxOld->RemoveFromMemoryPool();
543 AddToMemoryPoolUnchecked();
546 ///// are we sure this is ok when loading transactions or restoring block txes
547 // If updated, erase old tx from wallet
549 EraseFromWallets(ptxOld->GetHash());
551 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
555 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
558 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
561 bool CTransaction::AddToMemoryPoolUnchecked()
563 // Add to memory pool without checking anything. Don't call this directly,
564 // call AcceptToMemoryPool to properly check the transaction first.
565 CRITICAL_BLOCK(cs_mapTransactions)
567 uint256 hash = GetHash();
568 mapTransactions[hash] = *this;
569 for (int i = 0; i < vin.size(); i++)
570 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
571 nTransactionsUpdated++;
577 bool CTransaction::RemoveFromMemoryPool()
579 // Remove transaction from memory pool
580 CRITICAL_BLOCK(cs_mapTransactions)
582 BOOST_FOREACH(const CTxIn& txin, vin)
583 mapNextTx.erase(txin.prevout);
584 mapTransactions.erase(GetHash());
585 nTransactionsUpdated++;
595 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
597 if (hashBlock == 0 || nIndex == -1)
600 // Find the block it claims to be in
601 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
602 if (mi == mapBlockIndex.end())
604 CBlockIndex* pindex = (*mi).second;
605 if (!pindex || !pindex->IsInMainChain())
608 // Make sure the merkle branch connects to this block
609 if (!fMerkleVerified)
611 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
613 fMerkleVerified = true;
617 return pindexBest->nHeight - pindex->nHeight + 1;
621 int CMerkleTx::GetBlocksToMaturity() const
625 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
629 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
633 if (!IsInMainChain() && !ClientConnectInputs())
635 return CTransaction::AcceptToMemoryPool(txdb, false);
639 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
643 bool CMerkleTx::AcceptToMemoryPool()
646 return AcceptToMemoryPool(txdb);
651 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
653 CRITICAL_BLOCK(cs_mapTransactions)
655 // Add previous supporting transactions first
656 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
658 if (!tx.IsCoinBase())
660 uint256 hash = tx.GetHash();
661 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
662 tx.AcceptToMemoryPool(txdb, fCheckInputs);
665 return AcceptToMemoryPool(txdb, fCheckInputs);
670 bool CWalletTx::AcceptWalletTransaction()
673 return AcceptWalletTransaction(txdb);
676 int CTxIndex::GetDepthInMainChain() const
680 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
682 // Find the block in the index
683 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
684 if (mi == mapBlockIndex.end())
686 CBlockIndex* pindex = (*mi).second;
687 if (!pindex || !pindex->IsInMainChain())
689 return 1 + nBestHeight - pindex->nHeight;
701 //////////////////////////////////////////////////////////////////////////////
703 // CBlock and CBlockIndex
706 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
708 if (!fReadTransactions)
710 *this = pindex->GetBlockHeader();
713 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
715 if (GetHash() != pindex->GetBlockHash())
716 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
720 uint256 static GetOrphanRoot(const CBlock* pblock)
722 // Work back to the first block in the orphan chain
723 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
724 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
725 return pblock->GetHash();
728 int64 static GetBlockValue(int nHeight, int64 nFees)
730 int64 nSubsidy = 50 * COIN;
732 // Subsidy is cut in half every 4 years
733 nSubsidy >>= (nHeight / 210000);
735 return nSubsidy + nFees;
738 static const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
739 static const int64 nTargetSpacing = 10 * 60;
740 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
743 // minimum amount of work that could possibly be required nTime after
744 // minimum work required was nBase
746 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
749 bnResult.SetCompact(nBase);
750 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
752 // Maximum 400% adjustment...
754 // ... in best-case exactly 4-times-normal target time
755 nTime -= nTargetTimespan*4;
757 if (bnResult > bnProofOfWorkLimit)
758 bnResult = bnProofOfWorkLimit;
759 return bnResult.GetCompact();
762 unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
766 if (pindexLast == NULL)
767 return bnProofOfWorkLimit.GetCompact();
769 // Only change once per interval
770 if ((pindexLast->nHeight+1) % nInterval != 0)
771 return pindexLast->nBits;
773 // Go back by what we want to be 14 days worth of blocks
774 const CBlockIndex* pindexFirst = pindexLast;
775 for (int i = 0; pindexFirst && i < nInterval-1; i++)
776 pindexFirst = pindexFirst->pprev;
779 // Limit adjustment step
780 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
781 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
782 if (nActualTimespan < nTargetTimespan/4)
783 nActualTimespan = nTargetTimespan/4;
784 if (nActualTimespan > nTargetTimespan*4)
785 nActualTimespan = nTargetTimespan*4;
789 bnNew.SetCompact(pindexLast->nBits);
790 bnNew *= nActualTimespan;
791 bnNew /= nTargetTimespan;
793 if (bnNew > bnProofOfWorkLimit)
794 bnNew = bnProofOfWorkLimit;
797 printf("GetNextWorkRequired RETARGET\n");
798 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
799 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
800 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
802 return bnNew.GetCompact();
805 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
808 bnTarget.SetCompact(nBits);
811 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
812 return error("CheckProofOfWork() : nBits below minimum work");
814 // Check proof of work matches claimed amount
815 if (hash > bnTarget.getuint256())
816 return error("CheckProofOfWork() : hash doesn't match nBits");
821 // Return maximum amount of blocks that other nodes claim to have
822 int GetNumBlocksOfPeers()
824 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
827 bool IsInitialBlockDownload()
829 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
831 static int64 nLastUpdate;
832 static CBlockIndex* pindexLastBest;
833 if (pindexBest != pindexLastBest)
835 pindexLastBest = pindexBest;
836 nLastUpdate = GetTime();
838 return (GetTime() - nLastUpdate < 10 &&
839 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
842 void static InvalidChainFound(CBlockIndex* pindexNew)
844 if (pindexNew->bnChainWork > bnBestInvalidWork)
846 bnBestInvalidWork = pindexNew->bnChainWork;
847 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
850 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());
851 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
852 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
853 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
866 bool CTransaction::DisconnectInputs(CTxDB& txdb)
868 // Relinquish previous transactions' spent pointers
871 BOOST_FOREACH(const CTxIn& txin, vin)
873 COutPoint prevout = txin.prevout;
875 // Get prev txindex from disk
877 if (!txdb.ReadTxIndex(prevout.hash, txindex))
878 return error("DisconnectInputs() : ReadTxIndex failed");
880 if (prevout.n >= txindex.vSpent.size())
881 return error("DisconnectInputs() : prevout.n out of range");
883 // Mark outpoint as not spent
884 txindex.vSpent[prevout.n].SetNull();
887 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
888 return error("DisconnectInputs() : UpdateTxIndex failed");
892 // Remove transaction from index
893 if (!txdb.EraseTxIndex(*this))
894 return error("DisconnectInputs() : EraseTxPos failed");
900 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
901 bool fBlock, bool fMiner, map<uint256, pair<CTxIndex, CTransaction> >& inputsRet)
904 return true; // Coinbase transactions have no inputs to fetch.
906 for (int i = 0; i < vin.size(); i++)
908 COutPoint prevout = vin[i].prevout;
909 if (inputsRet.count(prevout.hash))
910 continue; // Got it already
913 CTxIndex& txindex = inputsRet[prevout.hash].first;
915 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
917 // Get txindex from current proposed changes
918 txindex = mapTestPool.find(prevout.hash)->second;
922 // Read txindex from txdb
923 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
925 if (!fFound && (fBlock || fMiner))
926 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());
929 CTransaction& txPrev = inputsRet[prevout.hash].second;
930 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
932 // Get prev tx from single transactions in memory
933 CRITICAL_BLOCK(cs_mapTransactions)
935 if (!mapTransactions.count(prevout.hash))
936 return error("FetchInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
937 txPrev = mapTransactions[prevout.hash];
940 txindex.vSpent.resize(txPrev.vout.size());
944 // Get prev tx from disk
945 if (!txPrev.ReadFromDisk(txindex.pos))
946 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
952 bool CTransaction::ConnectInputs(map<uint256, pair<CTxIndex, CTransaction> > inputs,
953 map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
954 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int& nSigOpsRet, int64 nMinFee)
956 // Take over previous transactions' spent pointers
957 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
958 // fMiner is true when called from the internal bitcoin miner
959 // ... both are false when called from CTransaction::AcceptToMemoryPool
963 for (int i = 0; i < vin.size(); i++)
965 COutPoint prevout = vin[i].prevout;
966 assert(inputs.count(prevout.hash) > 0);
967 CTxIndex& txindex = inputs[prevout.hash].first;
968 CTransaction& txPrev = inputs[prevout.hash].second;
970 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
971 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()));
973 // If prev is coinbase, check that it's matured
974 if (txPrev.IsCoinBase())
975 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
976 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
977 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
979 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
980 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
981 // still computed and checked, and any change will be caught at the next checkpoint.
982 if (!(fBlock && IsInitialBlockDownload()))
984 bool fStrictOpEval = true;
985 // This code should be removed when OP_EVAL has
986 // a majority of hashing power on the network.
989 // To avoid being on the short end of a block-chain split,
990 // interpret OP_EVAL as a NO_OP until blocks with timestamps
992 int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400); // Feb 1, 2012
993 fStrictOpEval = (pindexBlock->nTime >= nEvalSwitchTime);
995 // if !fBlock, then always be strict-- don't accept
996 // invalid-under-new-rules OP_EVAL transactions into
997 // our memory pool (don't relay them, don't include them
998 // in blocks we mine).
1001 if (!VerifySignature(txPrev, *this, i, nSigOpsRet, fStrictOpEval))
1002 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1005 // Check for conflicts (double-spend)
1006 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1007 // for an attacker to attempt to split the network.
1008 if (!txindex.vSpent[prevout.n].IsNull())
1009 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());
1011 // Check for negative or overflow input values
1012 nValueIn += txPrev.vout[prevout.n].nValue;
1013 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1014 return DoS(100, error("ConnectInputs() : txin values out of range"));
1016 // Mark outpoints as spent
1017 txindex.vSpent[prevout.n] = posThisTx;
1020 if (fBlock || fMiner)
1022 mapTestPool[prevout.hash] = txindex;
1026 if (nValueIn < GetValueOut())
1027 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1029 // Tally transaction fees
1030 int64 nTxFee = nValueIn - GetValueOut();
1032 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1033 if (nTxFee < nMinFee)
1036 if (!MoneyRange(nFees))
1037 return DoS(100, error("ConnectInputs() : nFees out of range"));
1042 // Add transaction to changes
1043 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
1047 // Add transaction to test pool
1048 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1055 bool CTransaction::ClientConnectInputs()
1060 // Take over previous transactions' spent pointers
1061 CRITICAL_BLOCK(cs_mapTransactions)
1064 for (int i = 0; i < vin.size(); i++)
1066 // Get prev tx from single transactions in memory
1067 COutPoint prevout = vin[i].prevout;
1068 if (!mapTransactions.count(prevout.hash))
1070 CTransaction& txPrev = mapTransactions[prevout.hash];
1072 if (prevout.n >= txPrev.vout.size())
1077 if (!VerifySignature(txPrev, *this, i, nUnused, false))
1078 return error("ConnectInputs() : VerifySignature failed");
1080 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1081 ///// this has to go away now that posNext is gone
1082 // // Check for conflicts
1083 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1084 // return error("ConnectInputs() : prev tx already used");
1086 // // Flag outpoints as used
1087 // txPrev.vout[prevout.n].posNext = posThisTx;
1089 nValueIn += txPrev.vout[prevout.n].nValue;
1091 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1092 return error("ClientConnectInputs() : txin values out of range");
1094 if (GetValueOut() > nValueIn)
1104 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1106 // Disconnect in reverse order
1107 for (int i = vtx.size()-1; i >= 0; i--)
1108 if (!vtx[i].DisconnectInputs(txdb))
1111 // Update block index on disk without changing it in memory.
1112 // The memory index structure will be changed after the db commits.
1115 CDiskBlockIndex blockindexPrev(pindex->pprev);
1116 blockindexPrev.hashNext = 0;
1117 if (!txdb.WriteBlockIndex(blockindexPrev))
1118 return error("DisconnectBlock() : WriteBlockIndex failed");
1124 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1126 // Check it again in case a previous version let a bad block in
1130 //// issue here: it doesn't know the version
1131 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1133 map<uint256, CTxIndex> mapQueuedChanges;
1136 BOOST_FOREACH(CTransaction& tx, vtx)
1138 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1139 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1141 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
1142 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs))
1144 if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, nFees, true, false, nSigOps))
1146 if (nSigOps > MAX_BLOCK_SIGOPS)
1147 return DoS(100, error("ConnectBlock() : too many sigops"));
1150 // Write queued txindex changes
1151 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1153 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1154 return error("ConnectBlock() : UpdateTxIndex failed");
1157 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1160 // Update block index on disk without changing it in memory.
1161 // The memory index structure will be changed after the db commits.
1164 CDiskBlockIndex blockindexPrev(pindex->pprev);
1165 blockindexPrev.hashNext = pindex->GetBlockHash();
1166 if (!txdb.WriteBlockIndex(blockindexPrev))
1167 return error("ConnectBlock() : WriteBlockIndex failed");
1170 // Watch for transactions paying to me
1171 BOOST_FOREACH(CTransaction& tx, vtx)
1172 SyncWithWallets(tx, this, true);
1177 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1179 printf("REORGANIZE\n");
1182 CBlockIndex* pfork = pindexBest;
1183 CBlockIndex* plonger = pindexNew;
1184 while (pfork != plonger)
1186 while (plonger->nHeight > pfork->nHeight)
1187 if (!(plonger = plonger->pprev))
1188 return error("Reorganize() : plonger->pprev is null");
1189 if (pfork == plonger)
1191 if (!(pfork = pfork->pprev))
1192 return error("Reorganize() : pfork->pprev is null");
1195 // List of what to disconnect
1196 vector<CBlockIndex*> vDisconnect;
1197 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1198 vDisconnect.push_back(pindex);
1200 // List of what to connect
1201 vector<CBlockIndex*> vConnect;
1202 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1203 vConnect.push_back(pindex);
1204 reverse(vConnect.begin(), vConnect.end());
1206 // Disconnect shorter branch
1207 vector<CTransaction> vResurrect;
1208 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1211 if (!block.ReadFromDisk(pindex))
1212 return error("Reorganize() : ReadFromDisk for disconnect failed");
1213 if (!block.DisconnectBlock(txdb, pindex))
1214 return error("Reorganize() : DisconnectBlock failed");
1216 // Queue memory transactions to resurrect
1217 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1218 if (!tx.IsCoinBase())
1219 vResurrect.push_back(tx);
1222 // Connect longer branch
1223 vector<CTransaction> vDelete;
1224 for (int i = 0; i < vConnect.size(); i++)
1226 CBlockIndex* pindex = vConnect[i];
1228 if (!block.ReadFromDisk(pindex))
1229 return error("Reorganize() : ReadFromDisk for connect failed");
1230 if (!block.ConnectBlock(txdb, pindex))
1234 return error("Reorganize() : ConnectBlock failed");
1237 // Queue memory transactions to delete
1238 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1239 vDelete.push_back(tx);
1241 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1242 return error("Reorganize() : WriteHashBestChain failed");
1244 // Make sure it's successfully written to disk before changing memory structure
1245 if (!txdb.TxnCommit())
1246 return error("Reorganize() : TxnCommit failed");
1248 // Disconnect shorter branch
1249 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1251 pindex->pprev->pnext = NULL;
1253 // Connect longer branch
1254 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1256 pindex->pprev->pnext = pindex;
1258 // Resurrect memory transactions that were in the disconnected branch
1259 BOOST_FOREACH(CTransaction& tx, vResurrect)
1260 tx.AcceptToMemoryPool(txdb, false);
1262 // Delete redundant memory transactions that are in the connected branch
1263 BOOST_FOREACH(CTransaction& tx, vDelete)
1264 tx.RemoveFromMemoryPool();
1270 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1272 uint256 hash = GetHash();
1275 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1277 txdb.WriteHashBestChain(hash);
1278 if (!txdb.TxnCommit())
1279 return error("SetBestChain() : TxnCommit failed");
1280 pindexGenesisBlock = pindexNew;
1282 else if (hashPrevBlock == hashBestChain)
1284 // Adding to current best branch
1285 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1288 InvalidChainFound(pindexNew);
1289 return error("SetBestChain() : ConnectBlock failed");
1291 if (!txdb.TxnCommit())
1292 return error("SetBestChain() : TxnCommit failed");
1294 // Add to current best branch
1295 pindexNew->pprev->pnext = pindexNew;
1297 // Delete redundant memory transactions
1298 BOOST_FOREACH(CTransaction& tx, vtx)
1299 tx.RemoveFromMemoryPool();
1304 if (!Reorganize(txdb, pindexNew))
1307 InvalidChainFound(pindexNew);
1308 return error("SetBestChain() : Reorganize failed");
1312 // Update best block in wallet (so we can detect restored wallets)
1313 if (!IsInitialBlockDownload())
1315 const CBlockLocator locator(pindexNew);
1316 ::SetBestChain(locator);
1320 hashBestChain = hash;
1321 pindexBest = pindexNew;
1322 nBestHeight = pindexBest->nHeight;
1323 bnBestChainWork = pindexNew->bnChainWork;
1324 nTimeBestReceived = GetTime();
1325 nTransactionsUpdated++;
1326 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1332 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1334 // Check for duplicate
1335 uint256 hash = GetHash();
1336 if (mapBlockIndex.count(hash))
1337 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1339 // Construct new block index object
1340 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1342 return error("AddToBlockIndex() : new CBlockIndex failed");
1343 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1344 pindexNew->phashBlock = &((*mi).first);
1345 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1346 if (miPrev != mapBlockIndex.end())
1348 pindexNew->pprev = (*miPrev).second;
1349 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1351 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1355 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1356 if (!txdb.TxnCommit())
1360 if (pindexNew->bnChainWork > bnBestChainWork)
1361 if (!SetBestChain(txdb, pindexNew))
1366 if (pindexNew == pindexBest)
1368 // Notify UI to display prev block's coinbase if it was ours
1369 static uint256 hashPrevBestCoinBase;
1370 UpdatedTransaction(hashPrevBestCoinBase);
1371 hashPrevBestCoinBase = vtx[0].GetHash();
1381 bool CBlock::CheckBlock() const
1383 // These are checks that are independent of context
1384 // that can be verified before saving an orphan block.
1387 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1388 return DoS(100, error("CheckBlock() : size limits failed"));
1390 // Check proof of work matches claimed amount
1391 if (!CheckProofOfWork(GetHash(), nBits))
1392 return DoS(50, error("CheckBlock() : proof of work failed"));
1395 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1396 return error("CheckBlock() : block timestamp too far in the future");
1398 // First transaction must be coinbase, the rest must not be
1399 if (vtx.empty() || !vtx[0].IsCoinBase())
1400 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1401 for (int i = 1; i < vtx.size(); i++)
1402 if (vtx[i].IsCoinBase())
1403 return DoS(100, error("CheckBlock() : more than one coinbase"));
1405 // Check transactions
1406 BOOST_FOREACH(const CTransaction& tx, vtx)
1407 if (!tx.CheckTransaction())
1408 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1410 // This code should be removed when a compatibility-breaking block chain split has passed.
1411 // Compatibility check for old clients that counted sigops differently:
1413 BOOST_FOREACH(const CTransaction& tx, vtx)
1415 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1417 nSigOps += txin.scriptSig.GetSigOpCount();
1419 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1421 nSigOps += txout.scriptPubKey.GetSigOpCount();
1424 if (nSigOps > MAX_BLOCK_SIGOPS)
1425 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1428 if (hashMerkleRoot != BuildMerkleTree())
1429 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1434 bool CBlock::AcceptBlock()
1436 // Check for duplicate
1437 uint256 hash = GetHash();
1438 if (mapBlockIndex.count(hash))
1439 return error("AcceptBlock() : block already in mapBlockIndex");
1441 // Get prev block index
1442 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1443 if (mi == mapBlockIndex.end())
1444 return DoS(10, error("AcceptBlock() : prev block not found"));
1445 CBlockIndex* pindexPrev = (*mi).second;
1446 int nHeight = pindexPrev->nHeight+1;
1448 // Check proof of work
1449 if (nBits != GetNextWorkRequired(pindexPrev))
1450 return DoS(100, error("AcceptBlock() : incorrect proof of work"));
1452 // Check timestamp against prev
1453 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1454 return error("AcceptBlock() : block's timestamp is too early");
1456 // Check that all transactions are finalized
1457 BOOST_FOREACH(const CTransaction& tx, vtx)
1458 if (!tx.IsFinal(nHeight, GetBlockTime()))
1459 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1461 // Check that the block chain matches the known block chain up to a checkpoint
1462 if (!Checkpoints::CheckBlock(nHeight, hash))
1463 return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
1465 // Write block to history file
1466 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1467 return error("AcceptBlock() : out of disk space");
1468 unsigned int nFile = -1;
1469 unsigned int nBlockPos = 0;
1470 if (!WriteToDisk(nFile, nBlockPos))
1471 return error("AcceptBlock() : WriteToDisk failed");
1472 if (!AddToBlockIndex(nFile, nBlockPos))
1473 return error("AcceptBlock() : AddToBlockIndex failed");
1475 // Relay inventory, but don't relay old inventory during initial block download
1476 if (hashBestChain == hash)
1477 CRITICAL_BLOCK(cs_vNodes)
1478 BOOST_FOREACH(CNode* pnode, vNodes)
1479 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1480 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1485 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1487 // Check for duplicate
1488 uint256 hash = pblock->GetHash();
1489 if (mapBlockIndex.count(hash))
1490 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1491 if (mapOrphanBlocks.count(hash))
1492 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1494 // Preliminary checks
1495 if (!pblock->CheckBlock())
1496 return error("ProcessBlock() : CheckBlock FAILED");
1498 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1499 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1501 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1502 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1505 pfrom->Misbehaving(100);
1506 return error("ProcessBlock() : block with timestamp before last checkpoint");
1509 bnNewBlock.SetCompact(pblock->nBits);
1511 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1512 if (bnNewBlock > bnRequired)
1514 pfrom->Misbehaving(100);
1515 return error("ProcessBlock() : block with too little proof-of-work");
1520 // If don't already have its previous block, shunt it off to holding area until we get it
1521 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1523 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1524 CBlock* pblock2 = new CBlock(*pblock);
1525 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1526 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1528 // Ask this guy to fill in what we're missing
1530 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1535 if (!pblock->AcceptBlock())
1536 return error("ProcessBlock() : AcceptBlock FAILED");
1538 // Recursively process any orphan blocks that depended on this one
1539 vector<uint256> vWorkQueue;
1540 vWorkQueue.push_back(hash);
1541 for (int i = 0; i < vWorkQueue.size(); i++)
1543 uint256 hashPrev = vWorkQueue[i];
1544 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1545 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1548 CBlock* pblockOrphan = (*mi).second;
1549 if (pblockOrphan->AcceptBlock())
1550 vWorkQueue.push_back(pblockOrphan->GetHash());
1551 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1552 delete pblockOrphan;
1554 mapOrphanBlocksByPrev.erase(hashPrev);
1557 printf("ProcessBlock: ACCEPTED\n");
1568 bool CheckDiskSpace(uint64 nAdditionalBytes)
1570 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1572 // Check for 15MB because database could create another 10MB log file at any time
1573 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1576 string strMessage = _("Warning: Disk space is low ");
1577 strMiscWarning = strMessage;
1578 printf("*** %s\n", strMessage.c_str());
1579 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1580 CreateThread(Shutdown, NULL);
1586 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1590 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1593 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1595 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1604 static unsigned int nCurrentBlockFile = 1;
1606 FILE* AppendBlockFile(unsigned int& nFileRet)
1611 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1614 if (fseek(file, 0, SEEK_END) != 0)
1616 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1617 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1619 nFileRet = nCurrentBlockFile;
1623 nCurrentBlockFile++;
1627 bool LoadBlockIndex(bool fAllowNew)
1631 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1632 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1633 pchMessageStart[0] = 0xfa;
1634 pchMessageStart[1] = 0xbf;
1635 pchMessageStart[2] = 0xb5;
1636 pchMessageStart[3] = 0xda;
1643 if (!txdb.LoadBlockIndex())
1648 // Init with genesis block
1650 if (mapBlockIndex.empty())
1656 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1657 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1658 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1659 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1660 // vMerkleTree: 4a5e1e
1663 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1665 txNew.vin.resize(1);
1666 txNew.vout.resize(1);
1667 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1668 txNew.vout[0].nValue = 50 * COIN;
1669 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1671 block.vtx.push_back(txNew);
1672 block.hashPrevBlock = 0;
1673 block.hashMerkleRoot = block.BuildMerkleTree();
1675 block.nTime = 1231006505;
1676 block.nBits = 0x1d00ffff;
1677 block.nNonce = 2083236893;
1681 block.nTime = 1296688602;
1682 block.nBits = 0x1d07fff8;
1683 block.nNonce = 384568319;
1687 printf("%s\n", block.GetHash().ToString().c_str());
1688 printf("%s\n", hashGenesisBlock.ToString().c_str());
1689 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1690 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1692 assert(block.GetHash() == hashGenesisBlock);
1694 // Start new block file
1696 unsigned int nBlockPos;
1697 if (!block.WriteToDisk(nFile, nBlockPos))
1698 return error("LoadBlockIndex() : writing genesis block to disk failed");
1699 if (!block.AddToBlockIndex(nFile, nBlockPos))
1700 return error("LoadBlockIndex() : genesis block not accepted");
1708 void PrintBlockTree()
1710 // precompute tree structure
1711 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1712 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1714 CBlockIndex* pindex = (*mi).second;
1715 mapNext[pindex->pprev].push_back(pindex);
1717 //while (rand() % 3 == 0)
1718 // mapNext[pindex->pprev].push_back(pindex);
1721 vector<pair<int, CBlockIndex*> > vStack;
1722 vStack.push_back(make_pair(0, pindexGenesisBlock));
1725 while (!vStack.empty())
1727 int nCol = vStack.back().first;
1728 CBlockIndex* pindex = vStack.back().second;
1731 // print split or gap
1732 if (nCol > nPrevCol)
1734 for (int i = 0; i < nCol-1; i++)
1738 else if (nCol < nPrevCol)
1740 for (int i = 0; i < nCol; i++)
1747 for (int i = 0; i < nCol; i++)
1752 block.ReadFromDisk(pindex);
1753 printf("%d (%u,%u) %s %s tx %d",
1757 block.GetHash().ToString().substr(0,20).c_str(),
1758 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1761 PrintWallets(block);
1763 // put the main timechain first
1764 vector<CBlockIndex*>& vNext = mapNext[pindex];
1765 for (int i = 0; i < vNext.size(); i++)
1767 if (vNext[i]->pnext)
1769 swap(vNext[0], vNext[i]);
1775 for (int i = 0; i < vNext.size(); i++)
1776 vStack.push_back(make_pair(nCol+i, vNext[i]));
1789 //////////////////////////////////////////////////////////////////////////////
1794 map<uint256, CAlert> mapAlerts;
1795 CCriticalSection cs_mapAlerts;
1797 string GetWarnings(string strFor)
1800 string strStatusBar;
1802 if (GetBoolArg("-testsafemode"))
1805 // Misc warnings like out of disk space and clock is wrong
1806 if (strMiscWarning != "")
1809 strStatusBar = strMiscWarning;
1812 // Longer invalid proof-of-work chain
1813 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1816 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1820 CRITICAL_BLOCK(cs_mapAlerts)
1822 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1824 const CAlert& alert = item.second;
1825 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1827 nPriority = alert.nPriority;
1828 strStatusBar = alert.strStatusBar;
1833 if (strFor == "statusbar")
1834 return strStatusBar;
1835 else if (strFor == "rpc")
1837 assert(!"GetWarnings() : invalid parameter");
1841 bool CAlert::ProcessAlert()
1843 if (!CheckSignature())
1848 CRITICAL_BLOCK(cs_mapAlerts)
1850 // Cancel previous alerts
1851 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1853 const CAlert& alert = (*mi).second;
1856 printf("cancelling alert %d\n", alert.nID);
1857 mapAlerts.erase(mi++);
1859 else if (!alert.IsInEffect())
1861 printf("expiring alert %d\n", alert.nID);
1862 mapAlerts.erase(mi++);
1868 // Check if this alert has been cancelled
1869 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1871 const CAlert& alert = item.second;
1872 if (alert.Cancels(*this))
1874 printf("alert already cancelled by %d\n", alert.nID);
1880 mapAlerts.insert(make_pair(GetHash(), *this));
1883 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1895 //////////////////////////////////////////////////////////////////////////////
1901 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
1905 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
1906 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
1908 // Don't know what it is, just say we already got one
1915 // The message start string is designed to be unlikely to occur in normal data.
1916 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
1917 // a large 4-byte int at any alignment.
1918 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
1921 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
1923 static map<unsigned int, vector<unsigned char> > mapReuseKey;
1924 RandAddSeedPerfmon();
1926 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
1927 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
1929 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
1931 printf("dropmessagestest DROPPING RECV MESSAGE\n");
1939 if (strCommand == "version")
1941 // Each connection can only send one version message
1942 if (pfrom->nVersion != 0)
1944 pfrom->Misbehaving(1);
1952 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
1953 if (pfrom->nVersion == 10300)
1954 pfrom->nVersion = 300;
1955 if (pfrom->nVersion >= 106 && !vRecv.empty())
1956 vRecv >> addrFrom >> nNonce;
1957 if (pfrom->nVersion >= 106 && !vRecv.empty())
1958 vRecv >> pfrom->strSubVer;
1959 if (pfrom->nVersion >= 209 && !vRecv.empty())
1960 vRecv >> pfrom->nStartingHeight;
1962 if (pfrom->nVersion == 0)
1965 // Disconnect if we connected to ourself
1966 if (nNonce == nLocalHostNonce && nNonce > 1)
1968 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
1969 pfrom->fDisconnect = true;
1973 // Be shy and don't send version until we hear
1974 if (pfrom->fInbound)
1975 pfrom->PushVersion();
1977 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
1979 AddTimeData(pfrom->addr.ip, nTime);
1982 if (pfrom->nVersion >= 209)
1983 pfrom->PushMessage("verack");
1984 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1985 if (pfrom->nVersion < 209)
1986 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
1988 if (!pfrom->fInbound)
1990 // Advertise our address
1991 if (addrLocalHost.IsRoutable() && !fUseProxy)
1993 CAddress addr(addrLocalHost);
1994 addr.nTime = GetAdjustedTime();
1995 pfrom->PushAddress(addr);
1998 // Get recent addresses
1999 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2001 pfrom->PushMessage("getaddr");
2002 pfrom->fGetAddr = true;
2006 // Ask the first connected node for block updates
2007 static int nAskedForBlocks;
2008 if (!pfrom->fClient &&
2009 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2010 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2013 pfrom->PushGetBlocks(pindexBest, uint256(0));
2017 CRITICAL_BLOCK(cs_mapAlerts)
2018 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2019 item.second.RelayTo(pfrom);
2021 pfrom->fSuccessfullyConnected = true;
2023 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2025 cPeerBlockCounts.input(pfrom->nStartingHeight);
2029 else if (pfrom->nVersion == 0)
2031 // Must have a version message before anything else
2032 pfrom->Misbehaving(1);
2037 else if (strCommand == "verack")
2039 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2043 else if (strCommand == "addr")
2045 vector<CAddress> vAddr;
2048 // Don't want addr from older versions unless seeding
2049 if (pfrom->nVersion < 209)
2051 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2053 if (vAddr.size() > 1000)
2055 pfrom->Misbehaving(20);
2056 return error("message addr size() = %d", vAddr.size());
2059 // Store the new addresses
2062 int64 nNow = GetAdjustedTime();
2063 int64 nSince = nNow - 10 * 60;
2064 BOOST_FOREACH(CAddress& addr, vAddr)
2068 // ignore IPv6 for now, since it isn't implemented anyway
2071 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2072 addr.nTime = nNow - 5 * 24 * 60 * 60;
2073 AddAddress(addr, 2 * 60 * 60, &addrDB);
2074 pfrom->AddAddressKnown(addr);
2075 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2077 // Relay to a limited number of other nodes
2078 CRITICAL_BLOCK(cs_vNodes)
2080 // Use deterministic randomness to send to the same nodes for 24 hours
2081 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2082 static uint256 hashSalt;
2084 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2085 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2086 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2087 multimap<uint256, CNode*> mapMix;
2088 BOOST_FOREACH(CNode* pnode, vNodes)
2090 if (pnode->nVersion < 31402)
2092 unsigned int nPointer;
2093 memcpy(&nPointer, &pnode, sizeof(nPointer));
2094 uint256 hashKey = hashRand ^ nPointer;
2095 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2096 mapMix.insert(make_pair(hashKey, pnode));
2098 int nRelayNodes = 2;
2099 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2100 ((*mi).second)->PushAddress(addr);
2104 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2105 if (vAddr.size() < 1000)
2106 pfrom->fGetAddr = false;
2110 else if (strCommand == "inv")
2114 if (vInv.size() > 50000)
2116 pfrom->Misbehaving(20);
2117 return error("message inv size() = %d", vInv.size());
2121 BOOST_FOREACH(const CInv& inv, vInv)
2125 pfrom->AddInventoryKnown(inv);
2127 bool fAlreadyHave = AlreadyHave(txdb, inv);
2129 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2133 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2134 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2136 // Track requests for our stuff
2137 Inventory(inv.hash);
2142 else if (strCommand == "getdata")
2146 if (vInv.size() > 50000)
2148 pfrom->Misbehaving(20);
2149 return error("message getdata size() = %d", vInv.size());
2152 BOOST_FOREACH(const CInv& inv, vInv)
2156 printf("received getdata for: %s\n", inv.ToString().c_str());
2158 if (inv.type == MSG_BLOCK)
2160 // Send block from disk
2161 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2162 if (mi != mapBlockIndex.end())
2165 block.ReadFromDisk((*mi).second);
2166 pfrom->PushMessage("block", block);
2168 // Trigger them to send a getblocks request for the next batch of inventory
2169 if (inv.hash == pfrom->hashContinue)
2171 // Bypass PushInventory, this must send even if redundant,
2172 // and we want it right after the last block so they don't
2173 // wait for other stuff first.
2175 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2176 pfrom->PushMessage("inv", vInv);
2177 pfrom->hashContinue = 0;
2181 else if (inv.IsKnownType())
2183 // Send stream from relay memory
2184 CRITICAL_BLOCK(cs_mapRelay)
2186 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2187 if (mi != mapRelay.end())
2188 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2192 // Track requests for our stuff
2193 Inventory(inv.hash);
2198 else if (strCommand == "getblocks")
2200 CBlockLocator locator;
2202 vRecv >> locator >> hashStop;
2204 // Find the last block the caller has in the main chain
2205 CBlockIndex* pindex = locator.GetBlockIndex();
2207 // Send the rest of the chain
2209 pindex = pindex->pnext;
2210 int nLimit = 500 + locator.GetDistanceBack();
2211 unsigned int nBytes = 0;
2212 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2213 for (; pindex; pindex = pindex->pnext)
2215 if (pindex->GetBlockHash() == hashStop)
2217 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2220 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2222 block.ReadFromDisk(pindex, true);
2223 nBytes += block.GetSerializeSize(SER_NETWORK);
2224 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2226 // When this block is requested, we'll send an inv that'll make them
2227 // getblocks the next batch of inventory.
2228 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2229 pfrom->hashContinue = pindex->GetBlockHash();
2236 else if (strCommand == "getheaders")
2238 CBlockLocator locator;
2240 vRecv >> locator >> hashStop;
2242 CBlockIndex* pindex = NULL;
2243 if (locator.IsNull())
2245 // If locator is null, return the hashStop block
2246 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2247 if (mi == mapBlockIndex.end())
2249 pindex = (*mi).second;
2253 // Find the last block the caller has in the main chain
2254 pindex = locator.GetBlockIndex();
2256 pindex = pindex->pnext;
2259 vector<CBlock> vHeaders;
2260 int nLimit = 2000 + locator.GetDistanceBack();
2261 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2262 for (; pindex; pindex = pindex->pnext)
2264 vHeaders.push_back(pindex->GetBlockHeader());
2265 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2268 pfrom->PushMessage("headers", vHeaders);
2272 else if (strCommand == "tx")
2274 vector<uint256> vWorkQueue;
2275 CDataStream vMsg(vRecv);
2279 CInv inv(MSG_TX, tx.GetHash());
2280 pfrom->AddInventoryKnown(inv);
2282 bool fMissingInputs = false;
2283 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2285 SyncWithWallets(tx, NULL, true);
2286 RelayMessage(inv, vMsg);
2287 mapAlreadyAskedFor.erase(inv);
2288 vWorkQueue.push_back(inv.hash);
2290 // Recursively process any orphan transactions that depended on this one
2291 for (int i = 0; i < vWorkQueue.size(); i++)
2293 uint256 hashPrev = vWorkQueue[i];
2294 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2295 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2298 const CDataStream& vMsg = *((*mi).second);
2300 CDataStream(vMsg) >> tx;
2301 CInv inv(MSG_TX, tx.GetHash());
2303 if (tx.AcceptToMemoryPool(true))
2305 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2306 SyncWithWallets(tx, NULL, true);
2307 RelayMessage(inv, vMsg);
2308 mapAlreadyAskedFor.erase(inv);
2309 vWorkQueue.push_back(inv.hash);
2314 BOOST_FOREACH(uint256 hash, vWorkQueue)
2315 EraseOrphanTx(hash);
2317 else if (fMissingInputs)
2319 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2322 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2326 else if (strCommand == "block")
2331 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2334 CInv inv(MSG_BLOCK, block.GetHash());
2335 pfrom->AddInventoryKnown(inv);
2337 if (ProcessBlock(pfrom, &block))
2338 mapAlreadyAskedFor.erase(inv);
2339 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2343 else if (strCommand == "getaddr")
2345 // Nodes rebroadcast an addr every 24 hours
2346 pfrom->vAddrToSend.clear();
2347 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2348 CRITICAL_BLOCK(cs_mapAddresses)
2350 unsigned int nCount = 0;
2351 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2353 const CAddress& addr = item.second;
2354 if (addr.nTime > nSince)
2357 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2359 const CAddress& addr = item.second;
2360 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2361 pfrom->PushAddress(addr);
2367 else if (strCommand == "checkorder")
2372 if (!GetBoolArg("-allowreceivebyip"))
2374 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2381 /// we have a chance to check the order here
2383 // Keep giving the same key to the same ip until they use it
2384 if (!mapReuseKey.count(pfrom->addr.ip))
2385 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2387 // Send back approval of order and pubkey to use
2388 CScript scriptPubKey;
2389 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2390 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2394 else if (strCommand == "reply")
2399 CRequestTracker tracker;
2400 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2402 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2403 if (mi != pfrom->mapRequests.end())
2405 tracker = (*mi).second;
2406 pfrom->mapRequests.erase(mi);
2409 if (!tracker.IsNull())
2410 tracker.fn(tracker.param1, vRecv);
2414 else if (strCommand == "ping")
2419 else if (strCommand == "alert")
2424 if (alert.ProcessAlert())
2427 pfrom->setKnown.insert(alert.GetHash());
2428 CRITICAL_BLOCK(cs_vNodes)
2429 BOOST_FOREACH(CNode* pnode, vNodes)
2430 alert.RelayTo(pnode);
2437 // Ignore unknown commands for extensibility
2441 // Update the last seen time for this node's address
2442 if (pfrom->fNetworkNode)
2443 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2444 AddressCurrentlyConnected(pfrom->addr);
2450 bool ProcessMessages(CNode* pfrom)
2452 CDataStream& vRecv = pfrom->vRecv;
2456 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2460 // (4) message start
2469 // Scan for message start
2470 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2471 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2472 if (vRecv.end() - pstart < nHeaderSize)
2474 if (vRecv.size() > nHeaderSize)
2476 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2477 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2481 if (pstart - vRecv.begin() > 0)
2482 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2483 vRecv.erase(vRecv.begin(), pstart);
2486 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2491 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2494 string strCommand = hdr.GetCommand();
2497 unsigned int nMessageSize = hdr.nMessageSize;
2498 if (nMessageSize > MAX_SIZE)
2500 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2503 if (nMessageSize > vRecv.size())
2505 // Rewind and wait for rest of message
2506 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2511 if (vRecv.GetVersion() >= 209)
2513 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2514 unsigned int nChecksum = 0;
2515 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2516 if (nChecksum != hdr.nChecksum)
2518 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2519 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2524 // Copy message to its own buffer
2525 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2526 vRecv.ignore(nMessageSize);
2532 CRITICAL_BLOCK(cs_main)
2533 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2537 catch (std::ios_base::failure& e)
2539 if (strstr(e.what(), "end of data"))
2541 // Allow exceptions from underlength message on vRecv
2542 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());
2544 else if (strstr(e.what(), "size too large"))
2546 // Allow exceptions from overlong size
2547 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2551 PrintExceptionContinue(&e, "ProcessMessage()");
2554 catch (std::exception& e) {
2555 PrintExceptionContinue(&e, "ProcessMessage()");
2557 PrintExceptionContinue(NULL, "ProcessMessage()");
2561 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2569 bool SendMessages(CNode* pto, bool fSendTrickle)
2571 CRITICAL_BLOCK(cs_main)
2573 // Don't send anything until we get their version message
2574 if (pto->nVersion == 0)
2578 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2579 pto->PushMessage("ping");
2581 // Resend wallet transactions that haven't gotten in a block yet
2582 ResendWalletTransactions();
2584 // Address refresh broadcast
2585 static int64 nLastRebroadcast;
2586 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2588 nLastRebroadcast = GetTime();
2589 CRITICAL_BLOCK(cs_vNodes)
2591 BOOST_FOREACH(CNode* pnode, vNodes)
2593 // Periodically clear setAddrKnown to allow refresh broadcasts
2594 pnode->setAddrKnown.clear();
2596 // Rebroadcast our address
2597 if (addrLocalHost.IsRoutable() && !fUseProxy)
2599 CAddress addr(addrLocalHost);
2600 addr.nTime = GetAdjustedTime();
2601 pnode->PushAddress(addr);
2607 // Clear out old addresses periodically so it's not too much work at once
2608 static int64 nLastClear;
2609 if (nLastClear == 0)
2610 nLastClear = GetTime();
2611 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2613 nLastClear = GetTime();
2614 CRITICAL_BLOCK(cs_mapAddresses)
2617 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2618 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2619 mi != mapAddresses.end();)
2621 const CAddress& addr = (*mi).second;
2622 if (addr.nTime < nSince)
2624 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2626 addrdb.EraseAddress(addr);
2627 mapAddresses.erase(mi++);
2641 vector<CAddress> vAddr;
2642 vAddr.reserve(pto->vAddrToSend.size());
2643 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2645 // returns true if wasn't already contained in the set
2646 if (pto->setAddrKnown.insert(addr).second)
2648 vAddr.push_back(addr);
2649 // receiver rejects addr messages larger than 1000
2650 if (vAddr.size() >= 1000)
2652 pto->PushMessage("addr", vAddr);
2657 pto->vAddrToSend.clear();
2659 pto->PushMessage("addr", vAddr);
2664 // Message: inventory
2667 vector<CInv> vInvWait;
2668 CRITICAL_BLOCK(pto->cs_inventory)
2670 vInv.reserve(pto->vInventoryToSend.size());
2671 vInvWait.reserve(pto->vInventoryToSend.size());
2672 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2674 if (pto->setInventoryKnown.count(inv))
2677 // trickle out tx inv to protect privacy
2678 if (inv.type == MSG_TX && !fSendTrickle)
2680 // 1/4 of tx invs blast to all immediately
2681 static uint256 hashSalt;
2683 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2684 uint256 hashRand = inv.hash ^ hashSalt;
2685 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2686 bool fTrickleWait = ((hashRand & 3) != 0);
2688 // always trickle our own transactions
2692 if (GetTransaction(inv.hash, wtx))
2694 fTrickleWait = true;
2699 vInvWait.push_back(inv);
2704 // returns true if wasn't already contained in the set
2705 if (pto->setInventoryKnown.insert(inv).second)
2707 vInv.push_back(inv);
2708 if (vInv.size() >= 1000)
2710 pto->PushMessage("inv", vInv);
2715 pto->vInventoryToSend = vInvWait;
2718 pto->PushMessage("inv", vInv);
2724 vector<CInv> vGetData;
2725 int64 nNow = GetTime() * 1000000;
2727 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2729 const CInv& inv = (*pto->mapAskFor.begin()).second;
2730 if (!AlreadyHave(txdb, inv))
2732 printf("sending getdata: %s\n", inv.ToString().c_str());
2733 vGetData.push_back(inv);
2734 if (vGetData.size() >= 1000)
2736 pto->PushMessage("getdata", vGetData);
2740 mapAlreadyAskedFor[inv] = nNow;
2741 pto->mapAskFor.erase(pto->mapAskFor.begin());
2743 if (!vGetData.empty())
2744 pto->PushMessage("getdata", vGetData);
2763 //////////////////////////////////////////////////////////////////////////////
2768 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2770 unsigned char* pdata = (unsigned char*)pbuffer;
2771 unsigned int blocks = 1 + ((len + 8) / 64);
2772 unsigned char* pend = pdata + 64 * blocks;
2773 memset(pdata + len, 0, 64 * blocks - len);
2775 unsigned int bits = len * 8;
2776 pend[-1] = (bits >> 0) & 0xff;
2777 pend[-2] = (bits >> 8) & 0xff;
2778 pend[-3] = (bits >> 16) & 0xff;
2779 pend[-4] = (bits >> 24) & 0xff;
2783 static const unsigned int pSHA256InitState[8] =
2784 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2786 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2789 unsigned char data[64];
2793 for (int i = 0; i < 16; i++)
2794 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2796 for (int i = 0; i < 8; i++)
2797 ctx.h[i] = ((uint32_t*)pinit)[i];
2799 SHA256_Update(&ctx, data, sizeof(data));
2800 for (int i = 0; i < 8; i++)
2801 ((uint32_t*)pstate)[i] = ctx.h[i];
2805 // ScanHash scans nonces looking for a hash with at least some zero bits.
2806 // It operates on big endian data. Caller does the byte reversing.
2807 // All input buffers are 16-byte aligned. nNonce is usually preserved
2808 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2809 // the block is rebuilt and nNonce starts over at zero.
2811 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2813 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2817 // Hash pdata using pmidstate as the starting state into
2818 // preformatted buffer phash1, then hash phash1 into phash
2820 SHA256Transform(phash1, pdata, pmidstate);
2821 SHA256Transform(phash, phash1, pSHA256InitState);
2823 // Return the nonce if the hash has at least some zero bits,
2824 // caller will check if it has enough to reach the target
2825 if (((unsigned short*)phash)[14] == 0)
2828 // If nothing found after trying for a while, return -1
2829 if ((nNonce & 0xffff) == 0)
2831 nHashesDone = 0xffff+1;
2837 // Some explaining would be appreciated
2842 set<uint256> setDependsOn;
2845 COrphan(CTransaction* ptxIn)
2853 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2854 BOOST_FOREACH(uint256 hash, setDependsOn)
2855 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2860 CBlock* CreateNewBlock(CReserveKey& reservekey)
2862 CBlockIndex* pindexPrev = pindexBest;
2865 auto_ptr<CBlock> pblock(new CBlock());
2869 // Create coinbase tx
2871 txNew.vin.resize(1);
2872 txNew.vin[0].prevout.SetNull();
2873 txNew.vout.resize(1);
2874 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2876 // Add our coinbase tx as first transaction
2877 pblock->vtx.push_back(txNew);
2879 // Collect memory pool transactions into the block
2881 CRITICAL_BLOCK(cs_main)
2882 CRITICAL_BLOCK(cs_mapTransactions)
2886 // Priority order to process transactions
2887 list<COrphan> vOrphan; // list memory doesn't move
2888 map<uint256, vector<COrphan*> > mapDependers;
2889 multimap<double, CTransaction*> mapPriority;
2890 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
2892 CTransaction& tx = (*mi).second;
2893 if (tx.IsCoinBase() || !tx.IsFinal())
2896 COrphan* porphan = NULL;
2897 double dPriority = 0;
2898 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2900 // Read prev transaction
2901 CTransaction txPrev;
2903 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2905 // Has to wait for dependencies
2908 // Use list for automatic deletion
2909 vOrphan.push_back(COrphan(&tx));
2910 porphan = &vOrphan.back();
2912 mapDependers[txin.prevout.hash].push_back(porphan);
2913 porphan->setDependsOn.insert(txin.prevout.hash);
2916 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2918 // Read block header
2919 int nConf = txindex.GetDepthInMainChain();
2921 dPriority += (double)nValueIn * nConf;
2923 if (fDebug && GetBoolArg("-printpriority"))
2924 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
2927 // Priority is sum(valuein * age) / txsize
2928 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
2931 porphan->dPriority = dPriority;
2933 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
2935 if (fDebug && GetBoolArg("-printpriority"))
2937 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
2944 // Collect transactions into block
2945 map<uint256, CTxIndex> mapTestPool;
2946 uint64 nBlockSize = 1000;
2947 int nBlockSigOps = 100;
2948 while (!mapPriority.empty())
2950 // Take highest priority transaction off priority queue
2951 double dPriority = -(*mapPriority.begin()).first;
2952 CTransaction& tx = *(*mapPriority.begin()).second;
2953 mapPriority.erase(mapPriority.begin());
2956 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
2957 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
2960 // Transaction fee required depends on block size
2961 bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
2962 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
2964 // Connecting shouldn't fail due to dependency on other memory pool transactions
2965 // because we're already processing them in order of dependency
2966 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
2967 map<uint256, pair<CTxIndex, CTransaction> > mapInputs;
2968 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs))
2971 if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nTxSigOps, nMinFee))
2973 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
2975 swap(mapTestPool, mapTestPoolTmp);
2978 pblock->vtx.push_back(tx);
2979 nBlockSize += nTxSize;
2980 nBlockSigOps += nTxSigOps;
2982 // Add transactions that depend on this one to the priority queue
2983 uint256 hash = tx.GetHash();
2984 if (mapDependers.count(hash))
2986 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
2988 if (!porphan->setDependsOn.empty())
2990 porphan->setDependsOn.erase(hash);
2991 if (porphan->setDependsOn.empty())
2992 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
2998 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3001 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3002 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3003 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3004 pblock->nBits = GetNextWorkRequired(pindexPrev);
3007 return pblock.release();
3011 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3013 // Update nExtraNonce
3014 static uint256 hashPrevBlock;
3015 if (hashPrevBlock != pblock->hashPrevBlock)
3018 hashPrevBlock = pblock->hashPrevBlock;
3021 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3023 // Put "OP_EVAL" in the coinbase so everybody can tell when
3024 // a majority of miners support it
3025 const char* pOpEvalName = GetOpName(OP_EVAL);
3026 pblock->vtx[0].vin[0].scriptSig += CScript() << std::vector<unsigned char>(pOpEvalName, pOpEvalName+strlen(pOpEvalName));
3027 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3029 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3033 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3036 // Prebuild hash buffers
3043 uint256 hashPrevBlock;
3044 uint256 hashMerkleRoot;
3047 unsigned int nNonce;
3050 unsigned char pchPadding0[64];
3052 unsigned char pchPadding1[64];
3055 memset(&tmp, 0, sizeof(tmp));
3057 tmp.block.nVersion = pblock->nVersion;
3058 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3059 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3060 tmp.block.nTime = pblock->nTime;
3061 tmp.block.nBits = pblock->nBits;
3062 tmp.block.nNonce = pblock->nNonce;
3064 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3065 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3067 // Byte swap all the input buffer
3068 for (int i = 0; i < sizeof(tmp)/4; i++)
3069 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3071 // Precalc the first half of the first hash, which stays constant
3072 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3074 memcpy(pdata, &tmp.block, 128);
3075 memcpy(phash1, &tmp.hash1, 64);
3079 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3081 uint256 hash = pblock->GetHash();
3082 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3084 if (hash > hashTarget)
3088 printf("BitcoinMiner:\n");
3089 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3091 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3092 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3095 CRITICAL_BLOCK(cs_main)
3097 if (pblock->hashPrevBlock != hashBestChain)
3098 return error("BitcoinMiner : generated block is stale");
3100 // Remove key from key pool
3101 reservekey.KeepKey();
3103 // Track how many getdata requests this block gets
3104 CRITICAL_BLOCK(wallet.cs_wallet)
3105 wallet.mapRequestCount[pblock->GetHash()] = 0;
3107 // Process this block the same as if we had received it from another node
3108 if (!ProcessBlock(NULL, pblock))
3109 return error("BitcoinMiner : ProcessBlock, block not accepted");
3115 void static ThreadBitcoinMiner(void* parg);
3117 void static BitcoinMiner(CWallet *pwallet)
3119 printf("BitcoinMiner started\n");
3120 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3122 // Each thread has its own key and counter
3123 CReserveKey reservekey(pwallet);
3124 unsigned int nExtraNonce = 0;
3126 while (fGenerateBitcoins)
3128 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3132 while (vNodes.empty() || IsInitialBlockDownload())
3137 if (!fGenerateBitcoins)
3145 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3146 CBlockIndex* pindexPrev = pindexBest;
3148 auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
3151 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3153 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3157 // Prebuild hash buffers
3159 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3160 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3161 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3163 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3165 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3166 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3172 int64 nStart = GetTime();
3173 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3175 uint256& hash = *alignup<16>(hashbuf);
3178 unsigned int nHashesDone = 0;
3179 unsigned int nNonceFound;
3182 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3183 (char*)&hash, nHashesDone);
3185 // Check if something found
3186 if (nNonceFound != -1)
3188 for (int i = 0; i < sizeof(hash)/4; i++)
3189 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3191 if (hash <= hashTarget)
3194 pblock->nNonce = ByteReverse(nNonceFound);
3195 assert(hash == pblock->GetHash());
3197 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3198 CheckWork(pblock.get(), *pwalletMain, reservekey);
3199 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3205 static int64 nHashCounter;
3206 if (nHPSTimerStart == 0)
3208 nHPSTimerStart = GetTimeMillis();
3212 nHashCounter += nHashesDone;
3213 if (GetTimeMillis() - nHPSTimerStart > 4000)
3215 static CCriticalSection cs;
3218 if (GetTimeMillis() - nHPSTimerStart > 4000)
3220 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3221 nHPSTimerStart = GetTimeMillis();
3223 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3224 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3225 static int64 nLogTime;
3226 if (GetTime() - nLogTime > 30 * 60)
3228 nLogTime = GetTime();
3229 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3230 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3236 // Check for stop or if block needs to be rebuilt
3239 if (!fGenerateBitcoins)
3241 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3245 if (nBlockNonce >= 0xffff0000)
3247 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3249 if (pindexPrev != pindexBest)
3252 // Update nTime every few seconds
3253 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3254 nBlockTime = ByteReverse(pblock->nTime);
3259 void static ThreadBitcoinMiner(void* parg)
3261 CWallet* pwallet = (CWallet*)parg;
3264 vnThreadsRunning[3]++;
3265 BitcoinMiner(pwallet);
3266 vnThreadsRunning[3]--;
3268 catch (std::exception& e) {
3269 vnThreadsRunning[3]--;
3270 PrintException(&e, "ThreadBitcoinMiner()");
3272 vnThreadsRunning[3]--;
3273 PrintException(NULL, "ThreadBitcoinMiner()");
3275 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3277 if (vnThreadsRunning[3] == 0)
3279 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3283 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3285 if (fGenerateBitcoins != fGenerate)
3287 fGenerateBitcoins = fGenerate;
3288 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3291 if (fGenerateBitcoins)
3293 int nProcessors = boost::thread::hardware_concurrency();
3294 printf("%d processors\n", nProcessors);
3295 if (nProcessors < 1)
3297 if (fLimitProcessors && nProcessors > nLimitProcessors)
3298 nProcessors = nLimitProcessors;
3299 int nAddThreads = nProcessors - vnThreadsRunning[3];
3300 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3301 for (int i = 0; i < nAddThreads; i++)
3303 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3304 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");